diff --git a/src/core/address.zig b/src/core/address.zig index d91e3b6..bd4d6cc 100644 --- a/src/core/address.zig +++ b/src/core/address.zig @@ -145,36 +145,42 @@ pub const Ipv6Address = struct { } pub fn fromString(str: []const u8) Error!Ipv6Address { - var addr = Ipv6Address{ .bytes = [_]u8{0} ** 16 }; - var group_idx: usize = 0; + // Two-pass parsing for :: compression + // Pass 1: parse groups into front/back arrays around :: + var front: [8]u16 = [_]u16{0} ** 8; + var back: [8]u16 = [_]u16{0} ** 8; + var front_count: usize = 0; + var back_count: usize = 0; + var found_double_colon = false; var current_val: u16 = 0; var digit_count: usize = 0; var i: usize = 0; + // Handle leading :: + if (str.len >= 2 and str[0] == ':' and str[1] == ':') { + found_double_colon = true; + i = 2; + } + while (i < str.len) : (i += 1) { const c = str[i]; if (c == ':') { - if (i + 1 < str.len and str[i + 1] == ':') { - // Handle :: (compressed zeros) - if (group_idx > 0 and digit_count > 0) { - addr.bytes[group_idx * 2] = @intCast(current_val >> 8); - addr.bytes[group_idx * 2 + 1] = @intCast(current_val & 0xFF); - group_idx += 1; - } - // Skip remaining groups for compressed zeros - i += 1; - current_val = 0; - digit_count = 0; - continue; - } - if (group_idx >= 8) return Error.AddressParseError; - addr.bytes[group_idx * 2] = @intCast(current_val >> 8); - addr.bytes[group_idx * 2 + 1] = @intCast(current_val & 0xFF); - group_idx += 1; + // Write current group + const target = if (found_double_colon) &back else &front; + const count = if (found_double_colon) &back_count else &front_count; + if (count.* >= 8) return Error.AddressParseError; + target[count.*] = current_val; + count.* += 1; current_val = 0; digit_count = 0; + + if (i + 1 < str.len and str[i + 1] == ':') { + if (found_double_colon) return Error.AddressParseError; // only one :: allowed + found_double_colon = true; + i += 1; // skip second colon + } } else { - const digit = switch (c) { + const digit: u16 = switch (c) { '0'...'9' => c - '0', 'a'...'f' => c - 'a' + 10, 'A'...'F' => c - 'A' + 10, @@ -186,10 +192,33 @@ pub const Ipv6Address = struct { } } - // Handle last group - if (digit_count > 0 and group_idx < 8) { - addr.bytes[group_idx * 2] = @intCast(current_val >> 8); - addr.bytes[group_idx * 2 + 1] = @intCast(current_val & 0xFF); + // Write final group + if (digit_count > 0) { + const target = if (found_double_colon) &back else &front; + const count = if (found_double_colon) &back_count else &front_count; + if (count.* >= 8) return Error.AddressParseError; + target[count.*] = current_val; + count.* += 1; + } + + // Assemble: front groups + zero padding + back groups + const total = front_count + back_count; + if (found_double_colon) { + if (total > 8) return Error.AddressParseError; + } else { + if (total != 8) return Error.AddressParseError; + } + + var addr = Ipv6Address{ .bytes = [_]u8{0} ** 16 }; + for (front[0..front_count], 0..) |val, g| { + addr.bytes[g * 2] = @intCast(val >> 8); + addr.bytes[g * 2 + 1] = @intCast(val & 0xFF); + } + const back_start = 8 - back_count; + for (back[0..back_count], 0..) |val, g| { + const idx = back_start + g; + addr.bytes[idx * 2] = @intCast(val >> 8); + addr.bytes[idx * 2 + 1] = @intCast(val & 0xFF); } return addr; @@ -627,9 +656,9 @@ pub const Address = struct { /// Get address family constant for socket operations pub fn getSocketFamily(self: Address) u16 { return switch (self.family) { - .ipv4 => 2, // AF_INET - .ipv6 => 10, // AF_INET6 - .unix => 1, // AF_UNIX + .ipv4 => posix.AF.INET, + .ipv6 => posix.AF.INET6, + .unix => posix.AF.UNIX, .custom => 0, }; } diff --git a/src/core/connection.zig b/src/core/connection.zig index ec44610..c1e8357 100644 --- a/src/core/connection.zig +++ b/src/core/connection.zig @@ -432,12 +432,14 @@ pub const Connection = struct { // This was the last reference return true; } - // Safety check: underflow is an invariant violation (double-free) + // Defensive check: detect double-free bugs without crashing. + // Dumps a stack trace pointing to the exact call site, then returns + // an error so the application can continue running. if (old_count == 0) { - // fetchSub already wrapped the counter — this is unrecoverable corruption. - // Panic immediately so the bug is caught in development rather than - // silently propagated through the call chain. - @panic("Connection reference count underflow: double-free detected"); + _ = self.ref_count.fetchAdd(1, .acq_rel); // undo the wrapping fetchSub + std.log.err("BUG: Connection ref count underflow (double-free). Stack trace:", .{}); + std.debug.dumpCurrentStackTrace(@returnAddress()); + return Error.InternalError; } return false; } @@ -734,7 +736,7 @@ pub const Connection = struct { /// Thread-safe: uses socket_mutex to protect socket access pub fn checkHealth(self: *Connection) HealthCheckResult { self.stats.recordHealthCheck(); - self.last_health_check = std.time.timestamp(); + self.last_health_check = std.time.milliTimestamp(); // Acquire socket mutex to prevent race with connect/disconnect self.socket_mutex.lock(); @@ -845,7 +847,7 @@ pub const Connection = struct { /// Check if connection needs health check pub fn needsHealthCheck(self: *const Connection) bool { - const now = std.time.timestamp(); + const now = std.time.milliTimestamp(); return (now - self.last_health_check) >= self.config.health_check_interval; } diff --git a/src/p2p/dht.zig b/src/p2p/dht.zig index bf625a2..f0d9cfa 100644 --- a/src/p2p/dht.zig +++ b/src/p2p/dht.zig @@ -21,6 +21,12 @@ const protocol = @import("protocol"); // Import P2P type from sibling module const P2P = @import("p2p.zig").P2P; +// SECURITY: Limits for DHT message deserialization to prevent DoS +/// Maximum number of nodes in a single DHT response (matches k_bucket_size) +const MAX_DHT_NODES_PER_RESPONSE: u32 = 20; +/// Maximum size of a DHT value in bytes (1 MB) +const MAX_DHT_VALUE_SIZE: u32 = 1024 * 1024; + // ========================================================================= // DHT (Distributed Hash Table) API // ========================================================================= @@ -263,6 +269,23 @@ pub const DhtMsgType = enum(u8) { find_value_response = 0x13, }; +/// Compute the serialized size of a DHT message (for heap allocation when stack buffer is too small) +fn dhtMessageSize(msg: protocol.message.Message) ?usize { + const node_size = 32 + 46 + 1; + return switch (msg) { + .dht_find_node => |m| 1 + 8 + 32 + 32 + 1 + @as(usize, @min(m.target_observed_addr_len, 18)), + .dht_store => |m| 1 + 8 + 32 + 32 + 4 + 4 + m.value.len + 1 + @as(usize, @min(m.target_observed_addr_len, 18)), + .dht_find_value => |m| 1 + 8 + 32 + 32 + 1 + @as(usize, @min(m.target_observed_addr_len, 18)), + .dht_find_node_response => |m| 1 + 8 + 4 + (m.closest_nodes.len * node_size) + 1 + @as(usize, @min(m.observed_addr_len, 18)), + .dht_store_response => |m| 1 + 8 + 1 + 1 + @as(usize, @min(m.observed_addr_len, 18)), + .dht_find_value_response => |m| blk: { + const value_len = if (m.value) |v| v.len else 0; + break :blk 1 + 8 + 1 + 4 + value_len + 4 + (m.closest_nodes.len * node_size) + 1 + @as(usize, @min(m.observed_addr_len, 18)); + }, + else => null, + }; +} + /// Serialize a DHT message to simple binary format /// Format: [1 byte type][8 bytes request_id][32 bytes sender_id][payload...] /// Public for testing IP Reflection variable-length encoding @@ -491,6 +514,8 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr offset += 4; const value_len = std.mem.readInt(u32, data[offset..][0..4], .big); offset += 4; + // SECURITY: Reject excessive value sizes to prevent DoS + if (value_len > MAX_DHT_VALUE_SIZE) return null; if (data.len < offset + value_len) return null; // Allocate and copy value const value = allocator.dupe(u8, data[offset..][0..value_len]) catch return null; @@ -559,8 +584,12 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr offset += 8; const node_count = std.mem.readInt(u32, data[offset..][0..4], .big); offset += 4; + // SECURITY: Reject excessive node counts to prevent DoS + if (node_count > MAX_DHT_NODES_PER_RESPONSE) return null; const node_size = 32 + 46 + 1; - if (data.len < offset + (node_count * node_size) + 1) return null; + // SECURITY: Use checked multiplication to prevent integer overflow + const total_node_bytes = std.math.mul(usize, node_count, node_size) catch return null; + if (data.len < offset + total_node_bytes + 1) return null; // Allocate nodes array const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch return null; for (0..node_count) |i| { @@ -625,6 +654,8 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr offset += 1; const value_len = std.mem.readInt(u32, data[offset..][0..4], .big); offset += 4; + // SECURITY: Reject excessive value sizes to prevent DoS + if (value_len > MAX_DHT_VALUE_SIZE) return null; if (data.len < offset + value_len + 4 + 1) return null; // Read value (may be empty) const value: ?[]const u8 = if (value_len > 0) blk: { @@ -634,10 +665,26 @@ pub fn deserializeDhtMessage(data: []const u8, allocator: std.mem.Allocator) ?pr offset += value_len; const node_count = std.mem.readInt(u32, data[offset..][0..4], .big); offset += 4; + // SECURITY: Reject excessive node counts to prevent DoS + if (node_count > MAX_DHT_NODES_PER_RESPONSE) { + if (value) |v| allocator.free(v); + return null; + } const node_size = 32 + 46 + 1; - if (data.len < offset + (node_count * node_size) + 1) return null; + // SECURITY: Use checked multiplication to prevent integer overflow + const total_node_bytes = std.math.mul(usize, node_count, node_size) catch { + if (value) |v| allocator.free(v); + return null; + }; + if (data.len < offset + total_node_bytes + 1) { + if (value) |v| allocator.free(v); + return null; + } // Allocate nodes array - const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch return null; + const nodes = allocator.alloc(protocol.message.DhtFindNodeResponse.NodeInfo, node_count) catch { + if (value) |v| allocator.free(v); + return null; + }; for (0..node_count) |i| { nodes[i] = .{ .node_id = data[offset..][0..32].*, @@ -713,8 +760,27 @@ pub fn sendDhtMessageImpl(p2p: *P2P, dht_node_id: [32]u8, msg: protocol.message. }; // Use simple binary serialization (no HMAC - Noise transport provides security) - var buffer: [4096]u8 = undefined; - const len = serializeDhtMessage(msg, &buffer) orelse { + // Use stack buffer for small messages, heap for large (e.g. dht_store with big values) + var stack_buffer: [4096]u8 = undefined; + var heap_buffer: ?[]u8 = null; + defer if (heap_buffer) |hb| p2p.allocator.free(hb); + + var buffer: []u8 = &stack_buffer; + + // Try stack buffer first; if too small, compute needed size and heap-allocate + if (serializeDhtMessage(msg, buffer) == null) { + const needed = dhtMessageSize(msg) orelse { + std.log.warn("DHT: Failed to compute message size", .{}); + return false; + }; + heap_buffer = p2p.allocator.alloc(u8, needed) catch { + std.log.warn("DHT: Failed to allocate {d} bytes for message", .{needed}); + return false; + }; + buffer = heap_buffer.?; + } + + const len = serializeDhtMessage(msg, buffer) orelse { std.log.warn("DHT: Failed to serialize message", .{}); return false; }; diff --git a/src/protocol/serializer.zig b/src/protocol/serializer.zig index 9e18a11..195cbea 100644 --- a/src/protocol/serializer.zig +++ b/src/protocol/serializer.zig @@ -710,9 +710,18 @@ pub const MessageSerializer = struct { fn getPayloadSize(self: *MessageSerializer, msg: message.Message) usize { _ = self; return switch (msg) { - .discovery_hello => 2 + 4 + @sizeOf(message.NetworkAddress), - .discovery_response => 8 + 4 + @sizeOf(message.NetworkAddress), - .discovery_announce => 4 + @sizeOf(message.NetworkAddress), + .discovery_hello => |hello| blk: { + const base = 2 + 4 + @sizeOf(message.NetworkAddress); + break :blk if (hello.isSigned()) base + 64 + 32 + 8 else base; + }, + .discovery_response => |resp| blk: { + const base = 8 + 4 + @sizeOf(message.NetworkAddress); + break :blk if (resp.isSigned()) base + 64 + 32 + 8 else base; + }, + .discovery_announce => |announce| blk: { + const base = 4 + @sizeOf(message.NetworkAddress) + 1; // +1 for TTL + break :blk if (announce.isSigned()) base + 64 + 32 + 8 else base; + }, .topology_query => 8 + 1, .topology_response => |resp| blk: { // Safe addition with overflow check @@ -959,32 +968,67 @@ pub const MessageSerializer = struct { switch (msg) { .discovery_hello => |hello| { - // SECURITY: Safe bounds check with overflow protection - const required = safeAdd(safeAdd(2, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; + // Base fields: version(2) + capabilities(4) + address + const base = safeAdd(safeAdd(2, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; + const sig_size: usize = if (hello.isSigned()) 64 + 32 + 8 else 0; + const required = safeAdd(base, sig_size) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 2], std.mem.asBytes(&hello.version)); offset += 2; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&hello.capabilities)); offset += 4; @memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&hello.address)); + offset += @sizeOf(message.NetworkAddress); + // Serialize signature fields if signed + if (hello.isSigned()) { + @memcpy(buffer[offset..][0..64], &hello.signature); + offset += 64; + @memcpy(buffer[offset..][0..32], &hello.signer_id); + offset += 32; + std.mem.writeInt(i64, buffer[offset..][0..8], hello.timestamp, .little); + } }, .discovery_response => |resp| { - // SECURITY: Safe bounds check with overflow protection - const required = safeAdd(safeAdd(8, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; + // Base fields: original_id(8) + capabilities(4) + address + const base = safeAdd(safeAdd(8, 4) orelse return SerializationError.InvalidLength, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; + const sig_size: usize = if (resp.isSigned()) 64 + 32 + 8 else 0; + const required = safeAdd(base, sig_size) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 8], std.mem.asBytes(&resp.original_id)); offset += 8; @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&resp.capabilities)); offset += 4; @memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&resp.address)); + offset += @sizeOf(message.NetworkAddress); + // Serialize signature fields if signed + if (resp.isSigned()) { + @memcpy(buffer[offset..][0..64], &resp.signature); + offset += 64; + @memcpy(buffer[offset..][0..32], &resp.signer_id); + offset += 32; + std.mem.writeInt(i64, buffer[offset..][0..8], resp.timestamp, .little); + } }, .discovery_announce => |announce| { - // SECURITY: Safe bounds check with overflow protection - const required = safeAdd(4, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength; + // Base fields: capabilities(4) + address + ttl(1) + const base = safeAdd(safeAdd(4, @sizeOf(message.NetworkAddress)) orelse return SerializationError.InvalidLength, 1) orelse return SerializationError.InvalidLength; + const sig_size: usize = if (announce.isSigned()) 64 + 32 + 8 else 0; + const required = safeAdd(base, sig_size) orelse return SerializationError.InvalidLength; try checkBounds(buffer, offset, required); @memcpy(buffer[offset..offset + 4], std.mem.asBytes(&announce.capabilities)); offset += 4; @memcpy(buffer[offset..offset + @sizeOf(message.NetworkAddress)], std.mem.asBytes(&announce.address)); + offset += @sizeOf(message.NetworkAddress); + buffer[offset] = announce.ttl; + offset += 1; + // Serialize signature fields if signed + if (announce.isSigned()) { + @memcpy(buffer[offset..][0..64], &announce.signature); + offset += 64; + @memcpy(buffer[offset..][0..32], &announce.signer_id); + offset += 32; + std.mem.writeInt(i64, buffer[offset..][0..8], announce.timestamp, .little); + } }, .topology_query => |query| { // SECURITY: Safe bounds check with overflow protection diff --git a/tests/protocol/test_serializer_extended.zig b/tests/protocol/test_serializer_extended.zig index 17e7a83..5c5683c 100644 --- a/tests/protocol/test_serializer_extended.zig +++ b/tests/protocol/test_serializer_extended.zig @@ -169,7 +169,7 @@ test "getPayloadSizePublic discovery_announce" { var ser = MessageSerializer.initInsecureForTesting(allocator); const addr = message.NetworkAddress{ .ip = [_]u8{0} ** 16, .port = 8080 }; const msg = message.Message{ .discovery_announce = message.DiscoveryAnnounce.init(0, addr) }; - try testing.expectEqual(@as(usize, 4 + @sizeOf(message.NetworkAddress)), ser.getPayloadSizePublic(msg)); + try testing.expectEqual(@as(usize, 4 + @sizeOf(message.NetworkAddress) + 1), ser.getPayloadSizePublic(msg)); // +1 for TTL } test "getPayloadSizePublic topology_query" {