bidirectional ip reflection for listener address discovery

This commit is contained in:
2026-02-09 16:02:23 -03:00
parent 59e9e420be
commit 7b47ef155c
31 changed files with 3192 additions and 269 deletions

View File

@@ -414,6 +414,8 @@ pub const PendingResponse = struct {
query_type: QueryType,
sent_at: i64,
responded: bool = false,
/// Key being searched (for FIND_VALUE queries)
search_key: ?[32]u8 = null,
pub const QueryType = enum {
find_node,
@@ -583,6 +585,11 @@ pub const DhtCoordinator = struct {
/// SECURITY: Check rate limit for a peer
/// Returns error if rate limit exceeded
fn checkPeerRateLimit(self: *DhtCoordinator, peer_id: NodeId) DhtError!void {
// Skip rate limiting in development/insecure mode
if (!self.isSecureMode()) {
return;
}
const now = std.time.timestamp();
const now_ms = std.time.milliTimestamp();
@@ -626,6 +633,11 @@ pub const DhtCoordinator = struct {
/// SECURITY: Verify message authentication and apply TOFU
fn verifyMessageAuth(self: *DhtCoordinator, sender_id: NodeId, auth: ?SignedDhtMessage, msg_type: u8, payload: []const u8, request_id: u64) DhtError!void {
const auth_data = auth orelse {
// In development/insecure mode, allow unauthenticated messages
if (!self.isSecureMode()) {
std.log.debug("DHT: Processing unauthenticated message (insecure mode)", .{});
return;
}
std.log.err("DHT SECURITY: Message rejected - no authentication provided", .{});
return DhtError.MissingSignature;
};
@@ -1284,6 +1296,7 @@ pub const DhtCoordinator = struct {
.target = node_id,
.query_type = .find_value,
.sent_at = std.time.timestamp(),
.search_key = key,
});
sent_count += 1;
@@ -1305,14 +1318,22 @@ pub const DhtCoordinator = struct {
self.mutex.lock();
defer self.mutex.unlock();
// Mark the request as completed
// Get the search key from pending responses
var search_key: ?[32]u8 = null;
if (self.pending_responses.fetchRemove(response.request_id)) |pending| {
_ = pending;
search_key = pending.value.search_key;
}
// If value was found, store it locally and return
// If value was found, cache it locally for future findValue() calls
if (response.found) {
if (response.value) |value| {
// Cache locally if we know the key
if (search_key) |key| {
// Store unsigned since we're caching a remote response
self.storeLocalUnsigned(key, value, 300, self.local_id) catch |err| {
std.log.debug("DHT: Failed to cache FIND_VALUE result: {}", .{err});
};
}
// Return a copy of the value
return try self.allocator.dupe(u8, value);
}
@@ -1529,74 +1550,81 @@ pub const DhtCoordinator = struct {
}
// SECURITY: Verify value signature (proves publisher ownership)
const value_sig = msg.value_signature orelse {
std.log.err("DHT STORE rejected: no value signature provided", .{});
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing value signature" };
// In development/insecure mode, allow storing without signatures
if (!self.isSecureMode()) {
// Development mode: store without signature verification
std.log.debug("DHT: Storing value in insecure mode (no signature verification)", .{});
try self.storeLocalUnsigned(msg.key, msg.value, msg.ttl, msg.sender_id);
} else {
const value_sig = msg.value_signature orelse {
std.log.err("DHT STORE rejected: no value signature provided", .{});
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing value signature" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Missing value signature",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Missing value signature",
.auth = auth,
};
};
// Get the sender's identity key (already verified via TOFU)
const identity_key = if (msg.auth) |auth_data| auth_data.identity_key else {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing identity key" };
// Get the sender's identity key (already verified via TOFU)
const identity_key = if (msg.auth) |auth_data| auth_data.identity_key else {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Missing identity key" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Missing identity key",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Missing identity key",
.auth = auth,
};
};
// Verify value signature
const value_signing_data = DhtStore.createValueSigningData(self.allocator, msg.key, msg.value, msg.ttl) catch {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Internal error" };
// Verify value signature
const value_signing_data = DhtStore.createValueSigningData(self.allocator, msg.key, msg.value, msg.ttl) catch {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Internal error" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Internal error",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Internal error",
.auth = auth,
};
};
defer self.allocator.free(value_signing_data);
defer self.allocator.free(value_signing_data);
const sig = Ed25519.Signature.fromBytes(value_sig);
const pubkey = Ed25519.PublicKey.fromBytes(identity_key) catch {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Invalid identity key" };
const sig = Ed25519.Signature.fromBytes(value_sig);
const pubkey = Ed25519.PublicKey.fromBytes(identity_key) catch {
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Invalid identity key" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Invalid identity key",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Invalid identity key",
.auth = auth,
};
};
sig.verify(value_signing_data, pubkey) catch {
std.log.err("DHT STORE rejected: value signature verification failed", .{});
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Value signature failed" };
sig.verify(value_signing_data, pubkey) catch {
std.log.err("DHT STORE rejected: value signature verification failed", .{});
const auth = self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{}) catch {
return DhtStoreResponse{ .request_id = msg.request_id, .success = false, .error_message = "Value signature failed" };
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Value signature verification failed",
.auth = auth,
};
};
return DhtStoreResponse{
.request_id = msg.request_id,
.success = false,
.error_message = "Value signature verification failed",
.auth = auth,
};
};
// Store the value with signature for future verification
try self.storeLocalWithSignature(msg.key, msg.value, msg.ttl, msg.sender_id, value_sig, identity_key);
// Store the value with signature for future verification
try self.storeLocalWithSignature(msg.key, msg.value, msg.ttl, msg.sender_id, value_sig, identity_key);
}
// Sign and return success response
const auth = try self.signMessage(msg.request_id, DhtStoreResponse.MSG_TYPE, &[_]u8{});
@@ -1648,6 +1676,45 @@ pub const DhtCoordinator = struct {
});
}
/// Store value locally without signature verification (for insecure/development mode)
fn storeLocalUnsigned(
self: *DhtCoordinator,
key: [32]u8,
value: []const u8,
ttl: u32,
publisher: NodeId,
) !void {
// Remove old value if it exists
const had_existing = if (self.storage.fetchRemove(key)) |old| blk: {
old.value.deinit(self.allocator);
break :blk true;
} else false;
// CRIT-7 FIX: Check storage limit for new entries
if (!had_existing) {
const max_storage = core.limits.global.dht.max_storage_entries;
if (self.storage.count() >= max_storage) {
std.log.warn("DHT: Storage limit reached ({d} entries), rejecting new entry", .{max_storage});
return DhtError.OutOfMemory;
}
}
// Store new value without signature (insecure mode)
const value_copy = try self.allocator.dupe(u8, value);
errdefer self.allocator.free(value_copy);
const now = std.time.timestamp();
try self.storage.put(key, .{
.data = value_copy,
.expires_at = now + @as(i64, @intCast(ttl)),
.publisher = publisher,
.publisher_signature = [_]u8{0} ** 64, // No signature in insecure mode
.publisher_identity = [_]u8{0} ** 32, // No identity in insecure mode
.key = key,
.original_ttl = ttl,
});
}
/// Handle incoming FIND_VALUE request
/// SECURITY: Verifies message signature and applies rate limiting
pub fn handleFindValue(self: *DhtCoordinator, msg: DhtFindValue) !DhtFindValueResponse {

View File

@@ -1166,12 +1166,27 @@ pub const NetworkManager = struct {
// Free the encrypted data, keep decrypted
self.allocator.free(msg_data);
// Create properly sized slice (plaintext is a slice into decrypt_buf)
const decrypted = self.allocator.alloc(u8, plaintext.len) catch {
// FIX: The sender includes a 4-byte length header in the plaintext (for
// non-encrypted framing compatibility). Strip it here since ReceiveBuffer
// already handles framing for the encrypted packet.
if (plaintext.len < 4) {
self.allocator.free(decrypt_buf);
continue;
}
const inner_len = std.mem.readInt(u32, plaintext[0..4], .big);
if (inner_len > plaintext.len - 4) {
std.log.warn("Decrypted message inner length mismatch: {} > {}", .{ inner_len, plaintext.len - 4 });
self.allocator.free(decrypt_buf);
continue;
}
const payload = plaintext[4 .. 4 + inner_len];
// Create properly sized slice
const decrypted = self.allocator.alloc(u8, payload.len) catch {
self.allocator.free(decrypt_buf);
continue;
};
@memcpy(decrypted, plaintext);
@memcpy(decrypted, payload);
self.allocator.free(decrypt_buf);
break :blk decrypted;