feat: implement NTCP2 protocol, native TCP transport, and live I2P interop

This commit is contained in:
nandi committed 2026-11-27 19:42:34 +00:00
1 parent dff69dfac6
commit e6d1c464dd
12 files changed
+2557 -2

No files matched your search

+203
View File
@@ -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)
}
+728
View File
@@ -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,
}
}
+7
View File
@@ -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",
}
+194
View File
@@ -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")
}
}
+125
View File
@@ -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