From 4866f3c46d430848b79f99480a75899ea5a0a1f6 Mon Sep 17 00:00:00 2001 From: nandi <78769380+codegod100@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:45:58 +0000 Subject: [PATCH] feat: add pure-MoonBit Proposal 157 ShortTunnelBuild, TunnelData crypto, and relay --- tunnel/build.mbt | 274 +++++++++++++++++++++++++++++ tunnel/crypto.mbt | 351 ++++++++++++++++++++++++++++++++++++++ tunnel/moon.pkg | 6 + tunnel/pkg.generated.mbti | 139 +++++++++++++++ tunnel/relay.mbt | 183 ++++++++++++++++++++ tunnel/tunnel_test.mbt | 164 ++++++++++++++++++ 6 files changed, 1117 insertions(+) create mode 100644 tunnel/build.mbt create mode 100644 tunnel/crypto.mbt create mode 100644 tunnel/moon.pkg create mode 100644 tunnel/pkg.generated.mbti create mode 100644 tunnel/relay.mbt create mode 100644 tunnel/tunnel_test.mbt diff --git a/tunnel/build.mbt b/tunnel/build.mbt new file mode 100644 index 0000000..2374510 --- /dev/null +++ b/tunnel/build.mbt @@ -0,0 +1,274 @@ +///| +/// Errors raised by the I2P Tunnel subsystem (ShortTunnelBuild, TunnelData framing, layer crypto). +#derive(Eq, Debug) +pub suberror TunnelError { + Crypto(@crypto.CryptoError) + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + InvalidLength(String) + InvalidFormat(String) + ChecksumMismatch + RecordNotForUs +} + +///| +/// Proposal 157 ShortTunnelBuild Noise protocol name for ECIES-X25519 record encryption. +let stbm_protocol_name : Bytes = b"Noise_N_25519_ChaChaPoly_SHA256" + +///| +fn t_slice(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 t_concat(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) +} + +///| +/// Hop-derived symmetric keys from a Proposal 157 ShortTunnelBuild record. +#derive(Eq, Debug) +pub(all) struct HopKeys { + reply_key : Bytes // 32-byte ChaCha20-Poly1305 key for ShortBuildReplyRecord + layer_key : Bytes // 32-byte AES-256 tunnel layer key + iv_key : Bytes // 32-byte AES-256 tunnel IV key + handshake_hash : Bytes // 32-byte AD `h` for reply AEAD +} + +///| +/// Cleartext 154-byte Proposal 157 ShortBuildRequestRecord. +#derive(Eq, Debug) +pub(all) struct ShortBuildRequestRecord { + receive_tunnel_id : UInt32 + next_tunnel_id : UInt32 + next_ident : @common.Hash + flag : Byte // bit 7 = IBGW (0x80), bit 6 = OBEP (0x40) + layer_enc_type : Byte // 0 = AES-256-CBC + request_time_min : UInt32 // minutes since Unix epoch + request_expiration_sec : UInt32 // seconds (typically 600) + send_message_id : UInt32 + options : @common.Mapping +} + +///| +pub fn ShortBuildRequestRecord::encode_154( + self : ShortBuildRequestRecord, +) -> Bytes raise TunnelError { + let w = @encoding.Writer::new(capacity=154) + w.write_u32_be(self.receive_tunnel_id) + w.write_u32_be(self.next_tunnel_id) + self.next_ident.encode(w) + w.write_u8(self.flag) + w.write_u16_be(0U) // more_flags + w.write_u8(self.layer_enc_type) + w.write_u32_be(self.request_time_min) + w.write_u32_be(self.request_expiration_sec) + w.write_u32_be(self.send_message_id) + self.options.encode(w) catch { + e => raise Common(e) + } + let prefix = w.to_bytes() + if prefix.length() > 154 { + raise InvalidLength( + "ShortBuildRequestRecord exceeds 154 bytes: \{prefix.length()}", + ) + } + let out = FixedArray::make(154, b'\x00') + for i = 0; i < prefix.length(); i = i + 1 { + out[i] = prefix[i] + } + Bytes::from_array(out) +} + +///| +pub fn ShortBuildRequestRecord::decode_154( + data : Bytes, +) -> ShortBuildRequestRecord raise TunnelError { + if data.length() != 154 { + raise InvalidLength( + "ShortBuildRequestRecord must be 154 bytes, got \{data.length()}", + ) + } + let r = @encoding.Reader::new(data) + let receive_tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) } + let next_tunnel_id = r.read_u32_be() catch { e => raise Encoding(e) } + let next_ident = @common.Hash::decode(r) catch { e => raise Common(e) } + let flag = r.read_u8() catch { e => raise Encoding(e) } + let _ = r.read_u16_be() catch { e => raise Encoding(e) } + let layer_enc_type = r.read_u8() catch { e => raise Encoding(e) } + let request_time_min = r.read_u32_be() catch { e => raise Encoding(e) } + let request_expiration_sec = r.read_u32_be() catch { e => raise Encoding(e) } + let send_message_id = r.read_u32_be() catch { e => raise Encoding(e) } + let options = @common.Mapping::decode(r) catch { e => raise Common(e) } + { + receive_tunnel_id, + next_tunnel_id, + next_ident, + flag, + layer_enc_type, + request_time_min, + request_expiration_sec, + send_message_id, + options, + } +} + +///| +fn derive_hop_keys(ck : Bytes, h : Bytes) -> HopKeys raise TunnelError { + // Derive 96 bytes = reply_key (32) || layer_key (32) || iv_key (32) via HKDF-SHA256 + let okm = @crypto.hkdf(ck, b"", b"SMTunnelReplyKey", 96) catch { + e => raise Crypto(e) + } + { + reply_key: t_slice(okm, 0, 32), + layer_key: t_slice(okm, 32, 32), + iv_key: t_slice(okm, 64, 32), + handshake_hash: h, + } +} + +///| +fn stbm_init_state( + hop_static_pub : Bytes, + ephem_pub : Bytes, + dh : Bytes, +) -> (Bytes, Bytes, Bytes) { + let sym = @noise.SymmetricState::initialize(stbm_protocol_name) + sym.mix_hash(b"") // prologue + sym.mix_hash(hop_static_pub) // <- s + sym.mix_hash(ephem_pub) // -> e + sym.mix_key(dh) // es + let ck = sym.chaining_key() + let h = sym.handshake_hash() + // Extract the AEAD encryption key from ck/dh via standard Noise HKDF + let temp_k = @crypto.hmac_sha256( + @crypto.hmac_sha256( + @noise.SymmetricState::initialize(stbm_protocol_name).chaining_key(), + dh, + ), + t_concat(ck, b"\x02"), + ) + (ck, h, temp_k) +} + +///| +/// Encrypts a 154-byte `ShortBuildRequestRecord` into a 218-byte Proposal 157 build record +/// targeting `hop_ident_hash` / `hop_static_pub` using `ephemeral` X25519 keypair. +/// Returns `(encrypted_218B, derived_hop_keys)`. +pub fn encrypt_short_build_record( + record : ShortBuildRequestRecord, + hop_ident_hash : @common.Hash, + hop_static_pub : Bytes, + ephemeral : @noise.KeyPair, +) -> (Bytes, HopKeys) raise TunnelError { + if hop_static_pub.length() != 32 { + raise InvalidLength("hop_static_pub must be 32 bytes") + } + let pt = record.encode_154() + let dh = @crypto.x25519(ephemeral.private_key, hop_static_pub) catch { + e => raise Crypto(e) + } + let (ck, h, enc_key) = stbm_init_state( + hop_static_pub, + ephemeral.public_key, + dh, + ) + let nonce = Bytes::make(12, b'\x00') + let ct = @crypto.aead_chacha20_poly1305_encrypt(enc_key, nonce, h, pt) catch { + e => raise Crypto(e) + } + let h_after = @crypto.sha256(t_concat(h, ct)) + let keys = derive_hop_keys(ck, h_after) + // 218 bytes = to_peer[0..16] || ephem_pub (32B) || ciphertext (170B) + let to_peer = t_slice(hop_ident_hash.as_bytes(), 0, 16) + let out = t_concat(t_concat(to_peer, ephemeral.public_key), ct) + (out, keys) +} + +///| +/// Attempts to decrypt a 218-byte Proposal 157 build record addressed to `local_ident_hash`. +/// Raises `RecordNotForUs` if the 16-byte `to_peer` prefix does not match. +pub fn decrypt_short_build_record( + record_218 : Bytes, + local_ident_hash : @common.Hash, + local_static : @noise.KeyPair, +) -> (ShortBuildRequestRecord, HopKeys) raise TunnelError { + if record_218.length() != 218 { + raise InvalidLength( + "ShortTunnelBuild record must be 218 bytes, got \{record_218.length()}", + ) + } + let to_peer = t_slice(record_218, 0, 16) + let expected_prefix = t_slice(local_ident_hash.as_bytes(), 0, 16) + if !@crypto.ct_eq(to_peer, expected_prefix) { + raise RecordNotForUs + } + let ephem_pub = t_slice(record_218, 16, 32) + let ct = t_slice(record_218, 48, 170) + let dh = @crypto.x25519(local_static.private_key, ephem_pub) catch { + e => raise Crypto(e) + } + let (ck, h, enc_key) = stbm_init_state(local_static.public_key, ephem_pub, dh) + let nonce = Bytes::make(12, b'\x00') + let pt = @crypto.aead_chacha20_poly1305_decrypt(enc_key, nonce, h, ct) catch { + e => raise Crypto(e) + } + let h_after = @crypto.sha256(t_concat(h, ct)) + let keys = derive_hop_keys(ck, h_after) + let rec = ShortBuildRequestRecord::decode_154(pt) + (rec, keys) +} + +///| +/// Encrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` (`reply_code`: `0` = accept, `30` = reject). +pub fn encrypt_short_build_reply( + keys : HopKeys, + reply_code : Byte, +) -> Bytes raise TunnelError { + let pt = FixedArray::make(202, b'\x00') + // 2-byte empty options mapping (0x00, 0x00) + padding + final reply byte at index 201 + pt[201] = reply_code + let nonce = Bytes::make(12, b'\x00') + @crypto.aead_chacha20_poly1305_encrypt( + keys.reply_key, + nonce, + keys.handshake_hash, + Bytes::from_array(pt), + ) catch { + e => raise Crypto(e) + } +} + +///| +/// Decrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` and returns its `reply_code` byte (`0` = accept). +pub fn decrypt_short_build_reply( + keys : HopKeys, + reply_218 : Bytes, +) -> Byte raise TunnelError { + if reply_218.length() != 218 { + raise InvalidLength( + "ShortBuildReplyRecord must be 218 bytes, got \{reply_218.length()}", + ) + } + let nonce = Bytes::make(12, b'\x00') + let pt = @crypto.aead_chacha20_poly1305_decrypt( + keys.reply_key, + nonce, + keys.handshake_hash, + reply_218, + ) catch { + e => raise Crypto(e) + } + pt[201] +} diff --git a/tunnel/crypto.mbt b/tunnel/crypto.mbt new file mode 100644 index 0000000..9b5182f --- /dev/null +++ b/tunnel/crypto.mbt @@ -0,0 +1,351 @@ +///| +/// I2P 1024-byte TunnelData AES-256-CBC layer encryption/decryption and +/// delivery instruction / fragment framing & reassembly. + +///| +/// Applies one hop of I2P tunnel layer encryption to a 1024-byte `TunnelData` cell +/// (`16B IV || 1008B payload`): +/// 1. `iv1 = AES-256-ECB-Encrypt(iv_key, iv)` +/// 2. `payload_out = AES-256-CBC-Encrypt(layer_key, iv1, payload)` +/// 3. `iv_out = AES-256-ECB-Encrypt(iv_key, iv1)` +pub fn tunnel_layer_encrypt( + layer_key : Bytes, + iv_key : Bytes, + cell_1024 : Bytes, +) -> Bytes raise TunnelError { + if cell_1024.length() != 1024 { + raise InvalidLength( + "TunnelData cell must be 1024 bytes, got \{cell_1024.length()}", + ) + } + let iv_in = t_slice(cell_1024, 0, 16) + let payload_in = t_slice(cell_1024, 16, 1008) + let iv1 = @crypto.aes256_encrypt_block(iv_key, iv_in) catch { + e => raise Crypto(e) + } + let payload_out = @crypto.aes256_cbc_encrypt(layer_key, iv1, payload_in) catch { + e => raise Crypto(e) + } + let iv_out = @crypto.aes256_encrypt_block(iv_key, iv1) catch { + e => raise Crypto(e) + } + t_concat(iv_out, payload_out) +} + +///| +/// Applies the exact inverse of `tunnel_layer_encrypt` to a 1024-byte `TunnelData` cell. +pub fn tunnel_layer_decrypt( + layer_key : Bytes, + iv_key : Bytes, + cell_1024 : Bytes, +) -> Bytes raise TunnelError { + if cell_1024.length() != 1024 { + raise InvalidLength( + "TunnelData cell must be 1024 bytes, got \{cell_1024.length()}", + ) + } + let iv_in = t_slice(cell_1024, 0, 16) + let payload_in = t_slice(cell_1024, 16, 1008) + let iv1 = @crypto.aes256_decrypt_block(iv_key, iv_in) catch { + e => raise Crypto(e) + } + let payload_out = @crypto.aes256_cbc_decrypt(layer_key, iv1, payload_in) catch { + e => raise Crypto(e) + } + let iv_out = @crypto.aes256_decrypt_block(iv_key, iv1) catch { + e => raise Crypto(e) + } + t_concat(iv_out, payload_out) +} + +///| +/// Delivery target for a TunnelData first-fragment delivery instruction. +#derive(Eq, Debug) +pub(all) enum DeliveryTarget { + Local + Tunnel(tunnel_id~ : UInt32, gateway~ : @common.Hash) + Router(router_hash~ : @common.Hash) +} + +///| +/// Decoded fragment inside a 1024-byte `TunnelData` cell. +#derive(Eq, Debug) +pub(all) enum TunnelFragment { + First( + target~ : DeliveryTarget, + fragmented~ : Bool, + msg_id~ : UInt32, + data~ : Bytes, + ) + FollowOn(frag_num~ : Int32, is_last~ : Bool, msg_id~ : UInt32, data~ : Bytes) +} + +///| +fn encode_fragment(frag : TunnelFragment) -> Bytes { + let w = @encoding.Writer::new(capacity=1004) + match frag { + First(target~, fragmented~, msg_id~, data~) => { + let dt_bits = match target { + Local => 0x00 + Tunnel(..) => 0x20 + Router(..) => 0x40 + } + let frag_bit = if fragmented { 0x08 } else { 0x00 } + w.write_u8((dt_bits | frag_bit).to_byte()) + match target { + Local => () + Tunnel(tunnel_id~, gateway~) => { + w.write_u32_be(tunnel_id) + gateway.encode(w) + } + Router(router_hash~) => router_hash.encode(w) + } + if fragmented { + w.write_u32_be(msg_id) + } + w.write_u16_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + FollowOn(frag_num~, is_last~, msg_id~, data~) => { + let flag = 0x80 | ((frag_num & 0x3F) << 1) | (if is_last { 1 } else { 0 }) + w.write_u8(flag.to_byte()) + w.write_u32_be(msg_id) + w.write_u16_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + } + w.to_bytes() +} + +///| +/// Packs one or more `TunnelFragment`s into a cleartext 1024-byte `TunnelData` cell +/// with its 16-byte `iv`, 4-byte SHA-256 checksum, non-zero padding, and `0x00` delimiter. +pub fn pack_tunnel_cell( + iv : Bytes, + fragments : Array[TunnelFragment], +) -> Bytes raise TunnelError { + if iv.length() != 16 { + raise InvalidLength("TunnelData IV must be 16 bytes, got \{iv.length()}") + } + let body_w = @encoding.Writer::new(capacity=1003) + for frag in fragments { + body_w.write_bytes(encode_fragment(frag)) + } + let body = body_w.to_bytes() + // 1008 bytes = 4B checksum + non-zero padding + 1B zero delimiter + body + if body.length() > 1003 { + raise InvalidLength( + "TunnelData fragments exceed 1003 bytes: \{body.length()}", + ) + } + let pad_len = 1003 - body.length() + let checksum = @crypto.sha256(t_concat(body, iv)) + let cell = FixedArray::make(1024, b'\x00') + for i = 0; i < 16; i = i + 1 { + cell[i] = iv[i] + } + for i = 0; i < 4; i = i + 1 { + cell[16 + i] = checksum[i] + } + // Non-zero deterministic padding bytes + for i = 0; i < pad_len; i = i + 1 { + cell[20 + i] = (i % 254 + 1).to_byte() + } + // Zero delimiter at 20 + pad_len + cell[20 + pad_len] = b'\x00' + for i = 0; i < body.length(); i = i + 1 { + cell[21 + pad_len + i] = body[i] + } + Bytes::from_array(cell) +} + +///| +/// Verifies the SHA-256 checksum and unpacks all `TunnelFragment`s from a decrypted 1024-byte cell. +pub fn unpack_tunnel_cell( + cell_1024 : Bytes, +) -> Array[TunnelFragment] raise TunnelError { + if cell_1024.length() != 1024 { + raise InvalidLength("TunnelData cell must be 1024 bytes") + } + let iv = t_slice(cell_1024, 0, 16) + let expected_csum = t_slice(cell_1024, 16, 4) + // Find first 0x00 delimiter starting at offset 20 + let mut delim = -1 + for i = 20; i < 1024; i = i + 1 { + if cell_1024[i] == b'\x00' { + delim = i + break + } + } + if delim < 0 { + raise InvalidFormat("TunnelData cell missing 0x00 padding delimiter") + } + let body_start = delim + 1 + let body = t_slice(cell_1024, body_start, 1024 - body_start) + let actual_csum = t_slice(@crypto.sha256(t_concat(body, iv)), 0, 4) + if !@crypto.ct_eq(expected_csum, actual_csum) { + raise ChecksumMismatch + } + let r = @encoding.Reader::new(body) + let out : Array[TunnelFragment] = [] + while !r.is_eof() { + let flag = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + if (flag & 0x80) == 0 { + // First fragment + let dt = (flag >> 5) & 0x03 + let fragmented = (flag & 0x08) != 0 + let target : DeliveryTarget = match dt { + 0 => Local + 1 => { + let tid = r.read_u32_be() catch { e => raise Encoding(e) } + let gw = @common.Hash::decode(r) catch { e => raise Common(e) } + Tunnel(tunnel_id=tid, gateway=gw) + } + 2 => { + let rh = @common.Hash::decode(r) catch { e => raise Common(e) } + Router(router_hash=rh) + } + _ => raise InvalidFormat("invalid TunnelData delivery type: \{dt}") + } + let msg_id = if fragmented { + r.read_u32_be() catch { + e => raise Encoding(e) + } + } else { + 0U + } + let sz = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let data = r.read_bytes(sz) catch { e => raise Encoding(e) } + out.push(First(target~, fragmented~, msg_id~, data~)) + } else { + // Follow-on fragment + let frag_num = (flag >> 1) & 0x3F + let is_last = (flag & 0x01) != 0 + let msg_id = r.read_u32_be() catch { e => raise Encoding(e) } + let sz = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let data = r.read_bytes(sz) catch { e => raise Encoding(e) } + out.push(FollowOn(frag_num~, is_last~, msg_id~, data~)) + } + } + out +} + +///| +/// Splits an I2NP message into one or more 1024-byte cleartext `TunnelData` cells +/// (using First + FollowOn fragments when `payload` exceeds a single cell). +pub fn fragment_message_to_cells( + target : DeliveryTarget, + msg_id : UInt32, + payload : Bytes, + base_iv : Bytes, +) -> Array[Bytes] raise TunnelError { + if base_iv.length() != 16 { + raise InvalidLength("base_iv must be 16 bytes") + } + let target_overhead = match target { + Local => 0 + Tunnel(..) => 36 + Router(..) => 32 + } + let single_max = 1003 - (3 + target_overhead) + if payload.length() <= single_max { + let cell = pack_tunnel_cell(base_iv, [ + First(target~, fragmented=false, msg_id=0U, data=payload), + ]) + return [cell] + } + let cells : Array[Bytes] = [] + let first_max = 1003 - (7 + target_overhead) + let first_chunk = t_slice(payload, 0, first_max) + cells.push( + pack_tunnel_cell(base_iv, [ + First(target~, fragmented=true, msg_id~, data=first_chunk), + ]), + ) + let mut off = first_max + let mut frag_num = 1 + let follow_max = 1003 - 7 + while off < payload.length() { + let rem = payload.length() - off + let take = if rem < follow_max { rem } else { follow_max } + let is_last = off + take == payload.length() + let chunk = t_slice(payload, off, take) + // Derive unique IV per cell + let cell_iv = FixedArray::make(16, b'\x00') + for i = 0; i < 16; i = i + 1 { + cell_iv[i] = (base_iv[i].to_int() ^ frag_num).to_byte() + } + cells.push( + pack_tunnel_cell(Bytes::from_array(cell_iv), [ + FollowOn(frag_num~, is_last~, msg_id~, data=chunk), + ]), + ) + off += take + frag_num += 1 + } + cells +} + +///| +priv struct PendingReassembly { + msg_id : UInt32 + target : DeliveryTarget + chunks : Array[(Int32, Bytes)] + mut last_num : Int32 +} + +///| +/// Stateful reassembler for fragmented `TunnelData` messages. +pub struct FragmentReassembler { + priv pending : Array[PendingReassembly] +} + +///| +pub fn FragmentReassembler::new() -> FragmentReassembler { + { pending: [], } +} + +///| +/// Feeds a decoded `TunnelFragment` into the reassembler. +/// Returns `Some((target, full_payload))` once all fragments of a message have arrived. +pub fn FragmentReassembler::push( + self : FragmentReassembler, + frag : TunnelFragment, +) -> (DeliveryTarget, Bytes)? { + match frag { + First(target~, fragmented~, msg_id~, data~) => { + if !fragmented { + return Some((target, data)) + } + self.pending.push({ msg_id, target, chunks: [(0, data)], last_num: -1, }) + None + } + FollowOn(frag_num~, is_last~, msg_id~, data~) => { + for idx = 0; idx < self.pending.length(); idx = idx + 1 { + let p = self.pending[idx] + if p.msg_id == msg_id { + p.chunks.push((frag_num, data)) + if is_last { + p.last_num = frag_num + } + if p.last_num > 0 && p.chunks.length() == p.last_num + 1 { + let w = @encoding.Writer::new() + for n = 0; n <= p.last_num; n = n + 1 { + for ch in p.chunks { + if ch.0 == n { + w.write_bytes(ch.1) + break + } + } + } + let target = p.target + let _ = self.pending.remove(idx) + return Some((target, w.to_bytes())) + } + return None + } + } + None + } + } +} diff --git a/tunnel/moon.pkg b/tunnel/moon.pkg new file mode 100644 index 0000000..5346d11 --- /dev/null +++ b/tunnel/moon.pkg @@ -0,0 +1,6 @@ +import { + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/crypto", + "experiments/moon_i2p/common", + "experiments/moon_i2p/noise", +} diff --git a/tunnel/pkg.generated.mbti b/tunnel/pkg.generated.mbti new file mode 100644 index 0000000..e9c9ad3 --- /dev/null +++ b/tunnel/pkg.generated.mbti @@ -0,0 +1,139 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/tunnel" + +import { + "experiments/moon_i2p/common", + "experiments/moon_i2p/crypto", + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/noise", + "moonbitlang/core/debug", +} + +// Values +pub fn decrypt_short_build_record(Bytes, @common.Hash, @noise.KeyPair) -> (ShortBuildRequestRecord, HopKeys) raise TunnelError + +pub fn decrypt_short_build_reply(HopKeys, Bytes) -> Byte raise TunnelError + +pub fn encrypt_short_build_record(ShortBuildRequestRecord, @common.Hash, Bytes, @noise.KeyPair) -> (Bytes, HopKeys) raise TunnelError + +pub fn encrypt_short_build_reply(HopKeys, Byte) -> Bytes raise TunnelError + +pub fn fragment_message_to_cells(DeliveryTarget, UInt32, Bytes, Bytes) -> Array[Bytes] raise TunnelError + +pub fn pack_tunnel_cell(Bytes, Array[TunnelFragment]) -> Bytes raise TunnelError + +pub fn tunnel_layer_decrypt(Bytes, Bytes, Bytes) -> Bytes raise TunnelError + +pub fn tunnel_layer_encrypt(Bytes, Bytes, Bytes) -> Bytes raise TunnelError + +pub fn unpack_tunnel_cell(Bytes) -> Array[TunnelFragment] raise TunnelError + +// Errors +#derive(Eq, @debug.Debug) +pub suberror TunnelError { + Crypto(@crypto.CryptoError) + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + InvalidLength(String) + InvalidFormat(String) + ChecksumMismatch + RecordNotForUs +} + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) enum DeliveryTarget { + Local + Tunnel(tunnel_id~ : UInt32, gateway~ : @common.Hash) + Router(router_hash~ : @common.Hash) +} + +pub struct FragmentReassembler { + // private fields +} +pub fn FragmentReassembler::new() -> Self +pub fn FragmentReassembler::push(Self, TunnelFragment) -> (DeliveryTarget, Bytes)? + +#derive(Eq, @debug.Debug) +pub(all) struct HopKeys { + reply_key : Bytes + layer_key : Bytes + iv_key : Bytes + handshake_hash : Bytes +} + +#derive(Eq, @debug.Debug) +pub(all) struct ShortBuildRequestRecord { + receive_tunnel_id : UInt32 + next_tunnel_id : UInt32 + next_ident : @common.Hash + flag : Byte + layer_enc_type : Byte + request_time_min : UInt32 + request_expiration_sec : UInt32 + send_message_id : UInt32 + options : @common.Mapping +} +pub fn ShortBuildRequestRecord::decode_154(Bytes) -> Self raise TunnelError +pub fn ShortBuildRequestRecord::encode_154(Self) -> Bytes raise TunnelError + +#derive(Eq, @debug.Debug) +pub(all) struct TransitHop { + receive_tunnel_id : UInt32 + next_tunnel_id : UInt32 + next_router : @common.Hash + layer_key : Bytes + iv_key : Bytes + is_obep : Bool + expires_sec : UInt32 +} + +#derive(Eq, @debug.Debug) +pub(all) struct Tunnel { + id : UInt32 + direction : TunnelDirection + hops : Array[TunnelHop] + created_sec : UInt32 + expires_sec : UInt32 +} +pub fn Tunnel::decrypt_inbound_cell(Self, Bytes) -> Bytes raise TunnelError +pub fn Tunnel::prepare_outbound_cell(Self, Bytes) -> Bytes raise TunnelError + +#derive(Eq, @debug.Debug) +pub(all) enum TunnelDirection { + Inbound + Outbound +} + +#derive(Eq, @debug.Debug) +pub(all) enum TunnelFragment { + First(target~ : DeliveryTarget, fragmented~ : Bool, msg_id~ : UInt32, data~ : Bytes) + FollowOn(frag_num~ : Int32, is_last~ : Bool, msg_id~ : UInt32, data~ : Bytes) +} + +#derive(Eq, @debug.Debug) +pub(all) struct TunnelHop { + router_hash : @common.Hash + receive_tunnel_id : UInt32 + next_tunnel_id : UInt32 + layer_key : Bytes + iv_key : Bytes +} + +pub struct TunnelManager { + inbound : Array[Tunnel] + outbound : Array[Tunnel] + transit : Array[TransitHop] +} +pub fn TunnelManager::add_transit_hop(Self, TransitHop) -> Unit +pub fn TunnelManager::add_tunnel(Self, Tunnel) -> Unit +pub fn TunnelManager::inbound_count(Self) -> Int32 +pub fn TunnelManager::new() -> Self +pub fn TunnelManager::outbound_count(Self) -> Int32 +pub fn TunnelManager::prune_expired(Self, UInt32) -> Int32 +pub fn TunnelManager::relay_cell(Self, UInt32, Bytes) -> (@common.Hash, UInt32, Bytes, Bool)? raise TunnelError +pub fn TunnelManager::transit_count(Self) -> Int32 + +// Type aliases + +// Traits diff --git a/tunnel/relay.mbt b/tunnel/relay.mbt new file mode 100644 index 0000000..8d2a663 --- /dev/null +++ b/tunnel/relay.mbt @@ -0,0 +1,183 @@ +///| +/// Tunnel pool management, multi-hop encryption/decryption, and transit relay state machine. + +///| +/// Direction of a local tunnel. +#derive(Eq, Debug) +pub(all) enum TunnelDirection { + Inbound + Outbound +} + +///| +/// A single hop along a tunnel path. +#derive(Eq, Debug) +pub(all) struct TunnelHop { + router_hash : @common.Hash + receive_tunnel_id : UInt32 + next_tunnel_id : UInt32 + layer_key : Bytes // 32 bytes + iv_key : Bytes // 32 bytes +} + +///| +/// An active local inbound or outbound tunnel. +#derive(Eq, Debug) +pub(all) struct Tunnel { + id : UInt32 + direction : TunnelDirection + hops : Array[TunnelHop] + created_sec : UInt32 + expires_sec : UInt32 +} + +///| +/// Outbound originator: pre-decrypts a cleartext 1024-byte cell through all hops +/// in reverse order so each hop's `tunnel_layer_encrypt` peels off a layer until +/// the OBEP sees the cleartext cell. +pub fn Tunnel::prepare_outbound_cell( + self : Tunnel, + cleartext_cell : Bytes, +) -> Bytes raise TunnelError { + let mut cell = cleartext_cell + for i = self.hops.length() - 1; i >= 0; i = i - 1 { + let hop = self.hops[i] + cell = tunnel_layer_decrypt(hop.layer_key, hop.iv_key, cell) + } + cell +} + +///| +/// Inbound endpoint (originator): decrypts all hop layers in reverse order to +/// recover the cleartext 1024-byte cell encrypted along the inbound tunnel. +pub fn Tunnel::decrypt_inbound_cell( + self : Tunnel, + encrypted_cell : Bytes, +) -> Bytes raise TunnelError { + let mut cell = encrypted_cell + for i = self.hops.length() - 1; i >= 0; i = i - 1 { + let hop = self.hops[i] + cell = tunnel_layer_decrypt(hop.layer_key, hop.iv_key, cell) + } + cell +} + +///| +/// Transit hop entry stored by a participating router to relay `TunnelData` messages. +#derive(Eq, Debug) +pub(all) struct TransitHop { + receive_tunnel_id : UInt32 + next_tunnel_id : UInt32 + next_router : @common.Hash + layer_key : Bytes + iv_key : Bytes + is_obep : Bool + expires_sec : UInt32 +} + +///| +/// Manages local inbound/outbound tunnel pools and participating transit hops. +pub struct TunnelManager { + inbound : Array[Tunnel] + outbound : Array[Tunnel] + transit : Array[TransitHop] +} + +///| +pub fn TunnelManager::new() -> TunnelManager { + { inbound: [], outbound: [], transit: [], } +} + +///| +pub fn TunnelManager::add_tunnel(self : TunnelManager, t : Tunnel) -> Unit { + match t.direction { + Inbound => self.inbound.push(t) + Outbound => self.outbound.push(t) + } +} + +///| +pub fn TunnelManager::add_transit_hop( + self : TunnelManager, + hop : TransitHop, +) -> Unit { + self.transit.push(hop) +} + +///| +pub fn TunnelManager::inbound_count(self : TunnelManager) -> Int32 { + self.inbound.length() +} + +///| +pub fn TunnelManager::outbound_count(self : TunnelManager) -> Int32 { + self.outbound.length() +} + +///| +pub fn TunnelManager::transit_count(self : TunnelManager) -> Int32 { + self.transit.length() +} + +///| +/// Relays an incoming 1024-byte `TunnelData` cell for `receive_tunnel_id`. +/// Returns `Some((next_router, next_tunnel_id, encrypted_cell, is_obep))` if matched. +pub fn TunnelManager::relay_cell( + self : TunnelManager, + receive_tunnel_id : UInt32, + cell_1024 : Bytes, +) -> (@common.Hash, UInt32, Bytes, Bool)? raise TunnelError { + for hop in self.transit { + if hop.receive_tunnel_id == receive_tunnel_id { + let next_cell = tunnel_layer_encrypt(hop.layer_key, hop.iv_key, cell_1024) + return Some((hop.next_router, hop.next_tunnel_id, next_cell, hop.is_obep)) + } + } + None +} + +///| +/// Prunes expired tunnels and transit hops. +pub fn TunnelManager::prune_expired( + self : TunnelManager, + now_sec : UInt32, +) -> Int32 { + let mut removed = 0 + let kept_in : Array[Tunnel] = [] + for t in self.inbound { + if t.expires_sec > now_sec { + kept_in.push(t) + } else { + removed += 1 + } + } + self.inbound.clear() + for t in kept_in { + self.inbound.push(t) + } + let kept_out : Array[Tunnel] = [] + for t in self.outbound { + if t.expires_sec > now_sec { + kept_out.push(t) + } else { + removed += 1 + } + } + self.outbound.clear() + for t in kept_out { + self.outbound.push(t) + } + let kept_tr : Array[TransitHop] = [] + for h in self.transit { + if h.expires_sec > now_sec { + kept_tr.push(h) + } else { + removed += 1 + } + } + self.transit.clear() + for h in kept_tr { + self.transit.push(h) + } + removed +} diff --git a/tunnel/tunnel_test.mbt b/tunnel/tunnel_test.mbt new file mode 100644 index 0000000..d2449bb --- /dev/null +++ b/tunnel/tunnel_test.mbt @@ -0,0 +1,164 @@ +///| +test "Proposal 157 ShortTunnelBuild 218-byte record & reply round-trip" { + let hop_static = @noise.KeyPair::from_private(Bytes::make(32, b'\x11')) + let hop_hash = @common.Hash::sha256(b"hop-router-1") + let wrong_hash = @common.Hash::sha256(b"other-router") + let ephem = @noise.KeyPair::from_private(Bytes::make(32, b'\x22')) + let next_hash = @common.Hash::sha256(b"hop-router-2") + + let req : @tunnel.ShortBuildRequestRecord = { + receive_tunnel_id: 1001U, + next_tunnel_id: 2002U, + next_ident: next_hash, + flag: b'\x80', // IBGW + layer_enc_type: b'\x00', + request_time_min: 28333333U, + request_expiration_sec: 600U, + send_message_id: 5555U, + options: @common.Mapping::new(), + } + let (enc_rec, creator_keys) = @tunnel.encrypt_short_build_record( + req, + hop_hash, + hop_static.public_key, + ephem, + ) + assert_eq(enc_rec.length(), 218) + + // Wrong hop rejects with RecordNotForUs + let mut rejected = false + try { + let _ = @tunnel.decrypt_short_build_record(enc_rec, wrong_hash, hop_static) + } catch { + RecordNotForUs => rejected = true + _ => () + } + assert_eq(rejected, true) + + // Target hop decrypts record and derives identical HopKeys + let (dec_rec, hop_keys) = @tunnel.decrypt_short_build_record( + enc_rec, hop_hash, hop_static, + ) + assert_eq(dec_rec, req) + assert_eq(hop_keys, creator_keys) + + // Hop encrypts 218-byte accept reply (code 0); creator decrypts it + let reply = @tunnel.encrypt_short_build_reply(hop_keys, b'\x00') + assert_eq(reply.length(), 218) + assert_eq(@tunnel.decrypt_short_build_reply(creator_keys, reply), b'\x00') +} + +///| +test "TunnelData 1024-byte AES-256-CBC layer crypto and multi-hop relay with fragmentation" { + // Build a 3-hop outbound tunnel with 3 transit managers + let hops : Array[@tunnel.TunnelHop] = [] + let managers : Array[@tunnel.TunnelManager] = [] + for i = 0; i < 3; i = i + 1 { + let b = (i + 1).to_byte() + let layer_key = @crypto.sha256(Bytes::make(8, b)) + let iv_key = @crypto.sha256(Bytes::make(8, (i + 11).to_byte())) + let recv_tid = (1000 + i).reinterpret_as_uint() + let next_tid = (1001 + i).reinterpret_as_uint() + let rhash = @common.Hash::sha256(Bytes::make(4, b)) + let next_rhash = @common.Hash::sha256(Bytes::make(4, (i + 2).to_byte())) + hops.push({ + router_hash: rhash, + receive_tunnel_id: recv_tid, + next_tunnel_id: next_tid, + layer_key, + iv_key, + }) + let mgr = @tunnel.TunnelManager::new() + mgr.add_transit_hop({ + receive_tunnel_id: recv_tid, + next_tunnel_id: next_tid, + next_router: next_rhash, + layer_key, + iv_key, + is_obep: i == 2, + expires_sec: 1700000600U, + }) + managers.push(mgr) + } + + let out_tunnel : @tunnel.Tunnel = { + id: 1000U, + direction: Outbound, + hops, + created_sec: 1700000000U, + expires_sec: 1700000600U, + } + + // Create a 2500-byte payload so it fragments across 3 TunnelData cells + let big_buf = FixedArray::make(2500, b'\x00') + for i = 0; i < 2500; i = i + 1 { + big_buf[i] = ((i * 37 + 13) & 0xFF).to_byte() + } + let big_payload = Bytes::from_array(big_buf) + let base_iv = Bytes::make(16, b'\x5a') + let dest_gw = @common.Hash::sha256(b"target-ibgw") + let cells = @tunnel.fragment_message_to_cells( + Tunnel(tunnel_id=7777U, gateway=dest_gw), + 98765U, + big_payload, + base_iv, + ) + assert_eq(cells.length(), 3) + + // Originator pre-decrypts each cell, relays through all 3 hops, and OBEP unpacks & reassembles + let reasm = @tunnel.FragmentReassembler::new() + let mut delivered : (@tunnel.DeliveryTarget, Bytes)? = None + for cell in cells { + let mut wire = out_tunnel.prepare_outbound_cell(cell) + let mut cur_tid = 1000U + for hop_idx = 0; hop_idx < 3; hop_idx = hop_idx + 1 { + match managers[hop_idx].relay_cell(cur_tid, wire) { + Some((_next_r, next_tid, next_cell, is_obep)) => { + wire = next_cell + cur_tid = next_tid + assert_eq(is_obep, hop_idx == 2) + } + None => fail("transit hop did not match tunnel id") + } + } + // After hop 2 (OBEP), `wire` is the original cleartext 1024-byte cell! + assert_eq(wire, cell) + let frags = @tunnel.unpack_tunnel_cell(wire) + for f in frags { + match reasm.push(f) { + Some(res) => delivered = Some(res) + None => () + } + } + } + assert_eq( + delivered, + Some((Tunnel(tunnel_id=7777U, gateway=dest_gw), big_payload)), + ) + + // Also verify inbound multi-hop encryption -> originator decrypt_inbound_cell + let in_tunnel : @tunnel.Tunnel = { + id: 1000U, + direction: Inbound, + hops, + created_sec: 1700000000U, + expires_sec: 1700000600U, + } + let in_cell = @tunnel.pack_tunnel_cell(base_iv, [ + First(target=Local, fragmented=false, msg_id=0U, data=b"inbound-i2np"), + ]) + let mut enc_in = in_cell + for hop_idx = 0; hop_idx < 3; hop_idx = hop_idx + 1 { + enc_in = @tunnel.tunnel_layer_encrypt( + hops[hop_idx].layer_key, + hops[hop_idx].iv_key, + enc_in, + ) + } + let dec_in = in_tunnel.decrypt_inbound_cell(enc_in) + assert_eq(dec_in, in_cell) + let in_frags = @tunnel.unpack_tunnel_cell(dec_in) + assert_eq(in_frags, [ + First(target=Local, fragmented=false, msg_id=0U, data=b"inbound-i2np"), + ]) +}