create Mutual Witness Protocol specs and implementation. #1
@@ -88,6 +88,8 @@ pub const ConnectionType = turn_integration.ConnectionType;
|
|||||||
pub const DhtCoordinator = dht.DhtCoordinator;
|
pub const DhtCoordinator = dht.DhtCoordinator;
|
||||||
pub const StoredValue = dht.StoredValue;
|
pub const StoredValue = dht.StoredValue;
|
||||||
pub const LookupState = dht.LookupState;
|
pub const LookupState = dht.LookupState;
|
||||||
|
pub const DhtTofuCallback = dht.DhtTofuCallback;
|
||||||
|
pub const TofuDecision = dht.TofuDecision;
|
||||||
|
|
||||||
// Secure connection re-exports
|
// Secure connection re-exports
|
||||||
pub const SecureConnection = secure_connection.SecureConnection;
|
pub const SecureConnection = secure_connection.SecureConnection;
|
||||||
|
|||||||
@@ -26,6 +26,10 @@ pub const BackoffConfig = struct {
|
|||||||
jitter_percent: u32 = 25,
|
jitter_percent: u32 = 25,
|
||||||
/// How long to remember backoff state for an address (in seconds)
|
/// How long to remember backoff state for an address (in seconds)
|
||||||
state_ttl_secs: i64 = 300, // 5 minutes
|
state_ttl_secs: i64 = 300, // 5 minutes
|
||||||
|
/// How often to run automatic cleanup of expired entries (in seconds)
|
||||||
|
cleanup_interval_secs: i64 = 60,
|
||||||
|
/// Maximum number of tracked addresses before forced cleanup
|
||||||
|
max_entries: usize = 10_000,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Per-address backoff state
|
/// Per-address backoff state
|
||||||
@@ -57,6 +61,8 @@ pub const ConnectionBackoff = struct {
|
|||||||
mutex: std.Thread.Mutex,
|
mutex: std.Thread.Mutex,
|
||||||
/// Allocator for hashmap
|
/// Allocator for hashmap
|
||||||
allocator: Allocator,
|
allocator: Allocator,
|
||||||
|
/// Timestamp of last automatic cleanup
|
||||||
|
last_cleanup_time: i64,
|
||||||
|
|
||||||
const Self = @This();
|
const Self = @This();
|
||||||
|
|
||||||
@@ -67,6 +73,7 @@ pub const ConnectionBackoff = struct {
|
|||||||
.config = config,
|
.config = config,
|
||||||
.mutex = .{},
|
.mutex = .{},
|
||||||
.allocator = allocator,
|
.allocator = allocator,
|
||||||
|
.last_cleanup_time = std.time.timestamp(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -117,6 +124,13 @@ pub const ConnectionBackoff = struct {
|
|||||||
|
|
||||||
const now = std.time.timestamp();
|
const now = std.time.timestamp();
|
||||||
|
|
||||||
|
// Automatic cleanup: run when interval elapsed or map exceeds max_entries
|
||||||
|
if (now - self.last_cleanup_time >= self.config.cleanup_interval_secs or
|
||||||
|
self.backoff_states.count() >= self.config.max_entries)
|
||||||
|
{
|
||||||
|
_ = self.cleanupExpiredLocked(now);
|
||||||
|
}
|
||||||
|
|
||||||
const entry = self.backoff_states.getOrPut(address_hash) catch {
|
const entry = self.backoff_states.getOrPut(address_hash) catch {
|
||||||
// Can't track state, return initial delay
|
// Can't track state, return initial delay
|
||||||
return self.config.initial_delay_ms;
|
return self.config.initial_delay_ms;
|
||||||
@@ -220,29 +234,45 @@ pub const ConnectionBackoff = struct {
|
|||||||
self.backoff_states.clearRetainingCapacity();
|
self.backoff_states.clearRetainingCapacity();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Clean up expired entries (call periodically to prevent memory growth)
|
/// Clean up expired entries. Called automatically by recordFailure(),
|
||||||
|
/// but can also be called manually for explicit control.
|
||||||
pub fn cleanupExpired(self: *Self) usize {
|
pub fn cleanupExpired(self: *Self) usize {
|
||||||
self.mutex.lock();
|
self.mutex.lock();
|
||||||
defer self.mutex.unlock();
|
defer self.mutex.unlock();
|
||||||
|
|
||||||
const now = std.time.timestamp();
|
return self.cleanupExpiredLocked(std.time.timestamp());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Internal cleanup that assumes mutex is already held
|
||||||
|
fn cleanupExpiredLocked(self: *Self, now: i64) usize {
|
||||||
|
self.last_cleanup_time = now;
|
||||||
var removed: usize = 0;
|
var removed: usize = 0;
|
||||||
|
|
||||||
var iter = self.backoff_states.iterator();
|
// Collect expired keys into a heap-allocated buffer
|
||||||
var to_remove = std.ArrayList(u64).init(self.allocator);
|
const entry_count = self.backoff_states.count();
|
||||||
defer to_remove.deinit();
|
if (entry_count == 0) return 0;
|
||||||
|
|
||||||
|
const to_remove = self.allocator.alloc(u64, entry_count) catch return 0;
|
||||||
|
defer self.allocator.free(to_remove);
|
||||||
|
var remove_len: usize = 0;
|
||||||
|
|
||||||
|
var iter = self.backoff_states.iterator();
|
||||||
while (iter.next()) |entry| {
|
while (iter.next()) |entry| {
|
||||||
if (now - entry.value_ptr.last_attempt > self.config.state_ttl_secs) {
|
if (now - entry.value_ptr.last_attempt > self.config.state_ttl_secs) {
|
||||||
to_remove.append(entry.key_ptr.*) catch continue;
|
to_remove[remove_len] = entry.key_ptr.*;
|
||||||
|
remove_len += 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (to_remove.items) |key| {
|
for (to_remove[0..remove_len]) |key| {
|
||||||
_ = self.backoff_states.remove(key);
|
_ = self.backoff_states.remove(key);
|
||||||
removed += 1;
|
removed += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (removed > 0) {
|
||||||
|
std.log.debug("ConnectionBackoff: cleaned up {d} expired entries", .{removed});
|
||||||
|
}
|
||||||
|
|
||||||
return removed;
|
return removed;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -402,13 +402,24 @@ pub const PinnedKeyExport = struct {
|
|||||||
// File Persistence
|
// File Persistence
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
/// Save pinned keys to a file
|
/// Save pinned keys to a file.
|
||||||
|
/// Uses atomic write (temp file + rename) to prevent corruption on crash.
|
||||||
pub fn saveToFile(store: *KeyPinStore, path: []const u8) !void {
|
pub fn saveToFile(store: *KeyPinStore, path: []const u8) !void {
|
||||||
const exports = try store.exportKeys(store.allocator);
|
const exports = try store.exportKeys(store.allocator);
|
||||||
defer if (exports.len > 0) store.allocator.free(exports);
|
defer if (exports.len > 0) store.allocator.free(exports);
|
||||||
|
|
||||||
var file = try std.fs.cwd().createFile(path, .{});
|
// Build temp path: original path + ".tmp"
|
||||||
defer file.close();
|
const tmp_path = try store.allocator.alloc(u8, path.len + 4);
|
||||||
|
defer store.allocator.free(tmp_path);
|
||||||
|
@memcpy(tmp_path[0..path.len], path);
|
||||||
|
@memcpy(tmp_path[path.len..], ".tmp");
|
||||||
|
|
||||||
|
// Write to temp file
|
||||||
|
var file = try std.fs.cwd().createFile(tmp_path, .{});
|
||||||
|
errdefer {
|
||||||
|
file.close();
|
||||||
|
std.fs.cwd().deleteFile(tmp_path) catch {};
|
||||||
|
}
|
||||||
|
|
||||||
// Write header: magic + version
|
// Write header: magic + version
|
||||||
_ = try file.write("KEYPIN01");
|
_ = try file.write("KEYPIN01");
|
||||||
@@ -440,6 +451,14 @@ pub fn saveToFile(store: *KeyPinStore, path: []const u8) !void {
|
|||||||
_ = try file.write(&[_]u8{ 0, 0 });
|
_ = try file.write(&[_]u8{ 0, 0 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
file.close();
|
||||||
|
|
||||||
|
// Atomic rename: replaces target in one syscall
|
||||||
|
std.fs.cwd().rename(tmp_path, path) catch |err| {
|
||||||
|
std.fs.cwd().deleteFile(tmp_path) catch {};
|
||||||
|
return err;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Load pinned keys from a file
|
/// Load pinned keys from a file
|
||||||
|
|||||||
@@ -137,6 +137,12 @@ pub const NatPmp = struct {
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// SECURITY: Verify response came from our gateway (prevents LAN spoofing)
|
||||||
|
if (!verifySourceAddress(&src_addr, self.gateway_ip)) {
|
||||||
|
std.log.warn("NAT-PMP: Response from unexpected source, ignoring (possible spoofing)", .{});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
if (recv_len < 12) {
|
if (recv_len < 12) {
|
||||||
std.log.warn("NAT-PMP: Short response ({} bytes)", .{recv_len});
|
std.log.warn("NAT-PMP: Short response ({} bytes)", .{recv_len});
|
||||||
return null;
|
return null;
|
||||||
@@ -217,6 +223,12 @@ pub const NatPmp = struct {
|
|||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// SECURITY: Verify response came from our gateway (prevents LAN spoofing)
|
||||||
|
if (!verifySourceAddress(&src_addr, self.gateway_ip)) {
|
||||||
|
std.log.warn("NAT-PMP: Response from unexpected source, ignoring (possible spoofing)", .{});
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
if (recv_len < 16) {
|
if (recv_len < 16) {
|
||||||
std.log.warn("NAT-PMP: Short response ({} bytes)", .{recv_len});
|
std.log.warn("NAT-PMP: Short response ({} bytes)", .{recv_len});
|
||||||
return null;
|
return null;
|
||||||
@@ -296,6 +308,15 @@ pub const NatPmp = struct {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Verify that a received UDP response came from the expected gateway IP.
|
||||||
|
/// Prevents LAN-based spoofing of NAT-PMP responses.
|
||||||
|
fn verifySourceAddress(src: *const posix.sockaddr.storage, expected_ip: [4]u8) bool {
|
||||||
|
if (src.family != posix.AF.INET) return false;
|
||||||
|
const in_addr: *const posix.sockaddr.in = @ptrCast(src);
|
||||||
|
const src_ip: [4]u8 = @bitCast(in_addr.addr);
|
||||||
|
return std.mem.eql(u8, &src_ip, &expected_ip);
|
||||||
|
}
|
||||||
|
|
||||||
/// Discover the default gateway IP address
|
/// Discover the default gateway IP address
|
||||||
pub fn discoverGateway() ![4]u8 {
|
pub fn discoverGateway() ![4]u8 {
|
||||||
// Platform-specific gateway discovery
|
// Platform-specific gateway discovery
|
||||||
@@ -350,19 +371,21 @@ fn discoverGatewayDarwin() ![4]u8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback: assume common gateway
|
// No gateway responded — return error instead of guessing
|
||||||
return .{ 192, 168, 1, 1 };
|
std.log.warn("NAT-PMP: No gateway responded to probes, gateway discovery failed", .{});
|
||||||
|
return error.GatewayNotFound;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn discoverGatewayLinux() ![4]u8 {
|
fn discoverGatewayLinux() ![4]u8 {
|
||||||
// On Linux, read /proc/net/route
|
// On Linux, read /proc/net/route
|
||||||
const file = std.fs.openFileAbsolute("/proc/net/route", .{}) catch {
|
const file = std.fs.openFileAbsolute("/proc/net/route", .{}) catch {
|
||||||
return .{ 192, 168, 1, 1 }; // Fallback
|
std.log.warn("NAT-PMP: Cannot open /proc/net/route, gateway discovery failed", .{});
|
||||||
|
return error.GatewayNotFound;
|
||||||
};
|
};
|
||||||
defer file.close();
|
defer file.close();
|
||||||
|
|
||||||
var buf: [4096]u8 = undefined;
|
var buf: [4096]u8 = undefined;
|
||||||
const bytes_read = file.readAll(&buf) catch return .{ 192, 168, 1, 1 };
|
const bytes_read = file.readAll(&buf) catch return error.GatewayNotFound;
|
||||||
|
|
||||||
var lines = std.mem.splitScalar(u8, buf[0..bytes_read], '\n');
|
var lines = std.mem.splitScalar(u8, buf[0..bytes_read], '\n');
|
||||||
_ = lines.next(); // Skip header
|
_ = lines.next(); // Skip header
|
||||||
@@ -386,7 +409,8 @@ fn discoverGatewayLinux() ![4]u8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return .{ 192, 168, 1, 1 }; // Fallback
|
std.log.warn("NAT-PMP: No default route found in /proc/net/route, gateway discovery failed", .{});
|
||||||
|
return error.GatewayNotFound;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Tests
|
// Tests
|
||||||
|
|||||||
@@ -334,9 +334,11 @@ pub const PeerManager = struct {
|
|||||||
manager.mutex.lock();
|
manager.mutex.lock();
|
||||||
defer manager.mutex.unlock();
|
defer manager.mutex.unlock();
|
||||||
|
|
||||||
// Check connection limit
|
// Check connection limit — try to evict a stale disconnected peer if at capacity
|
||||||
if (manager.max_connections > 0 and manager.peers.count() >= manager.max_connections) {
|
if (manager.max_connections > 0 and manager.peers.count() >= manager.max_connections) {
|
||||||
return Error.ResourceExhausted;
|
if (!manager.evictStalestDisconnectedPeerLocked()) {
|
||||||
|
return Error.ResourceExhausted;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const peer = try manager.allocator.create(Peer);
|
const peer = try manager.allocator.create(Peer);
|
||||||
@@ -433,6 +435,45 @@ pub const PeerManager = struct {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Evict the disconnected peer with the oldest last_seen timestamp.
|
||||||
|
/// Assumes the caller already holds the write lock.
|
||||||
|
/// Returns true if a peer was evicted, false if no evictable peers exist.
|
||||||
|
fn evictStalestDisconnectedPeerLocked(manager: *PeerManager) bool {
|
||||||
|
var oldest_time: i64 = std.math.maxInt(i64);
|
||||||
|
var victim_id: ?[32]u8 = null;
|
||||||
|
|
||||||
|
var iter = manager.peer_ids.iterator();
|
||||||
|
while (iter.next()) |entry| {
|
||||||
|
const peer = entry.value_ptr.*;
|
||||||
|
if (peer.state == .Disconnected and peer.last_seen < oldest_time) {
|
||||||
|
oldest_time = peer.last_seen;
|
||||||
|
victim_id = entry.key_ptr.*;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const evict_id = victim_id orelse return false;
|
||||||
|
|
||||||
|
// Remove from peer_ids map
|
||||||
|
if (manager.peer_ids.fetchRemove(evict_id)) |kv| {
|
||||||
|
const peer = kv.value;
|
||||||
|
const lookup_str = peer.address.toString(manager.allocator) catch {
|
||||||
|
// Can't generate lookup key — destroy peer but leave address map entry orphaned.
|
||||||
|
// This is a best-effort path.
|
||||||
|
manager.allocator.destroy(peer);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
defer manager.allocator.free(lookup_str);
|
||||||
|
if (manager.peers.fetchRemove(lookup_str)) |addr_kv| {
|
||||||
|
manager.allocator.free(addr_kv.key);
|
||||||
|
}
|
||||||
|
std.log.debug("PeerManager: evicted stale disconnected peer (last_seen={d})", .{oldest_time});
|
||||||
|
manager.allocator.destroy(peer);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
/// Thread-safe RTT update for a peer
|
/// Thread-safe RTT update for a peer
|
||||||
/// Returns true if peer was found and updated, false if peer not found
|
/// Returns true if peer was found and updated, false if peer not found
|
||||||
pub fn updatePeerRTT(manager: *PeerManager, peer_id: PeerId, rtt_ms: u32) bool {
|
pub fn updatePeerRTT(manager: *PeerManager, peer_id: PeerId, rtt_ms: u32) bool {
|
||||||
|
|||||||
@@ -50,6 +50,10 @@ pub const Error = error{
|
|||||||
OutOfMemory,
|
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
|
/// SecureConnection wraps a socket with Noise protocol encryption
|
||||||
pub const SecureConnection = struct {
|
pub const SecureConnection = struct {
|
||||||
/// Underlying socket
|
/// Underlying socket
|
||||||
@@ -68,6 +72,12 @@ pub const SecureConnection = struct {
|
|||||||
decrypt_buf: [MAX_MESSAGE_SIZE]u8,
|
decrypt_buf: [MAX_MESSAGE_SIZE]u8,
|
||||||
/// Allocator for any dynamic allocations
|
/// Allocator for any dynamic allocations
|
||||||
allocator: mem.Allocator,
|
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();
|
const Self = @This();
|
||||||
|
|
||||||
@@ -163,6 +173,8 @@ pub const SecureConnection = struct {
|
|||||||
// Send encrypted payload
|
// Send encrypted payload
|
||||||
try self.sendRaw(self.encrypt_buf[0..encrypted_len]);
|
try self.sendRaw(self.encrypt_buf[0..encrypted_len]);
|
||||||
|
|
||||||
|
self.maybeRekeyOutbound();
|
||||||
|
|
||||||
return plaintext.len;
|
return plaintext.len;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,6 +218,8 @@ pub const SecureConnection = struct {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.maybeRekeyOutbound();
|
||||||
|
|
||||||
return packet;
|
return packet;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -249,6 +263,8 @@ pub const SecureConnection = struct {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
self.maybeRekeyInbound();
|
||||||
|
|
||||||
return plaintext;
|
return plaintext;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,6 +298,37 @@ pub const SecureConnection = struct {
|
|||||||
return self.socket;
|
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
|
// Private helpers for raw socket I/O during handshake
|
||||||
// =========================================================================
|
// =========================================================================
|
||||||
|
|||||||
@@ -430,9 +430,17 @@ fn httpRequest(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read response
|
// Read response with total wall-clock timeout to prevent slow-drip attacks.
|
||||||
|
// Individual recv calls have a 5s SO_RCVTIMEO, but an attacker could send 1 byte
|
||||||
|
// every 4s to keep the loop alive indefinitely. This bounds total elapsed time.
|
||||||
var total_read: usize = 0;
|
var total_read: usize = 0;
|
||||||
|
const recv_start = std.time.milliTimestamp();
|
||||||
|
const max_recv_total_ms: i64 = 10_000; // 10s total for entire response
|
||||||
while (total_read < resp_buf.len) {
|
while (total_read < resp_buf.len) {
|
||||||
|
if (std.time.milliTimestamp() - recv_start > max_recv_total_ms) {
|
||||||
|
std.log.debug("UPnP: HTTP response total timeout exceeded ({d}ms)", .{max_recv_total_ms});
|
||||||
|
break;
|
||||||
|
}
|
||||||
const n = posix.recv(sock, resp_buf[total_read..], 0) catch break;
|
const n = posix.recv(sock, resp_buf[total_read..], 0) catch break;
|
||||||
if (n == 0) break;
|
if (n == 0) break;
|
||||||
total_read += n;
|
total_read += n;
|
||||||
|
|||||||
Reference in New Issue
Block a user