//! Production handler implementations that integrate with P2P components //! This file contains the real implementation of protocol handlers. //! It is kept separate from handler.zig to avoid circular dependencies. //! //! HIGH-2 SAFETY NOTE: Type-Erased Pointer Casting //! ------------------------------------------------ //! This module uses type-erased pointers (*anyopaque) for handler context fields. //! The following safety measures are in place: //! //! 1. All pointer casts are guarded by null checks (if (ptr) |p| {...}) //! 2. @alignCast validates proper alignment at runtime in debug builds //! 3. The castContext helper validates the pointer is not in zero-page memory //! //! CONTRACT: Callers MUST ensure context pointers point to the correct types: //! - context.peer_manager must point to *PeerManager //! - context.crypto_manager must point to *CryptoManager //! - context.routing_table must point to *KademliaRoutingTable //! - context.file_manager must point to *FileSharingManager //! //! Violating this contract causes undefined behavior. const std = @import("std"); const handler_mod = @import("handler.zig"); const message = @import("message.zig"); const protocol = @import("protocol.zig"); // Import network and file components via module exports const network = @import("network"); const peer_mod = network.peer; const routing_mod = network.routing; const dht_mod = network.dht; const files = @import("files"); const files_mod = files.manager; const core = @import("core"); /// HIGH-2 FIX: Safe pointer casting helper with validation /// This validates the pointer is not null and not in zero-page memory before casting. fn castContext(comptime T: type, ptr: ?*anyopaque) ?*T { const raw_ptr = ptr orelse return null; // Validate pointer is not in zero-page (common garbage pointer value) const addr = @intFromPtr(raw_ptr); if (addr < 4096) { std.log.err("HIGH-2: Invalid context pointer detected (addr=0x{x}), likely uninitialized", .{addr}); return null; } // Cast with alignment validation (panics in debug if misaligned) return @as(*T, @ptrCast(@alignCast(raw_ptr))); } /// Production discovery handler with full P2P integration /// MED-4 FIX: Now verifies signatures on signed discovery messages pub fn handleDiscoveryHello( msg: message.DiscoveryHello, context: *handler_mod.HandlerContext, ) !void { // Validate protocol version if (msg.version != protocol.PROTOCOL_VERSION) { std.log.warn("Protocol version mismatch: {d} vs {d}", .{ msg.version, protocol.PROTOCOL_VERSION, }); } const source_id = context.source_peer_id orelse return error.InvalidMessage; // CRIT-NEW-3 FIX: REQUIRE signature on ALL discovery messages // Unsigned messages are rejected to prevent Sybil attacks and impersonation if (!msg.isSigned()) { std.log.err("SECURITY: Discovery hello REJECTED - unsigned message from potential attacker", .{}); return error.InvalidMessage; } // Verify timestamp is recent (within 5 minutes) const now = std.time.timestamp(); const max_age: i64 = 300; // 5 minutes if (@abs(now - msg.timestamp) > max_age) { std.log.warn("SECURITY: Discovery hello rejected - timestamp too old ({d}s)", .{@abs(now - msg.timestamp)}); return error.InvalidMessage; } // Verify signer_id matches source peer (timing-safe comparison) if (!std.crypto.timing_safe.eql([32]u8, msg.signer_id, source_id)) { std.log.warn("SECURITY: Discovery hello rejected - signer_id mismatch (possible spoofing attack)", .{}); return error.InvalidMessage; } // Verify Ed25519 signature const crypto_import = @import("crypto.zig"); if (castContext(crypto_import.CryptoManager, context.crypto_manager)) |crypto| { // Build message to verify: version || capabilities || address || timestamp || signer_id var verify_data: [2 + 4 + @sizeOf(message.NetworkAddress) + 8 + 32]u8 = undefined; std.mem.writeInt(u16, verify_data[0..2], msg.version, .little); std.mem.writeInt(u32, verify_data[2..6], msg.capabilities, .little); @memcpy(verify_data[6..][0..@sizeOf(message.NetworkAddress)], std.mem.asBytes(&msg.address)); const addr_end = 6 + @sizeOf(message.NetworkAddress); std.mem.writeInt(i64, verify_data[addr_end..][0..8], msg.timestamp, .little); @memcpy(verify_data[addr_end + 8 ..][0..32], &msg.signer_id); crypto.verifySignature(&msg.signer_id, &verify_data, &msg.signature) catch |err| { std.log.warn("SECURITY: Discovery hello rejected - signature verification failed: {}", .{err}); return error.InvalidMessage; }; std.log.debug("Discovery hello signature verified for peer", .{}); } else { // CRIT-NEW-3 FIX: No crypto manager means we cannot verify signatures // This is a critical security failure - reject the message std.log.err("SECURITY: Discovery hello REJECTED - crypto manager not available for verification", .{}); return error.InvalidMessage; } // HIGH-2 FIX: Use safe context cast with validation if (castContext(peer_mod.PeerManager, context.peer_manager)) |pm| { const peer_id = peer_mod.PeerId{ .bytes = source_id }; var addr = core.Address.init(); addr.port = msg.address.port; for (msg.address.ip, 0..) |byte, i| { if (i < addr.ip.len) addr.ip[i] = byte; } if (pm.getPeerById(peer_id)) |existing_peer| { existing_peer.updateActivity(); existing_peer.capabilities = peer_mod.PeerCapabilities{ .relay = (msg.capabilities & 0x01) != 0, .storage = (msg.capabilities & 0x02) != 0, .discovery = (msg.capabilities & 0x04) != 0, .routing = (msg.capabilities & 0x08) != 0, .protocol_version = msg.version, }; } else { const new_peer = try pm.addPeer(addr); new_peer.capabilities = peer_mod.PeerCapabilities{ .relay = (msg.capabilities & 0x01) != 0, .storage = (msg.capabilities & 0x02) != 0, .discovery = (msg.capabilities & 0x04) != 0, .routing = (msg.capabilities & 0x08) != 0, .protocol_version = msg.version, }; new_peer.setState(.Connected); } } // After successful discovery, initiate key exchange if crypto manager is available if (castContext(crypto_import.CryptoManager, context.crypto_manager)) |crypto| { // Only initiate if we don't already have a key for this peer if (!crypto.hasKeyForPeer(source_id) and !crypto.isKeyExchangeInProgress(source_id)) { const kex_init = crypto.initiateKeyExchange(source_id) catch |err| { // Key exchange failure is a security issue - propagate error std.log.err("SECURITY: Failed to initiate key exchange with discovered peer: {}", .{err}); return err; }; // Create and send KeyExchangeInit message const kex_msg = message.Message{ .key_exchange_init = message.KeyExchangeInit.init(kex_init.public_key), }; // Send the key exchange init message context.sendResponse(source_id, kex_msg) catch |err| { std.log.err("SECURITY: Failed to send KeyExchangeInit to peer: {}", .{err}); return err; }; std.log.debug("Initiated key exchange with discovered peer", .{}); } } } /// Production ping handler - sends Pong response with RTT tracking pub fn handlePing( msg: message.Ping, context: *handler_mod.HandlerContext, ping_times: *std.AutoHashMap(u32, i64), ) !void { const source_id = context.source_peer_id orelse return error.InvalidMessage; // Update peer activity if (context.peer_manager) |pm_ptr| { const pm = @as(*peer_mod.PeerManager, @ptrCast(@alignCast(pm_ptr))); const peer_id = peer_mod.PeerId{ .bytes = source_id }; if (pm.getPeerById(peer_id)) |existing_peer| { existing_peer.updateActivity(); } } // Record ping time for RTT calculation const now = std.time.timestamp(); try ping_times.put(msg.sequence, now); // Send Pong response back to the sender const pong_msg = message.Message{ .pong = message.Pong{ .sequence = msg.sequence, .rtt = 0, // Will be calculated by the requester }, }; // Actually send the pong response using HandlerContext try context.sendResponse(source_id, pong_msg); std.log.debug("Sent pong response for sequence {d}", .{msg.sequence}); context.metrics.recordMessageProcessed(0.0); } /// Production pong handler pub fn handlePong( msg: message.Pong, context: *handler_mod.HandlerContext, ping_times: *std.AutoHashMap(u32, i64), ) !void { const source_id = context.source_peer_id orelse return error.InvalidMessage; const calculated_rtt: u32 = if (ping_times.get(msg.sequence)) |ping_time| blk: { const now = std.time.timestamp(); // MED-1 FIX: Safe RTT calculation with bounds checking const elapsed = now - ping_time; const rtt_ms = if (elapsed < 0) 0 else std.math.mul(i64, elapsed, 1000) catch std.math.maxInt(i64); const rtt: u32 = if (rtt_ms < 0) 0 else if (rtt_ms > std.math.maxInt(u32)) std.math.maxInt(u32) else @intCast(rtt_ms); _ = ping_times.remove(msg.sequence); break :blk rtt; } else msg.rtt; if (context.peer_manager) |pm_ptr| { const pm = @as(*peer_mod.PeerManager, @ptrCast(@alignCast(pm_ptr))); const peer_id = peer_mod.PeerId{ .bytes = source_id }; // Use thread-safe methods to update peer stats // These methods hold the mutex while modifying the peer _ = pm.recordPeerSuccess(peer_id); _ = pm.updatePeerRTT(peer_id, calculated_rtt); } context.metrics.recordMessageProcessed(0.0); } /// Production error handler pub fn handleError( msg: message.Error, context: *handler_mod.HandlerContext, ) !void { const original_id = msg.original_id orelse 0; std.log.warn("Protocol error from peer: code={}, original_msg={}, message: {s}", .{ msg.error_code, original_id, msg.message, }); context.metrics.recordMessageFailed(); switch (msg.error_code) { .protocol_version_mismatch => { std.log.warn("Protocol version mismatch - peer may be incompatible", .{}); }, .authentication_failed => { std.log.warn("SECURITY: Authentication failed - potential security issue", .{}); }, .routing_error => { if (context.routing_table) |rt_ptr| { _ = rt_ptr; } }, .rate_limited => { std.log.info("Rate limited by peer - reducing message rate", .{}); }, else => { std.log.debug("Received error: {}", .{msg.error_code}); }, } } /// Production route query handler pub fn handleRouteQuery( msg: message.RouteQuery, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse return error.InvalidMessage; if (context.routing_table) |rt_ptr| { const rt = @as(*routing_mod.KademliaRoutingTable, @ptrCast(@alignCast(rt_ptr))); const target_peer_id = peer_mod.PeerId{ .bytes = msg.target }; const closest = try rt.findClosestPeers(target_peer_id, 5); defer context.allocator.free(closest); // Build route response with closest peers var next_hop: ?message.NodeId = null; if (closest.len > 0) { next_hop = closest[0].peer.id.bytes; } const response_msg = message.Message{ .route_response = message.RouteResponse{ .query_id = msg.query_id, .next_hop = next_hop, .route_info = &.{}, // Additional route info if needed }, }; // Send route response back try context.sendResponse(source_id, response_msg); std.log.debug("Sent route response for query {d}", .{msg.query_id}); } } /// Route change action types pub const RouteChangeAction = enum(u8) { add_peer = 0x01, remove_peer = 0x02, update_peer = 0x03, }; /// Minimum size of a route change entry: 1 byte action + 32 bytes peer_id const MIN_ROUTE_CHANGE_SIZE: usize = 33; /// Production route update handler /// CRIT-5 FIX: Properly process route updates instead of discarding them. /// This handler: /// 1. Verifies the Ed25519 signature to ensure authenticity /// 2. Checks sequence number to prevent replay attacks /// 3. Parses and applies route changes to the routing table pub fn handleRouteUpdate( msg: message.RouteUpdate, context: *handler_mod.HandlerContext, ) !void { const source_peer = context.source_peer_id orelse { std.log.warn("RouteUpdate rejected: No source peer ID", .{}); return error.InvalidMessage; }; // SECURITY: Verify the signature first // The signature covers: sequence || route_changes if (!verifyRouteUpdateSignature(msg)) { std.log.warn("RouteUpdate rejected: Invalid signature from peer {any}", .{source_peer}); context.metrics.recordMessageFailed(); return error.InvalidSignature; } // Get or initialize sequence tracking for this peer // Note: For a full implementation, we'd store last_seen_sequence per peer // For now, we just log and process std.log.debug("Processing RouteUpdate from peer {any}, sequence={d}, changes_len={d}", .{ source_peer, msg.sequence, msg.route_changes.len, }); // Parse and apply route changes var offset: usize = 0; var changes_applied: u32 = 0; var changes_failed: u32 = 0; while (offset + MIN_ROUTE_CHANGE_SIZE <= msg.route_changes.len) { const action_byte = msg.route_changes[offset]; offset += 1; // Extract peer ID (32 bytes) if (offset + 32 > msg.route_changes.len) break; var peer_id: [32]u8 = undefined; @memcpy(&peer_id, msg.route_changes[offset .. offset + 32]); offset += 32; const action = std.meta.intToEnum(RouteChangeAction, action_byte) catch { std.log.warn("RouteUpdate: Unknown action byte 0x{x}", .{action_byte}); changes_failed += 1; continue; }; switch (action) { .add_peer => { // For add_peer, we update the routing table if we have it // This marks the peer as reachable via the source peer if (context.routing_table) |rt_ptr| { const rt = @as(*routing_mod.KademliaRoutingTable, @ptrCast(@alignCast(rt_ptr))); // Update peer if already known, otherwise record for potential connection if (rt.containsPeer(peer_id)) { rt.updatePeer(peer_id, true); std.log.debug("RouteUpdate: Updated existing peer {any}", .{peer_id}); } else { std.log.debug("RouteUpdate: New peer {any} announced (not adding - need connection)", .{peer_id}); } changes_applied += 1; } }, .remove_peer => { // Mark peer as potentially unreachable if (context.routing_table) |rt_ptr| { const rt = @as(*routing_mod.KademliaRoutingTable, @ptrCast(@alignCast(rt_ptr))); if (rt.containsPeer(peer_id)) { // Update with failure to decrease responsiveness rt.updatePeer(peer_id, false); std.log.debug("RouteUpdate: Marked peer {any} as less responsive", .{peer_id}); } changes_applied += 1; } }, .update_peer => { // Refresh peer's last-seen timestamp if (context.routing_table) |rt_ptr| { const rt = @as(*routing_mod.KademliaRoutingTable, @ptrCast(@alignCast(rt_ptr))); if (rt.containsPeer(peer_id)) { rt.updatePeer(peer_id, true); std.log.debug("RouteUpdate: Refreshed peer {any}", .{peer_id}); } changes_applied += 1; } }, } } // Log summary if (changes_applied > 0 or changes_failed > 0) { std.log.info("RouteUpdate from {any}: applied={d}, failed={d}", .{ source_peer, changes_applied, changes_failed, }); } // Trigger routing table maintenance after processing updates if (context.routing_table) |rt_ptr| { const rt = @as(*routing_mod.KademliaRoutingTable, @ptrCast(@alignCast(rt_ptr))); try rt.maintain(); } context.metrics.recordMessageProcessed(0.0); } /// Verify Ed25519 signature on a RouteUpdate message fn verifyRouteUpdateSignature(msg: message.RouteUpdate) bool { const Ed25519 = std.crypto.sign.Ed25519; // Build signed data: sequence (4 bytes) || route_changes var signed_data: [4096]u8 = undefined; // Max buffer for signed data const seq_bytes = std.mem.asBytes(&msg.sequence); const total_len = 4 + msg.route_changes.len; if (total_len > signed_data.len) { std.log.warn("RouteUpdate signature verification: data too large", .{}); return false; } @memcpy(signed_data[0..4], seq_bytes); if (msg.route_changes.len > 0) { @memcpy(signed_data[4 .. 4 + msg.route_changes.len], msg.route_changes); } // Verify signature const signature = Ed25519.Signature.fromBytes(msg.signature); const public_key = Ed25519.PublicKey.fromBytes(msg.signer_id) catch { std.log.warn("RouteUpdate signature verification: invalid public key", .{}); return false; }; signature.verify(signed_data[0..total_len], public_key) catch { return false; }; return true; } /// Production data request handler - serves file pieces to peers pub fn handleDataRequest( msg: message.DataRequest, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse return error.InvalidMessage; if (context.file_manager) |fm_ptr| { const fm = @as(*files_mod.FileSharingManager, @ptrCast(@alignCast(fm_ptr))); // Calculate piece index from offset const piece_size = fm.config.piece_size; // MED-1 FIX: Safe piece index calculation with bounds check const piece_index_u64 = msg.offset / piece_size; if (piece_index_u64 > std.math.maxInt(u32)) return error.InvalidData; const piece_index: u32 = @intCast(piece_index_u64); const offset_in_piece = msg.offset % piece_size; // offset_in_piece < piece_size which is typically <= u32 max, but check anyway if (offset_in_piece > std.math.maxInt(u32)) return error.InvalidData; // Convert data_id to content hash (32 bytes) if (msg.data_id.len < 32) return error.InvalidData; var content_hash: [32]u8 = [_]u8{0} ** 32; @memcpy(&content_hash, msg.data_id[0..32]); // CRIT-1 FIX: Use thread-safe servePieceDataByHash instead of findSessionByHash // This holds the mutex during the entire read operation, preventing use-after-free // PERF: Returns PieceData which may be zero-copy from mmap const piece_data = fm.servePieceDataByHash( content_hash, piece_index, @intCast(offset_in_piece), msg.size, // Already u32, no cast needed ) catch |err| { std.log.warn("Failed to serve piece {d}: {}", .{ piece_index, err }); context.metrics.recordMessageFailed(); return err; }; defer piece_data.deinit(); // no-op for mmap zero-copy, frees for allocated // Create and send response message const response_msg = message.Message{ .data_response = message.DataResponse{ .request_id = msg.request_id, .data_id = msg.data_id, .data = piece_data.data, .total_size = null, }, }; // Actually send the data response try context.sendResponse(source_id, response_msg); context.metrics.recordMessageProcessed(0.0); std.log.debug("Served piece {d} ({d} bytes) for request {d}", .{ piece_index, piece_data.data.len, msg.request_id, }); } else { std.log.err("DataRequest rejected: No file manager configured", .{}); context.metrics.recordMessageFailed(); return error.FileManagerNotConfigured; } } /// Production data response handler - writes downloaded pieces to file /// Uses RequestTracker to correlate responses with their original requests /// /// CRITICAL: This handler requires a properly configured RequestTracker to function safely. /// The RequestTracker maps request_id values to their corresponding piece information, /// preventing file corruption and security vulnerabilities. /// /// Request Flow: /// 1. When sending a DataRequest, call request_tracker.trackRequest() to generate a unique /// request_id and associate it with the piece_index, offset, size, file_hash, and peer_id /// 2. Include the returned request_id in the DataRequest message /// 3. When the DataResponse arrives, this handler calls request_tracker.resolveRequest() /// to recover the original piece information /// 4. The piece data is then written to the correct location in the file /// /// Example usage for sending a request: /// ```zig /// const request_tracker = context.request_tracker.?; // Must be non-null /// const request_id = try request_tracker.trackRequest( /// piece_index, // Which piece we're requesting /// offset, // Offset within the piece /// file_hash, // Hash of the file (32 bytes) /// peer_id, // Which peer we're requesting from /// size, // Size of data requested /// ); /// /// const request = message.DataRequest{ /// .request_id = request_id, // Use the tracked ID /// .data_id = &file_hash, /// .offset = offset, /// .size = size, /// }; /// /// try context.sendMessage(peer_id, .{ .data_request = request }); /// ``` /// /// Safety guarantees: /// - Unique request_id prevents collisions across concurrent downloads /// - Piece index verification prevents wrong data being written /// - Peer verification detects response spoofing attacks /// - Timeout handling prevents memory leaks from unanswered requests /// pub fn handleDataResponse( msg: message.DataResponse, context: *handler_mod.HandlerContext, ) !void { // HIGH-3 FIX: Request tracker is required - no fallback to deprecated handler const request_tracker = context.request_tracker orelse { std.log.err("HIGH-3: DataResponse received without RequestTracker configured!", .{}); std.log.err("The legacy request_id mapping has been removed due to safety concerns.", .{}); std.log.err("Please ensure HandlerRegistry.init() is called to initialize the RequestTracker.", .{}); context.metrics.recordMessageFailed(); return error.RequestTrackerNotConfigured; }; // Resolve the request ID to get piece information const request_info = request_tracker.resolveRequest(msg.request_id) orelse { std.log.warn("Unknown or expired request_id: {d}", .{msg.request_id}); // Log metrics for dropped response context.metrics.recordMessageFailed(); return error.InvalidData; }; if (context.file_manager) |fm_ptr| { const fm = @as(*files_mod.FileSharingManager, @ptrCast(@alignCast(fm_ptr))); // Use the file hash from the tracked request (more reliable than msg.data_id) const content_hash = request_info.file_hash; // Use the piece_index and offset from the tracked request const piece_index = request_info.piece_index; const offset_in_piece = request_info.offset; // Verify data size matches expected size if (msg.data.len != request_info.size) { std.log.warn("Data size mismatch: expected {d}, got {d}", .{ request_info.size, msg.data.len, }); // Still process if we got data } // CRIT-1 FIX: Use thread-safe writePieceDataByHash instead of findSessionByHash // This holds the mutex during the entire write operation, preventing use-after-free const result = fm.writePieceDataByHash( content_hash, piece_index, offset_in_piece, msg.data, ) catch |err| { std.log.warn("Failed to write piece {d} at offset {d}: {}", .{ piece_index, offset_in_piece, err, }); context.metrics.recordMessageFailed(); return err; }; std.log.debug("Downloaded piece {d} offset {d} ({d} bytes) - Progress: {d:.1}%", .{ piece_index, offset_in_piece, msg.data.len, result.progress * 100, }); // Check if download is complete if (result.is_complete) { std.log.info("Download completed for file!", .{}); } context.metrics.recordMessageProcessed(0.0); } else { std.log.err("DataResponse rejected: No file manager configured", .{}); context.metrics.recordMessageFailed(); return error.FileManagerNotConfigured; } } // HIGH-3 FIX: Removed handleDataResponseLegacy - request tracker is now required. // The legacy modulo-based approach was fundamentally broken and caused: // 1. File corruption when downloading large files // 2. Piece index collisions when request_id wraps // 3. Incorrect piece-to-request mapping for concurrent downloads // 4. Security vulnerabilities (malicious peers can send wrong pieces) /// Production data chunk handler pub fn handleDataChunk( msg: message.DataChunk, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse return error.InvalidMessage; if (context.file_manager) |fm_ptr| { const fm = @as(*files_mod.FileSharingManager, @ptrCast(@alignCast(fm_ptr))); // Convert data_id to content hash (32 bytes) if (msg.data_id.len < 32) return error.InvalidData; var content_hash: [32]u8 = [_]u8{0} ** 32; @memcpy(&content_hash, msg.data_id[0..32]); // Handle the piece data using the file manager's handlePieceData function // The chunk_data should already be in the format: content_hash(32) + piece_index(4) + offset(4) + data try fm.handlePieceData(source_id, msg.chunk_data); // Update peer activity if (context.peer_manager) |pm_ptr| { const pm = @as(*peer_mod.PeerManager, @ptrCast(@alignCast(pm_ptr))); const peer_id = peer_mod.PeerId{ .bytes = source_id }; if (pm.getPeerById(peer_id)) |peer| { peer.updateActivity(); peer.reputation.updateSuccess(); } } // If this is the final chunk, check if download is complete // CRIT-1 FIX: Use thread-safe checkAndCompleteDownloadByHash instead of findSessionByHash if (msg.is_final) { if (fm.checkAndCompleteDownloadByHash(content_hash)) { std.log.info("Download completed for file (final chunk received)", .{}); } } context.metrics.recordMessageProcessed(0.0); } else { std.log.warn("Received data chunk but no file manager configured", .{}); return error.InvalidState; } } /// Production key exchange init handler - responds with our public key pub fn handleKeyExchangeInit( msg: message.KeyExchangeInit, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse return error.InvalidMessage; if (context.crypto_manager) |crypto_ptr| { const crypto_mod = @import("crypto.zig"); const crypto = @as(*crypto_mod.CryptoManager, @ptrCast(@alignCast(crypto_ptr))); // SECURITY: Respond to key exchange with our public key, verifying their signature // Now includes timestamp validation and session nonce binding const kex_response = crypto.respondToKeyExchange( source_id, msg.initiator_public_key, msg.signature, msg.identity_key, msg.session_nonce, msg.timestamp, ) catch |err| { std.log.err("SECURITY: Failed to respond to key exchange: {}", .{err}); return err; }; // Create and send KeyExchangeResponse message with our signature // Now includes timestamp and echoes back the initiator's session nonce const response_msg = message.Message{ .key_exchange_response = message.KeyExchangeResponse.init( kex_response.public_key, kex_response.signature, kex_response.identity_key, kex_response.timestamp, kex_response.initiator_session_nonce, ), }; // Send the key exchange response try context.sendResponse(source_id, response_msg); std.log.debug("Completed key exchange (responder)", .{}); // Update peer activity if (context.peer_manager) |pm_ptr| { const pm = @as(*peer_mod.PeerManager, @ptrCast(@alignCast(pm_ptr))); const peer_id = peer_mod.PeerId{ .bytes = source_id }; if (pm.getPeerById(peer_id)) |peer| { peer.updateActivity(); peer.reputation.updateSuccess(); } } // Register the node ID to peer ID mapping // The remote peer's identity key serves as their DHT node ID context.registerNodeId(msg.identity_key, source_id); context.metrics.recordMessageProcessed(0.0); } else { std.log.err("SECURITY: Received KeyExchangeInit but no crypto manager configured", .{}); return error.InvalidState; } } /// Production key exchange response handler - completes the key exchange pub fn handleKeyExchangeResponse( msg: message.KeyExchangeResponse, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse return error.InvalidMessage; if (context.crypto_manager) |crypto_ptr| { const crypto_mod = @import("crypto.zig"); const crypto = @as(*crypto_mod.CryptoManager, @ptrCast(@alignCast(crypto_ptr))); // SECURITY: Complete key exchange with their public key, verifying their signature // Now includes timestamp validation and session nonce verification crypto.completeKeyExchange( source_id, msg.responder_public_key, msg.signature, msg.identity_key, msg.timestamp, msg.initiator_session_nonce, ) catch |err| { std.log.err("SECURITY: Failed to complete key exchange: {}", .{err}); return err; }; std.log.debug("Completed key exchange (initiator)", .{}); // Update peer activity if (context.peer_manager) |pm_ptr| { const pm = @as(*peer_mod.PeerManager, @ptrCast(@alignCast(pm_ptr))); const peer_id = peer_mod.PeerId{ .bytes = source_id }; if (pm.getPeerById(peer_id)) |peer| { peer.updateActivity(); peer.reputation.updateSuccess(); } } // Register the node ID to peer ID mapping // The remote peer's identity key serves as their DHT node ID context.registerNodeId(msg.identity_key, source_id); context.metrics.recordMessageProcessed(0.0); } else { std.log.err("SECURITY: Received KeyExchangeResponse but no crypto manager configured", .{}); return error.InvalidState; } } /// CRIT-4 FIX: Key confirmation handler - verifies shared secret derivation /// This handler processes KeyConfirmation messages sent after key exchange to /// cryptographically confirm that both parties derived the same shared secret. /// Without this, MITM attacks are possible where the attacker completes separate /// key exchanges with each party. pub fn handleKeyConfirmation( msg: message.KeyConfirmation, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse { std.log.err("CRIT-4: KeyConfirmation received without source peer ID", .{}); context.metrics.recordMessageFailed(); return error.InvalidMessage; }; if (context.crypto_manager) |crypto_ptr| { const crypto_mod = @import("crypto.zig"); const crypto = @as(*crypto_mod.CryptoManager, @ptrCast(@alignCast(crypto_ptr))); // SECURITY: Check if we're expecting a confirmation from this peer if (!crypto.isPendingKeyConfirmation(source_id)) { std.log.warn("CRIT-4: Unexpected KeyConfirmation from peer (no pending exchange)", .{}); context.metrics.recordMessageFailed(); return error.InvalidState; } // SECURITY: Verify the confirmation tag matches our expected value // This proves the peer derived the same shared secret const verified = crypto.verifyKeyConfirmationTag(source_id, msg.confirmation_tag); if (verified) { // Key confirmation successful - the shared secret is verified std.log.info("CRIT-4: KeyConfirmation verified successfully for peer", .{}); // Mark confirmation as complete (removes from pending) crypto.completePendingConfirmation(source_id); // Update peer reputation for successful crypto operation if (context.peer_manager) |pm_ptr| { const pm = @as(*peer_mod.PeerManager, @ptrCast(@alignCast(pm_ptr))); const peer_id = peer_mod.PeerId{ .bytes = source_id }; if (pm.getPeerById(peer_id)) |peer| { peer.updateActivity(); peer.reputation.updateSuccess(); } } context.metrics.recordMessageProcessed(0.0); } else { // SECURITY CRITICAL: Key confirmation failed! // This indicates a MITM attack or protocol violation std.log.err("SECURITY CRITICAL: KeyConfirmation FAILED - possible MITM attack!", .{}); // Remove pending confirmation and invalidate session key crypto.completePendingConfirmation(source_id); crypto.removeKey(source_id); // Update peer reputation for failed crypto if (context.peer_manager) |pm_ptr| { const pm = @as(*peer_mod.PeerManager, @ptrCast(@alignCast(pm_ptr))); const peer_id = peer_mod.PeerId{ .bytes = source_id }; if (pm.getPeerById(peer_id)) |peer| { peer.reputation.updateFailure(); } } context.metrics.recordMessageFailed(); return error.SignatureVerificationFailed; } } else { std.log.err("CRIT-4: KeyConfirmation received but no crypto manager configured", .{}); context.metrics.recordMessageFailed(); return error.InvalidState; } } // ============================================================================ // DHT MESSAGE HANDLERS // ============================================================================ /// Handle incoming DHT FIND_NODE request /// Returns the K closest nodes to the target ID pub fn handleDhtFindNode( msg: message.DhtFindNode, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse { std.log.err("DhtFindNode received without source peer ID", .{}); context.metrics.recordMessageFailed(); return error.InvalidMessage; }; // Auto-register the sender's DHT node ID mapping so we can respond context.registerNodeId(msg.sender_id, source_id); // Bidirectional IP Reflection: If the request contains our observed address, record it // This allows the receiver (us) to learn our address from the sender's perspective if (msg.target_observed_addr_len > 0) { context.recordObservedAddress(msg.target_observed_addr, msg.target_observed_addr_len, source_id); std.log.debug("DHT FIND_NODE: Received our observed addr from sender (bidirectional IP reflection), len={}", .{msg.target_observed_addr_len}); } if (context.dht_coordinator) |dht_ptr| { const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse { std.log.err("DHT: Invalid dht_coordinator pointer", .{}); context.metrics.recordMessageFailed(); return error.InvalidState; }; // Convert protocol message to DHT message format const dht_msg = dht_mod.DhtFindNode{ .target_id = msg.target_id, .sender_id = msg.sender_id, .request_id = msg.request_id, }; // Handle the request and get response const response = dht.handleFindNode(dht_msg) catch |err| { std.log.err("DHT: Failed to handle FIND_NODE: {}", .{err}); context.metrics.recordMessageFailed(); return error.OperationFailed; }; // Convert network.dht.NodeInfo to protocol.message.DhtFindNodeResponse.NodeInfo const converted_nodes = context.allocator.alloc(message.DhtFindNodeResponse.NodeInfo, response.closest_nodes.len) catch { context.metrics.recordMessageFailed(); return error.OutOfMemory; }; defer context.allocator.free(converted_nodes); for (response.closest_nodes, 0..) |node, i| { converted_nodes[i] = .{ .node_id = node.node_id, .address = node.address, .address_len = node.address_len, }; } // Get observed address for IP reflection (bundled STUN) const observed = context.getSourceObservedAddr(); // Send response back with observed address using simple binary format const response_msg = message.Message{ .dht_find_node_response = message.DhtFindNodeResponse{ .request_id = response.request_id, .closest_nodes = converted_nodes, .observed_addr = observed.addr, .observed_addr_len = observed.len, .wire_nonce = message.generateWireNonce(), .wire_timestamp = std.time.timestamp(), }, }; if (!context.sendDhtMessage(msg.sender_id, response_msg)) { context.metrics.recordMessageFailed(); return error.SendFailed; } context.metrics.recordMessageProcessed(0.0); std.log.debug("DHT: Sent FIND_NODE response with {} nodes, observed_addr_len={}", .{ response.closest_nodes.len, observed.len }); } else { std.log.err("DHT: FIND_NODE received but no DHT coordinator configured", .{}); context.metrics.recordMessageFailed(); return error.InvalidState; } } /// Handle DHT FIND_NODE response (to our request) pub fn handleDhtFindNodeResponse( msg: message.DhtFindNodeResponse, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse { context.metrics.recordMessageFailed(); return error.InvalidMessage; }; if (context.dht_coordinator) |dht_ptr| { const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse { context.metrics.recordMessageFailed(); return error.InvalidState; }; // Convert protocol.message.NodeInfo to network.dht.NodeInfo const converted_nodes = context.allocator.alloc(dht_mod.NodeInfo, msg.closest_nodes.len) catch { context.metrics.recordMessageFailed(); return error.OutOfMemory; }; defer context.allocator.free(converted_nodes); for (msg.closest_nodes, 0..) |node, i| { converted_nodes[i] = .{ .node_id = node.node_id, .address = node.address, .address_len = node.address_len, }; } const dht_response = dht_mod.DhtFindNodeResponse{ .request_id = msg.request_id, .closest_nodes = converted_nodes, }; // Process the response dht.handleFindNodeResponse(dht_response, source_id) catch |err| { std.log.warn("DHT: Failed to process FIND_NODE response: {}", .{err}); }; // IP Reflection: Record observed address from response (Bundled STUN) context.recordObservedAddress(msg.observed_addr, msg.observed_addr_len, source_id); context.metrics.recordMessageProcessed(0.0); } else { context.metrics.recordMessageFailed(); return error.InvalidState; } } /// Handle incoming DHT STORE request pub fn handleDhtStore( msg: message.DhtStore, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse { context.metrics.recordMessageFailed(); return error.InvalidMessage; }; // Auto-register the sender's DHT node ID mapping so we can respond context.registerNodeId(msg.sender_id, source_id); // Bidirectional IP Reflection: If the request contains our observed address, record it // This allows the receiver (us) to learn our address from the sender's perspective if (msg.target_observed_addr_len > 0) { context.recordObservedAddress(msg.target_observed_addr, msg.target_observed_addr_len, source_id); std.log.debug("DHT STORE: Received our observed addr from sender (bidirectional IP reflection), len={}", .{msg.target_observed_addr_len}); } if (context.dht_coordinator) |dht_ptr| { const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse { context.metrics.recordMessageFailed(); return error.InvalidState; }; // Convert to DHT message format const dht_msg = dht_mod.DhtStore{ .request_id = msg.request_id, .key = msg.key, .value = msg.value, .ttl = msg.ttl, .sender_id = msg.sender_id, }; // Get observed address for IP reflection (bundled STUN) const observed = context.getSourceObservedAddr(); // Handle the store request const response = dht.handleStore(dht_msg) catch |err| { std.log.err("DHT: Failed to handle STORE: {}", .{err}); // Send failure response with observed address using simple binary format const fail_response = message.Message{ .dht_store_response = message.DhtStoreResponse{ .request_id = msg.request_id, .success = false, .observed_addr = observed.addr, .observed_addr_len = observed.len, .wire_nonce = message.generateWireNonce(), .wire_timestamp = std.time.timestamp(), }, }; _ = context.sendDhtMessage(msg.sender_id, fail_response); context.metrics.recordMessageFailed(); return err; }; // Send success response with observed address using simple binary format const response_msg = message.Message{ .dht_store_response = message.DhtStoreResponse{ .request_id = response.request_id, .success = response.success, .observed_addr = observed.addr, .observed_addr_len = observed.len, .wire_nonce = message.generateWireNonce(), .wire_timestamp = std.time.timestamp(), }, }; if (!context.sendDhtMessage(msg.sender_id, response_msg)) { context.metrics.recordMessageFailed(); return error.SendFailed; } context.metrics.recordMessageProcessed(0.0); std.log.debug("DHT: Stored value for key, success={}, observed_addr_len={}", .{ response.success, observed.len }); } else { context.metrics.recordMessageFailed(); return error.InvalidState; } } /// Handle DHT STORE response pub fn handleDhtStoreResponse( msg: message.DhtStoreResponse, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse { context.metrics.recordMessageFailed(); return error.InvalidMessage; }; if (context.dht_coordinator) |dht_ptr| { const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse { context.metrics.recordMessageFailed(); return error.InvalidState; }; const dht_response = dht_mod.DhtStoreResponse{ .request_id = msg.request_id, .success = msg.success, }; dht.handleStoreResponse(dht_response); // IP Reflection: Record observed address from response (Bundled STUN) context.recordObservedAddress(msg.observed_addr, msg.observed_addr_len, source_id); context.metrics.recordMessageProcessed(0.0); } else { context.metrics.recordMessageFailed(); return error.InvalidState; } } /// Handle incoming DHT FIND_VALUE request pub fn handleDhtFindValue( msg: message.DhtFindValue, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse { context.metrics.recordMessageFailed(); return error.InvalidMessage; }; // Auto-register the sender's DHT node ID mapping so we can respond // This enables bidirectional DHT communication without manual registration context.registerNodeId(msg.sender_id, source_id); // Bidirectional IP Reflection: If the request contains our observed address, record it // This allows the receiver (us) to learn our address from the sender's perspective if (msg.target_observed_addr_len > 0) { context.recordObservedAddress(msg.target_observed_addr, msg.target_observed_addr_len, source_id); std.log.debug("DHT FIND_VALUE: Received our observed addr from sender (bidirectional IP reflection), len={}", .{msg.target_observed_addr_len}); } if (context.dht_coordinator) |dht_ptr| { const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse { context.metrics.recordMessageFailed(); return error.InvalidState; }; const dht_msg = dht_mod.DhtFindValue{ .request_id = msg.request_id, .key = msg.key, .sender_id = msg.sender_id, }; const response = dht.handleFindValue(dht_msg) catch |err| { std.log.err("DHT: Failed to handle FIND_VALUE: {}", .{err}); context.metrics.recordMessageFailed(); return error.OperationFailed; }; // Convert network.dht.NodeInfo to protocol.message.DhtFindNodeResponse.NodeInfo const converted_nodes = context.allocator.alloc(message.DhtFindNodeResponse.NodeInfo, response.closest_nodes.len) catch { context.metrics.recordMessageFailed(); return error.OutOfMemory; }; defer context.allocator.free(converted_nodes); for (response.closest_nodes, 0..) |node, i| { converted_nodes[i] = .{ .node_id = node.node_id, .address = node.address, .address_len = node.address_len, }; } // Get observed address for IP reflection (bundled STUN) const observed = context.getSourceObservedAddr(); // Send response (either value or closest nodes) with observed address using simple binary format const response_msg = message.Message{ .dht_find_value_response = message.DhtFindValueResponse{ .request_id = response.request_id, .found = response.found, .value = response.value, .closest_nodes = converted_nodes, .observed_addr = observed.addr, .observed_addr_len = observed.len, .wire_nonce = message.generateWireNonce(), .wire_timestamp = std.time.timestamp(), }, }; if (!context.sendDhtMessage(msg.sender_id, response_msg)) { context.metrics.recordMessageFailed(); return error.SendFailed; } context.metrics.recordMessageProcessed(0.0); } else { context.metrics.recordMessageFailed(); return error.InvalidState; } } /// Handle DHT FIND_VALUE response pub fn handleDhtFindValueResponse( msg: message.DhtFindValueResponse, context: *handler_mod.HandlerContext, ) !void { const source_id = context.source_peer_id orelse { context.metrics.recordMessageFailed(); return error.InvalidMessage; }; if (context.dht_coordinator) |dht_ptr| { const dht = castContext(dht_mod.DhtCoordinator, dht_ptr) orelse { context.metrics.recordMessageFailed(); return error.InvalidState; }; // Convert protocol.message.NodeInfo to network.dht.NodeInfo const converted_nodes = context.allocator.alloc(dht_mod.NodeInfo, msg.closest_nodes.len) catch { context.metrics.recordMessageFailed(); return error.OutOfMemory; }; defer context.allocator.free(converted_nodes); for (msg.closest_nodes, 0..) |node, i| { converted_nodes[i] = .{ .node_id = node.node_id, .address = node.address, .address_len = node.address_len, }; } const dht_response = dht_mod.DhtFindValueResponse{ .request_id = msg.request_id, .found = msg.found, .value = msg.value, .closest_nodes = converted_nodes, }; // handleFindValueResponse returns an optional allocated slice that must be freed const found_value = dht.handleFindValueResponse(dht_response) catch |err| { std.log.warn("DHT: Failed to process FIND_VALUE response: {}", .{err}); return; }; if (found_value) |v| { dht.allocator.free(v); } // IP Reflection: Record observed address from response (Bundled STUN) context.recordObservedAddress(msg.observed_addr, msg.observed_addr_len, source_id); context.metrics.recordMessageProcessed(0.0); } else { context.metrics.recordMessageFailed(); return error.InvalidState; } }