diff --git a/noise/noise_xk.mbt b/noise/noise_xk.mbt index cd373d0..7d29f40 100644 --- a/noise/noise_xk.mbt +++ b/noise/noise_xk.mbt @@ -181,6 +181,11 @@ pub fn SymmetricState::handshake_hash(self : SymmetricState) -> Bytes { self.h } +///| +pub fn SymmetricState::chaining_key(self : SymmetricState) -> Bytes { + self.ck +} + ///| pub fn SymmetricState::split( self : SymmetricState, @@ -515,8 +520,8 @@ pub fn SipHashLengthMask::next_mask( next_iv[i] = ((h >> (i * 8)) & 0xFFUL).to_byte() } self.iv = Bytes::from_array(next_iv) - // First 2 bytes of the SipHash output (big-endian uint16 mask) - ((next_iv[0].to_uint() << 8) | next_iv[1].to_uint()) & 0xFFFFU + // Low 16 bits of the 64-bit SipHash-2-4 output (per I2P NTCP2 spec) + (h & 0xFFFFUL).to_uint() } ///| diff --git a/noise/pkg.generated.mbti b/noise/pkg.generated.mbti index 571b8f3..d22a34a 100644 --- a/noise/pkg.generated.mbti +++ b/noise/pkg.generated.mbti @@ -67,6 +67,7 @@ pub struct SymmetricState { mut h : Bytes cipher : CipherState } +pub fn SymmetricState::chaining_key(Self) -> Bytes pub fn SymmetricState::decrypt_and_hash(Self, Bytes) -> Bytes raise NoiseError pub fn SymmetricState::encrypt_and_hash(Self, Bytes) -> Bytes raise NoiseError pub fn SymmetricState::handshake_hash(Self) -> Bytes diff --git a/ntcp2/blocks.mbt b/ntcp2/blocks.mbt new file mode 100644 index 0000000..8701bc3 --- /dev/null +++ b/ntcp2/blocks.mbt @@ -0,0 +1,203 @@ +///| +/// Errors raised by the NTCP2 protocol engine. +#derive(Eq, Debug) +pub suberror Ntcp2Error { + Crypto(@crypto.CryptoError) + Noise(@noise.NoiseError) + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + I2np(@i2np.I2npError) + InvalidState(String) + InvalidFormat(String) + InvalidLength(String) +} + +///| +/// NTCP2 Data Phase & SessionConfirmed Part 2 block types. +#derive(Eq, Debug) +pub(all) enum Ntcp2Block { + /// Type 0: DateTime (4-byte uint32 Unix timestamp in seconds). + DateTime(UInt32) + /// Type 1: Options (opaque bytes). + Options(Bytes) + /// Type 2: RouterInfo (`flood_flag`: bit 0 requests floodfill; `router_info`: raw RouterInfo bytes). + RouterInfo(flood_flag~ : Byte, router_info~ : Bytes) + /// Type 3: I2NP message with 9-byte short header (`type | msg_id | expiration_sec | body`). + I2np(Bytes) + /// Type 4: Termination (`valid_frames_received`, `reason`, `additional_data`). + Termination( + valid_frames_received~ : UInt64, + reason~ : Byte, + additional_data~ : Bytes, + ) + /// Type 254: Padding (must be last block in frame). + Padding(Bytes) + /// Unknown / future block type. + Unknown(Byte, Bytes) +} + +///| +pub fn Ntcp2Block::encode( + self : Ntcp2Block, + w : @encoding.Writer, +) -> Unit raise Ntcp2Error { + match self { + DateTime(ts) => { + w.write_u8(b'\x00') + w.write_u16_be(4U) + w.write_u32_be(ts) + } + Options(data) => { + if data.length() > 65535 { + raise InvalidLength("NTCP2 Options block exceeds 65535 bytes") + } + w.write_u8(b'\x01') + w.write_u16_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + RouterInfo(flood_flag~, router_info~) => { + let sz = 1 + router_info.length() + if sz > 65535 { + raise InvalidLength("NTCP2 RouterInfo block exceeds 65535 bytes") + } + w.write_u8(b'\x02') + w.write_u16_be(sz.reinterpret_as_uint()) + w.write_u8(flood_flag) + w.write_bytes(router_info) + } + I2np(short_msg) => { + if short_msg.length() > 65535 { + raise InvalidLength("NTCP2 I2NP block exceeds 65535 bytes") + } + w.write_u8(b'\x03') + w.write_u16_be(short_msg.length().reinterpret_as_uint()) + w.write_bytes(short_msg) + } + Termination(valid_frames_received~, reason~, additional_data~) => { + let sz = 9 + additional_data.length() + if sz > 65535 { + raise InvalidLength("NTCP2 Termination block exceeds 65535 bytes") + } + w.write_u8(b'\x04') + w.write_u16_be(sz.reinterpret_as_uint()) + w.write_u64_be(valid_frames_received) + w.write_u8(reason) + w.write_bytes(additional_data) + } + Padding(data) => { + if data.length() > 65535 { + raise InvalidLength("NTCP2 Padding block exceeds 65535 bytes") + } + w.write_u8(b'\xfe') + w.write_u16_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + Unknown(btype, data) => { + if data.length() > 65535 { + raise InvalidLength("NTCP2 block exceeds 65535 bytes") + } + w.write_u8(btype) + w.write_u16_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + } +} + +///| +/// Encodes a sequence of NTCP2 blocks into a frame plaintext payload. +pub fn encode_blocks(blocks : Array[Ntcp2Block]) -> Bytes raise Ntcp2Error { + let w = @encoding.Writer::new(capacity=256) + for blk in blocks { + blk.encode(w) + } + w.to_bytes() +} + +///| +/// Decodes all NTCP2 blocks from a decrypted frame plaintext payload. +pub fn decode_blocks(data : Bytes) -> Array[Ntcp2Block] raise Ntcp2Error { + let r = @encoding.Reader::new(data) + let out : Array[Ntcp2Block] = [] + while !r.is_eof() { + let btype = r.read_u8() catch { e => raise Encoding(e) } + let size = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let body = r.read_bytes(size) catch { e => raise Encoding(e) } + match btype.to_int() { + 0 => { + if size != 4 { + raise InvalidLength( + "NTCP2 DateTime block must be 4 bytes, got \{size}", + ) + } + let br = @encoding.Reader::new(body) + let ts = br.read_u32_be() catch { e => raise Encoding(e) } + out.push(DateTime(ts)) + } + 1 => out.push(Options(body)) + 2 => { + if size < 1 { + raise InvalidLength("NTCP2 RouterInfo block must be at least 1 byte") + } + let br = @encoding.Reader::new(body) + let flag = br.read_u8() catch { e => raise Encoding(e) } + let ri = br.read_remaining() + out.push(RouterInfo(flood_flag=flag, router_info=ri)) + } + 3 => out.push(I2np(body)) + 4 => { + if size < 9 { + raise InvalidLength( + "NTCP2 Termination block must be at least 9 bytes, got \{size}", + ) + } + let br = @encoding.Reader::new(body) + let valid_frames = br.read_u64_be() catch { e => raise Encoding(e) } + let reason = br.read_u8() catch { e => raise Encoding(e) } + let extra = br.read_remaining() + out.push( + Termination( + valid_frames_received=valid_frames, + reason~, + additional_data=extra, + ), + ) + } + 254 => out.push(Padding(body)) + _ => out.push(Unknown(btype, body)) + } + } + out +} + +///| +/// Helper to build an NTCP2 I2NP block from a structured `I2npPayload`. +pub fn i2np_block( + msg_id : UInt32, + expiration_sec : UInt32, + payload : @i2np.I2npPayload, +) -> Ntcp2Block raise Ntcp2Error { + let encoded = @i2np.encode_short_message(msg_id, expiration_sec, payload) catch { + e => raise I2np(e) + } + I2np(encoded) +} + +///| +/// Helper to decode an NTCP2 I2NP block payload into `(ShortHeader, I2npPayload)`. +pub fn decode_i2np_block( + data : Bytes, +) -> (@i2np.ShortHeader, @i2np.I2npPayload) raise Ntcp2Error { + @i2np.decode_short_message(@encoding.Reader::new(data)) catch { + e => raise I2np(e) + } +} + +///| +/// Helper to build an NTCP2 RouterInfo block from a `@common.RouterInfo`. +pub fn router_info_block( + ri : @common.RouterInfo, + flood~ : Bool = false, +) -> Ntcp2Block raise Ntcp2Error { + let raw = ri.to_bytes() catch { e => raise Common(e) } + RouterInfo(flood_flag=if flood { b'\x01' } else { b'\x00' }, router_info=raw) +} diff --git a/ntcp2/handshake.mbt b/ntcp2/handshake.mbt new file mode 100644 index 0000000..49cb2ef --- /dev/null +++ b/ntcp2/handshake.mbt @@ -0,0 +1,728 @@ +///| +/// Pure-MoonBit I2P NTCP2 Protocol Engine (`Noise_XKaesobfse+hs2+hs3_25519_ChaChaPoly_SHA256`). +/// Implements AES-256-CBC ephemeral key obfuscation, SessionRequest (Msg 1), +/// SessionCreated (Msg 2), SessionConfirmed (Msg 3), and Data Phase KDF + SipHash-2-4 framing. + +///| +fn slice_b(data : Bytes, start : Int32, len : Int32) -> Bytes { + let out = FixedArray::make(len, b'\x00') + for i = 0; i < len; i = i + 1 { + out[i] = data[start + i] + } + Bytes::from_array(out) +} + +///| +fn concat_b(a : Bytes, b : Bytes) -> Bytes { + let out = FixedArray::make(a.length() + b.length(), b'\x00') + for i = 0; i < a.length(); i = i + 1 { + out[i] = a[i] + } + for i = 0; i < b.length(); i = i + 1 { + out[a.length() + i] = b[i] + } + Bytes::from_array(out) +} + +///| +/// Options block inside NTCP2 Message 1 (SessionRequest), 16 bytes plaintext. +#derive(Eq, Debug) +pub(all) struct SessionRequestOptions { + network_id : Byte // 2 for main I2P network + version : Byte // 2 for NTCP2 + pad_len : UInt32 // uint16 cleartext padding length + m3p2_len : UInt32 // uint16 Msg 3 Part 2 ciphertext length (including 16B MAC) + timestamp_sec : UInt32 // uint32 Unix timestamp in seconds +} + +///| +pub fn SessionRequestOptions::encode(self : SessionRequestOptions) -> Bytes { + let w = @encoding.Writer::new(capacity=16) + w.write_u8(self.network_id) + w.write_u8(self.version) + w.write_u16_be(self.pad_len) + w.write_u16_be(self.m3p2_len) + w.write_u16_be(0U) // reserved + w.write_u32_be(self.timestamp_sec) + w.write_u32_be(0U) // reserved + w.to_bytes() +} + +///| +pub fn SessionRequestOptions::decode( + data : Bytes, +) -> SessionRequestOptions raise Ntcp2Error { + if data.length() != 16 { + raise InvalidLength( + "SessionRequest options must be 16 bytes, got \{data.length()}", + ) + } + let r = @encoding.Reader::new(data) + let network_id = r.read_u8() catch { e => raise Encoding(e) } + let version = r.read_u8() catch { e => raise Encoding(e) } + let pad_len = r.read_u16_be() catch { e => raise Encoding(e) } + let m3p2_len = r.read_u16_be() catch { e => raise Encoding(e) } + let _ = r.read_u16_be() catch { e => raise Encoding(e) } + let timestamp_sec = r.read_u32_be() catch { e => raise Encoding(e) } + let _ = r.read_u32_be() catch { e => raise Encoding(e) } + { network_id, version, pad_len, m3p2_len, timestamp_sec, } +} + +///| +/// Options block inside NTCP2 Message 2 (SessionCreated), 16 bytes plaintext. +#derive(Eq, Debug) +pub(all) struct SessionCreatedOptions { + pad_len : UInt32 // uint16 cleartext padding length + timestamp_sec : UInt32 // uint32 Unix timestamp in seconds +} + +///| +pub fn SessionCreatedOptions::encode(self : SessionCreatedOptions) -> Bytes { + let w = @encoding.Writer::new(capacity=16) + w.write_u16_be(0U) // reserved + w.write_u16_be(self.pad_len) + w.write_u32_be(0U) // reserved + w.write_u32_be(self.timestamp_sec) + w.write_u32_be(0U) // reserved + w.to_bytes() +} + +///| +pub fn SessionCreatedOptions::decode( + data : Bytes, +) -> SessionCreatedOptions raise Ntcp2Error { + if data.length() != 16 { + raise InvalidLength( + "SessionCreated options must be 16 bytes, got \{data.length()}", + ) + } + let r = @encoding.Reader::new(data) + let _ = r.read_u16_be() catch { e => raise Encoding(e) } + let pad_len = r.read_u16_be() catch { e => raise Encoding(e) } + let _ = r.read_u32_be() catch { e => raise Encoding(e) } + let timestamp_sec = r.read_u32_be() catch { e => raise Encoding(e) } + let _ = r.read_u32_be() catch { e => raise Encoding(e) } + { pad_len, timestamp_sec, } +} + +///| +/// Derived NTCP2 Data Phase SipHash-2-4 keys and initial IVs for both directions. +#derive(Eq, Debug) +pub(all) struct SipHashParams { + key_ab : Bytes // 16-byte SipHash key (Alice -> Bob) + iv_ab : Bytes // 8-byte initial IV (Alice -> Bob) + key_ba : Bytes // 16-byte SipHash key (Bob -> Alice) + iv_ba : Bytes // 8-byte initial IV (Bob -> Alice) +} + +///| +/// Derives NTCP2 Data Phase SipHash-2-4 keys and IVs from final Noise `(ck, h)`. +/// Per NTCP2 spec: +/// - `temp_key = HMAC-SHA256(ck, "")` +/// - `ask_master = HMAC-SHA256(temp_key, "ask" || 0x01)` +/// - `temp_key_sip = HMAC-SHA256(ask_master, h || "siphash")` +/// - `sip_master = HMAC-SHA256(temp_key_sip, 0x01)` +/// - `temp_key_2 = HMAC-SHA256(sip_master, "")` +/// - `sipkeys_ab = HMAC-SHA256(temp_key_2, 0x01)` +/// - `sipkeys_ba = HMAC-SHA256(temp_key_2, sipkeys_ab || 0x02)` +pub fn derive_siphash_params(ck : Bytes, h : Bytes) -> SipHashParams { + let temp_key = @crypto.hmac_sha256(ck, b"") + let ask_master = @crypto.hmac_sha256(temp_key, b"ask\x01") + let temp_key_sip = @crypto.hmac_sha256(ask_master, concat_b(h, b"siphash")) + let sip_master = @crypto.hmac_sha256(temp_key_sip, b"\x01") + let temp_key_2 = @crypto.hmac_sha256(sip_master, b"") + let sipkeys_ab = @crypto.hmac_sha256(temp_key_2, b"\x01") + let sipkeys_ba = @crypto.hmac_sha256( + temp_key_2, + concat_b(sipkeys_ab, b"\x02"), + ) + { + key_ab: slice_b(sipkeys_ab, 0, 16), + iv_ab: slice_b(sipkeys_ab, 16, 8), + key_ba: slice_b(sipkeys_ba, 0, 16), + iv_ba: slice_b(sipkeys_ba, 16, 8), + } +} + +///| +/// Post-handshake NTCP2 Data Phase session with ChaCha20-Poly1305 AEAD and +/// SipHash-2-4 frame length obfuscation. +pub struct Ntcp2DataSession { + send_cipher : @noise.CipherState + recv_cipher : @noise.CipherState + send_mask : @noise.SipHashLengthMask + recv_mask : @noise.SipHashLengthMask + handshake_hash : Bytes + remote_static : Bytes +} + +///| +pub fn Ntcp2DataSession::handshake_hash(self : Ntcp2DataSession) -> Bytes { + self.handshake_hash +} + +///| +pub fn Ntcp2DataSession::remote_static(self : Ntcp2DataSession) -> Bytes { + self.remote_static +} + +///| +/// Encrypts a list of NTCP2 blocks into a complete wire frame: +/// `obfuscated_len (2B BE) || ChaCha20-Poly1305(plaintext, ad="")`. +pub fn Ntcp2DataSession::encrypt_frame( + self : Ntcp2DataSession, + blocks : Array[Ntcp2Block], +) -> Bytes raise Ntcp2Error { + let pt = encode_blocks(blocks) + let ct = self.send_cipher.encrypt_with_ad(b"", pt) catch { + e => raise Noise(e) + } + if ct.length() > 65535 { + raise InvalidLength("NTCP2 data frame exceeds 65535 bytes: \{ct.length()}") + } + let obf_len = self.send_mask.xor_length(ct.length().reinterpret_as_uint()) catch { + e => raise Noise(e) + } + let w = @encoding.Writer::new(capacity=2 + ct.length()) + w.write_u16_be(obf_len) + w.write_bytes(ct) + w.to_bytes() +} + +///| +/// De-obfuscates the 2-byte big-endian wire length prefix for the next incoming frame. +pub fn Ntcp2DataSession::unmask_frame_length( + self : Ntcp2DataSession, + obf_len_bytes : Bytes, +) -> Int32 raise Ntcp2Error { + if obf_len_bytes.length() != 2 { + raise InvalidLength("NTCP2 frame length prefix must be 2 bytes") + } + let obf_len = (obf_len_bytes[0].to_uint() << 8) | obf_len_bytes[1].to_uint() + let real_len = self.recv_mask.xor_length(obf_len) catch { + e => raise Noise(e) + } + real_len.reinterpret_as_int() +} + +///| +/// Decrypts a single NTCP2 data frame body (after reading `unmask_frame_length` bytes) +/// and decodes its constituent NTCP2 blocks. +pub fn Ntcp2DataSession::decrypt_frame_body( + self : Ntcp2DataSession, + ciphertext : Bytes, +) -> Array[Ntcp2Block] raise Ntcp2Error { + let pt = self.recv_cipher.decrypt_with_ad(b"", ciphertext) catch { + e => raise Noise(e) + } + decode_blocks(pt) +} + +///| +/// Convenience method that unmasks the 2-byte header and decrypts a complete wire frame. +pub fn Ntcp2DataSession::decrypt_frame( + self : Ntcp2DataSession, + frame : Bytes, +) -> Array[Ntcp2Block] raise Ntcp2Error { + if frame.length() < 18 { + raise InvalidLength("NTCP2 frame too short: \{frame.length()}") + } + let expected_len = self.unmask_frame_length(slice_b(frame, 0, 2)) + if frame.length() - 2 != expected_len { + raise InvalidLength( + "NTCP2 frame length mismatch: header=\{expected_len}, actual=\{frame.length() - 2}", + ) + } + self.decrypt_frame_body(slice_b(frame, 2, expected_len)) +} + +///| +/// NTCP2 Handshake State Machine (Initiator / Alice and Responder / Bob). +pub struct Ntcp2Handshake { + sym : @noise.SymmetricState + initiator : Bool + local_static : @noise.KeyPair + mut local_ephemeral : @noise.KeyPair? + mut remote_static : Bytes? + mut remote_ephemeral : Bytes? + responder_hash : Bytes // 32-byte RH_B (AES-256-CBC key) + published_iv : Bytes // 16-byte published 'i' IV (AES-256-CBC IV for Msg 1) + mut msg2_iv : Bytes // 16-byte IV for Msg 2 (= last 16 bytes of obfuscated X) + mut m3p2_len : Int32 // advertised Msg 3 Part 2 ciphertext length + mut step : Int32 // 0: msg1, 1: msg2, 2: msg3, 3: done +} + +///| +/// Creates an NTCP2 initiator (Alice) handshake state targeting responder Bob. +/// - `local_static`: Alice's X25519 static keypair +/// - `remote_static`: Bob's 32-byte X25519 static public key (`s` in RouterInfo) +/// - `responder_hash`: Bob's 32-byte RouterIdentity SHA-256 hash (`RH_B`) +/// - `published_iv`: Bob's 16-byte published IV (`i` in RouterInfo) +pub fn Ntcp2Handshake::new_initiator( + local_static : @noise.KeyPair, + remote_static : Bytes, + responder_hash : Bytes, + published_iv : Bytes, +) -> Ntcp2Handshake raise Ntcp2Error { + if remote_static.length() != 32 { + raise InvalidLength("remote_static must be 32 bytes") + } + if responder_hash.length() != 32 { + raise InvalidLength("responder_hash must be 32 bytes") + } + if published_iv.length() != 16 { + raise InvalidLength("published_iv must be 16 bytes") + } + let sym = @noise.SymmetricState::initialize(@noise.ntcp2_protocol_name) + sym.mix_hash(b"") // empty prologue + sym.mix_hash(remote_static) // pre-message: <- s + { + sym, + initiator: true, + local_static, + local_ephemeral: None, + remote_static: Some(remote_static), + remote_ephemeral: None, + responder_hash, + published_iv, + msg2_iv: Bytes::make(16, b'\x00'), + m3p2_len: 0, + step: 0, + } +} + +///| +/// Creates an NTCP2 responder (Bob) handshake state. +pub fn Ntcp2Handshake::new_responder( + local_static : @noise.KeyPair, + local_router_hash : Bytes, + published_iv : Bytes, +) -> Ntcp2Handshake raise Ntcp2Error { + if local_router_hash.length() != 32 { + raise InvalidLength("local_router_hash must be 32 bytes") + } + if published_iv.length() != 16 { + raise InvalidLength("published_iv must be 16 bytes") + } + let sym = @noise.SymmetricState::initialize(@noise.ntcp2_protocol_name) + sym.mix_hash(b"") // empty prologue + sym.mix_hash(local_static.public_key) // pre-message: <- s + { + sym, + initiator: false, + local_static, + local_ephemeral: None, + remote_static: None, + remote_ephemeral: None, + responder_hash: local_router_hash, + published_iv, + msg2_iv: Bytes::make(16, b'\x00'), + m3p2_len: 0, + step: 0, + } +} + +///| +/// Sets the local ephemeral X25519 keypair before writing Message 1 (initiator) or Message 2 (responder). +pub fn Ntcp2Handshake::set_ephemeral( + self : Ntcp2Handshake, + ephemeral : @noise.KeyPair, +) -> Unit { + self.local_ephemeral = Some(ephemeral) +} + +///| +/// Returns the advertised Msg 3 Part 2 ciphertext length (including 16-byte MAC). +pub fn Ntcp2Handshake::m3p2_len(self : Ntcp2Handshake) -> Int32 { + self.m3p2_len +} + +///| +/// Initiator: writes Message 1 (SessionRequest). +/// Returns `X_obf (32B) || AEAD(options_16B) (32B) || cleartext_padding`. +pub fn Ntcp2Handshake::write_session_request( + self : Ntcp2Handshake, + m3p2_ciphertext_len : Int32, + timestamp_sec : UInt32, + padding~ : Bytes = b"", + network_id~ : Byte = b'\x02', +) -> Bytes raise Ntcp2Error { + if !self.initiator || self.step != 0 { + raise InvalidState( + "write_session_request only valid for initiator at step 0", + ) + } + let ephem = match self.local_ephemeral { + Some(kp) => kp + None => raise InvalidState("initiator ephemeral key not set") + } + let rs = match self.remote_static { + Some(k) => k + None => raise InvalidState("remote static key missing") + } + // e + self.sym.mix_hash(ephem.public_key) + // es + let dh_es = @crypto.x25519(ephem.private_key, rs) catch { + e => raise Crypto(e) + } + self.sym.mix_key(dh_es) + // Encrypt 16-byte options + let opts : SessionRequestOptions = { + network_id, + version: b'\x02', + pad_len: padding.length().reinterpret_as_uint(), + m3p2_len: m3p2_ciphertext_len.reinterpret_as_uint(), + timestamp_sec, + } + let enc_opts = self.sym.encrypt_and_hash(opts.encode()) catch { + e => raise Noise(e) + } + // MixHash(padding) only if pad_len > 0 (per NTCP2 spec) + if padding.length() > 0 { + self.sym.mix_hash(padding) + } + // Obfuscate X with AES-256-CBC(RH_B, published_iv) + let x_obf = @crypto.aes256_cbc_encrypt( + self.responder_hash, + self.published_iv, + ephem.public_key, + ) catch { + e => raise Crypto(e) + } + // Save last 16 bytes of X_obf as IV for Msg 2 + self.msg2_iv = slice_b(x_obf, 16, 16) + self.m3p2_len = m3p2_ciphertext_len + self.step = 1 + concat_b(concat_b(x_obf, enc_opts), padding) +} + +///| +/// Responder: reads the first 64 bytes of Message 1 (SessionRequest), decrypting options +/// and returning `SessionRequestOptions` (caller must then read `opts.pad_len` bytes of +/// cleartext padding and pass them to `finish_read_session_request`). +pub fn Ntcp2Handshake::read_session_request_head( + self : Ntcp2Handshake, + head64 : Bytes, +) -> SessionRequestOptions raise Ntcp2Error { + if self.initiator || self.step != 0 { + raise InvalidState( + "read_session_request_head only valid for responder at step 0", + ) + } + if head64.length() != 64 { + raise InvalidLength( + "SessionRequest head must be 64 bytes, got \{head64.length()}", + ) + } + let x_obf = slice_b(head64, 0, 32) + let enc_opts = slice_b(head64, 32, 32) + // De-obfuscate X + let x = @crypto.aes256_cbc_decrypt( + self.responder_hash, + self.published_iv, + x_obf, + ) catch { + e => raise Crypto(e) + } + self.remote_ephemeral = Some(x) + self.msg2_iv = slice_b(x_obf, 16, 16) + // e + self.sym.mix_hash(x) + // es + let dh_es = @crypto.x25519(self.local_static.private_key, x) catch { + e => raise Crypto(e) + } + self.sym.mix_key(dh_es) + // Decrypt options + let opts_bytes = self.sym.decrypt_and_hash(enc_opts) catch { + e => raise Noise(e) + } + let opts = SessionRequestOptions::decode(opts_bytes) + if opts.version != b'\x02' { + raise InvalidFormat("unsupported NTCP2 version: \{opts.version.to_int()}") + } + self.m3p2_len = opts.m3p2_len.reinterpret_as_int() + opts +} + +///| +/// Responder: mixes the cleartext padding from Message 1 and advances state to step 1. +pub fn Ntcp2Handshake::finish_read_session_request( + self : Ntcp2Handshake, + padding : Bytes, +) -> Unit raise Ntcp2Error { + if self.initiator || self.step != 0 { + raise InvalidState( + "finish_read_session_request only valid for responder at step 0", + ) + } + if padding.length() > 0 { + self.sym.mix_hash(padding) + } + self.step = 1 +} + +///| +/// Responder: convenience method to read a complete Message 1 buffer in one call. +pub fn Ntcp2Handshake::read_session_request( + self : Ntcp2Handshake, + msg1 : Bytes, +) -> SessionRequestOptions raise Ntcp2Error { + if msg1.length() < 64 { + raise InvalidLength("SessionRequest shorter than 64 bytes") + } + let opts = self.read_session_request_head(slice_b(msg1, 0, 64)) + let pad_len = opts.pad_len.reinterpret_as_int() + if msg1.length() != 64 + pad_len { + raise InvalidLength( + "SessionRequest length mismatch: expected \{64 + pad_len}, got \{msg1.length()}", + ) + } + let padding = if pad_len > 0 { slice_b(msg1, 64, pad_len) } else { b"" } + self.finish_read_session_request(padding) + opts +} + +///| +/// Responder: writes Message 2 (SessionCreated). +/// Returns `Y_obf (32B) || AEAD(options_16B) (32B) || cleartext_padding`. +pub fn Ntcp2Handshake::write_session_created( + self : Ntcp2Handshake, + timestamp_sec : UInt32, + padding~ : Bytes = b"", +) -> Bytes raise Ntcp2Error { + if self.initiator || self.step != 1 { + raise InvalidState( + "write_session_created only valid for responder at step 1", + ) + } + let ephem = match self.local_ephemeral { + Some(kp) => kp + None => raise InvalidState("responder ephemeral key not set") + } + let re = match self.remote_ephemeral { + Some(k) => k + None => raise InvalidState("remote ephemeral key missing") + } + // e + self.sym.mix_hash(ephem.public_key) + // ee + let dh_ee = @crypto.x25519(ephem.private_key, re) catch { + e => raise Crypto(e) + } + self.sym.mix_key(dh_ee) + // Encrypt 16-byte options + let opts : SessionCreatedOptions = { + pad_len: padding.length().reinterpret_as_uint(), + timestamp_sec, + } + let enc_opts = self.sym.encrypt_and_hash(opts.encode()) catch { + e => raise Noise(e) + } + if padding.length() > 0 { + self.sym.mix_hash(padding) + } + // Obfuscate Y with AES-256-CBC(RH_B, msg2_iv) + let y_obf = @crypto.aes256_cbc_encrypt( + self.responder_hash, + self.msg2_iv, + ephem.public_key, + ) catch { + e => raise Crypto(e) + } + self.step = 2 + concat_b(concat_b(y_obf, enc_opts), padding) +} + +///| +/// Initiator: reads the first 64 bytes of Message 2 (SessionCreated), returning +/// `SessionCreatedOptions` (caller must then read `opts.pad_len` bytes and pass +/// them to `finish_read_session_created`). +pub fn Ntcp2Handshake::read_session_created_head( + self : Ntcp2Handshake, + head64 : Bytes, +) -> SessionCreatedOptions raise Ntcp2Error { + if !self.initiator || self.step != 1 { + raise InvalidState( + "read_session_created_head only valid for initiator at step 1", + ) + } + if head64.length() != 64 { + raise InvalidLength( + "SessionCreated head must be 64 bytes, got \{head64.length()}", + ) + } + let y_obf = slice_b(head64, 0, 32) + let enc_opts = slice_b(head64, 32, 32) + // De-obfuscate Y + let y = @crypto.aes256_cbc_decrypt(self.responder_hash, self.msg2_iv, y_obf) catch { + e => raise Crypto(e) + } + self.remote_ephemeral = Some(y) + // e + self.sym.mix_hash(y) + // ee + let ephem = match self.local_ephemeral { + Some(kp) => kp + None => raise InvalidState("initiator ephemeral key missing") + } + let dh_ee = @crypto.x25519(ephem.private_key, y) catch { + e => raise Crypto(e) + } + self.sym.mix_key(dh_ee) + let opts_bytes = self.sym.decrypt_and_hash(enc_opts) catch { + e => raise Noise(e) + } + SessionCreatedOptions::decode(opts_bytes) +} + +///| +/// Initiator: mixes the cleartext padding from Message 2 and advances state to step 2. +pub fn Ntcp2Handshake::finish_read_session_created( + self : Ntcp2Handshake, + padding : Bytes, +) -> Unit raise Ntcp2Error { + if !self.initiator || self.step != 1 { + raise InvalidState( + "finish_read_session_created only valid for initiator at step 1", + ) + } + if padding.length() > 0 { + self.sym.mix_hash(padding) + } + self.step = 2 +} + +///| +/// Initiator: convenience method to read a complete Message 2 buffer in one call. +pub fn Ntcp2Handshake::read_session_created( + self : Ntcp2Handshake, + msg2 : Bytes, +) -> SessionCreatedOptions raise Ntcp2Error { + if msg2.length() < 64 { + raise InvalidLength("SessionCreated shorter than 64 bytes") + } + let opts = self.read_session_created_head(slice_b(msg2, 0, 64)) + let pad_len = opts.pad_len.reinterpret_as_int() + if msg2.length() != 64 + pad_len { + raise InvalidLength( + "SessionCreated length mismatch: expected \{64 + pad_len}, got \{msg2.length()}", + ) + } + let padding = if pad_len > 0 { slice_b(msg2, 64, pad_len) } else { b"" } + self.finish_read_session_created(padding) + opts +} + +///| +/// Initiator: writes Message 3 (SessionConfirmed) containing Part 1 (48B encrypted static key) +/// and Part 2 (`m3p2_len` bytes encrypted blocks, starting with Alice's RouterInfo block). +pub fn Ntcp2Handshake::write_session_confirmed( + self : Ntcp2Handshake, + blocks : Array[Ntcp2Block], +) -> Bytes raise Ntcp2Error { + if !self.initiator || self.step != 2 { + raise InvalidState( + "write_session_confirmed only valid for initiator at step 2", + ) + } + let re = match self.remote_ephemeral { + Some(k) => k + None => raise InvalidState("remote ephemeral key missing") + } + let pt2 = encode_blocks(blocks) + if pt2.length() + 16 != self.m3p2_len { + raise InvalidLength( + "SessionConfirmed part 2 ciphertext len \{pt2.length() + 16} != advertised m3p2_len \{self.m3p2_len}", + ) + } + // Part 1: s + let enc_s = self.sym.encrypt_and_hash(self.local_static.public_key) catch { + e => raise Noise(e) + } + // se + let dh_se = @crypto.x25519(self.local_static.private_key, re) catch { + e => raise Crypto(e) + } + self.sym.mix_key(dh_se) + // Part 2: payload blocks + let enc_p2 = self.sym.encrypt_and_hash(pt2) catch { e => raise Noise(e) } + self.step = 3 + concat_b(enc_s, enc_p2) +} + +///| +/// Responder: reads Message 3 (SessionConfirmed, `48 + m3p2_len` bytes) and returns +/// the decoded Part 2 blocks (containing Alice's RouterInfo block). +pub fn Ntcp2Handshake::read_session_confirmed( + self : Ntcp2Handshake, + msg3 : Bytes, +) -> Array[Ntcp2Block] raise Ntcp2Error { + if self.initiator || self.step != 2 { + raise InvalidState( + "read_session_confirmed only valid for responder at step 2", + ) + } + let expected = 48 + self.m3p2_len + if msg3.length() != expected { + raise InvalidLength( + "SessionConfirmed length mismatch: expected \{expected}, got \{msg3.length()}", + ) + } + let enc_s = slice_b(msg3, 0, 48) + let enc_p2 = slice_b(msg3, 48, self.m3p2_len) + // Part 1: s + let rs = self.sym.decrypt_and_hash(enc_s) catch { e => raise Noise(e) } + self.remote_static = Some(rs) + // se + let ephem = match self.local_ephemeral { + Some(kp) => kp + None => raise InvalidState("responder ephemeral key missing") + } + let dh_se = @crypto.x25519(ephem.private_key, rs) catch { + e => raise Crypto(e) + } + self.sym.mix_key(dh_se) + // Part 2: payload blocks + let pt2 = self.sym.decrypt_and_hash(enc_p2) catch { e => raise Noise(e) } + self.step = 3 + decode_blocks(pt2) +} + +///| +/// Completes the NTCP2 handshake and transitions into a bidirectional `Ntcp2DataSession`. +pub fn Ntcp2Handshake::into_data_session( + self : Ntcp2Handshake, +) -> Ntcp2DataSession raise Ntcp2Error { + if self.step != 3 { + raise InvalidState("NTCP2 handshake not complete (step=\{self.step})") + } + let rs = match self.remote_static { + Some(k) => k + None => raise InvalidState("remote static key missing") + } + let ck = self.sym.chaining_key() + let h = self.sym.handshake_hash() + let (c_ab, c_ba) = self.sym.split() + let sip = derive_siphash_params(ck, h) + let mask_ab = @noise.SipHashLengthMask::new(sip.key_ab, sip.iv_ab) catch { + e => raise Noise(e) + } + let mask_ba = @noise.SipHashLengthMask::new(sip.key_ba, sip.iv_ba) catch { + e => raise Noise(e) + } + let (send_cipher, recv_cipher, send_mask, recv_mask) = if self.initiator { + (c_ab, c_ba, mask_ab, mask_ba) + } else { + (c_ba, c_ab, mask_ba, mask_ab) + } + { + send_cipher, + recv_cipher, + send_mask, + recv_mask, + handshake_hash: h, + remote_static: rs, + } +} diff --git a/ntcp2/moon.pkg b/ntcp2/moon.pkg new file mode 100644 index 0000000..531d9a8 --- /dev/null +++ b/ntcp2/moon.pkg @@ -0,0 +1,7 @@ +import { + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/crypto", + "experiments/moon_i2p/common", + "experiments/moon_i2p/i2np", + "experiments/moon_i2p/noise", +} diff --git a/ntcp2/ntcp2_test.mbt b/ntcp2/ntcp2_test.mbt new file mode 100644 index 0000000..be2ebba --- /dev/null +++ b/ntcp2/ntcp2_test.mbt @@ -0,0 +1,194 @@ +///| +test "NTCP2 options blocks encode/decode round-trip" { + let req : @ntcp2.SessionRequestOptions = { + network_id: b'\x02', + version: b'\x02', + pad_len: 32U, + m3p2_len: 512U, + timestamp_sec: 1700000123U, + } + let enc_req = req.encode() + assert_eq(enc_req.length(), 16) + assert_eq(@ntcp2.SessionRequestOptions::decode(enc_req), req) + + let created : @ntcp2.SessionCreatedOptions = { + pad_len: 16U, + timestamp_sec: 1700000124U, + } + let enc_created = created.encode() + assert_eq(enc_created.length(), 16) + assert_eq(@ntcp2.SessionCreatedOptions::decode(enc_created), created) +} + +///| +test "NTCP2 data phase blocks encode/decode round-trip" { + let i2np_blk = @ntcp2.i2np_block( + 12345U, + 1700000600U, + DeliveryStatus(msg_id=12345U, timestamp_ms=1700000123000UL), + ) + let blocks : Array[@ntcp2.Ntcp2Block] = [ + DateTime(1700000125U), + Options(b"\x01\x02\x03"), + RouterInfo(flood_flag=b'\x01', router_info=b"dummy-ri"), + i2np_blk, + Termination(valid_frames_received=42UL, reason=b'\x00', additional_data=b""), + Padding(b"\xaa\xbb\xcc\xdd"), + ] + let raw = @ntcp2.encode_blocks(blocks) + let decoded = @ntcp2.decode_blocks(raw) + assert_eq(decoded, blocks) + match decoded[3] { + I2np(msg_bytes) => { + let (hdr, payload) = @ntcp2.decode_i2np_block(msg_bytes) + assert_eq(hdr.msg_id, 12345U) + assert_eq( + payload, + DeliveryStatus(msg_id=12345U, timestamp_ms=1700000123000UL), + ) + } + _ => fail("expected I2np block") + } +} + +///| +test "NTCP2 full XKaesobfse handshake + Data Phase SipHash framing round-trip" { + // Alice static & ephemeral keys + let alice_s = @noise.KeyPair::from_private( + @encoding.hex_decode( + "77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a", + ), + ) + let alice_e = @noise.KeyPair::from_private( + @encoding.hex_decode( + "1111111111111111111111111111111111111111111111111111111111111111", + ), + ) + // Bob static & ephemeral keys + let bob_s = @noise.KeyPair::from_private( + @encoding.hex_decode( + "5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb", + ), + ) + let bob_e = @noise.KeyPair::from_private( + @encoding.hex_decode( + "2222222222222222222222222222222222222222222222222222222222222222", + ), + ) + let bob_hash = @crypto.sha256(b"bob-router-identity") + let bob_iv = @encoding.hex_decode("000102030405060708090a0b0c0d0e0f") + + // Build Alice's signed RouterInfo for Msg 3 Part 2 + let alice_ed_seed = @encoding.hex_decode( + "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + ) + let alice_ed_pub = @crypto.ed25519_public_key(alice_ed_seed) + let alice_id = @common.RouterIdentity::new_x25519_ed25519( + alice_s.public_key, + alice_ed_pub, + ) + let alice_ri : @common.RouterInfo = { + identity: alice_id, + published: 1700000123000UL, + addresses: [], + options: @common.Mapping::from_entries([ + ("caps", "LR"), + ("netId", "2"), + ("router.version", "0.9.64"), + ]), + signature: b"", + } + let alice_ri_signed = alice_ri.sign_ed25519(alice_ed_seed) + let m3p2_blocks : Array[@ntcp2.Ntcp2Block] = [ + RouterInfo(flood_flag=b'\x00', router_info=alice_ri_signed.to_bytes()), + Padding(b"\x01\x02\x03\x04\x05\x06\x07\x08"), + ] + let m3p2_pt_len = @ntcp2.encode_blocks(m3p2_blocks).length() + let m3p2_ct_len = m3p2_pt_len + 16 + + // Initialize initiator and responder + let alice = @ntcp2.Ntcp2Handshake::new_initiator( + alice_s, + bob_s.public_key, + bob_hash, + bob_iv, + ) + alice.set_ephemeral(alice_e) + + let bob = @ntcp2.Ntcp2Handshake::new_responder(bob_s, bob_hash, bob_iv) + bob.set_ephemeral(bob_e) + + // Message 1: SessionRequest + let msg1 = alice.write_session_request( + m3p2_ct_len, + 1700000123U, + padding=b"msg1-padding-bytes!", + ) + assert_eq(msg1.length(), 64 + 19) + // Verify X is obfuscated (not plaintext alice_e.public_key) + assert_true(msg1[:32].to_owned() != alice_e.public_key) + + let req_opts = bob.read_session_request(msg1) + assert_eq(req_opts.network_id, b'\x02') + assert_eq(req_opts.version, b'\x02') + assert_eq(req_opts.pad_len, 19U) + assert_eq(req_opts.m3p2_len, m3p2_ct_len.reinterpret_as_uint()) + + // Message 2: SessionCreated + let msg2 = bob.write_session_created(1700000124U, padding=b"msg2-pad") + assert_eq(msg2.length(), 64 + 8) + let created_opts = alice.read_session_created(msg2) + assert_eq(created_opts.pad_len, 8U) + assert_eq(created_opts.timestamp_sec, 1700000124U) + + // Message 3: SessionConfirmed + let msg3 = alice.write_session_confirmed(m3p2_blocks) + assert_eq(msg3.length(), 48 + m3p2_ct_len) + let recv_m3_blocks = bob.read_session_confirmed(msg3) + assert_eq(recv_m3_blocks.length(), 2) + match recv_m3_blocks[0] { + RouterInfo(router_info~, ..) => { + let parsed_ri = @common.RouterInfo::decode( + @encoding.Reader::new(router_info), + ) + assert_eq(parsed_ri.verify_signature(), true) + assert_eq(parsed_ri.identity.hash(), alice_id.hash()) + } + _ => fail("expected RouterInfo block in Msg 3 Part 2") + } + + // Transition to Data Phase + let alice_sess = alice.into_data_session() + let bob_sess = bob.into_data_session() + assert_eq(alice_sess.handshake_hash(), bob_sess.handshake_hash()) + assert_eq(alice_sess.remote_static(), bob_s.public_key) + assert_eq(bob_sess.remote_static(), alice_s.public_key) + + // Bidirectional Data Phase frames with SipHash length masking + let frame_ab = alice_sess.encrypt_frame([ + DateTime(1700000125U), + @ntcp2.i2np_block( + 99U, + 1700000600U, + DeliveryStatus(msg_id=99U, timestamp_ms=1700000125000UL), + ), + ]) + let recv_ab = bob_sess.decrypt_frame(frame_ab) + assert_eq(recv_ab.length(), 2) + assert_eq(recv_ab[0], DateTime(1700000125U)) + + let frame_ba = bob_sess.encrypt_frame([ + @ntcp2.i2np_block(100U, 1700000600U, Data(data=b"hello from bob")), + Padding(b"\x00\x00\x00\x00"), + ]) + let recv_ba = alice_sess.decrypt_frame(frame_ba) + assert_eq(recv_ba.length(), 2) + match recv_ba[0] { + I2np(raw) => { + let (hdr, payload) = @ntcp2.decode_i2np_block(raw) + assert_eq(hdr.msg_id, 100U) + assert_eq(payload, Data(data=b"hello from bob")) + } + _ => fail("expected I2np block from Bob") + } +} diff --git a/ntcp2/pkg.generated.mbti b/ntcp2/pkg.generated.mbti new file mode 100644 index 0000000..5ef620e --- /dev/null +++ b/ntcp2/pkg.generated.mbti @@ -0,0 +1,125 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/ntcp2" + +import { + "experiments/moon_i2p/common", + "experiments/moon_i2p/crypto", + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/i2np", + "experiments/moon_i2p/noise", + "moonbitlang/core/debug", +} + +// Values +pub fn decode_blocks(Bytes) -> Array[Ntcp2Block] raise Ntcp2Error + +pub fn decode_i2np_block(Bytes) -> (@i2np.ShortHeader, @i2np.I2npPayload) raise Ntcp2Error + +pub fn derive_siphash_params(Bytes, Bytes) -> SipHashParams + +pub fn encode_blocks(Array[Ntcp2Block]) -> Bytes raise Ntcp2Error + +pub fn i2np_block(UInt32, UInt32, @i2np.I2npPayload) -> Ntcp2Block raise Ntcp2Error + +pub fn router_info_block(@common.RouterInfo, flood? : Bool) -> Ntcp2Block raise Ntcp2Error + +// Errors +#derive(Eq, @debug.Debug) +pub suberror Ntcp2Error { + Crypto(@crypto.CryptoError) + Noise(@noise.NoiseError) + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + I2np(@i2np.I2npError) + InvalidState(String) + InvalidFormat(String) + InvalidLength(String) +} + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) enum Ntcp2Block { + DateTime(UInt32) + Options(Bytes) + RouterInfo(flood_flag~ : Byte, router_info~ : Bytes) + I2np(Bytes) + Termination(valid_frames_received~ : UInt64, reason~ : Byte, additional_data~ : Bytes) + Padding(Bytes) + Unknown(Byte, Bytes) +} +pub fn Ntcp2Block::encode(Self, @encoding.Writer) -> Unit raise Ntcp2Error + +pub struct Ntcp2DataSession { + send_cipher : @noise.CipherState + recv_cipher : @noise.CipherState + send_mask : @noise.SipHashLengthMask + recv_mask : @noise.SipHashLengthMask + handshake_hash : Bytes + remote_static : Bytes +} +pub fn Ntcp2DataSession::decrypt_frame(Self, Bytes) -> Array[Ntcp2Block] raise Ntcp2Error +pub fn Ntcp2DataSession::decrypt_frame_body(Self, Bytes) -> Array[Ntcp2Block] raise Ntcp2Error +pub fn Ntcp2DataSession::encrypt_frame(Self, Array[Ntcp2Block]) -> Bytes raise Ntcp2Error +pub fn Ntcp2DataSession::handshake_hash(Self) -> Bytes +pub fn Ntcp2DataSession::remote_static(Self) -> Bytes +pub fn Ntcp2DataSession::unmask_frame_length(Self, Bytes) -> Int32 raise Ntcp2Error + +pub struct Ntcp2Handshake { + sym : @noise.SymmetricState + initiator : Bool + local_static : @noise.KeyPair + mut local_ephemeral : @noise.KeyPair? + mut remote_static : Bytes? + mut remote_ephemeral : Bytes? + responder_hash : Bytes + published_iv : Bytes + mut msg2_iv : Bytes + mut m3p2_len : Int32 + mut step : Int32 +} +pub fn Ntcp2Handshake::finish_read_session_created(Self, Bytes) -> Unit raise Ntcp2Error +pub fn Ntcp2Handshake::finish_read_session_request(Self, Bytes) -> Unit raise Ntcp2Error +pub fn Ntcp2Handshake::into_data_session(Self) -> Ntcp2DataSession raise Ntcp2Error +pub fn Ntcp2Handshake::m3p2_len(Self) -> Int32 +pub fn Ntcp2Handshake::new_initiator(@noise.KeyPair, Bytes, Bytes, Bytes) -> Self raise Ntcp2Error +pub fn Ntcp2Handshake::new_responder(@noise.KeyPair, Bytes, Bytes) -> Self raise Ntcp2Error +pub fn Ntcp2Handshake::read_session_confirmed(Self, Bytes) -> Array[Ntcp2Block] raise Ntcp2Error +pub fn Ntcp2Handshake::read_session_created(Self, Bytes) -> SessionCreatedOptions raise Ntcp2Error +pub fn Ntcp2Handshake::read_session_created_head(Self, Bytes) -> SessionCreatedOptions raise Ntcp2Error +pub fn Ntcp2Handshake::read_session_request(Self, Bytes) -> SessionRequestOptions raise Ntcp2Error +pub fn Ntcp2Handshake::read_session_request_head(Self, Bytes) -> SessionRequestOptions raise Ntcp2Error +pub fn Ntcp2Handshake::set_ephemeral(Self, @noise.KeyPair) -> Unit +pub fn Ntcp2Handshake::write_session_confirmed(Self, Array[Ntcp2Block]) -> Bytes raise Ntcp2Error +pub fn Ntcp2Handshake::write_session_created(Self, UInt32, padding? : Bytes) -> Bytes raise Ntcp2Error +pub fn Ntcp2Handshake::write_session_request(Self, Int32, UInt32, padding? : Bytes, network_id? : Byte) -> Bytes raise Ntcp2Error + +#derive(Eq, @debug.Debug) +pub(all) struct SessionCreatedOptions { + pad_len : UInt32 + timestamp_sec : UInt32 +} +pub fn SessionCreatedOptions::decode(Bytes) -> Self raise Ntcp2Error +pub fn SessionCreatedOptions::encode(Self) -> Bytes + +#derive(Eq, @debug.Debug) +pub(all) struct SessionRequestOptions { + network_id : Byte + version : Byte + pad_len : UInt32 + m3p2_len : UInt32 + timestamp_sec : UInt32 +} +pub fn SessionRequestOptions::decode(Bytes) -> Self raise Ntcp2Error +pub fn SessionRequestOptions::encode(Self) -> Bytes + +#derive(Eq, @debug.Debug) +pub(all) struct SipHashParams { + key_ab : Bytes + iv_ab : Bytes + key_ba : Bytes + iv_ba : Bytes +} + +// Type aliases + +// Traits diff --git a/ntcp2_net/i2pd_interop_test.mbt b/ntcp2_net/i2pd_interop_test.mbt new file mode 100644 index 0000000..ea78dff --- /dev/null +++ b/ntcp2_net/i2pd_interop_test.mbt @@ -0,0 +1,134 @@ +///| +/// Live interop test against local `i2pd`'s `router.info` AND real public I2P NTCP2 peers +/// (when `/tmp/i2pd-interop/router.info` and `/tmp/i2pd-interop/seeds/peer_*.dat` exist). +test "live i2pd RouterInfo Ed25519 verify + real I2P NTCP2 handshake + Data Phase" { + // 1. Verify local i2pd's generated RouterInfo parsing & Ed25519 signature + let local_i2pd_ri_bytes = @ntcp2_net.read_file_bytes( + "/tmp/i2pd-interop/router.info", + ) catch { + _ => return // skip when local i2pd interop fixture is not present + } + let local_i2pd_ri = @common.RouterInfo::decode( + @encoding.Reader::new(local_i2pd_ri_bytes), + ) + assert_eq(local_i2pd_ri.verify_signature(), true) + let local_peer = @ntcp2_net.extract_ntcp2_peer(local_i2pd_ri) + assert_eq(local_peer.static_key.length(), 32) + assert_eq(local_peer.iv.length(), 16) + + // 2. Create transient MoonBit router identity & signed RouterInfo + let ed_seed = @ntcp2_net.random_bytes(32) + let ed_pub = @crypto.ed25519_public_key(ed_seed) + let static_priv = @ntcp2_net.random_bytes(32) + let local_static = @noise.KeyPair::from_private(static_priv) + let local_iv = @ntcp2_net.random_bytes(16) + let local_id = @common.RouterIdentity::new_x25519_ed25519( + local_static.public_key, + ed_pub, + ) + let addr_opts = @common.Mapping::from_entries([ + ("i", @encoding.base64_encode(local_iv)), + ("s", @encoding.base64_encode(local_static.public_key)), + ("v", "2"), + ]) + let local_ri : @common.RouterInfo = { + identity: local_id, + published: @ntcp2_net.unix_time_ms(), + addresses: [@common.RouterAddress::new(b'\x0e', "NTCP2", addr_opts)], + options: @common.Mapping::from_entries([ + ("caps", "LR"), + ("netId", "2"), + ("router.version", "0.9.64"), + ]), + signature: b"", + } + let signed_local_ri = local_ri.sign_ed25519(ed_seed) + assert_eq(signed_local_ri.verify_signature(), true) + + // 3. Complete a REAL NTCP2 handshake + Data Phase exchange against a live public I2P peer + let mut handshake_ok = false + let mut data_phase_ok = false + for idx = 0; idx < 15; idx = idx + 1 { + let path = "/tmp/i2pd-interop/seeds/peer_\{idx}.dat" + let raw = @ntcp2_net.read_file_bytes(path) catch { _ => continue } + let peer_ri = @common.RouterInfo::decode(@encoding.Reader::new(raw)) catch { + _ => continue + } + if !peer_ri.verify_signature() { + continue + } + // Prefer a floodfill peer so DatabaseLookup elicits a real Data Phase I2NP reply + match peer_ri.options.get("caps") { + Some(caps) => if !caps.contains("f") { continue } + None => continue + } + let peer = @ntcp2_net.extract_ntcp2_peer(peer_ri) catch { _ => continue } + // Skip IPv6 addresses in IPv4-only VM + if peer.host.contains(":") { + continue + } + let conn = @ntcp2_net.dial_ntcp2( + peer, + local_static, + signed_local_ri, + flood=false, + timeout_ms=5000, + ) catch { + _ => continue + } + handshake_ok = true + println( + "HANDSHAKE OK with floodfill peer_\{idx} (\{peer.host}:\{peer.port})", + ) + let now_sec = @ntcp2_net.unix_time_sec() + let lookup_ri = @i2np.I2npPayload::DatabaseLookup( + key=peer_ri.identity.hash(), + from=local_id.hash(), + flags=b'\x08', // direct reply, RouterInfo lookup + reply_tunnel_id=None, + excluded_peers=[], + ) + let lookup_exp = @i2np.I2npPayload::DatabaseLookup( + key=@common.Hash::sha256(b"moon-i2p-probe"), + from=local_id.hash(), + flags=b'\x0c', // direct reply, exploration lookup + reply_tunnel_id=None, + excluded_peers=[], + ) + conn.send_blocks([ + DateTime(now_sec), + @ntcp2.i2np_block(4242U, now_sec + 60U, lookup_ri), + @ntcp2.i2np_block(4243U, now_sec + 60U, lookup_exp), + Padding(b"\x00\x00\x00\x00"), + ]) catch { + _ => { + println("send_blocks failed") + conn.close() + continue + } + } + // Read at least one decrypted Data Phase frame back from the real I2P router + let blocks = conn.recv_blocks() catch { + e => { + match e { + Timeout => println("peer_\{idx} recv_blocks: Timeout") + Closed => println("peer_\{idx} recv_blocks: Closed") + IoError(m) => println("peer_\{idx} recv_blocks: IoError(\{m})") + Protocol(_) => println("peer_\{idx} recv_blocks: ProtocolError") + _ => println("peer_\{idx} recv_blocks: OtherError") + } + [] + } + } + conn.close() + if blocks.length() > 0 { + data_phase_ok = true + println( + "LIVE NTCP2 DATA PHASE OK with \{peer.host}:\{peer.port} (blocks=\{blocks.length()})", + ) + break + } + } + assert_eq(handshake_ok, true) + assert_eq(data_phase_ok, true) +} diff --git a/ntcp2_net/moon.pkg b/ntcp2_net/moon.pkg new file mode 100644 index 0000000..7663386 --- /dev/null +++ b/ntcp2_net/moon.pkg @@ -0,0 +1,17 @@ +import { + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/common", + "experiments/moon_i2p/i2np", + "experiments/moon_i2p/noise", + "experiments/moon_i2p/ntcp2", +} + +import { + "experiments/moon_i2p/crypto", +} for "test" + +supported_targets = "-all+native" + +options( + "native-stub": [ "net_stub.c" ], +) diff --git a/ntcp2_net/net_stub.c b/ntcp2_net/net_stub.c new file mode 100644 index 0000000..459e12f --- /dev/null +++ b/ntcp2_net/net_stub.c @@ -0,0 +1,366 @@ +/* + * Native POSIX TCP client/server, CSPRNG, clock, and file I/O FFI stub + * for moon-i2p ntcp2_net & router (native target only). + */ +#define _POSIX_C_SOURCE 200809L + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "moonbit.h" + +#ifndef MSG_NOSIGNAL +#define MSG_NOSIGNAL 0 +#endif + +static char g_net_last_error[256] = {0}; + +static void net_set_error(const char *msg) { + if (msg == NULL) { + g_net_last_error[0] = '\0'; + return; + } + strncpy(g_net_last_error, msg, sizeof(g_net_last_error) - 1); + g_net_last_error[sizeof(g_net_last_error) - 1] = '\0'; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_last_error_len(void) { + return (int32_t)strlen(g_net_last_error); +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_last_error_copy(moonbit_bytes_t dst, int32_t max_len) { + int32_t n = (int32_t)strlen(g_net_last_error); + if (n > max_len) { + n = max_len; + } + if (n > 0) { + memcpy(dst, g_net_last_error, (size_t)n); + } + return n; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_connect( + moonbit_bytes_t host_bytes, + int32_t host_len, + int32_t port) { + if (host_len <= 0 || host_len >= 256 || port <= 0 || port > 65535) { + net_set_error("invalid host or port"); + return -1; + } + signal(SIGPIPE, SIG_IGN); + + char host_buf[256]; + memcpy(host_buf, host_bytes, (size_t)host_len); + host_buf[host_len] = '\0'; + + char port_buf[16]; + snprintf(port_buf, sizeof(port_buf), "%d", port); + + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + + struct addrinfo *res = NULL; + int gai_err = getaddrinfo(host_buf, port_buf, &hints, &res); + if (gai_err != 0) { + net_set_error(gai_strerror(gai_err)); + return -1; + } + + int fd = -1; + int last_errno = 0; + for (struct addrinfo *p = res; p != NULL; p = p->ai_next) { + fd = socket(p->ai_family, p->ai_socktype, p->ai_protocol); + if (fd < 0) { + last_errno = errno; + continue; + } + if (connect(fd, p->ai_addr, p->ai_addrlen) == 0) { + break; + } + last_errno = errno; + close(fd); + fd = -1; + } + freeaddrinfo(res); + + if (fd < 0) { + net_set_error(strerror(last_errno ? last_errno : ECONNREFUSED)); + return -1; + } + return (int32_t)fd; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_listen( + moonbit_bytes_t host_bytes, + int32_t host_len, + int32_t port) { + if (host_len <= 0 || host_len >= 256 || port < 0 || port > 65535) { + net_set_error("invalid listen host or port"); + return -1; + } + signal(SIGPIPE, SIG_IGN); + + char host_buf[256]; + memcpy(host_buf, host_bytes, (size_t)host_len); + host_buf[host_len] = '\0'; + + char port_buf[16]; + snprintf(port_buf, sizeof(port_buf), "%d", port); + + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + hints.ai_flags = AI_PASSIVE; + + struct addrinfo *res = NULL; + int gai_err = getaddrinfo(host_buf, port_buf, &hints, &res); + if (gai_err != 0) { + net_set_error(gai_strerror(gai_err)); + return -1; + } + + int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); + if (fd < 0) { + net_set_error(strerror(errno)); + freeaddrinfo(res); + return -1; + } + + int opt = 1; + setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)); + + if (bind(fd, res->ai_addr, res->ai_addrlen) < 0) { + net_set_error(strerror(errno)); + close(fd); + freeaddrinfo(res); + return -1; + } + freeaddrinfo(res); + + if (listen(fd, 32) < 0) { + net_set_error(strerror(errno)); + close(fd); + return -1; + } + return (int32_t)fd; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_local_port(int32_t fd) { + struct sockaddr_in addr; + socklen_t len = sizeof(addr); + if (getsockname((int)fd, (struct sockaddr *)&addr, &len) < 0) { + net_set_error(strerror(errno)); + return -1; + } + return (int32_t)ntohs(addr.sin_port); +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_accept(int32_t listen_fd, int32_t timeout_ms) { + if (timeout_ms >= 0) { + struct pollfd pfd; + pfd.fd = (int)listen_fd; + pfd.events = POLLIN; + pfd.revents = 0; + int rc = poll(&pfd, 1, (int)timeout_ms); + if (rc == 0) { + return -2; // timeout + } + if (rc < 0) { + net_set_error(strerror(errno)); + return -1; + } + } + int cfd = accept((int)listen_fd, NULL, NULL); + if (cfd < 0) { + net_set_error(strerror(errno)); + return -1; + } + return (int32_t)cfd; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_set_recv_timeout(int32_t fd, int32_t timeout_ms) { + struct timeval tv; + tv.tv_sec = timeout_ms / 1000; + tv.tv_usec = (timeout_ms % 1000) * 1000; + if (setsockopt((int)fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) { + net_set_error(strerror(errno)); + return -1; + } + return 0; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_send( + int32_t fd, + moonbit_bytes_t data, + int32_t offset, + int32_t len) { + ssize_t n = send((int)fd, data + offset, (size_t)len, MSG_NOSIGNAL); + if (n < 0) { + net_set_error(strerror(errno)); + return -1; + } + return (int32_t)n; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_recv( + int32_t fd, + moonbit_bytes_t buf, + int32_t max_len) { + ssize_t n = recv((int)fd, buf, (size_t)max_len, 0); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { + return -2; // timeout + } + net_set_error(strerror(errno)); + return -1; + } + return (int32_t)n; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_poll_readable(int32_t fd, int32_t timeout_ms) { + struct pollfd pfd; + pfd.fd = (int)fd; + pfd.events = POLLIN; + pfd.revents = 0; + int rc = poll(&pfd, 1, (int)timeout_ms); + if (rc < 0) { + net_set_error(strerror(errno)); + return -1; + } + return rc > 0 ? 1 : 0; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_shutdown_write(int32_t fd) { + if (shutdown((int)fd, SHUT_WR) < 0) { + net_set_error(strerror(errno)); + return -1; + } + return 0; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_close(int32_t fd) { + if (close((int)fd) < 0) { + net_set_error(strerror(errno)); + return -1; + } + return 0; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_random_bytes(moonbit_bytes_t buf, int32_t len) { + int fd = open("/dev/urandom", O_RDONLY); + if (fd < 0) { + net_set_error(strerror(errno)); + return -1; + } + int32_t got = 0; + while (got < len) { + ssize_t n = read(fd, buf + got, (size_t)(len - got)); + if (n <= 0) { + net_set_error(strerror(errno)); + close(fd); + return -1; + } + got += (int32_t)n; + } + close(fd); + return got; +} + +MOONBIT_FFI_EXPORT +uint64_t moon_i2p_net_unix_time_ms(void) { + struct timespec ts; + if (clock_gettime(CLOCK_REALTIME, &ts) != 0) { + return (uint64_t)time(NULL) * 1000ULL; + } + return (uint64_t)ts.tv_sec * 1000ULL + (uint64_t)(ts.tv_nsec / 1000000L); +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_file_size(moonbit_bytes_t path_bytes, int32_t path_len) { + if (path_len <= 0 || path_len >= 1024) { + net_set_error("invalid path length"); + return -1; + } + char path[1024]; + memcpy(path, path_bytes, (size_t)path_len); + path[path_len] = '\0'; + struct stat st; + if (stat(path, &st) < 0) { + net_set_error(strerror(errno)); + return -1; + } + return (int32_t)st.st_size; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_read_file( + moonbit_bytes_t path_bytes, + int32_t path_len, + moonbit_bytes_t dst, + int32_t max_len) { + if (path_len <= 0 || path_len >= 1024) { + net_set_error("invalid path length"); + return -1; + } + char path[1024]; + memcpy(path, path_bytes, (size_t)path_len); + path[path_len] = '\0'; + int fd = open(path, O_RDONLY); + if (fd < 0) { + net_set_error(strerror(errno)); + return -1; + } + int32_t got = 0; + while (got < max_len) { + ssize_t n = read(fd, dst + got, (size_t)(max_len - got)); + if (n < 0) { + net_set_error(strerror(errno)); + close(fd); + return -1; + } + if (n == 0) { + break; + } + got += (int32_t)n; + } + close(fd); + return got; +} + +MOONBIT_FFI_EXPORT +void moon_i2p_net_flush_stdout(void) { + fflush(stdout); +} diff --git a/ntcp2_net/ntcp2_net_test.mbt b/ntcp2_net/ntcp2_net_test.mbt new file mode 100644 index 0000000..be132b8 --- /dev/null +++ b/ntcp2_net/ntcp2_net_test.mbt @@ -0,0 +1,57 @@ +///| +test "ntcp2_net CSPRNG, clock, and TCP loopback" { + let r1 = @ntcp2_net.random_bytes(32) + let r2 = @ntcp2_net.random_bytes(32) + assert_eq(r1.length(), 32) + assert_eq(r2.length(), 32) + assert_true(r1 != r2) + assert_true(@ntcp2_net.unix_time_sec() > 1700000000U) + + // Loopback TCP listener & client + let listener = @ntcp2_net.TcpListener::bind("127.0.0.1", 0) + let port = listener.local_port() + assert_true(port > 0) + let client = @ntcp2_net.TcpSocket::connect("127.0.0.1", port) + let server = match listener.accept(timeout_ms=2000) { + Some(s) => s + None => fail("expected accepted TCP socket") + } + client.write_all(b"ping\n") + assert_eq(server.read_line(), Some("ping")) + server.write_all(b"pong\n") + assert_eq(client.read_line(), Some("pong")) + client.close() + server.close() + listener.close() +} + +///| +test "extract_ntcp2_peer from signed RouterInfo" { + let ed_seed = @ntcp2_net.random_bytes(32) + let ed_pub = @crypto.ed25519_public_key(ed_seed) + let x_priv = @ntcp2_net.random_bytes(32) + let x_pub = @crypto.x25519_public_key(x_priv) + let iv = @ntcp2_net.random_bytes(16) + let ri_id = @common.RouterIdentity::new_x25519_ed25519(x_pub, ed_pub) + let addr_opts = @common.Mapping::from_entries([ + ("host", "127.0.0.1"), + ("i", @encoding.base64_encode(iv)), + ("port", "14567"), + ("s", @encoding.base64_encode(x_pub)), + ("v", "2"), + ]) + let ri : @common.RouterInfo = { + identity: ri_id, + published: @ntcp2_net.unix_time_ms(), + addresses: [@common.RouterAddress::new(b'\x03', "NTCP2", addr_opts)], + options: @common.Mapping::from_entries([("caps", "LR"), ("netId", "2")]), + signature: b"", + } + let signed = ri.sign_ed25519(ed_seed) + let peer = @ntcp2_net.extract_ntcp2_peer(signed) + assert_eq(peer.host, "127.0.0.1") + assert_eq(peer.port, 14567) + assert_eq(peer.static_key, x_pub) + assert_eq(peer.iv, iv) + assert_eq(peer.router_hash, ri_id.hash().as_bytes()) +} diff --git a/ntcp2_net/transport.mbt b/ntcp2_net/transport.mbt new file mode 100644 index 0000000..7fa9dc5 --- /dev/null +++ b/ntcp2_net/transport.mbt @@ -0,0 +1,718 @@ +///| +/// Native POSIX TCP transport, OS CSPRNG/clock helpers, and NTCP2 session manager. + +///| +#derive(Eq, Debug) +pub suberror Ntcp2NetError { + IoError(String) + Timeout + Closed + Protocol(@ntcp2.Ntcp2Error) + Common(@common.CommonError) + Noise(@noise.NoiseError) + InvalidPeer(String) +} + +///| +extern "C" fn c_last_error_len() -> Int32 = "moon_i2p_net_last_error_len" + +///| +#borrow(dst) +extern "C" fn c_last_error_copy( + dst : FixedArray[Byte], + max_len : Int32, +) -> Int32 = "moon_i2p_net_last_error_copy" + +///| +#borrow(host) +extern "C" fn c_tcp_connect( + host : Bytes, + host_len : Int32, + port : Int32, +) -> Int32 = "moon_i2p_net_tcp_connect" + +///| +#borrow(host) +extern "C" fn c_tcp_listen( + host : Bytes, + host_len : Int32, + port : Int32, +) -> Int32 = "moon_i2p_net_tcp_listen" + +///| +extern "C" fn c_tcp_local_port(fd : Int32) -> Int32 = "moon_i2p_net_tcp_local_port" + +///| +extern "C" fn c_tcp_accept(listen_fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_accept" + +///| +extern "C" fn c_tcp_set_recv_timeout(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_set_recv_timeout" + +///| +#borrow(data) +extern "C" fn c_tcp_send( + fd : Int32, + data : Bytes, + offset : Int32, + len : Int32, +) -> Int32 = "moon_i2p_net_tcp_send" + +///| +#borrow(buf) +extern "C" fn c_tcp_recv( + fd : Int32, + buf : FixedArray[Byte], + max_len : Int32, +) -> Int32 = "moon_i2p_net_tcp_recv" + +///| +extern "C" fn c_tcp_poll_readable(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_poll_readable" + +///| +extern "C" fn c_tcp_shutdown_write(fd : Int32) -> Int32 = "moon_i2p_net_tcp_shutdown_write" + +///| +extern "C" fn c_tcp_close(fd : Int32) -> Int32 = "moon_i2p_net_tcp_close" + +///| +#borrow(buf) +extern "C" fn c_random_bytes(buf : FixedArray[Byte], len : Int32) -> Int32 = "moon_i2p_net_random_bytes" + +///| +extern "C" fn c_unix_time_ms() -> UInt64 = "moon_i2p_net_unix_time_ms" + +///| +#borrow(path) +extern "C" fn c_file_size(path : Bytes, path_len : Int32) -> Int32 = "moon_i2p_net_file_size" + +///| +#borrow(path, dst) +extern "C" fn c_read_file( + path : Bytes, + path_len : Int32, + dst : FixedArray[Byte], + max_len : Int32, +) -> Int32 = "moon_i2p_net_read_file" + +///| +extern "C" fn c_flush_stdout() -> Unit = "moon_i2p_net_flush_stdout" + +///| +fn last_os_error() -> String { + let n = c_last_error_len() + if n <= 0 { + return "unknown OS error" + } + let buf = FixedArray::make(n, b'\x00') + let copied = c_last_error_copy(buf, n) + @encoding.utf8_bytes_to_string(Bytes::from_array(buf)[:copied].to_owned()) catch { + _ => "OS error" + } +} + +///| +pub fn flush_stdout() -> Unit { + c_flush_stdout() +} + +///| +/// Reads `n` cryptographically secure random bytes from `/dev/urandom`. +pub fn random_bytes(n : Int32) -> Bytes raise Ntcp2NetError { + if n <= 0 { + return b"" + } + let buf = FixedArray::make(n, b'\x00') + let got = c_random_bytes(buf, n) + if got != n { + raise IoError("failed to read random bytes: \{last_os_error()}") + } + Bytes::from_array(buf) +} + +///| +/// Returns the current Unix timestamp in milliseconds. +pub fn unix_time_ms() -> UInt64 { + c_unix_time_ms() +} + +///| +/// Returns the current Unix timestamp in seconds. +pub fn unix_time_sec() -> UInt32 { + (c_unix_time_ms() / 1000UL).to_uint() +} + +///| +/// Reads an entire local file into `Bytes`. +pub fn read_file_bytes(path : String) -> Bytes raise Ntcp2NetError { + let pb = @encoding.string_to_utf8_bytes(path) + let sz = c_file_size(pb, pb.length()) + if sz < 0 { + raise IoError("stat(\{path}) failed: \{last_os_error()}") + } + if sz == 0 { + return b"" + } + let buf = FixedArray::make(sz, b'\x00') + let got = c_read_file(pb, pb.length(), buf, sz) + if got < 0 { + raise IoError("read(\{path}) failed: \{last_os_error()}") + } + Bytes::from_array(buf)[:got].to_owned() +} + +///| +/// Native POSIX TCP socket wrapper with exact-length reads and line reading. +pub struct TcpSocket { + mut fd : Int32 + buf : FixedArray[Byte] + mut pos : Int32 + mut len : Int32 +} + +///| +pub fn TcpSocket::connect( + host : String, + port : Int32, +) -> TcpSocket raise Ntcp2NetError { + let hb = @encoding.string_to_utf8_bytes(host) + let fd = c_tcp_connect(hb, hb.length(), port) + if fd < 0 { + raise IoError("connect(\{host}:\{port}) failed: \{last_os_error()}") + } + { fd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, } +} + +///| +pub fn TcpSocket::set_recv_timeout( + self : TcpSocket, + timeout_ms : Int32, +) -> Unit raise Ntcp2NetError { + if self.fd < 0 { + raise Closed + } + if c_tcp_set_recv_timeout(self.fd, timeout_ms) < 0 { + raise IoError("setsockopt(SO_RCVTIMEO) failed: \{last_os_error()}") + } +} + +///| +pub fn TcpSocket::poll_readable( + self : TcpSocket, + timeout_ms : Int32, +) -> Bool raise Ntcp2NetError { + if self.pos < self.len { + return true + } + if self.fd < 0 { + raise Closed + } + let rc = c_tcp_poll_readable(self.fd, timeout_ms) + if rc < 0 { + raise IoError("poll failed: \{last_os_error()}") + } + rc > 0 +} + +///| +pub fn TcpSocket::write_all( + self : TcpSocket, + data : Bytes, +) -> Unit raise Ntcp2NetError { + if self.fd < 0 { + raise Closed + } + let total = data.length() + let mut sent = 0 + while sent < total { + let n = c_tcp_send(self.fd, data, sent, total - sent) + if n < 0 { + raise IoError("send failed: \{last_os_error()}") + } + if n == 0 { + raise Closed + } + sent += n + } +} + +///| +fn TcpSocket::refill(self : TcpSocket) -> Int32 raise Ntcp2NetError { + if self.fd < 0 { + raise Closed + } + let n = c_tcp_recv(self.fd, self.buf, self.buf.length()) + if n == -2 { + raise Timeout + } + if n < 0 { + raise IoError("recv failed: \{last_os_error()}") + } + self.pos = 0 + self.len = n + n +} + +///| +/// Reads exactly `count` bytes from the socket (or raises `Closed`/`Timeout`/`IoError`). +pub fn TcpSocket::read_exact( + self : TcpSocket, + count : Int32, +) -> Bytes raise Ntcp2NetError { + if count <= 0 { + return b"" + } + let out = FixedArray::make(count, b'\x00') + let mut got = 0 + while got < count { + if self.pos < self.len { + let avail = self.len - self.pos + let need = count - got + let take = if avail < need { avail } else { need } + for i = 0; i < take; i = i + 1 { + out[got + i] = self.buf[self.pos + i] + } + self.pos += take + got += take + } else { + let n = self.refill() + if n == 0 { + raise Closed + } + } + } + Bytes::from_array(out) +} + +///| +/// Reads up to `max_bytes` available bytes (returns empty `Bytes` on EOF). +pub fn TcpSocket::read_some( + self : TcpSocket, + max_bytes : Int32, +) -> Bytes raise Ntcp2NetError { + if max_bytes <= 0 { + return b"" + } + if self.pos < self.len { + let avail = self.len - self.pos + let take = if avail < max_bytes { avail } else { max_bytes } + let out = FixedArray::make(take, b'\x00') + for i = 0; i < take; i = i + 1 { + out[i] = self.buf[self.pos + i] + } + self.pos += take + return Bytes::from_array(out) + } + let n = self.refill() + if n == 0 { + return b"" + } + let take = if self.len < max_bytes { self.len } else { max_bytes } + let out = FixedArray::make(take, b'\x00') + for i = 0; i < take; i = i + 1 { + out[i] = self.buf[i] + } + self.pos = take + Bytes::from_array(out) +} + +///| +/// Reads a `\n`-terminated UTF-8 line (stripping trailing `\r`). Returns `None` on clean EOF. +pub fn TcpSocket::read_line(self : TcpSocket) -> String? raise Ntcp2NetError { + let line : Array[Byte] = [] + while true { + while self.pos < self.len { + let b = self.buf[self.pos] + self.pos += 1 + if b == b'\n' { + if line.length() > 0 && line[line.length() - 1] == b'\r' { + let _ = line.pop() + } + let s = @encoding.utf8_bytes_to_string(Bytes::from_array(line)) catch { + _ => raise IoError("invalid UTF-8 in line") + } + return Some(s) + } + line.push(b) + } + let n = self.refill() + if n == 0 { + if line.length() == 0 { + return None + } + let s = @encoding.utf8_bytes_to_string(Bytes::from_array(line)) catch { + _ => raise IoError("invalid UTF-8 in line") + } + return Some(s) + } + } + None +} + +///| +pub fn TcpSocket::shutdown_write(self : TcpSocket) -> Unit { + if self.fd >= 0 { + let _ = c_tcp_shutdown_write(self.fd) + } +} + +///| +pub fn TcpSocket::close(self : TcpSocket) -> Unit { + if self.fd >= 0 { + let _ = c_tcp_close(self.fd) + self.fd = -1 + } +} + +///| +/// Native POSIX TCP server listener. +pub struct TcpListener { + mut fd : Int32 + port : Int32 +} + +///| +pub fn TcpListener::bind( + host : String, + port : Int32, +) -> TcpListener raise Ntcp2NetError { + let hb = @encoding.string_to_utf8_bytes(host) + let fd = c_tcp_listen(hb, hb.length(), port) + if fd < 0 { + raise IoError("listen(\{host}:\{port}) failed: \{last_os_error()}") + } + let bound_port = c_tcp_local_port(fd) + { fd, port: if bound_port > 0 { bound_port } else { port }, } +} + +///| +pub fn TcpListener::local_port(self : TcpListener) -> Int32 { + self.port +} + +///| +/// Accepts an incoming TCP connection. If `timeout_ms >= 0`, returns `None` on timeout. +pub fn TcpListener::accept( + self : TcpListener, + timeout_ms~ : Int32 = -1, +) -> TcpSocket? raise Ntcp2NetError { + if self.fd < 0 { + raise Closed + } + let cfd = c_tcp_accept(self.fd, timeout_ms) + if cfd == -2 { + return None + } + if cfd < 0 { + raise IoError("accept failed: \{last_os_error()}") + } + Some({ fd: cfd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, }) +} + +///| +pub fn TcpListener::close(self : TcpListener) -> Unit { + if self.fd >= 0 { + let _ = c_tcp_close(self.fd) + self.fd = -1 + } +} + +///| +/// Extracted NTCP2 connection parameters from a peer's `RouterInfo`. +#derive(Eq, Debug) +pub(all) struct Ntcp2PeerInfo { + router_hash : Bytes // 32-byte RH_B + static_key : Bytes // 32-byte X25519 's' + iv : Bytes // 16-byte 'i' + host : String + port : Int32 +} + +///| +fn parse_port_str(s : String) -> Int32? { + if s.length() == 0 { + return None + } + let mut v = 0 + for i = 0; i < s.length(); i = i + 1 { + let c = s[i].to_int() + if c < 48 || c > 57 { + return None + } + v = v * 10 + (c - 48) + } + if v > 0 && v <= 65535 { + Some(v) + } else { + None + } +} + +///| +/// Extracts the first reachable NTCP2 address (`host`, `port`, `s`, `i`) and `RH_B` +/// from a peer's `RouterInfo`. +pub fn extract_ntcp2_peer( + ri : @common.RouterInfo, + host_override~ : String? = None, +) -> Ntcp2PeerInfo raise Ntcp2NetError { + for addr in ri.addresses { + if addr.transport_style != "NTCP2" { + continue + } + let s_b64 = match addr.options.get("s") { + Some(v) => v + None => continue + } + let i_b64 = match addr.options.get("i") { + Some(v) => v + None => continue + } + let port_str = match addr.options.get("port") { + Some(v) => v + None => continue + } + let host = match host_override { + Some(h) => h + None => + match addr.options.get("host") { + Some(v) => v + None => continue + } + } + let port = match parse_port_str(port_str) { + Some(p) => p + None => continue + } + let static_key = @encoding.base64_decode(s_b64) catch { + _ => raise InvalidPeer("invalid base64 in NTCP2 's' option") + } + let iv = @encoding.base64_decode(i_b64) catch { + _ => raise InvalidPeer("invalid base64 in NTCP2 'i' option") + } + return { + router_hash: ri.identity.hash().as_bytes(), + static_key, + iv, + host, + port, + } + } + raise InvalidPeer( + "no reachable NTCP2 address with s/i/port found in RouterInfo", + ) +} + +///| +/// Active NTCP2 encrypted TCP connection in Data Phase. +pub struct Ntcp2Conn { + socket : TcpSocket + session : @ntcp2.Ntcp2DataSession + remote_router_info : @common.RouterInfo? +} + +///| +/// Connects to a remote NTCP2 peer over TCP and completes the full 3-message +/// NTCP2 handshake (`SessionRequest` -> `SessionCreated` -> `SessionConfirmed`). +pub fn dial_ntcp2( + peer : Ntcp2PeerInfo, + local_static : @noise.KeyPair, + local_ri : @common.RouterInfo, + flood~ : Bool = false, + timeout_ms~ : Int32 = 10000, +) -> Ntcp2Conn raise Ntcp2NetError { + let sock = TcpSocket::connect(peer.host, peer.port) + sock.set_recv_timeout(timeout_ms) + let hs = @ntcp2.Ntcp2Handshake::new_initiator( + local_static, + peer.static_key, + peer.router_hash, + peer.iv, + ) catch { + e => { + sock.close() + raise Protocol(e) + } + } + let ephem_priv = random_bytes(32) + let ephem = @noise.KeyPair::from_private(ephem_priv) catch { + e => { + sock.close() + raise Noise(e) + } + } + hs.set_ephemeral(ephem) + + // Prepare Msg 3 Part 2 blocks first so we know exact m3p2_len for Msg 1 + let ri_blk = @ntcp2.router_info_block(local_ri, flood~) catch { + e => { + sock.close() + raise Protocol(e) + } + } + let m3_pad = random_bytes(16) + let m3_blocks : Array[@ntcp2.Ntcp2Block] = [ri_blk, Padding(m3_pad)] + let m3p2_pt = @ntcp2.encode_blocks(m3_blocks) catch { + e => { + sock.close() + raise Protocol(e) + } + } + let m3p2_ct_len = m3p2_pt.length() + 16 + + // Send Msg 1 (SessionRequest) with 16 bytes of random cleartext padding + let m1_pad = random_bytes(16) + let msg1 = hs.write_session_request( + m3p2_ct_len, + unix_time_sec(), + padding=m1_pad, + ) catch { + e => { + sock.close() + raise Protocol(e) + } + } + sock.write_all(msg1) + + // Read Msg 2 (SessionCreated): 64-byte head + pad_len bytes + let m2_head = sock.read_exact(64) + let m2_opts = hs.read_session_created_head(m2_head) catch { + e => { + sock.close() + raise Protocol(e) + } + } + let m2_pad_len = m2_opts.pad_len.reinterpret_as_int() + let m2_pad = if m2_pad_len > 0 { sock.read_exact(m2_pad_len) } else { b"" } + hs.finish_read_session_created(m2_pad) catch { + e => { + sock.close() + raise Protocol(e) + } + } + + // Send Msg 3 (SessionConfirmed) + let msg3 = hs.write_session_confirmed(m3_blocks) catch { + e => { + sock.close() + raise Protocol(e) + } + } + sock.write_all(msg3) + + let session = hs.into_data_session() catch { + e => { + sock.close() + raise Protocol(e) + } + } + { socket: sock, session, remote_router_info: None, } +} + +///| +/// Accepts an incoming NTCP2 handshake on an already-accepted `TcpSocket`. +pub fn accept_ntcp2( + sock : TcpSocket, + local_static : @noise.KeyPair, + local_router_hash : Bytes, + local_iv : Bytes, + timeout_ms~ : Int32 = 10000, +) -> Ntcp2Conn raise Ntcp2NetError { + sock.set_recv_timeout(timeout_ms) + let hs = @ntcp2.Ntcp2Handshake::new_responder( + local_static, local_router_hash, local_iv, + ) catch { + e => raise Protocol(e) + } + let ephem_priv = random_bytes(32) + let ephem = @noise.KeyPair::from_private(ephem_priv) catch { + e => raise Noise(e) + } + hs.set_ephemeral(ephem) + + // Read Msg 1 (SessionRequest) + let m1_head = sock.read_exact(64) + let m1_opts = hs.read_session_request_head(m1_head) catch { + e => raise Protocol(e) + } + let m1_pad_len = m1_opts.pad_len.reinterpret_as_int() + let m1_pad = if m1_pad_len > 0 { sock.read_exact(m1_pad_len) } else { b"" } + hs.finish_read_session_request(m1_pad) catch { + e => raise Protocol(e) + } + + // Send Msg 2 (SessionCreated) + let m2_pad = random_bytes(16) + let msg2 = hs.write_session_created(unix_time_sec(), padding=m2_pad) catch { + e => raise Protocol(e) + } + sock.write_all(msg2) + + // Read Msg 3 (SessionConfirmed) + let m3_total = 48 + hs.m3p2_len() + let msg3 = sock.read_exact(m3_total) + let blocks = hs.read_session_confirmed(msg3) catch { e => raise Protocol(e) } + let mut remote_ri : @common.RouterInfo? = None + for blk in blocks { + match blk { + RouterInfo(router_info~, ..) => { + let parsed = @common.RouterInfo::decode( + @encoding.Reader::new(router_info), + ) catch { + e => raise Common(e) + } + remote_ri = Some(parsed) + } + _ => () + } + } + let session = hs.into_data_session() catch { e => raise Protocol(e) } + { socket: sock, session, remote_router_info: remote_ri, } +} + +///| +/// Encrypts and sends a data-phase frame containing `blocks`. +pub fn Ntcp2Conn::send_blocks( + self : Ntcp2Conn, + blocks : Array[@ntcp2.Ntcp2Block], +) -> Unit raise Ntcp2NetError { + let frame = self.session.encrypt_frame(blocks) catch { + e => raise Protocol(e) + } + self.socket.write_all(frame) +} + +///| +/// Reads, unmasks, and decrypts the next data-phase frame. +pub fn Ntcp2Conn::recv_blocks( + self : Ntcp2Conn, +) -> Array[@ntcp2.Ntcp2Block] raise Ntcp2NetError { + let len_hdr = self.socket.read_exact(2) + let frame_len = self.session.unmask_frame_length(len_hdr) catch { + e => raise Protocol(e) + } + if frame_len < 16 { + raise IoError("NTCP2 frame shorter than 16-byte MAC: \{frame_len}") + } + let ct = self.socket.read_exact(frame_len) + self.session.decrypt_frame_body(ct) catch { + e => raise Protocol(e) + } +} + +///| +/// Convenience helper to send a single I2NP message in an NTCP2 Data Phase frame. +pub fn Ntcp2Conn::send_i2np( + self : Ntcp2Conn, + msg_id : UInt32, + expiration_sec : UInt32, + payload : @i2np.I2npPayload, +) -> Unit raise Ntcp2NetError { + let blk = @ntcp2.i2np_block(msg_id, expiration_sec, payload) catch { + e => raise Protocol(e) + } + self.send_blocks([blk]) +} + +///| +pub fn Ntcp2Conn::close(self : Ntcp2Conn) -> Unit { + self.socket.close() +}