diff --git a/src/network/dht.zig b/src/network/dht.zig index cc7023e..0f99ecb 100644 --- a/src/network/dht.zig +++ b/src/network/dht.zig @@ -134,7 +134,9 @@ pub const SignedDhtMessage = struct { /// Create signing data from message components pub fn createSigningData(allocator: Allocator, request_id: u64, sender_id: NodeId, msg_type: u8, payload: []const u8, timestamp: i64) ![]u8 { - const data = try allocator.alloc(u8, 8 + 32 + 1 + payload.len + 8); + // SECURITY: Prevent integer overflow in allocation size calculation + const total_size = std.math.add(usize, 49, payload.len) catch return error.OutOfMemory; + const data = try allocator.alloc(u8, total_size); var offset: usize = 0; // Request ID @@ -220,7 +222,9 @@ pub const DhtStore = struct { /// Create data to sign for value ownership proof pub fn createValueSigningData(allocator: Allocator, key: [32]u8, value: []const u8, ttl: u32) ![]u8 { - const data = try allocator.alloc(u8, 32 + value.len + 4); + // SECURITY: Prevent integer overflow in allocation size calculation + const total_size = std.math.add(usize, 36, value.len) catch return error.OutOfMemory; + const data = try allocator.alloc(u8, total_size); @memcpy(data[0..32], &key); @memcpy(data[32..][0..value.len], value); std.mem.writeInt(u32, data[32 + value.len ..][0..4], ttl, .little); @@ -1143,18 +1147,24 @@ pub const DhtCoordinator = struct { } const state = entry.?.value; + + if (!state.done) { + // Not done yet - put it back (do NOT destroy) + self.pending_lookups.put(lookup_id, state) catch { + // Can't reinsert - must clean up to avoid leak + state.deinit(); + self.allocator.destroy(state); + return error.OutOfMemory; + }; + return null; + } + + // Lookup is complete - extract results then destroy state defer { state.deinit(); self.allocator.destroy(state); } - if (!state.done) { - // Not done yet - put it back - try self.pending_lookups.put(lookup_id, state); - return null; - } - - // Sort by distance and return K closest const target_peer_id = PeerId{ .bytes = state.target }; std.mem.sort(NodeId, state.closest_seen.items, target_peer_id, compareNodeDistance); diff --git a/src/network/nat.zig b/src/network/nat.zig index 35b1734..2163994 100644 --- a/src/network/nat.zig +++ b/src/network/nat.zig @@ -988,7 +988,7 @@ pub fn TurnClientGeneric(comptime SocketType: type) type { switch (attr_type) { TURN_ATTR_XOR_RELAYED_ADDRESS => { - relayed_address = parseXorMappedAddress(response[attr_offset + 4 .. attr_offset + 4 + attr_length]); + relayed_address = parseXorMappedAddress(response[attr_offset + 4 .. attr_offset + 4 + attr_length], response[8..20]); }, TURN_ATTR_LIFETIME => { if (attr_length >= 4) { @@ -1115,10 +1115,13 @@ pub fn TurnClientGeneric(comptime SocketType: type) type { offset += 4 + ((addr_bytes.len + 3) & ~@as(usize, 3)); // Add DATA attribute + if (data.len > std.math.maxInt(u16)) return Error.NetworkError; + const padded_data_len = (data.len + 3) & ~@as(usize, 3); + if (offset + 4 + padded_data_len > request.len) return Error.NetworkError; std.mem.writeInt(u16, request[offset..][0..2], TURN_ATTR_DATA, .big); std.mem.writeInt(u16, request[offset + 2 ..][0..2], @intCast(data.len), .big); @memcpy(request[offset + 4 .. offset + 4 + data.len], data); - offset += 4 + ((data.len + 3) & ~@as(usize, 3)); + offset += 4 + padded_data_len; // Update message length const msg_length: u16 = @intCast(offset - STUN_HEADER_SIZE); @@ -1134,12 +1137,13 @@ pub fn TurnClientGeneric(comptime SocketType: type) type { // Header: 2 bytes channel number + 2 bytes length var message: [2048]u8 = undefined; + if (data.len > std.math.maxInt(u16)) return Error.NetworkError; + const padded_len = 4 + ((data.len + 3) & ~@as(usize, 3)); + if (padded_len > message.len) return Error.NetworkError; + std.mem.writeInt(u16, message[0..2], channel_number, .big); std.mem.writeInt(u16, message[2..4], @intCast(data.len), .big); @memcpy(message[4 .. 4 + data.len], data); - - // Pad to 4-byte boundary - const padded_len = 4 + ((data.len + 3) & ~@as(usize, 3)); _ = try self.socket.sendTo(message[0..padded_len], server_addr); } @@ -1196,7 +1200,7 @@ pub fn TurnClientGeneric(comptime SocketType: type) type { switch (attr_type) { TURN_ATTR_XOR_PEER_ADDRESS => { - peer_address = parseXorMappedAddress(recv_buffer[attr_offset + 4 ..][0..attr_length]); + peer_address = parseXorMappedAddress(recv_buffer[attr_offset + 4 ..][0..attr_length], recv_buffer[8..20]); }, TURN_ATTR_DATA => { data_slice = recv_buffer[attr_offset + 4 ..][0..attr_length]; @@ -1320,7 +1324,8 @@ fn encodeXorAddress(addr: Address) [12]u8 { } /// Parse XOR-MAPPED-ADDRESS attribute (standalone helper for TURN) -fn parseXorMappedAddress(attr_value: []const u8) ?Address { +/// `transaction_id` is needed for IPv6 XOR decoding (RFC 5389 ยง15.2) +fn parseXorMappedAddress(attr_value: []const u8, transaction_id: *const [STUN_TRANSACTION_ID_SIZE]u8) ?Address { if (attr_value.len < 8) { return null; } @@ -1332,10 +1337,6 @@ fn parseXorMappedAddress(attr_value: []const u8) ?Address { const port = x_port ^ @as(u16, @truncate(STUN_MAGIC_COOKIE >> 16)); if (family == 0x01) { // IPv4 - if (attr_value.len < 8) { - return null; - } - // XOR with magic cookie const magic_bytes: [4]u8 = @bitCast(@as(u32, @byteSwap(STUN_MAGIC_COOKIE))); const ip_bytes = [4]u8{ @@ -1346,9 +1347,24 @@ fn parseXorMappedAddress(attr_value: []const u8) ?Address { }; return Address.ipv4(ip_bytes, port); + } else if (family == 0x02) { // IPv6 + if (attr_value.len < 20) { // 4 header + 16 address bytes + return null; + } + + // XOR with magic cookie (4 bytes) + transaction ID (12 bytes) = 16 bytes + const magic_bytes: [4]u8 = @bitCast(@as(u32, @byteSwap(STUN_MAGIC_COOKIE))); + var ip6_bytes: [16]u8 = undefined; + for (0..4) |i| { + ip6_bytes[i] = attr_value[4 + i] ^ magic_bytes[i]; + } + for (0..12) |i| { + ip6_bytes[4 + i] = attr_value[8 + i] ^ transaction_id[i]; + } + + return Address.ipv6(ip6_bytes, port); } - // IPv6 not yet supported in this helper return null; } @@ -2116,25 +2132,52 @@ test "encodeXorAddress: roundtrip with parseXorMappedAddress" { const testing = std.testing; const original = Address.ipv4(.{ 192, 168, 1, 100 }, 12345); const encoded = encodeXorAddress(original); + const tx_id = [_]u8{0} ** STUN_TRANSACTION_ID_SIZE; // Parse it back - const decoded = parseXorMappedAddress(&encoded); + const decoded = parseXorMappedAddress(&encoded, &tx_id); try testing.expect(decoded != null); try testing.expectEqual(@as(u16, 12345), decoded.?.port); } test "parseXorMappedAddress: too short" { const testing = std.testing; + const tx_id = [_]u8{0} ** STUN_TRANSACTION_ID_SIZE; const short = [_]u8{ 0, 0, 0, 0, 0, 0, 0 }; // 7 bytes, need 8 - try testing.expect(parseXorMappedAddress(&short) == null); + try testing.expect(parseXorMappedAddress(&short, &tx_id) == null); } -test "parseXorMappedAddress: IPv6 not supported returns null" { +test "parseXorMappedAddress: IPv6 roundtrip" { const testing = std.testing; + const tx_id = [_]u8{ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C }; + + // Build a XOR-MAPPED-ADDRESS for IPv6: [2001:db8::1]:8080 + // Raw IPv6 bytes for 2001:0db8:0000:0000:0000:0000:0000:0001 + const ip6_raw = [16]u8{ 0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }; + const magic_bytes: [4]u8 = @bitCast(@as(u32, @byteSwap(STUN_MAGIC_COOKIE))); + const port: u16 = 8080; + const xor_port = port ^ @as(u16, @truncate(STUN_MAGIC_COOKIE >> 16)); + var attr: [20]u8 = undefined; - @memset(&attr, 0); + attr[0] = 0; // reserved attr[1] = 0x02; // IPv6 family - try testing.expect(parseXorMappedAddress(&attr) == null); + std.mem.writeInt(u16, attr[2..4], xor_port, .big); + // XOR first 4 bytes with magic cookie + for (0..4) |i| { + attr[4 + i] = ip6_raw[i] ^ magic_bytes[i]; + } + // XOR remaining 12 bytes with transaction ID + for (0..12) |i| { + attr[8 + i] = ip6_raw[4 + i] ^ tx_id[i]; + } + + const parsed = parseXorMappedAddress(&attr, &tx_id); + try testing.expect(parsed != null); + try testing.expectEqual(@as(u16, 8080), parsed.?.port); + + // Verify the IPv6 address bytes match + const parsed_bytes = parsed.?.data.ipv6.bytes; + try testing.expectEqualSlices(u8, &ip6_raw, &parsed_bytes); } test "ChannelBinding: isExpired with past creation" { diff --git a/src/network/turn_integration.zig b/src/network/turn_integration.zig index a0c7d85..8e03675 100644 --- a/src/network/turn_integration.zig +++ b/src/network/turn_integration.zig @@ -663,7 +663,7 @@ test "MockTurnIntegration: init creates empty state" { test "MockTurnIntegration: initWithSocket sets up state" { // Heap-allocate socket since deinit() will call allocator.destroy() - const mock_socket = testing.allocator.create(MockSocket) catch unreachable; + const mock_socket = try testing.allocator.create(MockSocket); mock_socket.* = MockSocket.init(testing.allocator); const turn_server = TurnServer{ @@ -671,7 +671,7 @@ test "MockTurnIntegration: initWithSocket sets up state" { .port = 3478, }; - const client_ptr = testing.allocator.create(MockTurnClient) catch unreachable; + const client_ptr = try testing.allocator.create(MockTurnClient); client_ptr.* = MockTurnClient.init(testing.allocator, mock_socket, turn_server); const config = TurnConfig{ .enabled = true }; @@ -698,7 +698,7 @@ test "MockTurnIntegration: refreshIfNeeded with no client is no-op" { test "MockTurnIntegration: isAvailable returns false without allocation" { // Heap-allocate socket since deinit() will call allocator.destroy() - const mock_socket = testing.allocator.create(MockSocket) catch unreachable; + const mock_socket = try testing.allocator.create(MockSocket); mock_socket.* = MockSocket.init(testing.allocator); const turn_server = TurnServer{ @@ -706,7 +706,7 @@ test "MockTurnIntegration: isAvailable returns false without allocation" { .port = 3478, }; - const client_ptr = testing.allocator.create(MockTurnClient) catch unreachable; + const client_ptr = try testing.allocator.create(MockTurnClient); client_ptr.* = MockTurnClient.init(testing.allocator, mock_socket, turn_server); const config = TurnConfig{ .enabled = true }; @@ -724,7 +724,7 @@ test "MockTurnIntegration: isAvailable returns false without allocation" { test "MockTurnIntegration: getRelayedAddress returns null without allocation" { // Heap-allocate socket since deinit() will call allocator.destroy() - const mock_socket = testing.allocator.create(MockSocket) catch unreachable; + const mock_socket = try testing.allocator.create(MockSocket); mock_socket.* = MockSocket.init(testing.allocator); const turn_server = TurnServer{ @@ -732,7 +732,7 @@ test "MockTurnIntegration: getRelayedAddress returns null without allocation" { .port = 3478, }; - const client_ptr = testing.allocator.create(MockTurnClient) catch unreachable; + const client_ptr = try testing.allocator.create(MockTurnClient); client_ptr.* = MockTurnClient.init(testing.allocator, mock_socket, turn_server); const config = TurnConfig{ .enabled = true }; @@ -811,7 +811,7 @@ test "ManagedConnection: hole_punched type" { test "MockTurnIntegration: deinit cleans up resources" { const mock_socket_storage = MockSocket.init(testing.allocator); - const mock_socket = testing.allocator.create(MockSocket) catch unreachable; + const mock_socket = try testing.allocator.create(MockSocket); mock_socket.* = mock_socket_storage; const turn_server = TurnServer{ @@ -819,7 +819,7 @@ test "MockTurnIntegration: deinit cleans up resources" { .port = 3478, }; - const client_ptr = testing.allocator.create(MockTurnClient) catch unreachable; + const client_ptr = try testing.allocator.create(MockTurnClient); client_ptr.* = MockTurnClient.init(testing.allocator, mock_socket, turn_server); const config = TurnConfig{ .enabled = true }; diff --git a/src/p2p/connection.zig b/src/p2p/connection.zig index beca2c8..e2fb1c2 100644 --- a/src/p2p/connection.zig +++ b/src/p2p/connection.zig @@ -336,6 +336,15 @@ pub fn disconnectPeerImpl(p2p: *P2P, peer_id: PeerId) Error!void { p2p.allocator.destroy(socket); } + // Clear DHT node-to-peer mapping to prevent stale identity spoofing on reconnect + { + p2p.dht_node_to_peer_mutex.lock(); + defer p2p.dht_node_to_peer_mutex.unlock(); + if (p2p.peer_to_dht_node.fetchRemove(peer_id)) |kv| { + _ = p2p.dht_node_to_peer.remove(kv.value); + } + } + // LEAK FIX: Also remove from peer_manager to free the address string // Previously only removed from peer_connections, leaking the peer entry if (p2p.peer_manager) |pm| {