///| /// 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 } } }