From b744ba5c09c84f39b80524cc5514ec76155e4242 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Tue, 10 Feb 2026 20:09:31 -0300 Subject: [PATCH] add DHT security mode and event queue overflow policy. bidirectional node-to-peer ID mapping with Sybil/impersonation checks, configurable event queue overflow strategy (drop_oldest/drop_newest/fail) --- src/p2p/config.zig | 24 +++++++++++++++++++++++ src/p2p/dht.zig | 24 +++++++++++++++++++++++ src/p2p/lifecycle.zig | 14 ++++++++++++-- src/p2p/messaging.zig | 25 ++++++++++++++++++++---- src/p2p/p2p.zig | 44 ++++++++++++++++++++++++++++++++++++++++--- 5 files changed, 122 insertions(+), 9 deletions(-) diff --git a/src/p2p/config.zig b/src/p2p/config.zig index 68a3dd2..c0ef759 100644 --- a/src/p2p/config.zig +++ b/src/p2p/config.zig @@ -199,6 +199,17 @@ pub const NetworkConfig = struct { max_pinned_keys: usize = 10000, /// Path to save/load pinned keys (null = no persistence) key_pin_file: ?[]const u8 = null, + /// DHT security mode + /// When true, DHT requires TOFU verification for all peers and enables + /// rate limiting + signature verification on all DHT messages. + /// When false (default), DHT runs in development/insecure mode where + /// peers are auto-accepted and messages are not authenticated. + /// WARNING: Set to true for any production deployment. + dht_secure_mode: bool = false, + /// Optional TOFU callback for DHT peer verification (only used when dht_secure_mode=true) + /// If dht_secure_mode=true and this is null, unknown peers will be rejected entirely. + /// Provide a callback to implement Trust-On-First-Use peer acceptance logic. + dht_tofu_callback: ?network.DhtTofuCallback = null, /// Enable retry with exponential backoff for failed handshakes handshake_retry_enabled: bool = true, /// Maximum number of connection/handshake retry attempts @@ -231,6 +242,16 @@ pub const ProtocolConfig = struct { pub const FileSharingConfig = files.manager.FileSharingConfig; /// Event system configuration +/// Policy for handling event queue overflow +pub const EventOverflowPolicy = enum { + /// Drop the oldest event to make room for the new one (default) + drop_oldest, + /// Drop the new event — caller is not notified + drop_newest, + /// Return QueueFull error to the caller + fail, +}; + pub const EventConfig = struct { /// Maximum event queue size max_event_queue: usize = 10000, @@ -238,6 +259,8 @@ pub const EventConfig = struct { enable_logging: bool = true, /// Event processing interval in milliseconds processing_interval: u32 = 100, + /// Behavior when event queue is full + overflow_policy: EventOverflowPolicy = .drop_oldest, }; // Tests @@ -346,6 +369,7 @@ test "EventConfig: defaults" { const config = EventConfig{}; try std.testing.expect(config.max_event_queue > 0); + try std.testing.expectEqual(EventOverflowPolicy.drop_oldest, config.overflow_policy); } test "EventConfig: custom values" { diff --git a/src/p2p/dht.zig b/src/p2p/dht.zig index b0e67f8..bf625a2 100644 --- a/src/p2p/dht.zig +++ b/src/p2p/dht.zig @@ -69,7 +69,31 @@ pub fn registerDhtNodeIdImpl(p2p: *P2P, node_id: [32]u8, connection_peer_id: Pee p2p.dht_node_to_peer_mutex.lock(); defer p2p.dht_node_to_peer_mutex.unlock(); + // SECURITY: Check for conflicting mappings (same checks as registerNodeIdCallback) + if (p2p.dht_node_to_peer.get(node_id)) |existing_peer| { + if (!std.mem.eql(u8, &existing_peer.bytes, &connection_peer_id.bytes)) { + std.log.err("SECURITY: DHT node ID {x} already mapped to peer {x}, rejecting claim from peer {x}", .{ + node_id[0..8].*, existing_peer.bytes[0..8].*, connection_peer_id.bytes[0..8].*, + }); + return Error.InvalidState; + } + return; // Same mapping already exists + } + if (p2p.peer_to_dht_node.get(connection_peer_id)) |existing_node_id| { + if (!std.mem.eql(u8, &existing_node_id, &node_id)) { + std.log.err("SECURITY: Peer {x} already registered as node {x}, rejecting new claim for node {x}", .{ + connection_peer_id.bytes[0..8].*, existing_node_id[0..8].*, node_id[0..8].*, + }); + return Error.InvalidState; + } + return; // Same mapping already exists + } + p2p.dht_node_to_peer.put(node_id, connection_peer_id) catch return Error.OutOfMemory; + p2p.peer_to_dht_node.put(connection_peer_id, node_id) catch { + _ = p2p.dht_node_to_peer.remove(node_id); + return Error.OutOfMemory; + }; std.log.info("Manually registered DHT node ID mapping: {x} -> peer {x}", .{ node_id[0..8].*, connection_peer_id.bytes[0..8].* }); } diff --git a/src/p2p/lifecycle.zig b/src/p2p/lifecycle.zig index ac03f4d..6339869 100644 --- a/src/p2p/lifecycle.zig +++ b/src/p2p/lifecycle.zig @@ -307,8 +307,18 @@ pub fn startImpl(p2p: *P2P) Error!void { }; if (p2p.dht_coordinator) |dht| { - dht.* = network.DhtCoordinator.initInsecureForDevelopment(p2p.allocator, rt, p2p.local_node_id); - std.log.info("DHT coordinator initialized with node ID (from identity): ", .{}); + if (p2p.config.network.dht_secure_mode) { + if (p2p.config.network.dht_tofu_callback) |tofu_cb| { + dht.* = network.DhtCoordinator.initWithTofu(p2p.allocator, rt, p2p.local_node_id, tofu_cb); + std.log.info("DHT coordinator initialized in SECURE mode with TOFU callback", .{}); + } else { + dht.* = network.DhtCoordinator.init(p2p.allocator, rt, p2p.local_node_id); + std.log.warn("DHT coordinator initialized in SECURE mode WITHOUT TOFU callback - all unknown peers will be REJECTED. Provide dht_tofu_callback for peer acceptance.", .{}); + } + } else { + dht.* = network.DhtCoordinator.initInsecureForDevelopment(p2p.allocator, rt, p2p.local_node_id); + std.log.warn("DHT running in INSECURE development mode - set network.dht_secure_mode=true for production", .{}); + } // Wire DHT coordinator to handler context if (p2p.handler_registry) |hr| { diff --git a/src/p2p/messaging.zig b/src/p2p/messaging.zig index a9ec66a..bdc0867 100644 --- a/src/p2p/messaging.zig +++ b/src/p2p/messaging.zig @@ -76,11 +76,28 @@ pub fn emitEventImpl(p2p: *P2P, event: P2PEvent) Error!void { defer p2p.event_mutex.unlock(); if (p2p.event_queue.items.len >= p2p.config.events.max_event_queue) { - std.log.warn("Event queue overflow - dropping oldest event (queue size: {})", .{p2p.event_queue.items.len}); _ = p2p.stats.events_dropped.fetchAdd(1, .monotonic); - if (p2p.event_queue.items.len > 0) { - var dropped = p2p.event_queue.orderedRemove(0); - dropped.deinit(); + switch (p2p.config.events.overflow_policy) { + .drop_oldest => { + std.log.warn("Event queue overflow - dropping oldest event (queue size: {})", .{p2p.event_queue.items.len}); + if (p2p.event_queue.items.len > 0) { + var dropped = p2p.event_queue.orderedRemove(0); + dropped.deinit(); + } + }, + .drop_newest => { + std.log.warn("Event queue overflow - dropping new event '{s}' (queue size: {})", .{ @tagName(event.event_type), p2p.event_queue.items.len }); + // Caller passed event by value; deinit in case it owns payload + var mutable_event = event; + mutable_event.deinit(); + return; + }, + .fail => { + std.log.err("Event queue full (size: {}), rejecting event '{s}'", .{ p2p.event_queue.items.len, @tagName(event.event_type) }); + var mutable_event = event; + mutable_event.deinit(); + return Error.QueueFull; + }, } } diff --git a/src/p2p/p2p.zig b/src/p2p/p2p.zig index f0089e5..9252067 100644 --- a/src/p2p/p2p.zig +++ b/src/p2p/p2p.zig @@ -182,14 +182,46 @@ pub fn registerNodeIdCallback(node_id: [32]u8, peer_id: [32]u8, context: ?*anyop return; })); - // Store the mapping: DHT node ID -> connection peer ID + const connection_peer = PeerId{ .bytes = peer_id }; + p2p.dht_node_to_peer_mutex.lock(); defer p2p.dht_node_to_peer_mutex.unlock(); - p2p.dht_node_to_peer.put(node_id, PeerId{ .bytes = peer_id }) catch |err| { + // SECURITY: Check if this node_id is already mapped to a different connection peer. + // This prevents a peer from impersonating another peer's DHT node ID. + if (p2p.dht_node_to_peer.get(node_id)) |existing_peer| { + if (!std.mem.eql(u8, &existing_peer.bytes, &peer_id)) { + std.log.err("SECURITY: DHT node ID {x} already mapped to peer {x}, rejecting claim from peer {x} (possible impersonation)", .{ + node_id[0..8].*, existing_peer.bytes[0..8].*, peer_id[0..8].*, + }); + return; + } + return; // Same mapping already exists + } + + // SECURITY: Check if this connection peer already has a different node_id registered. + // This prevents a single peer from claiming multiple DHT node IDs (Sybil attack). + if (p2p.peer_to_dht_node.get(connection_peer)) |existing_node_id| { + if (!std.mem.eql(u8, &existing_node_id, &node_id)) { + std.log.err("SECURITY: Peer {x} already registered as node {x}, rejecting new claim for node {x} (possible Sybil attack)", .{ + peer_id[0..8].*, existing_node_id[0..8].*, node_id[0..8].*, + }); + return; + } + return; // Same mapping already exists + } + + // Store bidirectional mapping + p2p.dht_node_to_peer.put(node_id, connection_peer) catch |err| { std.log.warn("Failed to register node ID mapping: {}", .{err}); return; }; + p2p.peer_to_dht_node.put(connection_peer, node_id) catch |err| { + // Roll back the forward mapping on failure + _ = p2p.dht_node_to_peer.remove(node_id); + std.log.warn("Failed to register reverse node ID mapping: {}", .{err}); + return; + }; std.log.info("Registered DHT node ID mapping: {x} -> connection peer {x}", .{ node_id[0..8].*, peer_id[0..8].* }); } @@ -379,7 +411,10 @@ pub const P2P = struct { /// Mapping from remote DHT node IDs to connection peer IDs /// This allows DHT to send messages to peers by their node ID dht_node_to_peer: std.AutoHashMap([32]u8, PeerId), - /// Mutex for dht_node_to_peer map + /// Reverse mapping from connection peer IDs to DHT node IDs + /// Used to verify that a peer's claimed DHT node ID matches their key-exchange identity + peer_to_dht_node: std.AutoHashMap(PeerId, [32]u8), + /// Mutex for dht_node_to_peer and peer_to_dht_node maps dht_node_to_peer_mutex: Mutex, /// Observed public addresses from DHT responses (Bundled STUN / IP Reflection) /// Stores our public IP:port as seen by DHT peers @@ -461,6 +496,7 @@ pub const P2P = struct { .key_pin_store = null, .connection_backoff = null, .dht_node_to_peer = std.AutoHashMap([32]u8, PeerId).init(allocator), + .peer_to_dht_node = std.AutoHashMap(PeerId, [32]u8).init(allocator), .dht_node_to_peer_mutex = Mutex{}, .observed_addresses = .{}, .observed_addresses_mutex = Mutex{}, @@ -495,6 +531,7 @@ pub const P2P = struct { errdefer p2p.user_contexts.deinit(allocator); errdefer p2p.event_handlers.deinit(allocator); errdefer p2p.dht_node_to_peer.deinit(); + errdefer p2p.peer_to_dht_node.deinit(); // Set local node ID from identity public key p2p.local_node_id = p2p.identity_keypair.public_key.bytes; @@ -695,6 +732,7 @@ pub const P2P = struct { p2p.allocator.destroy(rt); } p2p.dht_node_to_peer.deinit(); + p2p.peer_to_dht_node.deinit(); p2p.observed_addresses.deinit(p2p.allocator); // Clean up network components