ab ovo
This commit is contained in:
364
src/network/secure_connection.zig
Normal file
364
src/network/secure_connection.zig
Normal file
@@ -0,0 +1,364 @@
|
||||
//! Secure Connection - Noise Protocol encrypted transport
|
||||
//!
|
||||
//! Wraps a socket with Noise_XX_25519_ChaChaPoly_BLAKE2b encryption.
|
||||
//! Provides transparent encryption/decryption for all communication
|
||||
//! after the initial handshake completes.
|
||||
|
||||
const std = @import("std");
|
||||
const mem = std.mem;
|
||||
const posix = std.posix;
|
||||
|
||||
const core = @import("core");
|
||||
const Socket = core.socket.Socket;
|
||||
const CoreError = core.errors.Error;
|
||||
|
||||
const noise = @import("noise");
|
||||
const NoiseError = noise.Error;
|
||||
const KeyPair = noise.KeyPair;
|
||||
const Transport = noise.Transport;
|
||||
const HandshakeState = noise.HandshakeState;
|
||||
const Role = noise.Role;
|
||||
|
||||
/// Maximum message size for Noise protocol
|
||||
pub const MAX_MESSAGE_SIZE = noise.MAX_MESSAGE_SIZE;
|
||||
|
||||
/// Authentication tag size
|
||||
pub const TAG_SIZE = noise.TAG_SIZE;
|
||||
|
||||
/// Handshake timeout in milliseconds
|
||||
pub const HANDSHAKE_TIMEOUT_MS: u32 = 5000;
|
||||
|
||||
/// Errors specific to secure connections
|
||||
pub const Error = error{
|
||||
/// Handshake failed
|
||||
HandshakeFailed,
|
||||
/// Handshake timed out
|
||||
HandshakeTimeout,
|
||||
/// Connection not encrypted
|
||||
NotEncrypted,
|
||||
/// Encryption failed
|
||||
EncryptionFailed,
|
||||
/// Decryption failed
|
||||
DecryptionFailed,
|
||||
/// Message too large
|
||||
MessageTooLarge,
|
||||
/// Socket error
|
||||
SocketError,
|
||||
/// Buffer too small
|
||||
BufferTooSmall,
|
||||
/// Out of memory
|
||||
OutOfMemory,
|
||||
};
|
||||
|
||||
/// SecureConnection wraps a socket with Noise protocol encryption
|
||||
pub const SecureConnection = struct {
|
||||
/// Underlying socket
|
||||
socket: *Socket,
|
||||
/// Noise transport state (null until handshake completes)
|
||||
transport: ?Transport,
|
||||
/// Whether handshake has completed successfully
|
||||
handshake_complete: bool,
|
||||
/// Remote peer's static public key (available after handshake)
|
||||
remote_static_key: ?[32]u8,
|
||||
/// Our static keypair used for this connection
|
||||
local_keypair: KeyPair,
|
||||
/// Pre-allocated encryption buffer
|
||||
encrypt_buf: [MAX_MESSAGE_SIZE + TAG_SIZE]u8,
|
||||
/// Pre-allocated decryption buffer
|
||||
decrypt_buf: [MAX_MESSAGE_SIZE]u8,
|
||||
/// Allocator for any dynamic allocations
|
||||
allocator: mem.Allocator,
|
||||
|
||||
const Self = @This();
|
||||
|
||||
/// Initialize a secure connection (handshake not yet performed)
|
||||
pub fn init(socket: *Socket, local_keypair: KeyPair, allocator: mem.Allocator) Self {
|
||||
return Self{
|
||||
.socket = socket,
|
||||
.transport = null,
|
||||
.handshake_complete = false,
|
||||
.remote_static_key = null,
|
||||
.local_keypair = local_keypair,
|
||||
.encrypt_buf = undefined,
|
||||
.decrypt_buf = undefined,
|
||||
.allocator = allocator,
|
||||
};
|
||||
}
|
||||
|
||||
/// Perform handshake as initiator (client connecting to server)
|
||||
pub fn initiateHandshake(self: *Self) Error!void {
|
||||
var hs = HandshakeState.initXX(.initiator, self.local_keypair, null);
|
||||
|
||||
// Message 1: -> e
|
||||
var msg1: [48]u8 = undefined; // 32 (ephemeral) + 16 (tag for empty payload)
|
||||
const msg1_len = hs.writeMessage(&.{}, &msg1) catch return Error.HandshakeFailed;
|
||||
try self.sendRaw(msg1[0..msg1_len]);
|
||||
|
||||
// Message 2: <- e, ee, s, es
|
||||
var msg2_buf: [96]u8 = undefined; // 32 (e) + 48 (encrypted s) + 16 (tag)
|
||||
const msg2_len = try self.receiveRaw(&msg2_buf, 80); // minimum expected size
|
||||
var payload_buf: [64]u8 = undefined;
|
||||
_ = hs.readMessage(msg2_buf[0..msg2_len], &payload_buf) catch return Error.HandshakeFailed;
|
||||
|
||||
// Message 3: -> s, se
|
||||
var msg3: [64]u8 = undefined; // 48 (encrypted s) + 16 (tag)
|
||||
const msg3_len = hs.writeMessage(&.{}, &msg3) catch return Error.HandshakeFailed;
|
||||
try self.sendRaw(msg3[0..msg3_len]);
|
||||
|
||||
// Split into transport ciphers
|
||||
self.transport = hs.split() catch return Error.HandshakeFailed;
|
||||
self.remote_static_key = hs.rs;
|
||||
self.handshake_complete = true;
|
||||
}
|
||||
|
||||
/// Perform handshake as responder (server accepting connection)
|
||||
pub fn acceptHandshake(self: *Self) Error!void {
|
||||
var hs = HandshakeState.initXX(.responder, self.local_keypair, null);
|
||||
|
||||
// Message 1: <- e
|
||||
var msg1_buf: [48]u8 = undefined;
|
||||
const msg1_len = try self.receiveRaw(&msg1_buf, 32); // minimum: ephemeral key
|
||||
var payload_buf: [64]u8 = undefined;
|
||||
_ = hs.readMessage(msg1_buf[0..msg1_len], &payload_buf) catch return Error.HandshakeFailed;
|
||||
|
||||
// Message 2: -> e, ee, s, es
|
||||
var msg2: [96]u8 = undefined;
|
||||
const msg2_len = hs.writeMessage(&.{}, &msg2) catch return Error.HandshakeFailed;
|
||||
try self.sendRaw(msg2[0..msg2_len]);
|
||||
|
||||
// Message 3: <- s, se
|
||||
var msg3_buf: [64]u8 = undefined;
|
||||
const msg3_len = try self.receiveRaw(&msg3_buf, 48); // minimum: encrypted static
|
||||
_ = hs.readMessage(msg3_buf[0..msg3_len], &payload_buf) catch return Error.HandshakeFailed;
|
||||
|
||||
// Split into transport ciphers
|
||||
self.transport = hs.split() catch return Error.HandshakeFailed;
|
||||
self.remote_static_key = hs.rs;
|
||||
self.handshake_complete = true;
|
||||
}
|
||||
|
||||
/// Send encrypted data (blocking - will sleep on WouldBlock)
|
||||
pub fn send(self: *Self, plaintext: []const u8) Error!usize {
|
||||
if (!self.handshake_complete) return Error.NotEncrypted;
|
||||
|
||||
if (plaintext.len > MAX_MESSAGE_SIZE) return Error.MessageTooLarge;
|
||||
|
||||
var transport_state = &self.transport.?;
|
||||
|
||||
// Encrypt the plaintext
|
||||
const encrypted_len = transport_state.send(plaintext, &self.encrypt_buf) catch |err| {
|
||||
return switch (err) {
|
||||
NoiseError.MessageTooLarge => Error.MessageTooLarge,
|
||||
NoiseError.BufferTooSmall => Error.BufferTooSmall,
|
||||
else => Error.EncryptionFailed,
|
||||
};
|
||||
};
|
||||
|
||||
// Send the encrypted data with length prefix
|
||||
var header: [4]u8 = undefined;
|
||||
std.mem.writeInt(u32, &header, @intCast(encrypted_len), .big);
|
||||
|
||||
// Send header
|
||||
try self.sendRaw(&header);
|
||||
// Send encrypted payload
|
||||
try self.sendRaw(self.encrypt_buf[0..encrypted_len]);
|
||||
|
||||
return plaintext.len;
|
||||
}
|
||||
|
||||
/// ASYNC SEND: Encrypt data and return the encrypted packet (header + ciphertext)
|
||||
/// This is for non-blocking send paths - caller handles actual socket send
|
||||
/// Returns a heap-allocated buffer that caller must free
|
||||
pub fn encryptPacket(self: *Self, plaintext: []const u8, allocator: std.mem.Allocator) Error![]u8 {
|
||||
const start_time = std.time.nanoTimestamp();
|
||||
|
||||
if (!self.handshake_complete) return Error.NotEncrypted;
|
||||
if (plaintext.len > MAX_MESSAGE_SIZE) return Error.MessageTooLarge;
|
||||
|
||||
var transport_state = &self.transport.?;
|
||||
|
||||
// Encrypt the plaintext into our buffer
|
||||
const encrypted_len = transport_state.send(plaintext, &self.encrypt_buf) catch |err| {
|
||||
return switch (err) {
|
||||
NoiseError.MessageTooLarge => Error.MessageTooLarge,
|
||||
NoiseError.BufferTooSmall => Error.BufferTooSmall,
|
||||
else => Error.EncryptionFailed,
|
||||
};
|
||||
};
|
||||
|
||||
// Allocate buffer for header + encrypted data
|
||||
const total_len = 4 + encrypted_len;
|
||||
const packet = allocator.alloc(u8, total_len) catch return Error.OutOfMemory;
|
||||
|
||||
// Write length header
|
||||
std.mem.writeInt(u32, packet[0..4], @intCast(encrypted_len), .big);
|
||||
// Copy encrypted data
|
||||
@memcpy(packet[4..][0..encrypted_len], self.encrypt_buf[0..encrypted_len]);
|
||||
|
||||
// PERF: Log encryption time for large packets
|
||||
const elapsed = std.time.nanoTimestamp() - start_time;
|
||||
const elapsed_ms = @as(f64, @floatFromInt(elapsed)) / 1_000_000.0;
|
||||
if (plaintext.len > 100_000 and elapsed_ms > 5.0) {
|
||||
std.log.warn("CRYPTO PERF: encrypted {}KB in {d:.1}ms ({d:.0}MB/s)", .{
|
||||
plaintext.len / 1024,
|
||||
elapsed_ms,
|
||||
@as(f64, @floatFromInt(plaintext.len)) / (elapsed_ms * 1000.0),
|
||||
});
|
||||
}
|
||||
|
||||
return packet;
|
||||
}
|
||||
|
||||
/// ASYNC SEND: Try to send data without blocking
|
||||
/// Returns bytes sent, or 0 if would block
|
||||
pub fn trySendRawNonBlocking(self: *Self, data: []const u8) Error!usize {
|
||||
const bytes = self.socket.send(data) catch |err| {
|
||||
switch (err) {
|
||||
CoreError.ConnectionTimeout => return 0, // WouldBlock - return 0
|
||||
else => return Error.SocketError,
|
||||
}
|
||||
};
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/// Receive and decrypt data
|
||||
/// Returns the decrypted plaintext slice within the provided buffer
|
||||
pub fn receive(self: *Self, out: []u8) Error![]u8 {
|
||||
if (!self.handshake_complete) return Error.NotEncrypted;
|
||||
|
||||
// Read length header
|
||||
var header: [4]u8 = undefined;
|
||||
_ = try self.receiveRaw(&header, 4);
|
||||
const encrypted_len = std.mem.readInt(u32, &header, .big);
|
||||
|
||||
if (encrypted_len > MAX_MESSAGE_SIZE + TAG_SIZE) return Error.MessageTooLarge;
|
||||
if (encrypted_len < TAG_SIZE) return Error.DecryptionFailed;
|
||||
|
||||
// Read encrypted payload
|
||||
const actual_len = try self.receiveRaw(self.encrypt_buf[0..encrypted_len], encrypted_len);
|
||||
if (actual_len < encrypted_len) return Error.DecryptionFailed;
|
||||
|
||||
var transport_state = &self.transport.?;
|
||||
|
||||
// Decrypt
|
||||
const plaintext = transport_state.receive(self.encrypt_buf[0..encrypted_len], out) catch |err| {
|
||||
return switch (err) {
|
||||
NoiseError.DecryptionFailed => Error.DecryptionFailed,
|
||||
NoiseError.MessageTooLarge => Error.MessageTooLarge,
|
||||
else => Error.DecryptionFailed,
|
||||
};
|
||||
};
|
||||
|
||||
return plaintext;
|
||||
}
|
||||
|
||||
/// Check if encryption is active
|
||||
pub fn isEncrypted(self: *const Self) bool {
|
||||
return self.handshake_complete;
|
||||
}
|
||||
|
||||
/// Get the remote peer's static public key (for authentication)
|
||||
pub fn getRemotePublicKey(self: *const Self) ?[32]u8 {
|
||||
return self.remote_static_key;
|
||||
}
|
||||
|
||||
/// Get the handshake hash for channel binding
|
||||
pub fn getHandshakeHash(self: *const Self) ?[32]u8 {
|
||||
if (self.transport) |*t| {
|
||||
return t.getHandshakeHash();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Rekey for forward secrecy (both directions)
|
||||
pub fn rekey(self: *Self) void {
|
||||
if (self.transport) |*t| {
|
||||
t.rekeyBoth();
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the underlying socket for non-encrypted operations
|
||||
pub fn getSocket(self: *Self) *Socket {
|
||||
return self.socket;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Private helpers for raw socket I/O during handshake
|
||||
// =========================================================================
|
||||
|
||||
/// Send raw data (unencrypted, for handshake)
|
||||
fn sendRaw(self: *Self, data: []const u8) Error!void {
|
||||
var sent: usize = 0;
|
||||
var retries: u32 = 0;
|
||||
const max_retries: u32 = 500; // 5 seconds with 10ms sleep
|
||||
|
||||
while (sent < data.len) {
|
||||
const bytes = self.socket.send(data[sent..]) catch |err| {
|
||||
switch (err) {
|
||||
CoreError.ConnectionTimeout => {
|
||||
// WouldBlock - retry
|
||||
retries += 1;
|
||||
if (retries > max_retries) return Error.HandshakeTimeout;
|
||||
std.Thread.sleep(10 * std.time.ns_per_ms);
|
||||
continue;
|
||||
},
|
||||
else => return Error.SocketError,
|
||||
}
|
||||
};
|
||||
sent += bytes;
|
||||
retries = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Receive raw data (unencrypted, for handshake)
|
||||
/// Returns actual bytes received
|
||||
fn receiveRaw(self: *Self, buffer: []u8, min_bytes: usize) Error!usize {
|
||||
var received: usize = 0;
|
||||
var retries: u32 = 0;
|
||||
const max_retries: u32 = 500; // 5 seconds with 10ms sleep
|
||||
|
||||
while (received < min_bytes) {
|
||||
const bytes = self.socket.receive(buffer[received..]) catch |err| {
|
||||
switch (err) {
|
||||
CoreError.ConnectionTimeout => {
|
||||
// WouldBlock - retry
|
||||
retries += 1;
|
||||
if (retries > max_retries) return Error.HandshakeTimeout;
|
||||
std.Thread.sleep(10 * std.time.ns_per_ms);
|
||||
continue;
|
||||
},
|
||||
CoreError.ConnectionClosed => return Error.HandshakeFailed,
|
||||
else => return Error.SocketError,
|
||||
}
|
||||
};
|
||||
received += bytes;
|
||||
retries = 0;
|
||||
}
|
||||
|
||||
return received;
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// Tests
|
||||
// ============================================================================
|
||||
|
||||
test "SecureConnection init" {
|
||||
const testing = std.testing;
|
||||
|
||||
// Just test initialization (can't test full handshake without network)
|
||||
var socket: Socket = undefined;
|
||||
const keypair = KeyPair.generate();
|
||||
const secure = SecureConnection.init(&socket, keypair, testing.allocator);
|
||||
|
||||
try testing.expect(!secure.isEncrypted());
|
||||
try testing.expect(secure.getRemotePublicKey() == null);
|
||||
}
|
||||
|
||||
test "SecureConnection message size limits" {
|
||||
const testing = std.testing;
|
||||
|
||||
// Verify constants
|
||||
try testing.expect(MAX_MESSAGE_SIZE == 65535);
|
||||
try testing.expect(TAG_SIZE == 16);
|
||||
}
|
||||
Reference in New Issue
Block a user