diff --git a/README.md b/README.md index d9608a8..4be54a4 100644 --- a/README.md +++ b/README.md @@ -6,22 +6,24 @@ A clean, zero-dependency, pure-[MoonBit](https://www.moonbitlang.com/) implement ``` moon-i2p/ -├── encoding/ # I2P Base64 (-/~), Base32 (.b32.i2p), big-endian Reader/Writer, UTF-8, Hex -├── crypto/ # Pure-MoonBit SHA-256, SHA-512, HMAC/HKDF-SHA256, ChaCha20-Poly1305, AES-256-CBC, X25519, Ed25519, SipHash-2-4 -├── common/ # Hash, KeyTypes, Certificate/KeyCertificate, Mapping, Destination, RouterIdentity, signed RouterInfo & LeaseSet2 -├── i2np/ # 16-byte standard & 9-byte NTCP2 short headers, SHA-256 checksums, core I2NP messages +├── encoding/ # I2P Base64 (-/~), Base32 (.b32.i2p), DEFLATE/gzip/I2CP-gzip/ZIP, big-endian Reader/Writer, UTF-8, Hex +├── crypto/ # Pure-MoonBit SHA-256, SHA-512, HMAC/HKDF-SHA256, ChaCha20-Poly1305, AES-256-CBC, X25519, Elligator2, Ed25519, SipHash-2-4 +├── common/ # Hash, KeyTypes, Certificate/KeyCertificate, Mapping, Destination, RouterIdentity, OfflineSignature, .su3 reseed, signed RouterInfo & LeaseSet2 +├── i2np/ # 16-byte standard & 9-byte NTCP2 short headers, SHA-256 checksums, encrypted DatabaseLookup & core I2NP messages ├── noise/ # Noise_XK_25519_ChaChaPoly_SHA256 handshake/transport + NTCP2 SipHash-2-4 length masking -├── ntcp2/ # Pure-MoonBit NTCP2 (Noise_XKaesobfse+hs2+hs3, AES-256-CBC obfuscation, SipHash KDF, data-phase blocks) -├── ntcp2_net/ # Native POSIX TCP transport, OS CSPRNG/clock, and NTCP2 dial/accept session manager -├── netdb/ # Pure-MoonBit NetDB & Floodfill Kademlia DHT (XOR distance, daily routing keys, Ed25519-verified store) -├── tunnel/ # Pure-MoonBit Proposal 157 ShortTunnelBuild (218B records), 1024B TunnelData AES-256-CBC layer crypto, fragmentation & relay -├── sam/ # SAMv3 text protocol parser, serializer, and command builders -├── sam_client/ # Native POSIX TCP SAMv3 client with sane modern I2P defaults -├── router/ # Native MoonBit I2P Router Core with transient identity, NetDB, TunnelManager, NTCP2 listener & embedded SAMv3 bridge +├── ntcp2/ # Pure-MoonBit NTCP2 (Noise_XKaesobfse+hs2+hs3, AES-256-CBC obfuscation, SipHash KDF, replay/clock checks, data-phase blocks) +├── ntcp2_net/ # Native POSIX non-blocking TCP dial/accept/frame transport, OS CSPRNG/clock, reseed HTTP/dir helpers +├── netdb/ # Pure-MoonBit NetDB & Floodfill Kademlia DHT (XOR distance, daily routing keys, gunzip type 0 RI, Ed25519-verified store) +├── tunnel/ # Pure-MoonBit Proposal 157 ShortTunnelBuild (218B records), 1024B TunnelData AES-256-CBC layer crypto, fragmentation & out-of-order relay +├── ratchet/ # Pure-MoonBit Proposal 144 ECIES-X25519-AEAD-Ratchet (Noise_IKelg2+hs2, NS/NSR/ES, DH ratchet, Garlic cloves, ECIES DSM replies) +├── streaming/ # Pure-MoonBit Ed25519-signed I2P Streaming (SYN/ACK/NACK/CLOSE/RESET, RTO retransmit, sliding window) & Repliable/Raw Datagrams +├── sam/ # SAMv3 text protocol parser, serializer, PING/PONG, and command builders +├── sam_client/ # Native POSIX TCP SAMv3 client with PING/PONG, --dest support, and modern I2P defaults +├── router/ # Native MoonBit I2P Router Core with NTCP2 peer pool, floodfill NetDB crawl, Proposal 157 transit tunnels, Garlic/Streaming & SAMv3 bridge ├── cmd/main/ # Pure protocol demo CLI entrypoint -├── cmd/router/ # Native MoonBit I2P router daemon (`--sam`, `--ntcp2-port`, `--peer`) -├── cmd/client/ # Native SAMv3 CLI (`keygen`, `lookup`, `http-get`, `dial`, `listen`) -└── scripts/ # Loopback SAMv3 bridge (`mock_sam.py`) and end-to-end test (`e2e_test.py`) +├── cmd/router/ # Native MoonBit I2P router daemon (`--sam`, `--ntcp2-port`, `--peer`, `--peer-dir`, `--su3`, `--reseed`, `--floodfill`) +├── cmd/client/ # Native SAMv3 CLI (`keygen`, `lookup`, `http-get`, `dial`, `listen`, `--sam`, `--dest`) +└── scripts/ # Loopback SAMv3 bridge (`mock_sam.py`), multi-router `demo.py`, and end-to-end test (`e2e_test.py`) ``` ### Verified Test Vectors & Interop @@ -75,7 +77,9 @@ python3 scripts/e2e_test.py - [x] **Phase 3 (Signatures & Block Crypto):** Pure-MoonBit **SHA-512**, **Ed25519** (RFC 8032), **AES-256-CBC** (FIPS-197 / SP 800-38A), and Ed25519-signed `RouterInfo` & `LeaseSet2` (Proposal 123). - [x] **Phase 4 (Direct Transport):** Full **NTCP2** protocol (`ntcp2/`) + native POSIX TCP transport (`ntcp2_net/`), verified live against public I2P floodfill routers. - [x] **Phase 5 (Router Core):** Pure-MoonBit **NetDB** & Floodfill Kademlia DHT (`netdb/`), Proposal 157 **ShortTunnelBuild** & 1024-byte `TunnelData` layer crypto/relay (`tunnel/`), and native **Router Core** + embedded SAMv3 bridge (`router/`, `cmd/router/`). -- [ ] **Phase 6 (Full End-to-End I2P Network Tunneling):** - - **ECIES-X25519-AEAD-Ratchet** (Proposal 144) for Garlic encryption & end-to-end remote peer sessions. - - Active remote floodfill NetDB lookup/publish over NTCP2 + gzip decompression for `DatabaseStore` type 0. - - **I2P Streaming** (SYN/ACK/windowing) & **Repliable Datagrams** over multi-hop remote tunnels. +- [x] **Phase 6 (Full End-to-End I2P Network Tunneling):** + - **ECIES-X25519-AEAD-Ratchet** (Proposal 144) with Elligator2, Bound/Unbound NS/NSR/ES, DH `NextKey` ratchet, Garlic cloves, and Proposal 154 ECIES `DatabaseLookup` replies (`ratchet/`). + - Active floodfill NetDB lookup/publish over NTCP2, `DatabaseSearchReply` iterative crawl, `.su3` reseed ZIP extraction, and gzip decompression for `DatabaseStore` type 0 (`netdb/`, `common/su3.mbt`, `router/`). + - Ed25519-signed **I2P Streaming** (SYN/ACK/NACK/CLOSE/RESET, sliding window & retransmit), **Repliable/Raw Datagrams** (`streaming/`), and multi-hop Proposal 157 **ShortTunnelBuild** + fragmented `TunnelData` transit relay (`tunnel/`, `router/`). + +> **Note / Current Scope:** Transport is NTCP2 over TCP (`ntcp2/` / `ntcp2_net/`); SSU2 UDP transport and RSA-4096 certificate signature verification of `.su3` signer certificates are currently out of scope (all contained `RouterInfo` Ed25519 signatures inside `.su3` ZIP archives are verified before NetDB import). diff --git a/cmd/client/main.mbt b/cmd/client/main.mbt index e7049b1..d93a48d 100644 --- a/cmd/client/main.mbt +++ b/cmd/client/main.mbt @@ -3,7 +3,9 @@ fn print_usage() -> Unit { println("moon-i2p SAMv3 client (native)") println("") println("Usage:") - println(" moon-i2p [--sam ] [args...]") + println( + " moon-i2p [--sam ] [--dest ] [args...]", + ) println("") println("Commands:") println( @@ -26,6 +28,9 @@ fn print_usage() -> Unit { println( " --sam SAMv3 bridge address (default: 127.0.0.1:7656)", ) + println( + " --dest Persistent private destination key (default: TRANSIENT)", + ) println(" -h, --help Show this help message") println("") println("Environment:") @@ -175,6 +180,22 @@ fn strip_prefix(s : String, prefix : String) -> String? { Some(buf.to_string()) } +///| +fn resolve_destination_arg( + arg : String, +) -> String raise @sam_client.SamClientError { + if arg == "TRANSIENT" { + return arg + } + if @sam_client.file_exists(arg) { + return @sam_client.read_trimmed_text_file(arg) + } + if arg.length() >= 400 { + return arg + } + @sam_client.read_trimmed_text_file(arg) +} + ///| fn run_cli() -> Unit raise @sam_client.SamClientError { let raw_args = @env.args() @@ -193,10 +214,22 @@ fn run_cli() -> Unit raise @sam_client.SamClientError { @env.exit(2) } config = config.with_address(raw_args[i]) + } else if arg == "--dest" { + i += 1 + if i >= raw_args.length() { + println("Error: missing value after --dest") + @env.exit(2) + } + config = config.with_destination(resolve_destination_arg(raw_args[i])) } else { match strip_prefix(arg, "--sam=") { Some(addr) => config = config.with_address(addr) - None => positional.push(arg) + None => + match strip_prefix(arg, "--dest=") { + Some(d) => + config = config.with_destination(resolve_destination_arg(d)) + None => positional.push(arg) + } } } i += 1 diff --git a/cmd/router/main.mbt b/cmd/router/main.mbt index e9c9140..e6ee9ab 100644 --- a/cmd/router/main.mbt +++ b/cmd/router/main.mbt @@ -44,7 +44,12 @@ fn main { let mut sam_port = 7656 let mut ntcp2_host = "127.0.0.1" let mut ntcp2_port = 0 + let mut floodfill = false + let mut check_clock_skew = true let peer_files : Array[String] = [] + let peer_dirs : Array[String] = [] + let su3_files : Array[String] = [] + let reseed_urls : Array[String] = [] let mut i = 1 while i < args.length() { @@ -86,16 +91,44 @@ fn main { } else { i += 1 } + "--peer-dir" => + if i + 1 < args.length() { + peer_dirs.push(args[i + 1]) + i += 2 + } else { + i += 1 + } + "--su3" => + if i + 1 < args.length() { + su3_files.push(args[i + 1]) + i += 2 + } else { + i += 1 + } + "--reseed" => + if i + 1 < args.length() { + reseed_urls.push(args[i + 1]) + i += 2 + } else { + i += 1 + } + "--floodfill" => { + floodfill = true + i += 1 + } + "--no-clock-skew" => { + check_clock_skew = false + i += 1 + } _ => i += 1 } } - let r = @i2p_router.Router::start({ - sam_host, - sam_port, - ntcp2_host, - ntcp2_port, - }) catch { + let r = @i2p_router.Router::start( + { sam_host, sam_port, ntcp2_host, ntcp2_port, }, + floodfill~, + check_clock_skew~, + ) catch { _ => { println("error: failed to start moon-i2p router") return @@ -109,6 +142,33 @@ fn main { } } } + for pd in peer_dirs { + let n = r.load_peer_dir(pd) catch { + _ => { + println("warning: failed to load peer dir \{pd}") + continue + } + } + println(" Loaded \{n} peer(s) from \{pd}") + } + for sf in su3_files { + let n = r.load_reseed_su3_file(sf) catch { + _ => { + println("warning: failed to load reseed .su3 from \{sf}") + continue + } + } + println(" Imported \{n} peer(s) from \{sf}") + } + for url in reseed_urls { + let n = r.reseed_from_url(url) catch { + _ => { + println("warning: reseed fetch failed for \{url}") + continue + } + } + println(" Reseeded \{n} peer(s) from \{url}") + } println("moon-i2p router started (transient identity)") println(" Router Hash: \{r.router_hash().to_base64()}") println(" Router B32: \{r.router_hash().to_b32_address()}") diff --git a/common/common_test.mbt b/common/common_test.mbt index e0374ef..2400af7 100644 --- a/common/common_test.mbt +++ b/common/common_test.mbt @@ -97,6 +97,7 @@ test "LeaseSet2 encode and decode round-trip" { published_sec: 1700000000U, expires_offset: 600U, flags: 0U, + offline_sig: None, options: @common.Mapping::new(), encryption_keys: [{ key_type: X25519, key_data: Bytes::make(32, b'\xdd'), }], leases: [lease], @@ -173,6 +174,7 @@ test "LeaseSet2 Ed25519 sign, encode/decode round-trip, and verify" { published_sec: 1700000000U, expires_offset: 600U, flags: 0U, + offline_sig: None, options: @common.Mapping::new(), encryption_keys: [{ key_type: X25519, key_data: x_pub, }], leases: [{ tunnel_gw: gw, tunnel_id: 777U, end_date_sec: 1700000600U, }], @@ -193,6 +195,7 @@ test "LeaseSet2 Ed25519 sign, encode/decode round-trip, and verify" { published_sec: decoded.published_sec + 1U, expires_offset: decoded.expires_offset, flags: decoded.flags, + offline_sig: decoded.offline_sig, options: decoded.options, encryption_keys: decoded.encryption_keys, leases: decoded.leases, @@ -200,3 +203,204 @@ test "LeaseSet2 Ed25519 sign, encode/decode round-trip, and verify" { } assert_eq(tampered.verify_signature(), false) } + +///| +fn write_u16_le_test(out : Array[Byte], v : UInt32) -> Unit { + out.push((v & 0xFFU).to_byte()) + out.push(((v >> 8) & 0xFFU).to_byte()) +} + +///| +fn write_u32_le_test(out : Array[Byte], v : UInt32) -> Unit { + out.push((v & 0xFFU).to_byte()) + out.push(((v >> 8) & 0xFFU).to_byte()) + out.push(((v >> 16) & 0xFFU).to_byte()) + out.push(((v >> 24) & 0xFFU).to_byte()) +} + +///| +fn build_stored_zip(entries : Array[(String, Bytes)]) -> Bytes { + let out : Array[Byte] = [] + let cd_entries : Array[(Bytes, UInt32, Int32, Int32)] = [] + for item in entries { + let (name, data) = item + let name_bytes = @encoding.string_to_utf8_bytes(name) + let local_off = out.length() + let csum = @encoding.crc32(data) + // Local file header PK\x03\x04 + out.push(b'\x50') + out.push(b'\x4b') + out.push(b'\x03') + out.push(b'\x04') + write_u16_le_test(out, 20U) + write_u16_le_test(out, 0U) + write_u16_le_test(out, 0U) // stored + write_u16_le_test(out, 0U) + write_u16_le_test(out, 0U) + write_u32_le_test(out, csum) + write_u32_le_test(out, data.length().reinterpret_as_uint()) + write_u32_le_test(out, data.length().reinterpret_as_uint()) + write_u16_le_test(out, name_bytes.length().reinterpret_as_uint()) + write_u16_le_test(out, 0U) + for i = 0; i < name_bytes.length(); i = i + 1 { + out.push(name_bytes[i]) + } + for i = 0; i < data.length(); i = i + 1 { + out.push(data[i]) + } + cd_entries.push((name_bytes, csum, data.length(), local_off)) + } + let cd_off = out.length() + for rec in cd_entries { + let (name_bytes, csum, sz, local_off) = rec + out.push(b'\x50') + out.push(b'\x4b') + out.push(b'\x01') + out.push(b'\x02') + write_u16_le_test(out, 20U) + write_u16_le_test(out, 20U) + write_u16_le_test(out, 0U) + write_u16_le_test(out, 0U) + write_u16_le_test(out, 0U) + write_u16_le_test(out, 0U) + write_u32_le_test(out, csum) + write_u32_le_test(out, sz.reinterpret_as_uint()) + write_u32_le_test(out, sz.reinterpret_as_uint()) + write_u16_le_test(out, name_bytes.length().reinterpret_as_uint()) + write_u16_le_test(out, 0U) + write_u16_le_test(out, 0U) + write_u16_le_test(out, 0U) + write_u16_le_test(out, 0U) + write_u32_le_test(out, 0U) + write_u32_le_test(out, local_off.reinterpret_as_uint()) + for i = 0; i < name_bytes.length(); i = i + 1 { + out.push(name_bytes[i]) + } + } + let cd_size = out.length() - cd_off + // EOCD PK\x05\x06 + out.push(b'\x50') + out.push(b'\x4b') + out.push(b'\x05') + out.push(b'\x06') + write_u16_le_test(out, 0U) + write_u16_le_test(out, 0U) + write_u16_le_test(out, cd_entries.length().reinterpret_as_uint()) + write_u16_le_test(out, cd_entries.length().reinterpret_as_uint()) + write_u32_le_test(out, cd_size.reinterpret_as_uint()) + write_u32_le_test(out, cd_off.reinterpret_as_uint()) + write_u16_le_test(out, 0U) + Bytes::from_array(out) +} + +///| +test "LeaseSet2 with OfflineSignature (flags & 1) encode/decode and verify" { + let master_seed = Bytes::make(32, b'\x15') + let master_ed = @crypto.ed25519_public_key(master_seed) + let transient_seed = Bytes::make(32, b'\x26') + let transient_ed = @crypto.ed25519_public_key(transient_seed) + let x_pub = @crypto.x25519_public_key(Bytes::make(32, b'\x37')) + let dest = @common.Destination::new_x25519_ed25519(x_pub, master_ed) + + let off_sig : @common.OfflineSignature = { + expires_sec: 1700086400U, + transient_sig_type: EdDsaSha512Ed25519, + transient_pub_key: transient_ed, + signature: b"", + } + let signed_off = off_sig.sign_ed25519(master_seed) + let ls2 : @common.LeaseSet2 = { + destination: dest, + published_sec: 1700000000U, + expires_offset: 600U, + flags: 1U, + offline_sig: Some(signed_off), + options: @common.Mapping::new(), + encryption_keys: [{ key_type: X25519, key_data: x_pub, }], + leases: [ + { + tunnel_gw: @common.Hash::sha256(b"off-gw"), + tunnel_id: 999U, + end_date_sec: 1700000600U, + }, + ], + signature: b"", + } + let signed = ls2.sign_with_transient_ed25519(transient_seed) + assert_eq(signed.verify_signature(), true) + + let decoded = @common.LeaseSet2::decode( + @encoding.Reader::new(signed.to_bytes()), + ) + assert_eq(decoded, signed) + assert_eq(decoded.verify_signature(), true) + + // Tampering offline signature fails verification + let bad_off : @common.OfflineSignature = { + expires_sec: signed_off.expires_sec + 1U, + transient_sig_type: signed_off.transient_sig_type, + transient_pub_key: signed_off.transient_pub_key, + signature: signed_off.signature, + } + let bad_ls2 : @common.LeaseSet2 = { + destination: decoded.destination, + published_sec: decoded.published_sec, + expires_offset: decoded.expires_offset, + flags: decoded.flags, + offline_sig: Some(bad_off), + options: decoded.options, + encryption_keys: decoded.encryption_keys, + leases: decoded.leases, + signature: decoded.signature, + } + assert_eq(bad_ls2.verify_signature(), false) +} + +///| +test "SU3 reseed bundle decodes and verifies embedded RouterInfo" { + let ed_seed = Bytes::make(32, b'\x41') + let ed_pub = @crypto.ed25519_public_key(ed_seed) + let x_pub = @crypto.x25519_public_key(Bytes::make(32, b'\x42')) + let id = @common.RouterIdentity::new_x25519_ed25519(x_pub, ed_pub) + let ri : @common.RouterInfo = { + identity: id, + published: 1700000000000UL, + addresses: [], + options: @common.Mapping::from_entries([("caps", "XfR"), ("netId", "2")]), + signature: b"", + } + let signed_ri = ri.sign_ed25519(ed_seed) + let zip = build_stored_zip([ + ("routerInfo-\{id.hash().to_base64()}.dat", signed_ri.to_bytes()), + ]) + + let ver = b"1700000000000000" + let signer = b"test@mail.i2p" + let sig = Bytes::make(64, b'\xaa') + let w = @encoding.Writer::new() + w.write_bytes(b"I2Psu3") + w.write_u8(b'\x00') + w.write_u8(b'\x00') + w.write_u16_be(8U) // Ed25519ph + w.write_u16_be(sig.length().reinterpret_as_uint()) + w.write_u8(b'\x00') + w.write_u8(ver.length().to_byte()) + w.write_u8(b'\x00') + w.write_u8(signer.length().to_byte()) + w.write_u64_be(zip.length().to_uint64()) + w.write_u8(b'\x00') + w.write_u8(b'\x00') // ZIP + w.write_u8(b'\x00') + w.write_u8(b'\x03') // Reseed + for _i = 0; _i < 12; _i = _i + 1 { + w.write_u8(b'\x00') + } + w.write_bytes(ver) + w.write_bytes(signer) + w.write_bytes(zip) + w.write_bytes(sig) + + let peers = @common.parse_reseed_su3(w.to_bytes()) + assert_eq(peers.length(), 1) + assert_eq(peers[0], signed_ri) +} diff --git a/common/pkg.generated.mbti b/common/pkg.generated.mbti index 41e3199..2325451 100644 --- a/common/pkg.generated.mbti +++ b/common/pkg.generated.mbti @@ -8,6 +8,7 @@ import { } // Values +pub fn parse_reseed_su3(Bytes) -> Array[RouterInfo] raise CommonError // Errors #derive(Eq, @debug.Debug) @@ -121,6 +122,7 @@ pub(all) struct LeaseSet2 { published_sec : UInt32 expires_offset : UInt32 flags : UInt32 + offline_sig : OfflineSignature? options : Mapping encryption_keys : Array[LeaseSet2EncryptionKey] leases : Array[Lease2] @@ -129,6 +131,7 @@ pub(all) struct LeaseSet2 { pub fn LeaseSet2::decode(@encoding.Reader) -> Self raise CommonError pub fn LeaseSet2::encode(Self, @encoding.Writer) -> Unit raise CommonError pub fn LeaseSet2::sign_ed25519(Self, Bytes) -> Self raise CommonError +pub fn LeaseSet2::sign_with_transient_ed25519(Self, Bytes) -> Self raise CommonError pub fn LeaseSet2::signing_bytes(Self) -> Bytes raise CommonError pub fn LeaseSet2::to_bytes(Self) -> Bytes raise CommonError pub fn LeaseSet2::unsigned_bytes(Self) -> Bytes raise CommonError @@ -152,6 +155,19 @@ pub fn Mapping::length(Self) -> Int32 pub fn Mapping::new() -> Self pub fn Mapping::set(Self, String, String) -> Unit +#derive(Eq, @debug.Debug) +pub(all) struct OfflineSignature { + expires_sec : UInt32 + transient_sig_type : SigningPublicKeyType + transient_pub_key : Bytes + signature : Bytes +} +pub fn OfflineSignature::decode(@encoding.Reader, SigningPublicKeyType) -> Self raise CommonError +pub fn OfflineSignature::encode(Self, @encoding.Writer) -> Unit +pub fn OfflineSignature::sign_ed25519(Self, Bytes) -> Self raise CommonError +pub fn OfflineSignature::unsigned_bytes(Self) -> Bytes +pub fn OfflineSignature::verify_ed25519(Self, Bytes) -> Bool + #derive(Eq, @debug.Debug) pub(all) struct RouterAddress { cost : Byte @@ -224,6 +240,20 @@ pub fn SigningPublicKeyType::public_key_length(Self) -> Int32 pub fn SigningPublicKeyType::signature_length(Self) -> Int32 pub fn SigningPublicKeyType::to_u16(Self) -> UInt32 +#derive(Eq, @debug.Debug) +pub(all) struct Su3File { + format_version : Byte + sig_type : UInt32 + version : String + signer_id : String + file_type : Byte + content_type : Byte + content : Bytes + signature : Bytes + signed_bytes_len : Int32 +} +pub fn Su3File::decode(Bytes) -> Self raise CommonError + // Type aliases // Traits diff --git a/common/router_info.mbt b/common/router_info.mbt index 208ceb0..5db15a1 100644 --- a/common/router_info.mbt +++ b/common/router_info.mbt @@ -206,6 +206,94 @@ pub(all) struct LeaseSet2EncryptionKey { key_data : Bytes } +///| +/// Offline signature block inside a `LeaseSet2` (Proposal 123, `flags & 1 != 0`): +/// allows a transient signing key to sign the LeaseSet2 while the Destination's +/// long-term signing key stays offline. +#derive(Eq, Debug) +pub(all) struct OfflineSignature { + expires_sec : UInt32 + transient_sig_type : SigningPublicKeyType + transient_pub_key : Bytes + signature : Bytes +} + +///| +pub fn OfflineSignature::unsigned_bytes(self : OfflineSignature) -> Bytes { + let w = @encoding.Writer::new(capacity=6 + self.transient_pub_key.length()) + w.write_u32_be(self.expires_sec) + w.write_u16_be(self.transient_sig_type.to_u16()) + w.write_bytes(self.transient_pub_key) + w.to_bytes() +} + +///| +pub fn OfflineSignature::encode( + self : OfflineSignature, + w : @encoding.Writer, +) -> Unit { + w.write_bytes(self.unsigned_bytes()) + w.write_bytes(self.signature) +} + +///| +pub fn OfflineSignature::decode( + r : @encoding.Reader, + dest_sig_type : SigningPublicKeyType, +) -> OfflineSignature raise CommonError { + let expires_sec = r.read_u32_be() catch { e => raise Encoding(e) } + let transient_sig_type = SigningPublicKeyType::from_u16( + r.read_u16_be() catch { + e => raise Encoding(e) + }, + ) + let tkey_len = transient_sig_type.public_key_length() + if tkey_len <= 0 { + raise InvalidFormat( + "unsupported transient signing type in OfflineSignature", + ) + } + let transient_pub_key = r.read_bytes(tkey_len) catch { + e => raise Encoding(e) + } + let dsig_len = dest_sig_type.signature_length() + if dsig_len <= 0 { + raise InvalidFormat( + "unsupported destination signing type in OfflineSignature", + ) + } + let signature = r.read_bytes(dsig_len) catch { e => raise Encoding(e) } + { expires_sec, transient_sig_type, transient_pub_key, signature, } +} + +///| +pub fn OfflineSignature::sign_ed25519( + self : OfflineSignature, + dest_seed : Bytes, +) -> OfflineSignature raise CommonError { + let sig = @crypto.ed25519_sign(dest_seed, self.unsigned_bytes()) catch { + e => raise Crypto(e) + } + { + expires_sec: self.expires_sec, + transient_sig_type: self.transient_sig_type, + transient_pub_key: self.transient_pub_key, + signature: sig, + } +} + +///| +pub fn OfflineSignature::verify_ed25519( + self : OfflineSignature, + dest_signing_pub : Bytes, +) -> Bool { + @crypto.ed25519_verify( + dest_signing_pub, + self.unsigned_bytes(), + self.signature, + ) +} + ///| /// Modern LeaseSet2 (I2P Proposal 123, NetDB type 3). #derive(Eq, Debug) @@ -213,7 +301,8 @@ pub(all) struct LeaseSet2 { destination : Destination published_sec : UInt32 expires_offset : UInt32 // uint16 offset in seconds from published_sec - flags : UInt32 // uint16 + flags : UInt32 // uint16 (bit 0 = offline keys present) + offline_sig : OfflineSignature? options : Mapping encryption_keys : Array[LeaseSet2EncryptionKey] leases : Array[Lease2] @@ -228,6 +317,15 @@ pub fn LeaseSet2::unsigned_bytes(self : LeaseSet2) -> Bytes raise CommonError { w.write_u32_be(self.published_sec) w.write_u16_be(self.expires_offset) w.write_u16_be(self.flags) + if (self.flags & 0x0001U) != 0U { + match self.offline_sig { + Some(os) => os.encode(w) + None => + raise InvalidFormat( + "LeaseSet2 offline signature flag set without offline_sig", + ) + } + } self.options.encode(w) w.write_u8(self.encryption_keys.length().to_byte()) for ek in self.encryption_keys { @@ -289,6 +387,7 @@ pub fn LeaseSet2::sign_ed25519( published_sec: self.published_sec, expires_offset: self.expires_offset, flags: self.flags, + offline_sig: self.offline_sig, options: self.options, encryption_keys: self.encryption_keys, leases: self.leases, @@ -297,17 +396,68 @@ pub fn LeaseSet2::sign_ed25519( } ///| -/// Verifies the `LeaseSet2` Ed25519 signature against `self.destination.inner.signing_public_key()`. +/// Signs a `LeaseSet2` that carries an `OfflineSignature` (`flags & 1 != 0`) +/// using the transient Ed25519 signing seed. +pub fn LeaseSet2::sign_with_transient_ed25519( + self : LeaseSet2, + transient_seed : Bytes, +) -> LeaseSet2 raise CommonError { + if (self.flags & 0x0001U) == 0U { + raise InvalidFormat("LeaseSet2 offline signature flag (bit 0) must be set") + } + match self.offline_sig { + Some(os) => + if os.transient_sig_type != EdDsaSha512Ed25519 { + raise InvalidFormat( + "LeaseSet2 transient signing type must be EdDsaSha512Ed25519", + ) + } + None => raise InvalidFormat("LeaseSet2 offline_sig is missing") + } + let to_sign = self.signing_bytes() + let signature = @crypto.ed25519_sign(transient_seed, to_sign) catch { + e => raise Crypto(e) + } + { + destination: self.destination, + published_sec: self.published_sec, + expires_offset: self.expires_offset, + flags: self.flags, + offline_sig: self.offline_sig, + options: self.options, + encryption_keys: self.encryption_keys, + leases: self.leases, + signature, + } +} + +///| +/// Verifies the `LeaseSet2` Ed25519 signature (including any `OfflineSignature` chain). pub fn LeaseSet2::verify_signature(self : LeaseSet2) -> Bool { if self.destination.inner.signing_type() != EdDsaSha512Ed25519 { return false } let to_sign = self.signing_bytes() catch { _ => return false } - @crypto.ed25519_verify( - self.destination.inner.signing_public_key(), - to_sign, - self.signature, - ) + if (self.flags & 0x0001U) != 0U { + match self.offline_sig { + Some(os) => { + if os.transient_sig_type != EdDsaSha512Ed25519 { + return false + } + if !os.verify_ed25519(self.destination.inner.signing_public_key()) { + return false + } + @crypto.ed25519_verify(os.transient_pub_key, to_sign, self.signature) + } + None => false + } + } else { + @crypto.ed25519_verify( + self.destination.inner.signing_public_key(), + to_sign, + self.signature, + ) + } } ///| @@ -316,6 +466,11 @@ pub fn LeaseSet2::decode(r : @encoding.Reader) -> LeaseSet2 raise CommonError { let published_sec = r.read_u32_be() catch { e => raise Encoding(e) } let expires_offset = r.read_u16_be() catch { e => raise Encoding(e) } let flags = r.read_u16_be() catch { e => raise Encoding(e) } + let offline_sig = if (flags & 0x0001U) != 0U { + Some(OfflineSignature::decode(r, destination.inner.signing_type())) + } else { + None + } let options = Mapping::decode(r) let key_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int() let encryption_keys : Array[LeaseSet2EncryptionKey] = Array( @@ -336,7 +491,10 @@ pub fn LeaseSet2::decode(r : @encoding.Reader) -> LeaseSet2 raise CommonError { for _i = 0; _i < lease_count; _i = _i + 1 { leases.push(Lease2::decode(r)) } - let sig_len = destination.inner.signing_type().signature_length() + let sig_len = match offline_sig { + Some(os) => os.transient_sig_type.signature_length() + None => destination.inner.signing_type().signature_length() + } let signature = if sig_len > 0 { r.read_bytes(sig_len) catch { e => raise Encoding(e) @@ -349,6 +507,7 @@ pub fn LeaseSet2::decode(r : @encoding.Reader) -> LeaseSet2 raise CommonError { published_sec, expires_offset, flags, + offline_sig, options, encryption_keys, leases, diff --git a/common/su3.mbt b/common/su3.mbt new file mode 100644 index 0000000..853b7fc --- /dev/null +++ b/common/su3.mbt @@ -0,0 +1,118 @@ +///| +/// I2P SU3 signed container parser & reseed bundle (`i2pseeds.su3`) extractor. + +///| +#derive(Eq, Debug) +pub(all) struct Su3File { + format_version : Byte + sig_type : UInt32 + version : String + signer_id : String + file_type : Byte // 0 = ZIP, 1 = XML, 2 = HTML, 3 = XML.GZ + content_type : Byte // 1 = router update, 2 = plugin, 3 = reseed, 4 = news, 5 = blocklist + content : Bytes + signature : Bytes + signed_bytes_len : Int32 +} + +///| +/// Decodes an I2P SU3 file header, payload content, and trailing signature. +pub fn Su3File::decode(data : Bytes) -> Su3File raise CommonError { + if data.length() < 40 { + raise InvalidLength("SU3 file shorter than 40 bytes: \{data.length()}") + } + if data[0] != b'\x49' || + data[1] != b'\x32' || + data[2] != b'\x50' || + data[3] != b'\x73' || + data[4] != b'\x75' || + data[5] != b'\x33' { + raise InvalidFormat("invalid SU3 magic header (expected 'I2Psu3')") + } + let r = @encoding.Reader::new(data) + r.skip(6) catch { + e => raise Encoding(e) + } + let _unused6 = r.read_u8() catch { e => raise Encoding(e) } + let format_version = r.read_u8() catch { e => raise Encoding(e) } + if format_version != b'\x00' { + raise InvalidFormat( + "unsupported SU3 format version: \{format_version.to_int()}", + ) + } + let sig_type = r.read_u16_be() catch { e => raise Encoding(e) } + let sig_len = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let _unused12 = r.read_u8() catch { e => raise Encoding(e) } + let version_len = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let _unused14 = r.read_u8() catch { e => raise Encoding(e) } + let signer_id_len = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let content_len_u64 = r.read_u64_be() catch { e => raise Encoding(e) } + if content_len_u64 > 64UL * 1024UL * 1024UL { + raise InvalidLength("SU3 content length too large") + } + let content_len = content_len_u64.to_int() + let _unused24 = r.read_u8() catch { e => raise Encoding(e) } + let file_type = r.read_u8() catch { e => raise Encoding(e) } + let _unused26 = r.read_u8() catch { e => raise Encoding(e) } + let content_type = r.read_u8() catch { e => raise Encoding(e) } + r.skip(12) catch { + e => raise Encoding(e) + } + let version_bytes = r.read_bytes(version_len) catch { e => raise Encoding(e) } + let version = @encoding.utf8_bytes_to_string(version_bytes) catch { + e => raise Encoding(e) + } + let signer_bytes = r.read_bytes(signer_id_len) catch { + e => raise Encoding(e) + } + let signer_id = @encoding.utf8_bytes_to_string(signer_bytes) catch { + e => raise Encoding(e) + } + let content = r.read_bytes(content_len) catch { e => raise Encoding(e) } + let signed_bytes_len = r.position() + let signature = r.read_bytes(sig_len) catch { e => raise Encoding(e) } + { + format_version, + sig_type, + version, + signer_id, + file_type, + content_type, + content, + signature, + signed_bytes_len, + } +} + +///| +/// Extracts and Ed25519-verifies all `routerInfo-*.dat` entries from an I2P reseed `.su3` file. +pub fn parse_reseed_su3(data : Bytes) -> Array[RouterInfo] raise CommonError { + let su3 = Su3File::decode(data) + if su3.file_type != b'\x00' { + raise InvalidFormat( + "reseed SU3 must contain a ZIP file (type 0), got \{su3.file_type.to_int()}", + ) + } + if su3.content_type != b'\x03' { + raise InvalidFormat( + "reseed SU3 must have content type 3, got \{su3.content_type.to_int()}", + ) + } + let files = @encoding.zip_extract_entries(su3.content) catch { + e => raise Encoding(e) + } + let peers : Array[RouterInfo] = [] + for item in files { + let (name, raw) = item + if !name.has_suffix(".dat") { + continue + } + let ri = RouterInfo::decode(@encoding.Reader::new(raw)) catch { + _ => continue + } + if ri.verify_signature() { + peers.push(ri) + } + } + peers +} diff --git a/crypto/crypto_test.mbt b/crypto/crypto_test.mbt index ef6db74..fab221a 100644 --- a/crypto/crypto_test.mbt +++ b/crypto/crypto_test.mbt @@ -238,3 +238,51 @@ test "aes256 FIPS-197 Appendix C.3 and SP 800-38A CBC vectors" { assert_eq(ct2, expected_ct2) assert_eq(@crypto.aes256_cbc_decrypt(key2, iv2, ct2), pt2) } + +///| +test "curve25519 elligator2 encode/decode reference vectors and properties" { + // Reference vector cross-checked with Python F_p implementation + let priv_key = @encoding.hex_decode( + "dd8464b2cad5dc7381309cc5d57c9d421a58b7a0648eedb387543a594c1988ac", + ) + let pub_u = @crypto.x25519_public_key(priv_key) + assert_eq( + @encoding.hex_encode(pub_u), + "85d7ef41e7a6ded4d12312f796c30183a6325a56b734ae7fd19e416b7a47196b", + ) + let rf = match @crypto.elligator2_encode(pub_u, high_bits=b'\xc0') { + Some(r) => r + None => fail("expected Elligator2 encode to succeed") + } + assert_eq( + @encoding.hex_encode(rf), + "0da9aad9ab2472b3d50db797d9d880adcb5c2440ed0db37eb30076f208ab23c2", + ) + assert_eq(@crypto.elligator2_decode(rf), pub_u) + + let rt = match + @crypto.elligator2_encode(pub_u, high_bits=b'\x80', tweak_sign=true) { + Some(r) => r + None => fail("expected Elligator2 tweaked encode to succeed") + } + assert_eq( + @encoding.hex_encode(rt), + "631c48beab8932fafe3e39ee45099a29e8a461c08bdfb037baf33ac61d42a090", + ) + assert_eq(@crypto.elligator2_decode(rt), pub_u) + + // Sweep 40 keys and verify round-trip for every encodable key + let mut encodable_count = 0 + for i = 0; i < 40; i = i + 1 { + let seed = @crypto.sha256(Bytes::make(4, i.to_byte())) + let pk = @crypto.x25519_public_key(seed) + match @crypto.elligator2_encode(pk, high_bits=b'\xc0') { + Some(rep) => { + encodable_count += 1 + assert_eq(@crypto.elligator2_decode(rep), pk) + } + None => () + } + } + assert_true(encodable_count >= 10) +} diff --git a/crypto/elligator2.mbt b/crypto/elligator2.mbt new file mode 100644 index 0000000..c7ec444 --- /dev/null +++ b/crypto/elligator2.mbt @@ -0,0 +1,158 @@ +///| +/// Pure-MoonBit Curve25519 Elligator2 point encoding & decoding (I2P Proposal 144). +/// Maps uniformly random-looking 32-byte representatives (with random high 2 bits) +/// to/from Montgomery Curve25519 u-coordinates (`v^2 = u^3 + 486662*u^2 + u mod 2^255-19`). + +///| +/// Curve parameter A = 486662 = 0x76d06 in 16-bit limbs. +fn gf_a() -> FixedArray[Int64] { + let a = gf_zero() + a[0] = 0x6d06L + a[1] = 0x0007L + a +} + +///| +/// Constant-time zero check on a field element after canonical `gf_pack`. +fn gf_is_zero(w : FixedArray[Int64]) -> Bool { + ct_eq(gf_pack(w), Bytes::make(32, b'\x00')) +} + +///| +/// Computes a square root of `w` modulo `2^255 - 19`, or returns `None` if non-square. +fn gf_sqrt_opt(w : FixedArray[Int64]) -> FixedArray[Int64]? { + if gf_is_zero(w) { + return Some(gf_zero()) + } + let x = gf_mul(w, gf_pow2523(w)) + let x2_packed = gf_pack(gf_sq(x)) + let w_packed = gf_pack(w) + if ct_eq(x2_packed, w_packed) { + return Some(x) + } + let neg_w_packed = gf_pack(gf_sub(gf_zero(), w)) + if ct_eq(x2_packed, neg_w_packed) { + return Some(gf_mul(x, ed_sqrt_m1())) + } + None +} + +///| +fn gf_is_square(w : FixedArray[Int64]) -> Bool { + gf_sqrt_opt(w) is Some(_) +} + +///| +/// Canonical `(p - 1) / 2 = 2^254 - 10` in little-endian bytes for selecting +/// the principal non-negative square root `0 <= r <= (p - 1) / 2`. +let half_p_le : FixedArray[Byte] = [ + b'\xf6', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', + b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', + b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', b'\xff', + b'\xff', b'\xff', b'\xff', b'\xff', b'\x3f', +] + +///| +fn gf_canonical_half(r : FixedArray[Int64]) -> FixedArray[Byte] { + let packed = gf_pack(r) + let mut gt = false + for i = 31; i >= 0; i = i - 1 { + let rb = packed[i].to_int() + let hb = half_p_le[i].to_int() + if rb > hb { + gt = true + break + } + if rb < hb { + break + } + } + let chosen = if gt { gf_pack(gf_sub(gf_zero(), r)) } else { packed } + let out = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + out[i] = chosen[i] + } + out +} + +///| +/// Decodes a 32-byte Elligator2 representative (clearing the 2 high padding bits +/// per I2P Proposal 144) into its Curve25519 Montgomery u-coordinate (32 bytes LE). +pub fn elligator2_decode(repr : Bytes) -> Bytes raise CryptoError { + if repr.length() != 32 { + raise InvalidKeyLength( + "Elligator2 representative must be 32 bytes, got \{repr.length()}", + ) + } + let buf = FixedArray::make(32, b'\x00') + for i = 0; i < 32; i = i + 1 { + buf[i] = repr[i] + } + buf[31] = (buf[31].to_int() & 0x3F).to_byte() + let r = gf_unpack(Bytes::from_array(buf)) + let r2 = gf_sq(r) + let two_r2 = gf_add(r2, r2) + let denom = gf_add(gf_one(), two_r2) + if gf_is_zero(denom) { + return Bytes::make(32, b'\x00') + } + let a = gf_a() + let neg_a = gf_sub(gf_zero(), a) + let d = gf_mul(neg_a, gf_inv(denom)) + let d2 = gf_sq(d) + let ad = gf_mul(a, d) + let rhs = gf_mul(d, gf_add(gf_add(d2, ad), gf_one())) + let u = if gf_is_zero(rhs) || gf_is_square(rhs) { + d + } else { + gf_sub(gf_sub(gf_zero(), d), a) + } + gf_pack(u) +} + +///| +/// Attempts to encode a Curve25519 public key `pub_u` into a 32-byte Elligator2 +/// representative with random `high_bits` injected into bits 254..255 (`& 0xC0`). +/// Returns `None` if `pub_u` is not in the image of Elligator2 (~50% of keys). +pub fn elligator2_encode( + pub_u : Bytes, + high_bits~ : Byte = b'\x00', + tweak_sign~ : Bool = false, +) -> Bytes? raise CryptoError { + if pub_u.length() != 32 { + raise InvalidKeyLength( + "Elligator2 public key must be 32 bytes, got \{pub_u.length()}", + ) + } + let u = gf_unpack(pub_u) + let a = gf_a() + if gf_is_zero(u) { + if tweak_sign { + return None + } + let out = FixedArray::make(32, b'\x00') + out[31] = (high_bits.to_int() & 0xC0).to_byte() + return Some(Bytes::from_array(out)) + } + let u_plus_a = gf_add(u, a) + if gf_is_zero(u_plus_a) { + return None + } + let r2 = if !tweak_sign { + let num = gf_sub(gf_zero(), u_plus_a) + let den = gf_add(u, u) + gf_mul(num, gf_inv(den)) + } else { + let num = gf_sub(gf_zero(), u) + let den = gf_add(u_plus_a, u_plus_a) + gf_mul(num, gf_inv(den)) + } + match gf_sqrt_opt(r2) { + None => None + Some(r) => { + let out = gf_canonical_half(r) + out[31] = (out[31].to_int() | (high_bits.to_int() & 0xC0)).to_byte() + Some(Bytes::from_array(out)) + } + } +} diff --git a/crypto/pkg.generated.mbti b/crypto/pkg.generated.mbti index 7cbdaf9..c9f2444 100644 --- a/crypto/pkg.generated.mbti +++ b/crypto/pkg.generated.mbti @@ -30,6 +30,10 @@ pub fn ed25519_sign(Bytes, Bytes) -> Bytes raise CryptoError pub fn ed25519_verify(Bytes, Bytes, Bytes) -> Bool +pub fn elligator2_decode(Bytes) -> Bytes raise CryptoError + +pub fn elligator2_encode(Bytes, high_bits? : Byte, tweak_sign? : Bool) -> Bytes? raise CryptoError + pub fn hkdf(Bytes, Bytes, Bytes, Int32) -> Bytes raise CryptoError pub fn hkdf_expand(Bytes, Bytes, Int32) -> Bytes raise CryptoError diff --git a/encoding/encoding_test.mbt b/encoding/encoding_test.mbt index 20fb8e2..cb5cafa 100644 --- a/encoding/encoding_test.mbt +++ b/encoding/encoding_test.mbt @@ -79,3 +79,46 @@ test "hex encode and decode" { assert_eq(@encoding.hex_encode(raw), "000fa5ff") assert_eq(@encoding.hex_decode("000F a5ff"), raw) } + +///| +test "crc32, gzip dynamic Huffman inflate, deflate/gzip round-trip, I2CP mux, and ZIP extraction" { + // Known-answer dynamic Huffman gzip from Python zlib/gzip (BTYPE=2) + let gz_dyn = @encoding.hex_decode( + "1f8b08000000000000ff85d53b6a03411084e11359a8aaf45a161dc0a923a7c69670a415927c7fcb513185a1266b9a3ffbe8b92d3f8fd3edf5725e5ed6cf77fc5eee8f2326aed62bae305f97db73fcdbcc9f1fd7fbf1fdfc365f4e8fd7af23e7db90624ce9142de598ca295baa31dd38554b3763ba75ba69e9764c774eb72ddd8de9dee9aea5fb313d38ddb7f430a693d3434ba720b1763b9516c9c99ed03c213cc1a0d0402140c1a2d0442144c1a4d0482148c1a6d04c214cc1a8d0502150c1aad0542154c1acd0582158c1aed05c215cd1aed05c315cd1aed85c31ef945db1b962b8a25db1b962b8a25db1b962b8a25db1b962b8a25db1b962b8a25db1b962b8a25db1b962b8a25db1b962b8925db1b952b8925da9b952b8925da9b9527e8076a5e64ae14a76a5e64ae14a76a5e64ae14a76a5e64ae14a76a5e64ae14a76a5e64ae14a76a5e64ae16a6357fac7d52f616a009557090000", + ) + let plain_dyn = @encoding.gzip_decompress(gz_dyn) + assert_eq(plain_dyn.length(), 2391) + assert_true( + @encoding.utf8_bytes_to_string(plain_dyn[:43].to_owned()).has_prefix( + "routerInfo-0000=host=192.0.2.1;port=10000;", + ), + ) + + // Compress & decompress round-trip + I2CP port/protocol multiplexing + let recompressed = @encoding.gzip_compress(plain_dyn) + assert_true(recompressed.length() < plain_dyn.length()) + assert_eq(@encoding.gzip_decompress(recompressed), plain_dyn) + + let i2cp_pkt = @encoding.i2cp_gzip_wrap( + b"GET / HTTP/1.1\r\nHost: stats.i2p\r\n\r\n", + from_port=12345U, + to_port=80U, + protocol=b'\x06', + ) + let (hdr, unwrapped) = @encoding.i2cp_gzip_unwrap(i2cp_pkt) + assert_eq(hdr.from_port, 12345U) + assert_eq(hdr.to_port, 80U) + assert_eq(hdr.protocol, b'\x06') + assert_eq(unwrapped, b"GET / HTTP/1.1\r\nHost: stats.i2p\r\n\r\n") + + // Real Python-generated ZIP archive with STORED ("a.txt") + DEFLATED ("b.dat") entries + let zip_bytes = @encoding.hex_decode( + "504b030414000000000046ae7b5dee81b1340c0000000c00000005000000612e74787473746f7265642d68656c6c6f504b030414000000080046ae7b5d53b7ea5194000000ac03000005000000622e646174f3340a5008ca2f2d492df2cc4bcb575053f0494d2c4e0d4e2d3152484ecccbcfcb4c4ecc5128492d2e512848acccc94f4c5128cf2cc950284a2d484d2cc9cc4b5728c828026a2856f01c3568d4a05183f019c4c0c8c4ccc2cac6cec1c9c5cdc3cbc72f2028242c222a262e2129252d232b27afa0a8a4aca2aaa6aea1a9a5ada3aba76f6068646c626a666e6169656d636b670f00504b0102140314000000000046ae7b5dee81b1340c0000000c000000050000000000000000000000800100000000612e747874504b0102140314000000080046ae7b5d53b7ea5194000000ac03000005000000000000000000000080012f000000622e646174504b0506000000000200020066000000e60000000000", + ) + let zip_entries = @encoding.zip_extract_entries(zip_bytes) + assert_eq(zip_entries.length(), 2) + assert_eq(zip_entries[0], ("a.txt", b"stored-hello")) + assert_eq(zip_entries[1].0, "b.dat") + assert_eq(zip_entries[1].1.length(), 940) + assert_eq(@encoding.crc32(zip_entries[1].1), 0x51eab753U) +} diff --git a/encoding/gzip.mbt b/encoding/gzip.mbt new file mode 100644 index 0000000..fd16802 --- /dev/null +++ b/encoding/gzip.mbt @@ -0,0 +1,781 @@ +///| +/// Pure-MoonBit IEEE CRC-32, RFC 1951 DEFLATE inflate/deflate, RFC 1952 Gzip, +/// I2CP Gzip header (protocol & port multiplexing), and ZIP archive extraction. + +///| +let max_inflate_bytes : Int32 = 8 * 1024 * 1024 + +///| +/// Computes standard IEEE 802.3 CRC-32 (`0xEDB88320` reflected polynomial). +pub fn crc32(data : Bytes) -> UInt32 { + let mut crc = 0xFFFFFFFFU + for i = 0; i < data.length(); i = i + 1 { + crc = crc ^ data[i].to_uint() + for _bit = 0; _bit < 8; _bit = _bit + 1 { + if (crc & 1U) != 0U { + crc = (crc >> 1) ^ 0xEDB88320U + } else { + crc = crc >> 1 + } + } + } + crc ^ 0xFFFFFFFFU +} + +///| +fn read_u16_le_bytes(data : Bytes, pos : Int32) -> UInt32 { + data[pos].to_uint() | (data[pos + 1].to_uint() << 8) +} + +///| +fn read_u32_le_bytes(data : Bytes, pos : Int32) -> UInt32 { + data[pos].to_uint() | + (data[pos + 1].to_uint() << 8) | + (data[pos + 2].to_uint() << 16) | + (data[pos + 3].to_uint() << 24) +} + +///| +fn push_u16_le(out : Array[Byte], v : UInt32) -> Unit { + out.push((v & 0xFFU).to_byte()) + out.push(((v >> 8) & 0xFFU).to_byte()) +} + +///| +fn push_u32_le(out : Array[Byte], v : UInt32) -> Unit { + out.push((v & 0xFFU).to_byte()) + out.push(((v >> 8) & 0xFFU).to_byte()) + out.push(((v >> 16) & 0xFFU).to_byte()) + out.push(((v >> 24) & 0xFFU).to_byte()) +} + +///| +priv struct BitReader { + data : Bytes + mut byte_pos : Int32 + mut bit_buf : UInt32 + mut bit_count : Int32 +} + +///| +fn BitReader::new(data : Bytes, start_pos : Int32) -> BitReader { + { data, byte_pos: start_pos, bit_buf: 0U, bit_count: 0, } +} + +///| +fn BitReader::ensure(self : BitReader, n : Int32) -> Unit raise EncodingError { + while self.bit_count < n { + if self.byte_pos >= self.data.length() { + raise UnexpectedEof("DEFLATE unexpected end of input stream") + } + self.bit_buf = self.bit_buf | + (self.data[self.byte_pos].to_uint() << self.bit_count) + self.byte_pos += 1 + self.bit_count += 8 + } +} + +///| +fn BitReader::read_bits( + self : BitReader, + n : Int32, +) -> UInt32 raise EncodingError { + if n == 0 { + return 0U + } + self.ensure(n) + let mask = if n >= 32 { 0xFFFFFFFFU } else { (1U << n) - 1U } + let val = self.bit_buf & mask + self.bit_buf = self.bit_buf >> n + self.bit_count -= n + val +} + +///| +fn BitReader::align_byte(self : BitReader) -> Int32 { + let discard = self.bit_count & 7 + self.bit_buf = self.bit_buf >> discard + self.bit_count -= discard + let unread_bytes = self.bit_count / 8 + self.byte_pos -= unread_bytes + self.bit_buf = 0U + self.bit_count = 0 + self.byte_pos +} + +///| +priv struct HuffTable { + counts : FixedArray[Int32] + symbols : FixedArray[Int32] +} + +///| +fn HuffTable::build(lengths : Array[Int32]) -> HuffTable raise EncodingError { + let counts = FixedArray::make(16, 0) + for len in lengths { + if len < 0 || len > 15 { + raise InvalidCharacter("invalid Huffman code length: \{len}") + } + counts[len] += 1 + } + if counts[0] == lengths.length() { + return { counts, symbols: FixedArray::make(0, 0), } + } + let mut left = 1 + for len = 1; len <= 15; len = len + 1 { + left = (left << 1) - counts[len] + if left < 0 { + raise InvalidCharacter("oversubscribed Huffman tree") + } + } + let offsets = FixedArray::make(16, 0) + let mut total = 0 + for len = 1; len <= 15; len = len + 1 { + offsets[len] = total + total += counts[len] + } + let symbols = FixedArray::make(total, 0) + for sym = 0; sym < lengths.length(); sym = sym + 1 { + let len = lengths[sym] + if len != 0 { + symbols[offsets[len]] = sym + offsets[len] += 1 + } + } + { counts, symbols, } +} + +///| +fn HuffTable::decode( + self : HuffTable, + br : BitReader, +) -> Int32 raise EncodingError { + let mut code = 0 + let mut first = 0 + let mut index = 0 + for len = 1; len <= 15; len = len + 1 { + code = code | br.read_bits(1).reinterpret_as_int() + let count = self.counts[len] + if code < first + count { + return self.symbols[index + (code - first)] + } + index += count + first = (first + count) << 1 + code = code << 1 + } + raise InvalidCharacter("invalid Huffman symbol code") +} + +///| +let cl_order : FixedArray[Int32] = [ + 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15, +] + +///| +let len_bases : FixedArray[Int32] = [ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, + 99, 115, 131, 163, 195, 227, 258, +] + +///| +let len_extra : FixedArray[Int32] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, + 5, 0, +] + +///| +let dist_bases : FixedArray[Int32] = [ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, + 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, +] + +///| +let dist_extra : FixedArray[Int32] = [ + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, + 12, 12, 13, 13, +] + +///| +fn fixed_lit_table() -> HuffTable raise EncodingError { + let lens : Array[Int32] = [] + for i = 0; i <= 143; i = i + 1 { + lens.push(8) + } + for i = 144; i <= 255; i = i + 1 { + lens.push(9) + } + for i = 256; i <= 279; i = i + 1 { + lens.push(7) + } + for i = 280; i <= 287; i = i + 1 { + lens.push(8) + } + HuffTable::build(lens) +} + +///| +fn fixed_dist_table() -> HuffTable raise EncodingError { + let lens : Array[Int32] = [] + for i = 0; i < 32; i = i + 1 { + lens.push(5) + } + HuffTable::build(lens) +} + +///| +fn decode_dynamic_tables( + br : BitReader, +) -> (HuffTable, HuffTable) raise EncodingError { + let hlit = br.read_bits(5).reinterpret_as_int() + 257 + let hdist = br.read_bits(5).reinterpret_as_int() + 1 + let hclen = br.read_bits(4).reinterpret_as_int() + 4 + let cl_lens : Array[Int32] = [] + for _i = 0; _i < 19; _i = _i + 1 { + cl_lens.push(0) + } + for i = 0; i < hclen; i = i + 1 { + cl_lens[cl_order[i]] = br.read_bits(3).reinterpret_as_int() + } + let cl_table = HuffTable::build(cl_lens) + let total = hlit + hdist + let all_lens : Array[Int32] = [] + while all_lens.length() < total { + let sym = cl_table.decode(br) + if sym < 16 { + all_lens.push(sym) + } else if sym == 16 { + if all_lens.length() == 0 { + raise InvalidCharacter("DEFLATE repeat code 16 at start of lengths") + } + let prev = all_lens[all_lens.length() - 1] + let rep = 3 + br.read_bits(2).reinterpret_as_int() + for _k = 0; _k < rep; _k = _k + 1 { + all_lens.push(prev) + } + } else if sym == 17 { + let rep = 3 + br.read_bits(3).reinterpret_as_int() + for _k = 0; _k < rep; _k = _k + 1 { + all_lens.push(0) + } + } else if sym == 18 { + let rep = 11 + br.read_bits(7).reinterpret_as_int() + for _k = 0; _k < rep; _k = _k + 1 { + all_lens.push(0) + } + } else { + raise InvalidCharacter("invalid dynamic code-length symbol: \{sym}") + } + } + if all_lens.length() != total { + raise InvalidLength("DEFLATE dynamic code lengths exceeded hlit+hdist") + } + let lit_lens : Array[Int32] = [] + for i = 0; i < hlit; i = i + 1 { + lit_lens.push(all_lens[i]) + } + let dist_lens : Array[Int32] = [] + for i = hlit; i < total; i = i + 1 { + dist_lens.push(all_lens[i]) + } + (HuffTable::build(lit_lens), HuffTable::build(dist_lens)) +} + +///| +fn inflate_huffman_block( + br : BitReader, + lit_table : HuffTable, + dist_table : HuffTable, + out : Array[Byte], +) -> Unit raise EncodingError { + while true { + let sym = lit_table.decode(br) + if sym < 256 { + if out.length() >= max_inflate_bytes { + raise ValueOutOfRange("DEFLATE output exceeded max allowed size") + } + out.push(sym.to_byte()) + } else if sym == 256 { + break + } else { + let lidx = sym - 257 + if lidx < 0 || lidx >= 29 { + raise InvalidCharacter("invalid DEFLATE length symbol: \{sym}") + } + let extra_l = len_extra[lidx] + let length = len_bases[lidx] + br.read_bits(extra_l).reinterpret_as_int() + let dsym = dist_table.decode(br) + if dsym < 0 || dsym >= 30 { + raise InvalidCharacter("invalid DEFLATE distance symbol: \{dsym}") + } + let extra_d = dist_extra[dsym] + let dist = dist_bases[dsym] + br.read_bits(extra_d).reinterpret_as_int() + if dist <= 0 || dist > out.length() { + raise InvalidLength( + "DEFLATE back-reference distance \{dist} exceeds output \{out.length()}", + ) + } + if out.length() + length > max_inflate_bytes { + raise ValueOutOfRange("DEFLATE output exceeded max allowed size") + } + for _i = 0; _i < length; _i = _i + 1 { + let b = out[out.length() - dist] + out.push(b) + } + } + } +} + +///| +fn inflate_raw_from( + data : Bytes, + start_pos : Int32, +) -> (Bytes, Int32) raise EncodingError { + let br = BitReader::new(data, start_pos) + let out : Array[Byte] = [] + let fixed_lit = fixed_lit_table() + let fixed_dist = fixed_dist_table() + while true { + let bfinal = br.read_bits(1) + let btype = br.read_bits(2) + if btype == 0U { + let pos = br.align_byte() + if pos + 4 > data.length() { + raise UnexpectedEof("DEFLATE stored block header truncated") + } + let len = read_u16_le_bytes(data, pos) + let nlen = read_u16_le_bytes(data, pos + 2) + if (len ^ 0xFFFFU) != nlen { + raise InvalidCharacter("DEFLATE stored block len/nlen mismatch") + } + let len_i = len.reinterpret_as_int() + if pos + 4 + len_i > data.length() { + raise UnexpectedEof("DEFLATE stored block payload truncated") + } + if out.length() + len_i > max_inflate_bytes { + raise ValueOutOfRange("DEFLATE output exceeded max allowed size") + } + for i = 0; i < len_i; i = i + 1 { + out.push(data[pos + 4 + i]) + } + br.byte_pos = pos + 4 + len_i + } else if btype == 1U { + inflate_huffman_block(br, fixed_lit, fixed_dist, out) + } else if btype == 2U { + let (dyn_lit, dyn_dist) = decode_dynamic_tables(br) + inflate_huffman_block(br, dyn_lit, dyn_dist, out) + } else { + raise InvalidCharacter("invalid DEFLATE block type: 3") + } + if bfinal == 1U { + break + } + } + let end_pos = br.align_byte() + (Bytes::from_array(out), end_pos) +} + +///| +/// Decompresses an RFC 1951 raw DEFLATE stream. +pub fn inflate_raw(data : Bytes) -> Bytes raise EncodingError { + let (out, _end) = inflate_raw_from(data, 0) + out +} + +///| +priv struct BitWriter { + out : Array[Byte] + mut bit_buf : UInt32 + mut bit_count : Int32 +} + +///| +fn BitWriter::new() -> BitWriter { + { out: [], bit_buf: 0U, bit_count: 0, } +} + +///| +fn BitWriter::write_bits(self : BitWriter, val : UInt32, n : Int32) -> Unit { + if n == 0 { + return + } + self.bit_buf = self.bit_buf | ((val & ((1U << n) - 1U)) << self.bit_count) + self.bit_count += n + while self.bit_count >= 8 { + self.out.push((self.bit_buf & 0xFFU).to_byte()) + self.bit_buf = self.bit_buf >> 8 + self.bit_count -= 8 + } +} + +///| +fn BitWriter::write_huff_msb( + self : BitWriter, + code : UInt32, + nbits : Int32, +) -> Unit { + for i = nbits - 1; i >= 0; i = i - 1 { + self.write_bits((code >> i) & 1U, 1) + } +} + +///| +fn BitWriter::finish(self : BitWriter) -> Bytes { + if self.bit_count > 0 { + self.out.push((self.bit_buf & 0xFFU).to_byte()) + self.bit_buf = 0U + self.bit_count = 0 + } + Bytes::from_array(self.out) +} + +///| +fn write_fixed_literal(bw : BitWriter, sym : Int32) -> Unit { + if sym <= 143 { + bw.write_huff_msb((48 + sym).reinterpret_as_uint(), 8) + } else if sym <= 255 { + bw.write_huff_msb((400 + (sym - 144)).reinterpret_as_uint(), 9) + } else if sym <= 279 { + bw.write_huff_msb((sym - 256).reinterpret_as_uint(), 7) + } else { + bw.write_huff_msb((192 + (sym - 280)).reinterpret_as_uint(), 8) + } +} + +///| +fn write_fixed_match(bw : BitWriter, length : Int32, dist : Int32) -> Unit { + // Find length code 257..285 + let mut lidx = 28 + for i = 0; i < 29; i = i + 1 { + let base = len_bases[i] + let max_v = if i == 28 { 258 } else { len_bases[i + 1] - 1 } + if length >= base && length <= max_v { + lidx = i + break + } + } + write_fixed_literal(bw, 257 + lidx) + let lex = len_extra[lidx] + if lex > 0 { + bw.write_bits((length - len_bases[lidx]).reinterpret_as_uint(), lex) + } + // Find distance code 0..29 + let mut didx = 29 + for i = 0; i < 30; i = i + 1 { + let base = dist_bases[i] + let max_v = if i == 29 { 32768 } else { dist_bases[i + 1] - 1 } + if dist >= base && dist <= max_v { + didx = i + break + } + } + bw.write_huff_msb(didx.reinterpret_as_uint(), 5) + let dex = dist_extra[didx] + if dex > 0 { + bw.write_bits((dist - dist_bases[didx]).reinterpret_as_uint(), dex) + } +} + +///| +fn deflate_stored(data : Bytes) -> Bytes { + let out : Array[Byte] = [] + if data.length() == 0 { + out.push(b'\x01') + push_u16_le(out, 0U) + push_u16_le(out, 0xFFFFU) + return Bytes::from_array(out) + } + let mut off = 0 + while off < data.length() { + let rem = data.length() - off + let chunk = if rem > 65535 { 65535 } else { rem } + let is_final = off + chunk == data.length() + out.push(if is_final { b'\x01' } else { b'\x00' }) + let len_u = chunk.reinterpret_as_uint() + push_u16_le(out, len_u) + push_u16_le(out, len_u ^ 0xFFFFU) + for i = 0; i < chunk; i = i + 1 { + out.push(data[off + i]) + } + off += chunk + } + Bytes::from_array(out) +} + +///| +/// Compresses `data` as an RFC 1951 DEFLATE stream using fixed-Huffman LZ77 +/// (automatically falling back to stored blocks if incompressible). +pub fn deflate_raw(data : Bytes) -> Bytes { + let len = data.length() + if len < 16 { + return deflate_stored(data) + } + let bw = BitWriter::new() + bw.write_bits(1U, 1) // BFINAL=1 + bw.write_bits(1U, 2) // BTYPE=1 (fixed Huffman) + + let head = FixedArray::make(4096, -1) + let prev = FixedArray::make(len, -1) + let hash3 = fn(pos : Int32) -> Int32 { + let h = ( + (data[pos].to_int() << 8) ^ + (data[pos + 1].to_int() << 4) ^ + data[pos + 2].to_int() + ) & + 0xFFF + h + } + + let mut i = 0 + while i < len { + let mut best_len = 0 + let mut best_dist = 0 + if i + 3 <= len { + let h = hash3(i) + let mut cand = head[h] + prev[i] = cand + head[h] = i + let mut steps = 0 + while cand >= 0 && i - cand <= 32768 && steps < 32 { + let mut mlen = 0 + let max_m = if len - i < 258 { len - i } else { 258 } + while mlen < max_m && data[cand + mlen] == data[i + mlen] { + mlen += 1 + } + if mlen >= 3 && mlen > best_len { + best_len = mlen + best_dist = i - cand + if best_len == 258 { + break + } + } + cand = prev[cand] + steps += 1 + } + } + if best_len >= 3 { + write_fixed_match(bw, best_len, best_dist) + // Insert skipped positions into hash chain for better matches + for k = 1; k < best_len; k = k + 1 { + if i + k + 3 <= len { + let h = hash3(i + k) + prev[i + k] = head[h] + head[h] = i + k + } + } + i += best_len + } else { + write_fixed_literal(bw, data[i].to_int()) + i += 1 + } + } + write_fixed_literal(bw, 256) + let compressed = bw.finish() + let stored = deflate_stored(data) + if compressed.length() <= stored.length() { + compressed + } else { + stored + } +} + +///| +/// Compresses `data` as a standard RFC 1952 Gzip stream. +pub fn gzip_compress(data : Bytes) -> Bytes { + i2cp_gzip_wrap(data, from_port=0U, to_port=0U, protocol=b'\x00') +} + +///| +/// Decompresses a standard RFC 1952 Gzip stream, verifying CRC-32 and ISIZE. +pub fn gzip_decompress(data : Bytes) -> Bytes raise EncodingError { + let (_hdr, body) = i2cp_gzip_unwrap(data) + body +} + +///| +/// I2CP multiplexed Gzip header fields (bytes 4..9 of RFC 1952 Gzip header). +#derive(Eq, Debug) +pub(all) struct I2cpGzipHeader { + from_port : UInt32 + to_port : UInt32 + protocol : Byte +} + +///| +/// Wraps `payload` in an I2CP Gzip envelope with big-endian `from_port` / `to_port` +/// in MTIME (bytes 4..7) and `protocol` in OS (byte 9) (`6` = Streaming, `17` = Repliable Datagram, `18` = Raw Datagram). +pub fn i2cp_gzip_wrap( + payload : Bytes, + from_port~ : UInt32 = 0U, + to_port~ : UInt32 = 0U, + protocol~ : Byte = b'\x06', +) -> Bytes { + let deflated = deflate_raw(payload) + let csum = crc32(payload) + let isize = payload.length().reinterpret_as_uint() + let out : Array[Byte] = [ + b'\x1f', + b'\x8b', + b'\x08', + b'\x00', + ((from_port >> 8) & 0xFFU).to_byte(), + (from_port & 0xFFU).to_byte(), + ((to_port >> 8) & 0xFFU).to_byte(), + (to_port & 0xFFU).to_byte(), + b'\x02', + protocol, + ] + for i = 0; i < deflated.length(); i = i + 1 { + out.push(deflated[i]) + } + push_u32_le(out, csum) + push_u32_le(out, isize) + Bytes::from_array(out) +} + +///| +/// Parses an I2CP or standard RFC 1952 Gzip envelope, verifying header, DEFLATE stream, CRC-32, and ISIZE. +pub fn i2cp_gzip_unwrap( + data : Bytes, +) -> (I2cpGzipHeader, Bytes) raise EncodingError { + if data.length() < 18 { + raise UnexpectedEof("gzip payload shorter than 18 bytes: \{data.length()}") + } + if data[0] != b'\x1f' || data[1] != b'\x8b' || data[2] != b'\x08' { + raise InvalidCharacter("invalid gzip magic/method header") + } + let flg = data[3].to_int() + let from_port = (data[4].to_uint() << 8) | data[5].to_uint() + let to_port = (data[6].to_uint() << 8) | data[7].to_uint() + let protocol = data[9] + let mut pos = 10 + if (flg & 0x04) != 0 { + if pos + 2 > data.length() { + raise UnexpectedEof("gzip FEXTRA truncated") + } + let xlen = read_u16_le_bytes(data, pos).reinterpret_as_int() + pos += 2 + xlen + } + if (flg & 0x08) != 0 { + while pos < data.length() && data[pos] != b'\x00' { + pos += 1 + } + pos += 1 + } + if (flg & 0x10) != 0 { + while pos < data.length() && data[pos] != b'\x00' { + pos += 1 + } + pos += 1 + } + if (flg & 0x02) != 0 { + pos += 2 + } + if pos >= data.length() - 8 { + raise UnexpectedEof("gzip header exceeds total length") + } + let (plain, end_pos) = inflate_raw_from(data, pos) + if end_pos + 8 > data.length() { + raise UnexpectedEof("gzip 8-byte trailer truncated") + } + let expected_crc = read_u32_le_bytes(data, end_pos) + let expected_isize = read_u32_le_bytes(data, end_pos + 4) + let actual_crc = crc32(plain) + if actual_crc != expected_crc { + raise InvalidCharacter("gzip CRC-32 mismatch") + } + if (plain.length().reinterpret_as_uint() & 0xFFFFFFFFU) != expected_isize { + raise InvalidLength("gzip ISIZE mismatch") + } + ({ from_port, to_port, protocol, }, plain) +} + +///| +/// Extracts all `(filename, file_bytes)` entries from a ZIP archive (supports Store=0 and Deflate=8). +pub fn zip_extract_entries( + zip_bytes : Bytes, +) -> Array[(String, Bytes)] raise EncodingError { + let len = zip_bytes.length() + if len < 22 { + raise InvalidLength("ZIP archive shorter than 22 bytes") + } + let min_off = if len > 65557 { len - 65557 } else { 0 } + let mut eocd = -1 + for i = len - 22; i >= min_off; i = i - 1 { + if zip_bytes[i] == b'\x50' && + zip_bytes[i + 1] == b'\x4b' && + zip_bytes[i + 2] == b'\x05' && + zip_bytes[i + 3] == b'\x06' { + eocd = i + break + } + } + if eocd < 0 { + raise InvalidCharacter("ZIP End-of-Central-Directory signature not found") + } + let total_entries = read_u16_le_bytes(zip_bytes, eocd + 10).reinterpret_as_int() + let cd_offset = read_u32_le_bytes(zip_bytes, eocd + 16).reinterpret_as_int() + if cd_offset < 0 || cd_offset > eocd { + raise InvalidLength("ZIP Central Directory offset out of range") + } + let entries : Array[(String, Bytes)] = [] + let mut pos = cd_offset + for _idx = 0; _idx < total_entries; _idx = _idx + 1 { + if pos + 46 > len || + zip_bytes[pos] != b'\x50' || + zip_bytes[pos + 1] != b'\x4b' || + zip_bytes[pos + 2] != b'\x01' || + zip_bytes[pos + 3] != b'\x02' { + raise InvalidCharacter("invalid ZIP Central Directory entry signature") + } + let method_id = read_u16_le_bytes(zip_bytes, pos + 10).reinterpret_as_int() + let expected_crc = read_u32_le_bytes(zip_bytes, pos + 16) + let comp_size = read_u32_le_bytes(zip_bytes, pos + 20).reinterpret_as_int() + let uncomp_size = read_u32_le_bytes(zip_bytes, pos + 24).reinterpret_as_int() + let name_len = read_u16_le_bytes(zip_bytes, pos + 28).reinterpret_as_int() + let extra_len = read_u16_le_bytes(zip_bytes, pos + 30).reinterpret_as_int() + let comment_len = read_u16_le_bytes(zip_bytes, pos + 32).reinterpret_as_int() + let local_off = read_u32_le_bytes(zip_bytes, pos + 42).reinterpret_as_int() + if pos + 46 + name_len + extra_len + comment_len > len { + raise UnexpectedEof("ZIP Central Directory entry truncated") + } + let name_bytes = zip_bytes[pos + 46:pos + 46 + name_len].to_owned() + let name = utf8_bytes_to_string(name_bytes) + pos += 46 + name_len + extra_len + comment_len + + // Skip directory entries + if name.has_suffix("/") { + continue + } + if local_off < 0 || + local_off + 30 > len || + zip_bytes[local_off] != b'\x50' || + zip_bytes[local_off + 1] != b'\x4b' || + zip_bytes[local_off + 2] != b'\x03' || + zip_bytes[local_off + 3] != b'\x04' { + raise InvalidCharacter("invalid ZIP Local File Header") + } + let l_name_len = read_u16_le_bytes(zip_bytes, local_off + 26).reinterpret_as_int() + let l_extra_len = read_u16_le_bytes(zip_bytes, local_off + 28).reinterpret_as_int() + let data_off = local_off + 30 + l_name_len + l_extra_len + if data_off + comp_size > len { + raise UnexpectedEof("ZIP entry data truncated") + } + let comp_data = zip_bytes[data_off:data_off + comp_size].to_owned() + let plain = match method_id { + 0 => comp_data + 8 => inflate_raw(comp_data) + _ => + raise InvalidCharacter( + "unsupported ZIP compression method: \{method_id}", + ) + } + if plain.length() != uncomp_size { + raise InvalidLength("ZIP entry uncompressed size mismatch for \{name}") + } + if crc32(plain) != expected_crc { + raise InvalidCharacter("ZIP entry CRC-32 mismatch for \{name}") + } + entries.push((name, plain)) + } + entries +} diff --git a/encoding/pkg.generated.mbti b/encoding/pkg.generated.mbti index d80b208..dc26d77 100644 --- a/encoding/pkg.generated.mbti +++ b/encoding/pkg.generated.mbti @@ -14,14 +14,30 @@ pub fn base64_decode(String) -> Bytes raise EncodingError pub fn base64_encode(Bytes) -> String +pub fn crc32(Bytes) -> UInt32 + +pub fn deflate_raw(Bytes) -> Bytes + +pub fn gzip_compress(Bytes) -> Bytes + +pub fn gzip_decompress(Bytes) -> Bytes raise EncodingError + pub fn hex_decode(String) -> Bytes raise EncodingError pub fn hex_encode(Bytes) -> String +pub fn i2cp_gzip_unwrap(Bytes) -> (I2cpGzipHeader, Bytes) raise EncodingError + +pub fn i2cp_gzip_wrap(Bytes, from_port? : UInt32, to_port? : UInt32, protocol? : Byte) -> Bytes + +pub fn inflate_raw(Bytes) -> Bytes raise EncodingError + pub fn string_to_utf8_bytes(String) -> Bytes pub fn utf8_bytes_to_string(Bytes) -> String raise EncodingError +pub fn zip_extract_entries(Bytes) -> Array[(String, Bytes)] raise EncodingError + // Errors #derive(Eq, @debug.Debug) pub suberror EncodingError { @@ -32,6 +48,13 @@ pub suberror EncodingError { } // Types and methods +#derive(Eq, @debug.Debug) +pub(all) struct I2cpGzipHeader { + from_port : UInt32 + to_port : UInt32 + protocol : Byte +} + pub struct Reader { data : Bytes mut pos : Int32 diff --git a/i2np/i2np_test.mbt b/i2np/i2np_test.mbt index 24ef51c..a3755ed 100644 --- a/i2np/i2np_test.mbt +++ b/i2np/i2np_test.mbt @@ -94,3 +94,36 @@ test "I2NP TunnelData and DatabaseSearchReply round-trip" { ) assert_eq(dsr_dec, dsr) } + +///| +test "I2NP DatabaseLookup ECIES (0x10) and AES (0x02) reply key/tags round-trip" { + let key = @common.Hash::from_bytes(Bytes::make(32, b'\x11')) + let from = @common.Hash::from_bytes(Bytes::make(32, b'\x22')) + let ecies_dbl = @i2np.I2npPayload::DatabaseLookup( + key~, + from~, + flags=b'\x11', // tunnel delivery (0x01) + ECIES reply (0x10) + reply_tunnel_id=Some(445566U), + excluded_peers=[@common.Hash::from_bytes(Bytes::make(32, b'\x33'))], + reply_key=Some(Bytes::make(32, b'\x44')), + reply_tags=[Bytes::make(8, b'\x55')], + ) + let ecies_wire = @i2np.encode_short_message(11U, 1700000900U, ecies_dbl) + let (_, ecies_dec) = @i2np.decode_short_message( + @encoding.Reader::new(ecies_wire), + ) + assert_eq(ecies_dec, ecies_dbl) + + let aes_dbl = @i2np.I2npPayload::DatabaseLookup( + key~, + from~, + flags=b'\x0a', // RouterInfo lookup (0x08) + AES encryption (0x02) + reply_tunnel_id=None, + excluded_peers=[], + reply_key=Some(Bytes::make(32, b'\x66')), + reply_tags=[Bytes::make(32, b'\x77')], + ) + let aes_wire = @i2np.encode_short_message(12U, 1700000900U, aes_dbl) + let (_, aes_dec) = @i2np.decode_short_message(@encoding.Reader::new(aes_wire)) + assert_eq(aes_dec, aes_dbl) +} diff --git a/i2np/message.mbt b/i2np/message.mbt index 00a028a..32f9ae4 100644 --- a/i2np/message.mbt +++ b/i2np/message.mbt @@ -166,7 +166,9 @@ pub(all) enum I2npPayload { from~ : @common.Hash, flags~ : Byte, reply_tunnel_id~ : UInt32?, - excluded_peers~ : Array[@common.Hash] + excluded_peers~ : Array[@common.Hash], + reply_key~ : Bytes?, + reply_tags~ : Array[Bytes] ) /// Type 3: DatabaseSearchReply (floodfill returns closest router hashes). DatabaseSearchReply( @@ -236,7 +238,15 @@ pub fn I2npPayload::encode_body(self : I2npPayload) -> Bytes raise I2npError { } w.write_bytes(data) } - DatabaseLookup(key~, from~, flags~, reply_tunnel_id~, excluded_peers~) => { + DatabaseLookup( + key~, + from~, + flags~, + reply_tunnel_id~, + excluded_peers~, + reply_key~, + reply_tags~ + ) => { key.encode(w) from.encode(w) w.write_u8(flags) @@ -253,6 +263,39 @@ pub fn I2npPayload::encode_body(self : I2npPayload) -> Bytes raise I2npError { for peer in excluded_peers { peer.encode(w) } + let enc_aes = (flags.to_int() & 0x02) != 0 + let enc_ecies = (flags.to_int() & 0x10) != 0 + if enc_aes || enc_ecies { + match reply_key { + Some(rk) => { + if rk.length() != 32 { + raise InvalidLength( + "DatabaseLookup reply_key must be 32 bytes, got \{rk.length()}", + ) + } + w.write_bytes(rk) + } + None => + raise InvalidLength( + "DatabaseLookup encryption flag requires reply_key", + ) + } + let expected_tag_len = if enc_ecies { 8 } else { 32 } + if reply_tags.length() == 0 || reply_tags.length() > 255 { + raise InvalidLength( + "DatabaseLookup encrypted reply requires 1..255 reply_tags", + ) + } + w.write_u8(reply_tags.length().to_byte()) + for tag in reply_tags { + if tag.length() != expected_tag_len { + raise InvalidLength( + "DatabaseLookup reply_tag must be \{expected_tag_len} bytes, got \{tag.length()}", + ) + } + w.write_bytes(tag) + } + } } DatabaseSearchReply(key~, peer_hashes~, from~) => { key.encode(w) @@ -353,7 +396,29 @@ pub fn I2npPayload::decode_body( }, ) } - DatabaseLookup(key~, from~, flags~, reply_tunnel_id~, excluded_peers~) + let enc_aes = (flags.to_int() & 0x02) != 0 + let enc_ecies = (flags.to_int() & 0x10) != 0 + let (reply_key, reply_tags) = if enc_aes || enc_ecies { + let rk = r.read_bytes(32) catch { e => raise Encoding(e) } + let tag_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let tag_len = if enc_ecies { 8 } else { 32 } + let tags : Array[Bytes] = Array(capacity=tag_count) + for _i = 0; _i < tag_count; _i = _i + 1 { + tags.push(r.read_bytes(tag_len) catch { e => raise Encoding(e) }) + } + (Some(rk), tags) + } else { + (None, []) + } + DatabaseLookup( + key~, + from~, + flags~, + reply_tunnel_id~, + excluded_peers~, + reply_key~, + reply_tags~, + ) } DatabaseSearchReply => { let key = @common.Hash::decode(r) catch { e => raise Common(e) } diff --git a/i2np/pkg.generated.mbti b/i2np/pkg.generated.mbti index cc75b9a..caba41c 100644 --- a/i2np/pkg.generated.mbti +++ b/i2np/pkg.generated.mbti @@ -52,7 +52,7 @@ pub fn I2npMessageType::to_byte(Self) -> Byte #derive(Eq, @debug.Debug) pub(all) enum I2npPayload { DatabaseStore(key~ : @common.Hash, store_type~ : Byte, reply_token~ : UInt32, reply_tunnel_id~ : UInt32, reply_gateway~ : @common.Hash?, data~ : Bytes) - DatabaseLookup(key~ : @common.Hash, from~ : @common.Hash, flags~ : Byte, reply_tunnel_id~ : UInt32?, excluded_peers~ : Array[@common.Hash]) + DatabaseLookup(key~ : @common.Hash, from~ : @common.Hash, flags~ : Byte, reply_tunnel_id~ : UInt32?, excluded_peers~ : Array[@common.Hash], reply_key~ : Bytes?, reply_tags~ : Array[Bytes]) DatabaseSearchReply(key~ : @common.Hash, peer_hashes~ : Array[@common.Hash], from~ : @common.Hash) DeliveryStatus(msg_id~ : UInt32, timestamp_ms~ : UInt64) Garlic(data~ : Bytes) diff --git a/netdb/netdb.mbt b/netdb/netdb.mbt index b90d2a9..c084e6e 100644 --- a/netdb/netdb.mbt +++ b/netdb/netdb.mbt @@ -301,8 +301,25 @@ pub fn NetDb::closest_peers( } ///| -/// Processes an incoming I2NP `DatabaseStore` payload (type 0 = uncompressed RouterInfo, -/// type 3 = LeaseSet2). Returns `true` if stored/updated. +/// Encodes a `RouterInfo` in canonical I2P `DatabaseStore` type 0 wire format: +/// `2-byte BE gzip length || gzip(RouterInfo)`. +pub fn encode_router_info_store_data( + ri : @common.RouterInfo, +) -> Bytes raise NetDbError { + let raw = ri.to_bytes() catch { e => raise Common(e) } + let gz = @encoding.gzip_compress(raw) + if gz.length() > 65535 { + raise InvalidRecord("compressed RouterInfo exceeds 65535 bytes") + } + let w = @encoding.Writer::new(capacity=2 + gz.length()) + w.write_u16_be(gz.length().reinterpret_as_uint()) + w.write_bytes(gz) + w.to_bytes() +} + +///| +/// Processes an incoming I2NP `DatabaseStore` payload (type 0 = gzip-prefixed or +/// raw uncompressed RouterInfo, type 3 = LeaseSet2). Returns `true` if stored/updated. pub fn NetDb::handle_database_store( self : NetDb, store_type : Byte, @@ -312,8 +329,22 @@ pub fn NetDb::handle_database_store( ) -> Bool raise NetDbError { match store_type.to_int() & 0x0F { 0 => { - // Uncompressed RouterInfo (if gzipped with 2-byte len prefix, caller decompresses first) - let ri = @common.RouterInfo::decode(@encoding.Reader::new(data)) catch { + let raw = if data.length() >= 4 && + data[2] == b'\x1f' && + data[3] == b'\x8b' { + let gz_len = (data[0].to_int() << 8) | data[1].to_int() + if gz_len + 2 != data.length() { + raise InvalidRecord( + "DatabaseStore gzip length prefix \{gz_len} does not match payload \{data.length() - 2}", + ) + } + @encoding.gzip_decompress(data[2:].to_owned()) catch { + _ => raise InvalidRecord("DatabaseStore RouterInfo gunzip failed") + } + } else { + data + } + let ri = @common.RouterInfo::decode(@encoding.Reader::new(raw)) catch { e => raise Common(e) } if ri.identity.hash() != key { @@ -370,7 +401,7 @@ pub fn NetDb::handle_database_lookup( if lookup_type == 0 || lookup_type == 2 { match self.get_router_info(key) { Some(ri) => { - let raw = ri.to_bytes() catch { e => raise Common(e) } + let raw = encode_router_info_store_data(ri) return DatabaseStore( key~, store_type=b'\x00', diff --git a/netdb/netdb_test.mbt b/netdb/netdb_test.mbt index cb07a94..34ffe3f 100644 --- a/netdb/netdb_test.mbt +++ b/netdb/netdb_test.mbt @@ -128,6 +128,7 @@ test "NetDB LeaseSet2 store, .b32.i2p lookup, and expiration pruning" { published_sec: 1700000000U, expires_offset: 300U, flags: 0U, + offline_sig: None, options: @common.Mapping::new(), encryption_keys: [{ key_type: X25519, key_data: x_pub, }], leases: [ @@ -151,3 +152,35 @@ test "NetDB LeaseSet2 store, .b32.i2p lookup, and expiration pruning" { assert_eq(db.prune_expired(1700000301U), 1) assert_eq(db.leaseset_count(), 0) } + +///| +test "NetDB canonical gzipped DatabaseStore type 0 round-trip" { + let src = @netdb.NetDb::new() + let dst = @netdb.NetDb::new() + let r1 = make_signed_router(b'\x0a', "XfR", 1700000000000UL) + let r2 = make_signed_router(b'\x0b', "LR", 1700000000000UL) + assert_eq(src.store_router_info(r1), true) + assert_eq(src.store_router_info(r2), true) + + let resp = src.handle_database_lookup( + r1.identity.hash(), + r2.identity.hash(), + b'\x08', + [], + 1700000010U, + ) + match resp { + DatabaseStore(key~, store_type~, data~, ..) => { + assert_eq(store_type, b'\x00') + // Canonical DatabaseStore type 0 starts with 2-byte BE length + gzip magic 0x1f 0x8b + assert_eq(data[2], b'\x1f') + assert_eq(data[3], b'\x8b') + assert_eq( + dst.handle_database_store(store_type, key, data, 1700000010U), + true, + ) + assert_eq(dst.get_router_info(r2.identity.hash()), Some(r2)) + } + _ => fail("expected gzipped DatabaseStore") + } +} diff --git a/netdb/pkg.generated.mbti b/netdb/pkg.generated.mbti index c77d065..47da05f 100644 --- a/netdb/pkg.generated.mbti +++ b/netdb/pkg.generated.mbti @@ -10,6 +10,8 @@ import { // Values pub fn compare_distance(Bytes, Bytes) -> Int32 +pub fn encode_router_info_store_data(@common.RouterInfo) -> Bytes raise NetDbError + pub fn format_utc_date(UInt64) -> String pub fn is_floodfill(@common.RouterInfo) -> Bool diff --git a/noise/noise_xk.mbt b/noise/noise_xk.mbt index 7d29f40..16088fb 100644 --- a/noise/noise_xk.mbt +++ b/noise/noise_xk.mbt @@ -186,6 +186,11 @@ pub fn SymmetricState::chaining_key(self : SymmetricState) -> Bytes { self.ck } +///| +pub fn SymmetricState::from_parts(ck : Bytes, h : Bytes) -> SymmetricState { + { ck, h, cipher: CipherState::empty(), } +} + ///| pub fn SymmetricState::split( self : SymmetricState, diff --git a/noise/pkg.generated.mbti b/noise/pkg.generated.mbti index d22a34a..76c9815 100644 --- a/noise/pkg.generated.mbti +++ b/noise/pkg.generated.mbti @@ -70,6 +70,7 @@ pub struct SymmetricState { 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::from_parts(Bytes, Bytes) -> Self pub fn SymmetricState::handshake_hash(Self) -> Bytes pub fn SymmetricState::initialize(Bytes) -> Self pub fn SymmetricState::mix_hash(Self, Bytes) -> Unit diff --git a/ntcp2/blocks.mbt b/ntcp2/blocks.mbt index 4aac693..a429a6e 100644 --- a/ntcp2/blocks.mbt +++ b/ntcp2/blocks.mbt @@ -10,6 +10,9 @@ pub suberror Ntcp2Error { InvalidState(String) InvalidFormat(String) InvalidLength(String) + InvalidNetworkId(Byte) + ClockSkew(UInt32, UInt32) + ReplayDetected } ///| diff --git a/ntcp2/handshake.mbt b/ntcp2/handshake.mbt index 49cb2ef..e474284 100644 --- a/ntcp2/handshake.mbt +++ b/ntcp2/handshake.mbt @@ -331,12 +331,89 @@ pub fn Ntcp2Handshake::set_ephemeral( self.local_ephemeral = Some(ephemeral) } +///| +/// Validates that `peer_ts` is within `max_skew_sec` of `now_sec`. +pub fn validate_clock_skew( + peer_ts : UInt32, + now_sec : UInt32, + max_skew_sec~ : UInt32 = 60U, +) -> Unit raise Ntcp2Error { + let diff = if peer_ts >= now_sec { + peer_ts - now_sec + } else { + now_sec - peer_ts + } + if diff > max_skew_sec { + raise ClockSkew(peer_ts, now_sec) + } +} + +///| +/// Bounded replay cache for incoming NTCP2 ephemeral X keys (`X` de-obfuscated in Msg 1). +pub struct EphemeralReplayCache { + entries : Array[(Bytes, UInt32)] + max_entries : Int32 +} + +///| +pub fn EphemeralReplayCache::new( + max_entries~ : Int32 = 2048, +) -> EphemeralReplayCache { + { entries: [], max_entries, } +} + +///| +/// Returns `true` if `ephem_x` has not been seen within `window_sec` and records it, +/// or `false` if a replay was detected. +pub fn EphemeralReplayCache::check_and_insert( + self : EphemeralReplayCache, + ephem_x : Bytes, + now_sec : UInt32, + window_sec~ : UInt32 = 120U, +) -> Bool { + let mut i = 0 + while i < self.entries.length() { + if now_sec > self.entries[i].1 + window_sec { + let _ = self.entries.remove(i) + } else { + if @crypto.ct_eq(self.entries[i].0, ephem_x) { + return false + } + i += 1 + } + } + if self.entries.length() >= self.max_entries { + let _ = self.entries.remove(0) + } + self.entries.push((ephem_x, now_sec)) + true +} + +///| +/// Like `check_and_insert`, raising `Ntcp2Error::ReplayDetected` on replay. +pub fn EphemeralReplayCache::check_or_raise( + self : EphemeralReplayCache, + ephem_x : Bytes, + now_sec : UInt32, + window_sec~ : UInt32 = 120U, +) -> Unit raise Ntcp2Error { + if !self.check_and_insert(ephem_x, now_sec, window_sec~) { + raise ReplayDetected + } +} + ///| /// Returns the advertised Msg 3 Part 2 ciphertext length (including 16-byte MAC). pub fn Ntcp2Handshake::m3p2_len(self : Ntcp2Handshake) -> Int32 { self.m3p2_len } +///| +/// Returns the decoded remote ephemeral X25519 key (after Msg 1 / Msg 2 head). +pub fn Ntcp2Handshake::remote_ephemeral(self : Ntcp2Handshake) -> Bytes? { + self.remote_ephemeral +} + ///| /// Initiator: writes Message 1 (SessionRequest). /// Returns `X_obf (32B) || AEAD(options_16B) (32B) || cleartext_padding`. @@ -404,6 +481,7 @@ pub fn Ntcp2Handshake::write_session_request( pub fn Ntcp2Handshake::read_session_request_head( self : Ntcp2Handshake, head64 : Bytes, + expected_network_id~ : Byte = b'\x02', ) -> SessionRequestOptions raise Ntcp2Error { if self.initiator || self.step != 0 { raise InvalidState( @@ -439,6 +517,9 @@ pub fn Ntcp2Handshake::read_session_request_head( e => raise Noise(e) } let opts = SessionRequestOptions::decode(opts_bytes) + if opts.network_id != expected_network_id { + raise InvalidNetworkId(opts.network_id) + } if opts.version != b'\x02' { raise InvalidFormat("unsupported NTCP2 version: \{opts.version.to_int()}") } diff --git a/ntcp2/ntcp2_test.mbt b/ntcp2/ntcp2_test.mbt index be2ebba..9423b6f 100644 --- a/ntcp2/ntcp2_test.mbt +++ b/ntcp2/ntcp2_test.mbt @@ -192,3 +192,49 @@ test "NTCP2 full XKaesobfse handshake + Data Phase SipHash framing round-trip" { _ => fail("expected I2np block from Bob") } } + +///| +test "NTCP2 replay cache, clock skew validation, and network_id check" { + let rc = @ntcp2.EphemeralReplayCache::new(max_entries=4) + let x1 = Bytes::make(32, b'\x01') + let x2 = Bytes::make(32, b'\x02') + assert_eq(rc.check_and_insert(x1, 1000U), true) + assert_eq(rc.check_and_insert(x1, 1010U), false) // replay within window + assert_eq(rc.check_and_insert(x2, 1010U), true) + assert_eq(rc.check_and_insert(x1, 1200U), true) // expired after 120s window + + @ntcp2.validate_clock_skew(1000U, 1059U) + let mut skewed = false + @ntcp2.validate_clock_skew(1000U, 1061U) catch { + ClockSkew(_, _) => skewed = true + _ => () + } + assert_eq(skewed, true) + + let alice_s = @noise.KeyPair::from_private(Bytes::make(32, b'\x33')) + let alice_e = @noise.KeyPair::from_private(Bytes::make(32, b'\x44')) + let bob_s = @noise.KeyPair::from_private(Bytes::make(32, b'\x55')) + let bob_hash = @crypto.sha256(b"bob-netid") + let bob_iv = Bytes::make(16, b'\x66') + let alice = @ntcp2.Ntcp2Handshake::new_initiator( + alice_s, + bob_s.public_key, + bob_hash, + bob_iv, + ) + alice.set_ephemeral(alice_e) + let bad_msg1 = alice.write_session_request( + 64, + 1700000000U, + network_id=b'\x09', + ) + let bob = @ntcp2.Ntcp2Handshake::new_responder(bob_s, bob_hash, bob_iv) + let mut bad_net = false + try { + let _ = bob.read_session_request(bad_msg1) + } catch { + InvalidNetworkId(b'\x09') => bad_net = true + _ => () + } + assert_eq(bad_net, true) +} diff --git a/ntcp2/pkg.generated.mbti b/ntcp2/pkg.generated.mbti index 5ef620e..09cfa16 100644 --- a/ntcp2/pkg.generated.mbti +++ b/ntcp2/pkg.generated.mbti @@ -23,6 +23,8 @@ pub fn i2np_block(UInt32, UInt32, @i2np.I2npPayload) -> Ntcp2Block raise Ntcp2Er pub fn router_info_block(@common.RouterInfo, flood? : Bool) -> Ntcp2Block raise Ntcp2Error +pub fn validate_clock_skew(UInt32, UInt32, max_skew_sec? : UInt32) -> Unit raise Ntcp2Error + // Errors #derive(Eq, @debug.Debug) pub suberror Ntcp2Error { @@ -34,9 +36,20 @@ pub suberror Ntcp2Error { InvalidState(String) InvalidFormat(String) InvalidLength(String) + InvalidNetworkId(Byte) + ClockSkew(UInt32, UInt32) + ReplayDetected } // Types and methods +pub struct EphemeralReplayCache { + entries : Array[(Bytes, UInt32)] + max_entries : Int32 +} +pub fn EphemeralReplayCache::check_and_insert(Self, Bytes, UInt32, window_sec? : UInt32) -> Bool +pub fn EphemeralReplayCache::check_or_raise(Self, Bytes, UInt32, window_sec? : UInt32) -> Unit raise Ntcp2Error +pub fn EphemeralReplayCache::new(max_entries? : Int32) -> Self + #derive(Eq, @debug.Debug) pub(all) enum Ntcp2Block { DateTime(UInt32) @@ -87,7 +100,8 @@ pub fn Ntcp2Handshake::read_session_confirmed(Self, Bytes) -> Array[Ntcp2Block] 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::read_session_request_head(Self, Bytes, expected_network_id? : Byte) -> SessionRequestOptions raise Ntcp2Error +pub fn Ntcp2Handshake::remote_ephemeral(Self) -> Bytes? 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 diff --git a/ntcp2_net/i2pd_interop_test.mbt b/ntcp2_net/i2pd_interop_test.mbt index ea78dff..1342c66 100644 --- a/ntcp2_net/i2pd_interop_test.mbt +++ b/ntcp2_net/i2pd_interop_test.mbt @@ -87,6 +87,8 @@ test "live i2pd RouterInfo Ed25519 verify + real I2P NTCP2 handshake + Data Phas flags=b'\x08', // direct reply, RouterInfo lookup reply_tunnel_id=None, excluded_peers=[], + reply_key=None, + reply_tags=[], ) let lookup_exp = @i2np.I2npPayload::DatabaseLookup( key=@common.Hash::sha256(b"moon-i2p-probe"), @@ -94,6 +96,8 @@ test "live i2pd RouterInfo Ed25519 verify + real I2P NTCP2 handshake + Data Phas flags=b'\x0c', // direct reply, exploration lookup reply_tunnel_id=None, excluded_peers=[], + reply_key=None, + reply_tags=[], ) conn.send_blocks([ DateTime(now_sec), diff --git a/ntcp2_net/moon.pkg b/ntcp2_net/moon.pkg index 7663386..cc6af1f 100644 --- a/ntcp2_net/moon.pkg +++ b/ntcp2_net/moon.pkg @@ -1,15 +1,12 @@ import { "experiments/moon_i2p/encoding", + "experiments/moon_i2p/crypto", "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( diff --git a/ntcp2_net/net_stub.c b/ntcp2_net/net_stub.c index 459e12f..4fde5a5 100644 --- a/ntcp2_net/net_stub.c +++ b/ntcp2_net/net_stub.c @@ -5,6 +5,7 @@ #define _POSIX_C_SOURCE 200809L #include +#include #include #include #include @@ -19,6 +20,7 @@ #include #include #include +#include #include #include @@ -111,6 +113,111 @@ int32_t moon_i2p_net_tcp_connect( return (int32_t)fd; } +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_set_nonblocking(int32_t fd, int32_t nonblocking) { + int flags = fcntl((int)fd, F_GETFL, 0); + if (flags < 0) { + net_set_error(strerror(errno)); + return -1; + } + if (nonblocking) { + flags |= O_NONBLOCK; + } else { + flags &= ~O_NONBLOCK; + } + if (fcntl((int)fd, F_SETFL, flags) < 0) { + net_set_error(strerror(errno)); + return -1; + } + return 0; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_connect_nb( + 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; + } + int flags = fcntl(fd, F_GETFL, 0); + if (flags >= 0) { + fcntl(fd, F_SETFL, flags | O_NONBLOCK); + } + if (connect(fd, p->ai_addr, p->ai_addrlen) == 0 || errno == EINPROGRESS) { + 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_check_connected(int32_t fd) { + struct pollfd pfd; + pfd.fd = (int)fd; + pfd.events = POLLOUT | POLLERR | POLLHUP; + pfd.revents = 0; + int rc = poll(&pfd, 1, 0); + if (rc < 0) { + net_set_error(strerror(errno)); + return -1; + } + if (rc == 0) { + return 0; // still in progress + } + int err = 0; + socklen_t len = sizeof(err); + if (getsockopt((int)fd, SOL_SOCKET, SO_ERROR, &err, &len) < 0) { + net_set_error(strerror(errno)); + return -1; + } + if (err != 0) { + net_set_error(strerror(err)); + return -1; + } + return 1; +} + MOONBIT_FFI_EXPORT int32_t moon_i2p_net_tcp_listen( moonbit_bytes_t host_bytes, @@ -224,12 +331,29 @@ int32_t moon_i2p_net_tcp_send( int32_t len) { ssize_t n = send((int)fd, data + offset, (size_t)len, MSG_NOSIGNAL); if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { + return -2; + } net_set_error(strerror(errno)); return -1; } return (int32_t)n; } +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_poll_writable(int32_t fd, int32_t timeout_ms) { + struct pollfd pfd; + pfd.fd = (int)fd; + pfd.events = POLLOUT; + 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_recv( int32_t fd, @@ -246,6 +370,22 @@ int32_t moon_i2p_net_tcp_recv( return (int32_t)n; } +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_tcp_recv_nb( + int32_t fd, + moonbit_bytes_t buf, + int32_t max_len) { + ssize_t n = recv((int)fd, buf, (size_t)max_len, MSG_DONTWAIT); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { + return -2; // would block + } + 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; @@ -364,3 +504,112 @@ MOONBIT_FFI_EXPORT void moon_i2p_net_flush_stdout(void) { fflush(stdout); } + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_list_dir( + moonbit_bytes_t path_bytes, + int32_t path_len, + moonbit_bytes_t dst, + int32_t max_len) { + if (path_len <= 0 || path_len >= 1024 || max_len <= 0) { + net_set_error("invalid list_dir arguments"); + return -1; + } + char path[1024]; + memcpy(path, path_bytes, (size_t)path_len); + path[path_len] = '\0'; + DIR *d = opendir(path); + if (d == NULL) { + net_set_error(strerror(errno)); + return -1; + } + int32_t pos = 0; + struct dirent *ent; + while ((ent = readdir(d)) != NULL) { + if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) { + continue; + } + int32_t nlen = (int32_t)strlen(ent->d_name); + if (pos + nlen + 1 > max_len) { + break; + } + memcpy(dst + pos, ent->d_name, (size_t)nlen); + pos += nlen; + dst[pos++] = '\n'; + } + closedir(d); + return pos; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_net_fetch_https( + moonbit_bytes_t url_bytes, + int32_t url_len, + moonbit_bytes_t dst, + int32_t max_len) { + if (url_len < 9 || url_len >= 1024 || max_len <= 0) { + net_set_error("invalid https url"); + return -1; + } + char url[1024]; + memcpy(url, url_bytes, (size_t)url_len); + url[url_len] = '\0'; + if (strncmp(url, "https://", 8) != 0) { + net_set_error("reseed URL must start with https://"); + return -1; + } + for (int32_t i = 0; i < url_len; i++) { + if ((unsigned char)url[i] < 0x21) { + net_set_error("reseed URL contains control or whitespace character"); + return -1; + } + } + int pfd[2]; + if (pipe(pfd) < 0) { + net_set_error(strerror(errno)); + return -1; + } + pid_t pid = fork(); + if (pid < 0) { + net_set_error(strerror(errno)); + close(pfd[0]); + close(pfd[1]); + return -1; + } + if (pid == 0) { + close(pfd[0]); + dup2(pfd[1], STDOUT_FILENO); + close(pfd[1]); + int devnull = open("/dev/null", O_WRONLY); + if (devnull >= 0) { + dup2(devnull, STDERR_FILENO); + close(devnull); + } + char *argv[] = { + "curl", "-fsSL", "--max-time", "15", "--max-filesize", "2097152", url, NULL + }; + execvp("curl", argv); + _exit(127); + } + close(pfd[1]); + int32_t total = 0; + while (total < max_len) { + ssize_t n = read(pfd[0], dst + total, (size_t)(max_len - total)); + if (n < 0) { + if (errno == EINTR) continue; + net_set_error(strerror(errno)); + close(pfd[0]); + waitpid(pid, NULL, 0); + return -1; + } + if (n == 0) break; + total += (int32_t)n; + } + close(pfd[0]); + int status = 0; + if (waitpid(pid, &status, 0) < 0 || !WIFEXITED(status) || WEXITSTATUS(status) != 0) { + net_set_error("curl HTTPS fetch failed"); + return -1; + } + return total; +} diff --git a/ntcp2_net/transport.mbt b/ntcp2_net/transport.mbt index 7fa9dc5..0bd30cf 100644 --- a/ntcp2_net/transport.mbt +++ b/ntcp2_net/transport.mbt @@ -31,6 +31,20 @@ extern "C" fn c_tcp_connect( port : Int32, ) -> Int32 = "moon_i2p_net_tcp_connect" +///| +#borrow(host) +extern "C" fn c_tcp_connect_nb( + host : Bytes, + host_len : Int32, + port : Int32, +) -> Int32 = "moon_i2p_net_tcp_connect_nb" + +///| +extern "C" fn c_tcp_check_connected(fd : Int32) -> Int32 = "moon_i2p_net_tcp_check_connected" + +///| +extern "C" fn c_tcp_set_nonblocking(fd : Int32, nonblocking : Int32) -> Int32 = "moon_i2p_net_tcp_set_nonblocking" + ///| #borrow(host) extern "C" fn c_tcp_listen( @@ -65,9 +79,20 @@ extern "C" fn c_tcp_recv( max_len : Int32, ) -> Int32 = "moon_i2p_net_tcp_recv" +///| +#borrow(buf) +extern "C" fn c_tcp_recv_nb( + fd : Int32, + buf : FixedArray[Byte], + max_len : Int32, +) -> Int32 = "moon_i2p_net_tcp_recv_nb" + ///| extern "C" fn c_tcp_poll_readable(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_poll_readable" +///| +extern "C" fn c_tcp_poll_writable(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_poll_writable" + ///| extern "C" fn c_tcp_shutdown_write(fd : Int32) -> Int32 = "moon_i2p_net_tcp_shutdown_write" @@ -97,6 +122,24 @@ extern "C" fn c_read_file( ///| extern "C" fn c_flush_stdout() -> Unit = "moon_i2p_net_flush_stdout" +///| +#borrow(path, dst) +extern "C" fn c_list_dir( + path : Bytes, + path_len : Int32, + dst : FixedArray[Byte], + max_len : Int32, +) -> Int32 = "moon_i2p_net_list_dir" + +///| +#borrow(url, dst) +extern "C" fn c_fetch_https( + url : Bytes, + url_len : Int32, + dst : FixedArray[Byte], + max_len : Int32, +) -> Int32 = "moon_i2p_net_fetch_https" + ///| fn last_os_error() -> String { let n = c_last_error_len() @@ -115,6 +158,48 @@ pub fn flush_stdout() -> Unit { c_flush_stdout() } +///| +/// Lists non-`.`/`..` entry names inside local directory `dir`. +pub fn list_dir_files(dir : String) -> Array[String] raise Ntcp2NetError { + let pb = @encoding.string_to_utf8_bytes(dir) + let buf = FixedArray::make(65536, b'\x00') + let n = c_list_dir(pb, pb.length(), buf, 65536) + if n < 0 { + raise IoError("opendir(\{dir}) failed: \{last_os_error()}") + } + let text = @encoding.utf8_bytes_to_string( + Bytes::from_array(buf)[:n].to_owned(), + ) catch { + _ => raise IoError("invalid UTF-8 in directory listing") + } + let out : Array[String] = [] + let cur = StringBuilder() + for ch in text { + if ch == '\n' { + let s = cur.to_string() + if s.length() > 0 { + out.push(s) + } + cur.reset() + } else { + cur.write_char(ch) + } + } + out +} + +///| +/// Fetches up to 2 MiB from an `https://` URL using system `curl` (no shell). +pub fn fetch_https_bytes(url : String) -> Bytes raise Ntcp2NetError { + let ub = @encoding.string_to_utf8_bytes(url) + let buf = FixedArray::make(2 * 1024 * 1024, b'\x00') + let n = c_fetch_https(ub, ub.length(), buf, 2 * 1024 * 1024) + if n < 0 { + raise IoError("https fetch(\{url}) failed: \{last_os_error()}") + } + Bytes::from_array(buf)[:n].to_owned() +} + ///| /// Reads `n` cryptographically secure random bytes from `/dev/urandom`. pub fn random_bytes(n : Int32) -> Bytes raise Ntcp2NetError { @@ -225,6 +310,16 @@ pub fn TcpSocket::write_all( let mut sent = 0 while sent < total { let n = c_tcp_send(self.fd, data, sent, total - sent) + if n == -2 { + let rc = c_tcp_poll_writable(self.fd, 5000) + if rc < 0 { + raise IoError("poll writable failed: \{last_os_error()}") + } + if rc == 0 { + raise Timeout + } + continue + } if n < 0 { raise IoError("send failed: \{last_os_error()}") } @@ -235,6 +330,52 @@ pub fn TcpSocket::write_all( } } +///| +/// Non-blocking read of up to `needed` bytes into `dst`. Returns bytes added +/// (`0` if socket would block). Raises `Closed` on EOF when no bytes were read. +pub fn TcpSocket::pump_nonblocking( + self : TcpSocket, + dst : Array[Byte], + needed : Int32, +) -> Int32 raise Ntcp2NetError { + if needed <= 0 { + return 0 + } + if self.fd < 0 { + raise Closed + } + let mut added = 0 + while added < needed { + if self.pos < self.len { + let avail = self.len - self.pos + let want = needed - added + let take = if avail < want { avail } else { want } + for i = 0; i < take; i = i + 1 { + dst.push(self.buf[self.pos + i]) + } + self.pos += take + added += take + } else { + let n = c_tcp_recv_nb(self.fd, self.buf, self.buf.length()) + if n == -2 { + break + } + if n < 0 { + raise IoError("recv_nb failed: \{last_os_error()}") + } + if n == 0 { + if added > 0 { + return added + } + raise Closed + } + self.pos = 0 + self.len = n + } + } + added +} + ///| fn TcpSocket::refill(self : TcpSocket) -> Int32 raise Ntcp2NetError { if self.fd < 0 { @@ -408,6 +549,14 @@ pub fn TcpListener::accept( Some({ fd: cfd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, }) } +///| +/// Non-blocking accept: returns `None` immediately when no peer is waiting. +pub fn TcpListener::accept_nonblocking( + self : TcpListener, +) -> TcpSocket? raise Ntcp2NetError { + self.accept(timeout_ms=0) +} + ///| pub fn TcpListener::close(self : TcpListener) -> Unit { if self.fd >= 0 { @@ -507,6 +656,488 @@ pub struct Ntcp2Conn { socket : TcpSocket session : @ntcp2.Ntcp2DataSession remote_router_info : @common.RouterInfo? + priv frame_buf : Array[Byte] + priv mut expected_frame_len : Int32 +} + +///| +fn make_ntcp2_conn( + socket : TcpSocket, + session : @ntcp2.Ntcp2DataSession, + remote_router_info : @common.RouterInfo?, +) -> Ntcp2Conn { + { + socket, + session, + remote_router_info, + frame_buf: [], + expected_frame_len: -1, + } +} + +///| +fn prepare_initiator_handshake( + peer : Ntcp2PeerInfo, + local_static : @noise.KeyPair, + local_ri : @common.RouterInfo, + flood : Bool, +) -> (@ntcp2.Ntcp2Handshake, Bytes, Array[@ntcp2.Ntcp2Block]) raise Ntcp2NetError { + let hs = @ntcp2.Ntcp2Handshake::new_initiator( + local_static, + peer.static_key, + peer.router_hash, + peer.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) + let ri_blk = @ntcp2.router_info_block(local_ri, flood~) catch { + e => 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 => raise Protocol(e) } + let m3p2_ct_len = m3p2_pt.length() + 16 + let m1_pad = random_bytes(16) + let msg1 = hs.write_session_request( + m3p2_ct_len, + unix_time_sec(), + padding=m1_pad, + ) catch { + e => raise Protocol(e) + } + (hs, msg1, m3_blocks) +} + +///| +fn verify_confirmed_blocks( + blocks : Array[@ntcp2.Ntcp2Block], + session : @ntcp2.Ntcp2DataSession, +) -> @common.RouterInfo? raise Ntcp2NetError { + 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) + } + if !parsed.verify_signature() { + raise InvalidPeer("incoming RouterInfo failed Ed25519 verification") + } + let mut bound = true + for addr in parsed.addresses { + if addr.transport_style == "NTCP2" { + match addr.options.get("s") { + Some(s_b64) => { + let s_bytes = @encoding.base64_decode(s_b64) catch { _ => b"" } + if s_bytes.length() == 32 && + !@crypto.ct_eq(s_bytes, session.remote_static()) { + bound = false + } + } + None => () + } + } + } + if !bound { + raise InvalidPeer("incoming RouterInfo static key mismatch") + } + remote_ri = Some(parsed) + } + _ => () + } + } + remote_ri +} + +///| +/// Non-blocking outbound NTCP2 handshake state machine (`connect_nb` -> Msg 1 -> Msg 2 -> Msg 3). +pub struct PendingNtcp2Dial { + sock : TcpSocket + hs : @ntcp2.Ntcp2Handshake + m1_bytes : Bytes + m3_blocks : Array[@ntcp2.Ntcp2Block] + remote_ri : @common.RouterInfo? + check_clock_skew : Bool + max_skew_sec : UInt32 + recv_buf : Array[Byte] + mut step : Int32 // 0: wait connect, 1: wait m2 head, 2: wait m2 pad + mut need_len : Int32 + started_ms : UInt64 +} + +///| +/// Starts a non-blocking NTCP2 dial to `peer`. Drive forward with `step()`. +pub fn PendingNtcp2Dial::start( + peer : Ntcp2PeerInfo, + local_static : @noise.KeyPair, + local_ri : @common.RouterInfo, + flood~ : Bool = false, + check_clock_skew~ : Bool = true, + max_skew_sec~ : UInt32 = 60U, + remote_ri~ : @common.RouterInfo? = None, +) -> PendingNtcp2Dial raise Ntcp2NetError { + let hb = @encoding.string_to_utf8_bytes(peer.host) + let fd = c_tcp_connect_nb(hb, hb.length(), peer.port) + if fd < 0 { + raise IoError( + "connect_nb(\{peer.host}:\{peer.port}) failed: \{last_os_error()}", + ) + } + let sock : TcpSocket = { + fd, + buf: FixedArray::make(4096, b'\x00'), + pos: 0, + len: 0, + } + let (hs, m1_bytes, m3_blocks) = prepare_initiator_handshake( + peer, local_static, local_ri, flood, + ) catch { + e => { + sock.close() + raise e + } + } + { + sock, + hs, + m1_bytes, + m3_blocks, + remote_ri, + check_clock_skew, + max_skew_sec, + recv_buf: [], + step: 0, + need_len: 0, + started_ms: unix_time_ms(), + } +} + +///| +pub fn PendingNtcp2Dial::started_at_ms(self : PendingNtcp2Dial) -> UInt64 { + self.started_ms +} + +///| +pub fn PendingNtcp2Dial::close(self : PendingNtcp2Dial) -> Unit { + self.sock.close() +} + +///| +/// Advances a pending non-blocking outbound NTCP2 dial. Returns `None` while +/// waiting for socket readiness, or `Some(Ntcp2Conn)` once Data Phase is ready. +pub fn PendingNtcp2Dial::step( + self : PendingNtcp2Dial, +) -> Ntcp2Conn? raise Ntcp2NetError { + while true { + if self.step == 0 { + let rc = c_tcp_check_connected(self.sock.fd) + if rc == 0 { + return None + } + if rc < 0 { + let msg = last_os_error() + self.sock.close() + raise IoError("non-blocking connect failed: \{msg}") + } + let _ = c_tcp_set_nonblocking(self.sock.fd, 0) + self.sock.write_all(self.m1_bytes) catch { + e => { + self.sock.close() + raise e + } + } + self.step = 1 + self.need_len = 64 + } else if self.step == 1 { + let need = self.need_len - self.recv_buf.length() + let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { + e => { + self.sock.close() + raise e + } + } + if self.recv_buf.length() < self.need_len { + return None + } + let m2_head = Bytes::from_array(self.recv_buf) + self.recv_buf.clear() + let m2_opts = self.hs.read_session_created_head(m2_head) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + if self.check_clock_skew { + @ntcp2.validate_clock_skew( + m2_opts.timestamp_sec, + unix_time_sec(), + max_skew_sec=self.max_skew_sec, + ) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + } + self.need_len = m2_opts.pad_len.reinterpret_as_int() + self.step = 2 + } else { + if self.need_len > 0 { + let need = self.need_len - self.recv_buf.length() + let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { + e => { + self.sock.close() + raise e + } + } + if self.recv_buf.length() < self.need_len { + return None + } + } + let m2_pad = Bytes::from_array(self.recv_buf) + self.recv_buf.clear() + self.hs.finish_read_session_created(m2_pad) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + let msg3 = self.hs.write_session_confirmed(self.m3_blocks) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + self.sock.write_all(msg3) catch { + e => { + self.sock.close() + raise e + } + } + let session = self.hs.into_data_session() catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + return Some(make_ntcp2_conn(self.sock, session, self.remote_ri)) + } + } + None +} + +///| +/// Non-blocking inbound NTCP2 handshake state machine (Msg 1 -> Msg 2 -> Msg 3). +pub struct PendingNtcp2Accept { + sock : TcpSocket + hs : @ntcp2.Ntcp2Handshake + replay_cache : @ntcp2.EphemeralReplayCache? + check_clock_skew : Bool + max_skew_sec : UInt32 + expected_network_id : Byte + recv_buf : Array[Byte] + mut step : Int32 // 0: wait m1 head, 1: wait m1 pad, 2: wait m3 + mut need_len : Int32 + started_ms : UInt64 +} + +///| +/// Begins a non-blocking NTCP2 responder handshake on an accepted TCP socket. +pub fn PendingNtcp2Accept::start( + sock : TcpSocket, + local_static : @noise.KeyPair, + local_router_hash : Bytes, + local_iv : Bytes, + replay_cache~ : @ntcp2.EphemeralReplayCache? = None, + check_clock_skew~ : Bool = true, + max_skew_sec~ : UInt32 = 60U, + expected_network_id~ : Byte = b'\x02', +) -> PendingNtcp2Accept raise Ntcp2NetError { + let hs = @ntcp2.Ntcp2Handshake::new_responder( + local_static, local_router_hash, local_iv, + ) catch { + e => { + sock.close() + raise Protocol(e) + } + } + let ephem_priv = random_bytes(32) catch { + e => { + sock.close() + raise e + } + } + let ephem = @noise.KeyPair::from_private(ephem_priv) catch { + e => { + sock.close() + raise Noise(e) + } + } + hs.set_ephemeral(ephem) + { + sock, + hs, + replay_cache, + check_clock_skew, + max_skew_sec, + expected_network_id, + recv_buf: [], + step: 0, + need_len: 64, + started_ms: unix_time_ms(), + } +} + +///| +pub fn PendingNtcp2Accept::started_at_ms(self : PendingNtcp2Accept) -> UInt64 { + self.started_ms +} + +///| +pub fn PendingNtcp2Accept::close(self : PendingNtcp2Accept) -> Unit { + self.sock.close() +} + +///| +/// Advances a pending non-blocking inbound NTCP2 handshake. +pub fn PendingNtcp2Accept::step( + self : PendingNtcp2Accept, +) -> Ntcp2Conn? raise Ntcp2NetError { + while true { + if self.step == 0 { + let need = self.need_len - self.recv_buf.length() + let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { + e => { + self.sock.close() + raise e + } + } + if self.recv_buf.length() < self.need_len { + return None + } + let m1_head = Bytes::from_array(self.recv_buf) + self.recv_buf.clear() + let m1_opts = self.hs.read_session_request_head( + m1_head, + expected_network_id=self.expected_network_id, + ) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + let now_sec = unix_time_sec() + if self.check_clock_skew { + @ntcp2.validate_clock_skew( + m1_opts.timestamp_sec, + now_sec, + max_skew_sec=self.max_skew_sec, + ) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + } + match self.replay_cache { + Some(rc) => + match self.hs.remote_ephemeral() { + Some(rx) => + rc.check_or_raise(rx, now_sec) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + None => () + } + None => () + } + self.need_len = m1_opts.pad_len.reinterpret_as_int() + self.step = 1 + } else if self.step == 1 { + if self.need_len > 0 { + let need = self.need_len - self.recv_buf.length() + let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { + e => { + self.sock.close() + raise e + } + } + if self.recv_buf.length() < self.need_len { + return None + } + } + let m1_pad = Bytes::from_array(self.recv_buf) + self.recv_buf.clear() + self.hs.finish_read_session_request(m1_pad) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + let m2_pad = random_bytes(16) catch { + e => { + self.sock.close() + raise e + } + } + let msg2 = self.hs.write_session_created(unix_time_sec(), padding=m2_pad) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + self.sock.write_all(msg2) catch { + e => { + self.sock.close() + raise e + } + } + self.need_len = 48 + self.hs.m3p2_len() + self.step = 2 + } else { + let need = self.need_len - self.recv_buf.length() + let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { + e => { + self.sock.close() + raise e + } + } + if self.recv_buf.length() < self.need_len { + return None + } + let msg3 = Bytes::from_array(self.recv_buf) + self.recv_buf.clear() + let blocks = self.hs.read_session_confirmed(msg3) catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + let session = self.hs.into_data_session() catch { + e => { + self.sock.close() + raise Protocol(e) + } + } + let remote_ri = verify_confirmed_blocks(blocks, session) catch { + e => { + self.sock.close() + raise e + } + } + return Some(make_ntcp2_conn(self.sock, session, remote_ri)) + } + } + None } ///| @@ -518,56 +1149,17 @@ pub fn dial_ntcp2( local_ri : @common.RouterInfo, flood~ : Bool = false, timeout_ms~ : Int32 = 10000, + check_clock_skew~ : Bool = true, + max_skew_sec~ : UInt32 = 60U, ) -> 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, + let (hs, msg1, m3_blocks) = prepare_initiator_handshake( + peer, local_static, local_ri, flood, ) 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) + raise e } } sock.write_all(msg1) @@ -580,6 +1172,18 @@ pub fn dial_ntcp2( raise Protocol(e) } } + if check_clock_skew { + @ntcp2.validate_clock_skew( + m2_opts.timestamp_sec, + unix_time_sec(), + max_skew_sec~, + ) 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 { @@ -604,17 +1208,23 @@ pub fn dial_ntcp2( raise Protocol(e) } } - { socket: sock, session, remote_router_info: None, } + make_ntcp2_conn(sock, session, None) } ///| /// Accepts an incoming NTCP2 handshake on an already-accepted `TcpSocket`. +/// Checks network ID, optional clock skew (`±60s`), optional ephemeral X replay cache, +/// remote `RouterInfo` Ed25519 signature, and static key binding. pub fn accept_ntcp2( sock : TcpSocket, local_static : @noise.KeyPair, local_router_hash : Bytes, local_iv : Bytes, timeout_ms~ : Int32 = 10000, + replay_cache~ : @ntcp2.EphemeralReplayCache? = None, + check_clock_skew~ : Bool = true, + max_skew_sec~ : UInt32 = 60U, + expected_network_id~ : Byte = b'\x02', ) -> Ntcp2Conn raise Ntcp2NetError { sock.set_recv_timeout(timeout_ms) let hs = @ntcp2.Ntcp2Handshake::new_responder( @@ -630,9 +1240,26 @@ pub fn accept_ntcp2( // Read Msg 1 (SessionRequest) let m1_head = sock.read_exact(64) - let m1_opts = hs.read_session_request_head(m1_head) catch { + let m1_opts = hs.read_session_request_head(m1_head, expected_network_id~) catch { e => raise Protocol(e) } + let now_sec = unix_time_sec() + if check_clock_skew { + @ntcp2.validate_clock_skew(m1_opts.timestamp_sec, now_sec, max_skew_sec~) catch { + e => raise Protocol(e) + } + } + match replay_cache { + Some(rc) => + match hs.remote_ephemeral() { + Some(rx) => + rc.check_or_raise(rx, now_sec) catch { + e => raise Protocol(e) + } + None => () + } + None => () + } 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 { @@ -650,22 +1277,56 @@ pub fn accept_ntcp2( 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, } + let remote_ri = verify_confirmed_blocks(blocks, session) + make_ntcp2_conn(sock, session, remote_ri) +} + +///| +/// Polls the underlying NTCP2 socket for readability (`timeout_ms=0` is non-blocking). +pub fn Ntcp2Conn::poll_readable( + self : Ntcp2Conn, + timeout_ms : Int32, +) -> Bool raise Ntcp2NetError { + self.frame_buf.length() > 0 || self.socket.poll_readable(timeout_ms) +} + +///| +/// Non-blocking Data Phase read: accumulates partial TCP chunks safely across calls, +/// returning `None` until a complete frame has arrived and been decrypted. +pub fn Ntcp2Conn::try_recv_blocks( + self : Ntcp2Conn, +) -> Array[@ntcp2.Ntcp2Block]? raise Ntcp2NetError { + if self.expected_frame_len < 0 { + let need = 2 - self.frame_buf.length() + let _ = self.socket.pump_nonblocking(self.frame_buf, need) + if self.frame_buf.length() < 2 { + return None + } + let hdr = Bytes::from_array(self.frame_buf) + self.frame_buf.clear() + let flen = self.session.unmask_frame_length(hdr) catch { + e => raise Protocol(e) + } + if flen < 16 { + raise IoError("NTCP2 frame shorter than 16-byte MAC: \{flen}") + } + self.expected_frame_len = flen + } + let need = self.expected_frame_len - self.frame_buf.length() + if need > 0 { + let _ = self.socket.pump_nonblocking(self.frame_buf, need) + } + if self.frame_buf.length() < self.expected_frame_len { + return None + } + let ct = Bytes::from_array(self.frame_buf) + self.frame_buf.clear() + self.expected_frame_len = -1 + let blocks = self.session.decrypt_frame_body(ct) catch { + e => raise Protocol(e) + } + Some(blocks) } ///| @@ -685,14 +1346,34 @@ pub fn Ntcp2Conn::send_blocks( 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 self.expected_frame_len < 0 { + let need_hdr = 2 - self.frame_buf.length() + if need_hdr > 0 { + let rest = self.socket.read_exact(need_hdr) + for i = 0; i < rest.length(); i = i + 1 { + self.frame_buf.push(rest[i]) + } + } + let len_hdr = Bytes::from_array(self.frame_buf) + self.frame_buf.clear() + 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}") + } + self.expected_frame_len = frame_len } - if frame_len < 16 { - raise IoError("NTCP2 frame shorter than 16-byte MAC: \{frame_len}") + let need_body = self.expected_frame_len - self.frame_buf.length() + if need_body > 0 { + let rest = self.socket.read_exact(need_body) + for i = 0; i < rest.length(); i = i + 1 { + self.frame_buf.push(rest[i]) + } } - let ct = self.socket.read_exact(frame_len) + let ct = Bytes::from_array(self.frame_buf) + self.frame_buf.clear() + self.expected_frame_len = -1 self.session.decrypt_frame_body(ct) catch { e => raise Protocol(e) } diff --git a/ratchet/blocks.mbt b/ratchet/blocks.mbt new file mode 100644 index 0000000..bdb3471 --- /dev/null +++ b/ratchet/blocks.mbt @@ -0,0 +1,322 @@ +///| +/// Proposal 144 ECIES-X25519-AEAD-Ratchet payload block codec & Garlic Clove delivery instructions. + +///| +#derive(Eq, Debug) +pub suberror RatchetError { + Crypto(@crypto.CryptoError) + Noise(@noise.NoiseError) + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + I2np(@i2np.I2npError) + InvalidLength(String) + InvalidFormat(String) + UnknownSession + AuthenticationFailed +} + +///| +/// Delivery target inside a Garlic Clove block (Block Type 11). +#derive(Eq, Debug) +pub(all) enum GarlicDelivery { + Local + Destination(@common.Hash) + Router(@common.Hash) + Tunnel(@common.Hash, UInt32) +} + +///| +fn encode_garlic_delivery( + delivery : GarlicDelivery, + w : @encoding.Writer, +) -> Unit { + match delivery { + Local => w.write_u8(b'\x00') + Destination(h) => { + w.write_u8(b'\x20') // delivery type 1 (bits 6..5 = 01) + h.encode(w) + } + Router(h) => { + w.write_u8(b'\x40') // delivery type 2 (bits 6..5 = 10) + h.encode(w) + } + Tunnel(gw, tid) => { + w.write_u8(b'\x60') // delivery type 3 (bits 6..5 = 11) + gw.encode(w) + w.write_u32_be(tid) + } + } +} + +///| +fn decode_garlic_delivery( + r : @encoding.Reader, +) -> GarlicDelivery raise RatchetError { + let flag = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + if (flag & 0x80) != 0 { + // Individual clove encryption is unsupported/unused in ECIES + let _ = r.read_bytes(32) catch { e => raise Encoding(e) } + } + let dtype = (flag >> 5) & 0x03 + let res : GarlicDelivery = match dtype { + 0 => Local + 1 => { + let h = @common.Hash::decode(r) catch { e => raise Common(e) } + Destination(h) + } + 2 => { + let h = @common.Hash::decode(r) catch { e => raise Common(e) } + Router(h) + } + _ => { + let gw = @common.Hash::decode(r) catch { e => raise Common(e) } + let tid = r.read_u32_be() catch { e => raise Encoding(e) } + Tunnel(gw, tid) + } + } + if (flag & 0x10) != 0 { + let _ = r.read_u32_be() catch { e => raise Encoding(e) } + } + res +} + +///| +/// Proposal 144 ECIES-X25519-AEAD-Ratchet payload blocks. +#derive(Eq, Debug) +pub(all) enum RatchetBlock { + /// Type 0: DateTime (4-byte uint32 Unix timestamp in seconds). + DateTime(UInt32) + /// Type 4: Termination (`reason`, `additional_data`). + Termination(reason~ : Byte, additional_data~ : Bytes) + /// Type 5: Options. + Options(Bytes) + /// Type 6: MessageNumber (`pn` uint16 BE previous chain length). + MessageNumber(UInt32) + /// Type 7: NextKey (`flags`, `key_id` uint16 BE, optional 32-byte X25519 public key). + NextKey(flags~ : Byte, key_id~ : UInt32, public_key~ : Bytes?) + /// Type 8: Ack (pairs of `(key_id, msg_num)` uint16 BE). + Ack(Array[(UInt32, UInt32)]) + /// Type 9: AckRequest (`flags` 1 byte). + AckRequest(Byte) + /// Type 11: GarlicClove (`delivery`, 9-byte short I2NP header + payload bytes). + GarlicClove(delivery~ : GarlicDelivery, i2np_short~ : Bytes) + /// Type 254: Padding (must be last block if present). + Padding(Bytes) + /// Fallback for other block types. + Unknown(Byte, Bytes) +} + +///| +pub fn RatchetBlock::encode( + self : RatchetBlock, + w : @encoding.Writer, +) -> Unit raise RatchetError { + match self { + DateTime(ts) => { + w.write_u8(b'\x00') + w.write_u16_be(4U) + w.write_u32_be(ts) + } + Termination(reason~, additional_data~) => { + let sz = 1 + additional_data.length() + if sz > 65535 { + raise InvalidLength("Termination block exceeds 65535 bytes") + } + w.write_u8(b'\x04') + w.write_u16_be(sz.reinterpret_as_uint()) + w.write_u8(reason) + w.write_bytes(additional_data) + } + Options(data) => { + if data.length() > 65535 { + raise InvalidLength("Options block exceeds 65535 bytes") + } + w.write_u8(b'\x05') + w.write_u16_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + MessageNumber(pn) => { + w.write_u8(b'\x06') + w.write_u16_be(2U) + w.write_u16_be(pn) + } + NextKey(flags~, key_id~, public_key~) => { + let bw = @encoding.Writer::new(capacity=35) + bw.write_u8(flags) + bw.write_u16_be(key_id) + match public_key { + Some(pk) => { + if pk.length() != 32 { + raise InvalidLength("NextKey public_key must be 32 bytes") + } + bw.write_bytes(pk) + } + None => () + } + let body = bw.to_bytes() + w.write_u8(b'\x07') + w.write_u16_be(body.length().reinterpret_as_uint()) + w.write_bytes(body) + } + Ack(pairs) => { + let sz = pairs.length() * 4 + if sz > 65535 { + raise InvalidLength("Ack block exceeds 65535 bytes") + } + w.write_u8(b'\x08') + w.write_u16_be(sz.reinterpret_as_uint()) + for p in pairs { + w.write_u16_be(p.0) + w.write_u16_be(p.1) + } + } + AckRequest(flags) => { + w.write_u8(b'\x09') + w.write_u16_be(1U) + w.write_u8(flags) + } + GarlicClove(delivery~, i2np_short~) => { + let bw = @encoding.Writer::new(capacity=40 + i2np_short.length()) + encode_garlic_delivery(delivery, bw) + bw.write_bytes(i2np_short) + let body = bw.to_bytes() + if body.length() > 65535 { + raise InvalidLength("GarlicClove block exceeds 65535 bytes") + } + w.write_u8(b'\x0b') + w.write_u16_be(body.length().reinterpret_as_uint()) + w.write_bytes(body) + } + Padding(data) => { + if data.length() > 65535 { + raise InvalidLength("Padding block exceeds 65535 bytes") + } + w.write_u8(b'\xfe') + w.write_u16_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + Unknown(t, data) => { + if data.length() > 65535 { + raise InvalidLength("Ratchet block exceeds 65535 bytes") + } + w.write_u8(t) + w.write_u16_be(data.length().reinterpret_as_uint()) + w.write_bytes(data) + } + } +} + +///| +pub fn encode_blocks(blocks : Array[RatchetBlock]) -> Bytes raise RatchetError { + let w = @encoding.Writer::new(capacity=256) + for blk in blocks { + blk.encode(w) + } + w.to_bytes() +} + +///| +pub fn decode_blocks(data : Bytes) -> Array[RatchetBlock] raise RatchetError { + let r = @encoding.Reader::new(data) + let out : Array[RatchetBlock] = [] + 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("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)) + } + 4 => { + if size < 1 { + raise InvalidLength("Termination block must be at least 1 byte") + } + let br = @encoding.Reader::new(body) + let reason = br.read_u8() catch { e => raise Encoding(e) } + out.push(Termination(reason~, additional_data=br.read_remaining())) + } + 5 => out.push(Options(body)) + 6 => { + if size != 2 { + raise InvalidLength( + "MessageNumber block must be 2 bytes, got \{size}", + ) + } + let br = @encoding.Reader::new(body) + let pn = br.read_u16_be() catch { e => raise Encoding(e) } + out.push(MessageNumber(pn)) + } + 7 => { + if size < 3 { + raise InvalidLength("NextKey block shorter than 3 bytes") + } + let br = @encoding.Reader::new(body) + let flags = br.read_u8() catch { e => raise Encoding(e) } + let key_id = br.read_u16_be() catch { e => raise Encoding(e) } + let public_key = if (flags.to_int() & 0x01) != 0 { + Some(br.read_bytes(32) catch { e => raise Encoding(e) }) + } else { + None + } + out.push(NextKey(flags~, key_id~, public_key~)) + } + 8 => { + if size % 4 != 0 { + raise InvalidLength("Ack block size must be multiple of 4 bytes") + } + let br = @encoding.Reader::new(body) + let pairs : Array[(UInt32, UInt32)] = [] + while !br.is_eof() { + let kid = br.read_u16_be() catch { e => raise Encoding(e) } + let n = br.read_u16_be() catch { e => raise Encoding(e) } + pairs.push((kid, n)) + } + out.push(Ack(pairs)) + } + 9 => { + if size != 1 { + raise InvalidLength("AckRequest block must be 1 byte") + } + out.push(AckRequest(body[0])) + } + 11 => { + let br = @encoding.Reader::new(body) + let delivery = decode_garlic_delivery(br) + let i2np_short = br.read_remaining() + out.push(GarlicClove(delivery~, i2np_short~)) + } + 254 => out.push(Padding(body)) + _ => out.push(Unknown(btype, body)) + } + } + out +} + +///| +/// Builds a `GarlicClove` block (type 11) wrapping a 9-byte short I2NP message. +pub fn garlic_clove_block( + delivery : GarlicDelivery, + msg_id : UInt32, + expiration_sec : UInt32, + payload : @i2np.I2npPayload, +) -> RatchetBlock raise RatchetError { + let short_msg = @i2np.encode_short_message(msg_id, expiration_sec, payload) catch { + e => raise I2np(e) + } + GarlicClove(delivery~, i2np_short=short_msg) +} + +///| +/// Decodes the 9-byte short I2NP message inside a `GarlicClove` block. +pub fn decode_garlic_clove_i2np( + i2np_short : Bytes, +) -> (@i2np.ShortHeader, @i2np.I2npPayload) raise RatchetError { + @i2np.decode_short_message(@encoding.Reader::new(i2np_short)) catch { + e => raise I2np(e) + } +} diff --git a/ratchet/ecies.mbt b/ratchet/ecies.mbt new file mode 100644 index 0000000..854a365 --- /dev/null +++ b/ratchet/ecies.mbt @@ -0,0 +1,783 @@ +///| +/// Pure-MoonBit Proposal 144 ECIES-X25519-AEAD-Ratchet Engine: +/// - `Noise_IKelg2+hs2_25519_ChaChaPoly_SHA256` +/// - Elligator2 ephemeral keys +/// - Bound & Unbound New Session (`NS`), New Session Reply (`NSR`), Existing Session (`ES`) +/// - Symmetric Ratchet (`STInitialization`, `SessionTagKeyGen`, `SymmetricRatchet`) & DH Ratchet (`NextKey`) +/// - Proposal 154 ECIES `DatabaseLookup` encrypted DSM reply. + +///| +pub let ecies_protocol_name : Bytes = b"Noise_IKelg2+hs2_25519_ChaChaPoly_SHA256" + +///| +fn r_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 make_ecies_nonce(n : UInt32) -> Bytes { + let buf = FixedArray::make(12, b'\x00') + let v = n.to_uint64() + for i = 0; i < 8; i = i + 1 { + buf[4 + i] = ((v >> (i * 8)) & 0xFFUL).to_byte() + } + Bytes::from_array(buf) +} + +///| +/// X25519 ephemeral keypair guaranteed to have a valid Curve25519 Elligator2 representation. +#derive(Eq, Debug) +pub(all) struct ElligatorKeyPair { + private_key : Bytes + public_key : Bytes + elligator_repr : Bytes +} + +///| +/// Generates an X25519 keypair with a valid Elligator2 representative using `next_rand_32`. +pub fn generate_elligator_keypair( + next_rand_32 : () -> Bytes, +) -> ElligatorKeyPair raise RatchetError { + for _attempt = 0; _attempt < 128; _attempt = _attempt + 1 { + let priv_key = next_rand_32() + if priv_key.length() != 32 { + raise InvalidLength("random key must be 32 bytes") + } + let pub_key = @crypto.x25519_public_key(priv_key) catch { + e => raise Crypto(e) + } + let tweak_seed = next_rand_32() + let high_bits = (tweak_seed[0].to_int() & 0xC0).to_byte() + let tweak_sign = (tweak_seed[1].to_int() & 1) != 0 + let rep_opt = @crypto.elligator2_encode(pub_key, high_bits~, tweak_sign~) catch { + e => raise Crypto(e) + } + match rep_opt { + Some(rep) => + return { + private_key: priv_key, + public_key: pub_key, + elligator_repr: rep, + } + None => () + } + } + raise InvalidFormat( + "failed to sample Elligator2-encodable keypair after 128 attempts", + ) +} + +///| +/// Proposal 144 Tag & Symmetric Key Ratchet state (`STInitialization` -> `SessionTagKeyGen` / `SymmetricRatchet`). +pub struct TagSet { + mut tag_ck : Bytes + sesstag_const : Bytes + mut symm_ck : Bytes + mut msg_num : UInt32 +} + +///| +/// Runs Proposal 144 `DH_INITIALIZE(root_key, k)`: +/// 1. `KDFDHRatchetStep` -> `(next_root_key, ck)` +/// 2. `TagAndKeyGenKeys` -> `(sess_tag_ck, symm_key_ck)` +/// 3. `STInitialization` -> `(tag_ck, sesstag_const)` +pub fn dh_initialize( + root_key : Bytes, + k : Bytes, +) -> (Bytes, TagSet) raise RatchetError { + let kd = @crypto.hkdf(root_key, k, b"KDFDHRatchetStep", 64) catch { + e => raise Crypto(e) + } + let next_root_key = r_slice(kd, 0, 32) + let ck = r_slice(kd, 32, 32) + let tk = @crypto.hkdf(ck, b"", b"TagAndKeyGenKeys", 64) catch { + e => raise Crypto(e) + } + let sess_tag_ck = r_slice(tk, 0, 32) + let symm_ck = r_slice(tk, 32, 32) + let st = @crypto.hkdf(sess_tag_ck, b"", b"STInitialization", 64) catch { + e => raise Crypto(e) + } + let tag_ck = r_slice(st, 0, 32) + let sesstag_const = r_slice(st, 32, 32) + (next_root_key, { tag_ck, sesstag_const, symm_ck, msg_num: 0U, }) +} + +///| +/// Advances both the session tag ratchet and symmetric key ratchet by one message index, +/// returning `(msg_num, tag_8B, symm_key_32B)`. +pub fn TagSet::next_entry( + self : TagSet, +) -> (UInt32, Bytes, Bytes) raise RatchetError { + let kd_tag = @crypto.hkdf( + self.tag_ck, + self.sesstag_const, + b"SessionTagKeyGen", + 64, + ) catch { + e => raise Crypto(e) + } + self.tag_ck = r_slice(kd_tag, 0, 32) + let tag = r_slice(kd_tag, 32, 8) + let kd_key = @crypto.hkdf(self.symm_ck, b"", b"SymmetricRatchet", 64) catch { + e => raise Crypto(e) + } + self.symm_ck = r_slice(kd_key, 0, 32) + let symm_key = r_slice(kd_key, 32, 32) + let n = self.msg_num + self.msg_num = self.msg_num + 1U + (n, tag, symm_key) +} + +///| +/// State captured after sending or receiving a Bound New Session, needed for New Session Reply (`NSR`). +pub struct PendingNewSession { + ck : Bytes + h : Bytes + local_ephem_priv : Bytes + remote_ephem_pub : Bytes + remote_static_pub : Bytes + nsr_tagset : TagSet +} + +///| +/// Encrypts a Proposal 144 New Session (`NS`) message (`bound` if `initiator_static` is `Some`, else unbound). +/// Wire format: `e_elg2 (32B) || enc_s (48B) || enc_payload`. +/// For Bound NS, also returns `Some(PendingNewSession)` to process the peer's `NSR`. +pub fn encrypt_new_session( + initiator_static : @noise.KeyPair?, + responder_static_pub : Bytes, + ephem : ElligatorKeyPair, + blocks : Array[RatchetBlock], +) -> (Bytes, PendingNewSession?) raise RatchetError { + if responder_static_pub.length() != 32 { + raise InvalidLength("responder_static_pub must be 32 bytes") + } + let sym = @noise.SymmetricState::initialize(ecies_protocol_name) + sym.mix_hash(b"") // null prologue + sym.mix_hash(responder_static_pub) // <- s + sym.mix_hash(ephem.public_key) // -> e (unencoded X25519 key) + let es = @crypto.x25519(ephem.private_key, responder_static_pub) catch { + e => raise Crypto(e) + } + sym.mix_key(es) + + let (enc_s, is_bound) = match initiator_static { + Some(kp) => { + let es_ct = sym.encrypt_and_hash(kp.public_key) catch { + e => raise Noise(e) + } + let ss = @crypto.x25519(kp.private_key, responder_static_pub) catch { + e => raise Crypto(e) + } + sym.mix_key(ss) + (es_ct, true) + } + None => { + let es_ct = sym.encrypt_and_hash(Bytes::make(32, b'\x00')) catch { + e => raise Noise(e) + } + (es_ct, false) + } + } + + let pt = encode_blocks(blocks) + let enc_payload = sym.encrypt_and_hash(pt) catch { e => raise Noise(e) } + let w = @encoding.Writer::new(capacity=80 + enc_payload.length()) + w.write_bytes(ephem.elligator_repr) + w.write_bytes(enc_s) + w.write_bytes(enc_payload) + let wire = w.to_bytes() + + if is_bound { + let ck = sym.chaining_key() + let h = sym.handshake_hash() + let tagset_key = @crypto.hkdf(ck, b"", b"SessionReplyTags", 32) catch { + e => raise Crypto(e) + } + let (_rk, nsr_tagset) = dh_initialize(ck, tagset_key) + ( + wire, + Some({ + ck, + h, + local_ephem_priv: ephem.private_key, + remote_ephem_pub: responder_static_pub, + remote_static_pub: responder_static_pub, + nsr_tagset, + }), + ) + } else { + (wire, None) + } +} + +///| +/// Decrypts an incoming Proposal 144 New Session (`NS`) message. +/// Returns `(decoded_blocks, pending_ns_if_bound)`. +pub fn decrypt_new_session( + responder_static : @noise.KeyPair, + ns_bytes : Bytes, +) -> (Array[RatchetBlock], PendingNewSession?) raise RatchetError { + if ns_bytes.length() < 96 { + raise InvalidLength("NewSession shorter than 96 bytes") + } + let elg_repr = r_slice(ns_bytes, 0, 32) + let enc_s = r_slice(ns_bytes, 32, 48) + let enc_payload = r_slice(ns_bytes, 80, ns_bytes.length() - 80) + + let re_pub = @crypto.elligator2_decode(elg_repr) catch { + e => raise Crypto(e) + } + let sym = @noise.SymmetricState::initialize(ecies_protocol_name) + sym.mix_hash(b"") + sym.mix_hash(responder_static.public_key) + sym.mix_hash(re_pub) + let es = @crypto.x25519(responder_static.private_key, re_pub) catch { + e => raise Crypto(e) + } + sym.mix_key(es) + + let rs_plain = sym.decrypt_and_hash(enc_s) catch { + _ => raise AuthenticationFailed + } + let is_bound = !@crypto.ct_eq(rs_plain, Bytes::make(32, b'\x00')) + if is_bound { + let ss = @crypto.x25519(responder_static.private_key, rs_plain) catch { + e => raise Crypto(e) + } + sym.mix_key(ss) + } + let pt = sym.decrypt_and_hash(enc_payload) catch { + _ => raise AuthenticationFailed + } + let blocks = decode_blocks(pt) + if is_bound { + let ck = sym.chaining_key() + let h = sym.handshake_hash() + let tagset_key = @crypto.hkdf(ck, b"", b"SessionReplyTags", 32) catch { + e => raise Crypto(e) + } + let (_rk, nsr_tagset) = dh_initialize(ck, tagset_key) + ( + blocks, + Some({ + ck, + h, + local_ephem_priv: b"", + remote_ephem_pub: re_pub, + remote_static_pub: rs_plain, + nsr_tagset, + }), + ) + } else { + (blocks, None) + } +} + +///| +/// Active bidirectional ECIES-X25519-AEAD-Ratchet session state for an established peer. +pub struct RatchetPeerSession { + remote_static_pub : Bytes + mut send_root_key : Bytes + mut send_tagset : TagSet + mut recv_root_key : Bytes + mut recv_tagset : TagSet + recv_window : Array[(UInt32, Bytes, Bytes)] // (msg_num, tag_8B, symm_key_32B) + mut dh_ratchet_key_id : UInt32 + mut local_next_priv : Bytes? + mut local_next_pub : Bytes? + mut remote_next_pub : Bytes? +} + +///| +fn RatchetPeerSession::refill_recv_window( + self : RatchetPeerSession, + target_size~ : Int32 = 32, +) -> Unit raise RatchetError { + while self.recv_window.length() < target_size { + let (n, tag, key) = self.recv_tagset.next_entry() + self.recv_window.push((n, tag, key)) + } +} + +///| +fn RatchetPeerSession::try_decrypt_es( + self : RatchetPeerSession, + tag_8 : Bytes, + ct : Bytes, +) -> Array[RatchetBlock]? raise RatchetError { + for idx = 0; idx < self.recv_window.length(); idx = idx + 1 { + let (msg_num, expected_tag, key) = self.recv_window[idx] + if @crypto.ct_eq(expected_tag, tag_8) { + let nonce = make_ecies_nonce(msg_num) + let pt = @crypto.aead_chacha20_poly1305_decrypt(key, nonce, tag_8, ct) catch { + _ => raise AuthenticationFailed + } + let _ = self.recv_window.remove(idx) + self.refill_recv_window() + return Some(decode_blocks(pt)) + } + } + None +} + +///| +/// Encrypts an Existing Session (`ES`) payload frame (`8B tag || AEAD ciphertext`). +pub fn RatchetPeerSession::encrypt_existing( + self : RatchetPeerSession, + blocks : Array[RatchetBlock], +) -> Bytes raise RatchetError { + let (msg_num, tag_8, key) = self.send_tagset.next_entry() + let pt = encode_blocks(blocks) + let nonce = make_ecies_nonce(msg_num) + let ct = @crypto.aead_chacha20_poly1305_encrypt(key, nonce, tag_8, pt) catch { + e => raise Crypto(e) + } + let w = @encoding.Writer::new(capacity=8 + ct.length()) + w.write_bytes(tag_8) + w.write_bytes(ct) + w.to_bytes() +} + +///| +/// Advances this session's send/receive tagsets by performing a DH ratchet step +/// with `local_priv` and `remote_pub`. +pub fn RatchetPeerSession::apply_dh_ratchet( + self : RatchetPeerSession, + local_priv : Bytes, + remote_pub : Bytes, + for_send~ : Bool, +) -> Unit raise RatchetError { + let shared = @crypto.x25519(local_priv, remote_pub) catch { + e => raise Crypto(e) + } + if for_send { + let (next_rk, ts) = dh_initialize(self.send_root_key, shared) + self.send_root_key = next_rk + self.send_tagset = ts + } else { + let (next_rk, ts) = dh_initialize(self.recv_root_key, shared) + self.recv_root_key = next_rk + self.recv_tagset = ts + self.recv_window.clear() + self.refill_recv_window() + } +} + +///| +/// Responder creates a New Session Reply (`NSR`) from `pending` (obtained via `decrypt_new_session`), +/// returning `(nsr_wire_bytes, established_session)`. +pub fn encrypt_new_session_reply( + pending : PendingNewSession, + ephem_b : ElligatorKeyPair, + blocks : Array[RatchetBlock], +) -> (Bytes, RatchetPeerSession) raise RatchetError { + let (_tag_n, nsr_tag, _nsr_key) = pending.nsr_tagset.next_entry() + let sym = @noise.SymmetricState::from_parts(pending.ck, pending.h) + sym.mix_hash(nsr_tag) + sym.mix_hash(ephem_b.public_key) + let ee = @crypto.x25519(ephem_b.private_key, pending.remote_ephem_pub) catch { + e => raise Crypto(e) + } + sym.mix_key(ee) + let se = @crypto.x25519(ephem_b.private_key, pending.remote_static_pub) catch { + e => raise Crypto(e) + } + sym.mix_key(se) + let key_sec_mac = sym.encrypt_and_hash(b"") catch { e => raise Noise(e) } + + let ck = sym.chaining_key() + let h = sym.handshake_hash() + let split_kd = @crypto.hkdf(ck, b"", b"", 64) catch { e => raise Crypto(e) } + let k_ab = r_slice(split_kd, 0, 32) + let k_ba = r_slice(split_kd, 32, 32) + + let (root_ab, tagset_ab) = dh_initialize(ck, k_ab) + let (root_ba, tagset_ba) = dh_initialize(ck, k_ba) + + let k_payload = @crypto.hkdf(k_ba, b"", b"AttachPayloadKDF", 32) catch { + e => raise Crypto(e) + } + let pt = encode_blocks(blocks) + let enc_payload = @crypto.aead_chacha20_poly1305_encrypt( + k_payload, + Bytes::make(12, b'\x00'), + h, + pt, + ) catch { + e => raise Crypto(e) + } + + let w = @encoding.Writer::new(capacity=56 + enc_payload.length()) + w.write_bytes(nsr_tag) + w.write_bytes(ephem_b.elligator_repr) + w.write_bytes(key_sec_mac) + w.write_bytes(enc_payload) + + let sess : RatchetPeerSession = { + remote_static_pub: pending.remote_static_pub, + send_root_key: root_ba, + send_tagset: tagset_ba, + recv_root_key: root_ab, + recv_tagset: tagset_ab, + recv_window: [], + dh_ratchet_key_id: 0U, + local_next_priv: None, + local_next_pub: None, + remote_next_pub: None, + } + sess.refill_recv_window() + (w.to_bytes(), sess) +} + +///| +/// Initiator decrypts an incoming New Session Reply (`NSR`), verifying `nsr_tag` and +/// returning `(decoded_blocks, established_session)`. +pub fn decrypt_new_session_reply( + initiator_static : @noise.KeyPair, + pending : PendingNewSession, + nsr_bytes : Bytes, +) -> (Array[RatchetBlock], RatchetPeerSession) raise RatchetError { + if nsr_bytes.length() < 72 { + raise InvalidLength("NewSessionReply shorter than 72 bytes") + } + let nsr_tag = r_slice(nsr_bytes, 0, 8) + let elg_repr = r_slice(nsr_bytes, 8, 32) + let key_sec_mac = r_slice(nsr_bytes, 40, 16) + let enc_payload = r_slice(nsr_bytes, 56, nsr_bytes.length() - 56) + + let e_b_pub = @crypto.elligator2_decode(elg_repr) catch { + e => raise Crypto(e) + } + let sym = @noise.SymmetricState::from_parts(pending.ck, pending.h) + sym.mix_hash(nsr_tag) + sym.mix_hash(e_b_pub) + let ee = @crypto.x25519(pending.local_ephem_priv, e_b_pub) catch { + e => raise Crypto(e) + } + sym.mix_key(ee) + let se = @crypto.x25519(initiator_static.private_key, e_b_pub) catch { + e => raise Crypto(e) + } + sym.mix_key(se) + let _ = sym.decrypt_and_hash(key_sec_mac) catch { + _ => raise AuthenticationFailed + } + + let ck = sym.chaining_key() + let h = sym.handshake_hash() + let split_kd = @crypto.hkdf(ck, b"", b"", 64) catch { e => raise Crypto(e) } + let k_ab = r_slice(split_kd, 0, 32) + let k_ba = r_slice(split_kd, 32, 32) + + let (root_ab, tagset_ab) = dh_initialize(ck, k_ab) + let (root_ba, tagset_ba) = dh_initialize(ck, k_ba) + + let k_payload = @crypto.hkdf(k_ba, b"", b"AttachPayloadKDF", 32) catch { + e => raise Crypto(e) + } + let pt = @crypto.aead_chacha20_poly1305_decrypt( + k_payload, + Bytes::make(12, b'\x00'), + h, + enc_payload, + ) catch { + _ => raise AuthenticationFailed + } + let blocks = decode_blocks(pt) + + let sess : RatchetPeerSession = { + remote_static_pub: pending.remote_static_pub, + send_root_key: root_ab, + send_tagset: tagset_ab, + recv_root_key: root_ba, + recv_tagset: tagset_ba, + recv_window: [], + dh_ratchet_key_id: 0U, + local_next_priv: None, + local_next_pub: None, + remote_next_pub: None, + } + sess.refill_recv_window() + (blocks, sess) +} + +///| +/// Proposal 154 ECIES `DatabaseLookup` encrypted DatabaseStore/DatabaseSearchReply payload: +/// `reply_tag (8B) || ChaCha20-Poly1305(reply_key, nonce=0, ad=reply_tag, blocks)`. +pub fn encrypt_ecies_lookup_reply( + reply_key : Bytes, + reply_tag : Bytes, + blocks : Array[RatchetBlock], +) -> Bytes raise RatchetError { + if reply_key.length() != 32 || reply_tag.length() != 8 { + raise InvalidLength("ECIES lookup reply requires 32B key and 8B tag") + } + let pt = encode_blocks(blocks) + let ct = @crypto.aead_chacha20_poly1305_encrypt( + reply_key, + Bytes::make(12, b'\x00'), + reply_tag, + pt, + ) catch { + e => raise Crypto(e) + } + let w = @encoding.Writer::new(capacity=8 + ct.length()) + w.write_bytes(reply_tag) + w.write_bytes(ct) + w.to_bytes() +} + +///| +/// Decrypts a Proposal 154 ECIES `DatabaseLookup` reply using `(reply_key, reply_tag)`. +pub fn decrypt_ecies_lookup_reply( + reply_key : Bytes, + reply_tag : Bytes, + data : Bytes, +) -> Array[RatchetBlock] raise RatchetError { + if data.length() < 24 || reply_key.length() != 32 || reply_tag.length() != 8 { + raise InvalidLength("invalid ECIES lookup reply parameters or length") + } + let wire_tag = r_slice(data, 0, 8) + if !@crypto.ct_eq(wire_tag, reply_tag) { + raise AuthenticationFailed + } + let ct = r_slice(data, 8, data.length() - 8) + let pt = @crypto.aead_chacha20_poly1305_decrypt( + reply_key, + Bytes::make(12, b'\x00'), + reply_tag, + ct, + ) catch { + _ => raise AuthenticationFailed + } + decode_blocks(pt) +} + +///| +/// High-level session manager handling New Session, New Session Reply, and Existing Session +/// state transitions for a local I2P Destination. +pub struct RatchetSessionManager { + local_static : @noise.KeyPair + sessions : Array[RatchetPeerSession] + outbound_pending : Array[(Bytes, PendingNewSession)] // (nsr_tag_8, pending) + inbound_pending : Array[PendingNewSession] // waiting to send NSR to remote_static_pub +} + +///| +pub fn RatchetSessionManager::new( + local_static : @noise.KeyPair, +) -> RatchetSessionManager { + { local_static, sessions: [], outbound_pending: [], inbound_pending: [], } +} + +///| +fn RatchetSessionManager::find_session( + self : RatchetSessionManager, + remote_static_pub : Bytes, +) -> Int32 { + for i = 0; i < self.sessions.length(); i = i + 1 { + if @crypto.ct_eq(self.sessions[i].remote_static_pub, remote_static_pub) { + return i + } + } + -1 +} + +///| +/// Initiates a DH ratchet step (`NextKey` block type 7) for `remote_static_pub`, +/// returning `Some(NextKey(...))` if a session is established. +pub fn RatchetSessionManager::create_next_key_block( + self : RatchetSessionManager, + remote_static_pub : Bytes, + next_rand_32 : () -> Bytes, +) -> RatchetBlock? raise RatchetError { + let sidx = self.find_session(remote_static_pub) + if sidx < 0 { + return None + } + let sess = self.sessions[sidx] + let kp = generate_elligator_keypair(next_rand_32) + sess.dh_ratchet_key_id = sess.dh_ratchet_key_id + 1U + sess.local_next_priv = Some(kp.private_key) + sess.local_next_pub = Some(kp.public_key) + Some( + NextKey( + flags=b'\x05', // key present (0x01) + request reverse (0x04) + key_id=sess.dh_ratchet_key_id, + public_key=Some(kp.public_key), + ), + ) +} + +///| +fn RatchetSessionManager::process_next_keys( + self : RatchetSessionManager, + sess : RatchetPeerSession, + blocks : Array[RatchetBlock], +) -> Unit raise RatchetError { + let _ = self + for blk in blocks { + match blk { + NextKey(flags~, key_id~, public_key~) => { + sess.dh_ratchet_key_id = key_id + match public_key { + Some(rpub) => { + sess.remote_next_pub = Some(rpub) + let is_reverse = (flags.to_int() & 0x02) != 0 + if is_reverse { + match sess.local_next_priv { + Some(lpriv) => { + sess.apply_dh_ratchet(lpriv, rpub, for_send=true) + sess.apply_dh_ratchet(lpriv, rpub, for_send=false) + } + None => () + } + } + } + None => () + } + } + _ => () + } + } +} + +///| +/// Encrypts `blocks` for `remote_static_pub`: +/// - Uses `Existing Session` if established; +/// - Uses `New Session Reply` if responding to a peer's `New Session`; +/// - Otherwise sends a Bound `New Session` (prepending `DateTime(now_sec)`). +pub fn RatchetSessionManager::encrypt_to_peer( + self : RatchetSessionManager, + remote_static_pub : Bytes, + blocks : Array[RatchetBlock], + now_sec : UInt32, + next_rand_32 : () -> Bytes, +) -> Bytes raise RatchetError { + let sidx = self.find_session(remote_static_pub) + if sidx >= 0 { + return self.sessions[sidx].encrypt_existing(blocks) + } + // Check if we owe this peer an NSR + for i = 0; i < self.inbound_pending.length(); i = i + 1 { + let p = self.inbound_pending[i] + if @crypto.ct_eq(p.remote_static_pub, remote_static_pub) { + let _ = self.inbound_pending.remove(i) + let ephem_b = generate_elligator_keypair(next_rand_32) + let (wire, sess) = encrypt_new_session_reply(p, ephem_b, blocks) + self.sessions.push(sess) + return wire + } + } + // Initiate Bound New Session (prepending DateTime block if not already present) + let ns_blocks : Array[RatchetBlock] = [] + let mut has_dt = false + for b in blocks { + if b is DateTime(_) { + has_dt = true + } + } + if !has_dt { + ns_blocks.push(DateTime(now_sec)) + } + for b in blocks { + ns_blocks.push(b) + } + let ephem = generate_elligator_keypair(next_rand_32) + let (wire, pending_opt) = encrypt_new_session( + Some(self.local_static), + remote_static_pub, + ephem, + ns_blocks, + ) + match pending_opt { + Some(p) => + // Pre-register first 4 NSR tags so any reply matches + for _k = 0; _k < 4; _k = _k + 1 { + let (_n, tag, _k32) = p.nsr_tagset.next_entry() + self.outbound_pending.push((tag, p)) + } + None => () + } + wire +} + +///| +/// Decrypts an incoming Garlic ECIES payload (`ES` tag lookup -> `NSR` tag lookup -> `NS`). +/// Returns `(remote_static_pub_if_bound, decoded_blocks)`. +pub fn RatchetSessionManager::decrypt_incoming( + self : RatchetSessionManager, + garlic_data : Bytes, +) -> (Bytes?, Array[RatchetBlock]) raise RatchetError { + if garlic_data.length() >= 24 { + let tag_8 = r_slice(garlic_data, 0, 8) + let ct = r_slice(garlic_data, 8, garlic_data.length() - 8) + // 1. Existing Session lookup + for sess in self.sessions { + match sess.try_decrypt_es(tag_8, ct) { + Some(blocks) => { + self.process_next_keys(sess, blocks) + return (Some(sess.remote_static_pub), blocks) + } + None => () + } + } + // 2. New Session Reply lookup + for i = 0; i < self.outbound_pending.length(); i = i + 1 { + let (expected_tag, p) = self.outbound_pending[i] + if @crypto.ct_eq(expected_tag, tag_8) { + let (blocks, sess) = decrypt_new_session_reply( + self.local_static, + p, + garlic_data, + ) + // Remove all pending entries sharing this PendingNewSession + let mut j = 0 + while j < self.outbound_pending.length() { + if @crypto.ct_eq(self.outbound_pending[j].1.h, p.h) { + let _ = self.outbound_pending.remove(j) + } else { + j += 1 + } + } + let existing_idx = self.find_session(sess.remote_static_pub) + if existing_idx >= 0 { + self.sessions[existing_idx] = sess + } else { + self.sessions.push(sess) + } + return (Some(sess.remote_static_pub), blocks) + } + } + } + // 3. New Session + let (blocks, pending_opt) = decrypt_new_session( + self.local_static, + garlic_data, + ) + match pending_opt { + Some(p) => { + // Replace any older inbound pending from same peer + let mut i = 0 + while i < self.inbound_pending.length() { + if @crypto.ct_eq( + self.inbound_pending[i].remote_static_pub, + p.remote_static_pub, + ) { + let _ = self.inbound_pending.remove(i) + } else { + i += 1 + } + } + self.inbound_pending.push(p) + (Some(p.remote_static_pub), blocks) + } + None => (None, blocks) + } +} diff --git a/ratchet/moon.pkg b/ratchet/moon.pkg new file mode 100644 index 0000000..531d9a8 --- /dev/null +++ b/ratchet/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/ratchet/pkg.generated.mbti b/ratchet/pkg.generated.mbti new file mode 100644 index 0000000..c1313e3 --- /dev/null +++ b/ratchet/pkg.generated.mbti @@ -0,0 +1,130 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/ratchet" + +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[RatchetBlock] raise RatchetError + +pub fn decode_garlic_clove_i2np(Bytes) -> (@i2np.ShortHeader, @i2np.I2npPayload) raise RatchetError + +pub fn decrypt_ecies_lookup_reply(Bytes, Bytes, Bytes) -> Array[RatchetBlock] raise RatchetError + +pub fn decrypt_new_session(@noise.KeyPair, Bytes) -> (Array[RatchetBlock], PendingNewSession?) raise RatchetError + +pub fn decrypt_new_session_reply(@noise.KeyPair, PendingNewSession, Bytes) -> (Array[RatchetBlock], RatchetPeerSession) raise RatchetError + +pub fn dh_initialize(Bytes, Bytes) -> (Bytes, TagSet) raise RatchetError + +pub let ecies_protocol_name : Bytes + +pub fn encode_blocks(Array[RatchetBlock]) -> Bytes raise RatchetError + +pub fn encrypt_ecies_lookup_reply(Bytes, Bytes, Array[RatchetBlock]) -> Bytes raise RatchetError + +pub fn encrypt_new_session(@noise.KeyPair?, Bytes, ElligatorKeyPair, Array[RatchetBlock]) -> (Bytes, PendingNewSession?) raise RatchetError + +pub fn encrypt_new_session_reply(PendingNewSession, ElligatorKeyPair, Array[RatchetBlock]) -> (Bytes, RatchetPeerSession) raise RatchetError + +pub fn garlic_clove_block(GarlicDelivery, UInt32, UInt32, @i2np.I2npPayload) -> RatchetBlock raise RatchetError + +pub fn generate_elligator_keypair(() -> Bytes) -> ElligatorKeyPair raise RatchetError + +// Errors +#derive(Eq, @debug.Debug) +pub suberror RatchetError { + Crypto(@crypto.CryptoError) + Noise(@noise.NoiseError) + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + I2np(@i2np.I2npError) + InvalidLength(String) + InvalidFormat(String) + UnknownSession + AuthenticationFailed +} + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) struct ElligatorKeyPair { + private_key : Bytes + public_key : Bytes + elligator_repr : Bytes +} + +#derive(Eq, @debug.Debug) +pub(all) enum GarlicDelivery { + Local + Destination(@common.Hash) + Router(@common.Hash) + Tunnel(@common.Hash, UInt32) +} + +pub struct PendingNewSession { + ck : Bytes + h : Bytes + local_ephem_priv : Bytes + remote_ephem_pub : Bytes + remote_static_pub : Bytes + nsr_tagset : TagSet +} + +#derive(Eq, @debug.Debug) +pub(all) enum RatchetBlock { + DateTime(UInt32) + Termination(reason~ : Byte, additional_data~ : Bytes) + Options(Bytes) + MessageNumber(UInt32) + NextKey(flags~ : Byte, key_id~ : UInt32, public_key~ : Bytes?) + Ack(Array[(UInt32, UInt32)]) + AckRequest(Byte) + GarlicClove(delivery~ : GarlicDelivery, i2np_short~ : Bytes) + Padding(Bytes) + Unknown(Byte, Bytes) +} +pub fn RatchetBlock::encode(Self, @encoding.Writer) -> Unit raise RatchetError + +pub struct RatchetPeerSession { + remote_static_pub : Bytes + mut send_root_key : Bytes + mut send_tagset : TagSet + mut recv_root_key : Bytes + mut recv_tagset : TagSet + recv_window : Array[(UInt32, Bytes, Bytes)] + mut dh_ratchet_key_id : UInt32 + mut local_next_priv : Bytes? + mut local_next_pub : Bytes? + mut remote_next_pub : Bytes? +} +pub fn RatchetPeerSession::apply_dh_ratchet(Self, Bytes, Bytes, for_send~ : Bool) -> Unit raise RatchetError +pub fn RatchetPeerSession::encrypt_existing(Self, Array[RatchetBlock]) -> Bytes raise RatchetError + +pub struct RatchetSessionManager { + local_static : @noise.KeyPair + sessions : Array[RatchetPeerSession] + outbound_pending : Array[(Bytes, PendingNewSession)] + inbound_pending : Array[PendingNewSession] +} +pub fn RatchetSessionManager::create_next_key_block(Self, Bytes, () -> Bytes) -> RatchetBlock? raise RatchetError +pub fn RatchetSessionManager::decrypt_incoming(Self, Bytes) -> (Bytes?, Array[RatchetBlock]) raise RatchetError +pub fn RatchetSessionManager::encrypt_to_peer(Self, Bytes, Array[RatchetBlock], UInt32, () -> Bytes) -> Bytes raise RatchetError +pub fn RatchetSessionManager::new(@noise.KeyPair) -> Self + +pub struct TagSet { + mut tag_ck : Bytes + sesstag_const : Bytes + mut symm_ck : Bytes + mut msg_num : UInt32 +} +pub fn TagSet::next_entry(Self) -> (UInt32, Bytes, Bytes) raise RatchetError + +// Type aliases + +// Traits diff --git a/ratchet/ratchet_test.mbt b/ratchet/ratchet_test.mbt new file mode 100644 index 0000000..6dce22b --- /dev/null +++ b/ratchet/ratchet_test.mbt @@ -0,0 +1,165 @@ +///| +fn det_rand_gen(seed_init : Byte) -> () -> Bytes { + let ctr : Ref[Int32] = { val: seed_init.to_int(), } + fn() { + let idx = ctr.val + ctr.val = idx + 1 + let w = @encoding.Writer::new(capacity=8) + w.write_u32_be(idx.reinterpret_as_uint()) + @crypto.sha256(w.to_bytes()) + } +} + +///| +test "Proposal 144 GarlicClove and RatchetBlock encode/decode round-trip" { + let clove = @ratchet.garlic_clove_block( + Destination(@common.Hash::sha256(b"dest-a")), + 42U, + 1700000600U, + Data(data=b"hello-clove"), + ) + let blocks : Array[@ratchet.RatchetBlock] = [ + DateTime(1700000123U), + Options(b"\x01\x02"), + MessageNumber(5U), + NextKey(flags=b'\x05', key_id=1U, public_key=Some(Bytes::make(32, b'\xaa'))), + Ack([(1U, 3U), (1U, 4U)]), + AckRequest(b'\x00'), + clove, + Padding(b"\x00\x00\x00"), + ] + let wire = @ratchet.encode_blocks(blocks) + let decoded = @ratchet.decode_blocks(wire) + assert_eq(decoded, blocks) + match decoded[6] { + GarlicClove(delivery~, i2np_short~) => { + assert_eq(delivery, Destination(@common.Hash::sha256(b"dest-a"))) + let (hdr, payload) = @ratchet.decode_garlic_clove_i2np(i2np_short) + assert_eq(hdr.msg_id, 42U) + assert_eq(payload, Data(data=b"hello-clove")) + } + _ => fail("expected GarlicClove") + } +} + +///| +test "Proposal 144 ECIES-X25519-AEAD-Ratchet NS -> NSR -> bidirectional ES + DH ratchet + Unbound + DSM" { + let alice_s = @noise.KeyPair::from_private( + @crypto.sha256(b"alice-ecies-static"), + ) + let bob_s = @noise.KeyPair::from_private(@crypto.sha256(b"bob-ecies-static")) + let alice_mgr = @ratchet.RatchetSessionManager::new(alice_s) + let bob_mgr = @ratchet.RatchetSessionManager::new(bob_s) + let rand_a = det_rand_gen(b'\x10') + let rand_b = det_rand_gen(b'\x50') + + // 1. Alice -> Bob: Bound New Session + let c1 = @ratchet.garlic_clove_block( + Local, + 1U, + 1700000600U, + Data(data=b"msg-1-ns"), + ) + let ns_wire = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [c1], + 1700000100U, + rand_a, + ) + let (bob_from, bob_dec1) = bob_mgr.decrypt_incoming(ns_wire) + assert_eq(bob_from, Some(alice_s.public_key)) + assert_eq(bob_dec1.length(), 2) // DateTime + GarlicClove + + // 2. Bob -> Alice: New Session Reply (NSR) + let c2 = @ratchet.garlic_clove_block( + Local, + 2U, + 1700000600U, + Data(data=b"msg-2-nsr"), + ) + let nsr_wire = bob_mgr.encrypt_to_peer( + alice_s.public_key, + [c2], + 1700000101U, + rand_b, + ) + let (alice_from, alice_dec2) = alice_mgr.decrypt_incoming(nsr_wire) + assert_eq(alice_from, Some(bob_s.public_key)) + assert_eq(alice_dec2, [c2]) + + // 3. Alice <-> Bob: Existing Session (ES) bidirectional messages + for i = 0; i < 4; i = i + 1 { + let ca = @ratchet.garlic_clove_block( + Local, + (10 + i).reinterpret_as_uint(), + 1700000600U, + Data(data=b"alice-es"), + ) + let w_ab = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [ca], + 1700000102U, + rand_a, + ) + let (f1, d1) = bob_mgr.decrypt_incoming(w_ab) + assert_eq(f1, Some(alice_s.public_key)) + assert_eq(d1, [ca]) + + let cb = @ratchet.garlic_clove_block( + Local, + (20 + i).reinterpret_as_uint(), + 1700000600U, + Data(data=b"bob-es"), + ) + let w_ba = bob_mgr.encrypt_to_peer( + alice_s.public_key, + [cb], + 1700000103U, + rand_b, + ) + let (f2, d2) = alice_mgr.decrypt_incoming(w_ba) + assert_eq(f2, Some(bob_s.public_key)) + assert_eq(d2, [cb]) + } + + // 3b. DH Ratchet rotation with NextKey block + match alice_mgr.create_next_key_block(bob_s.public_key, rand_a) { + Some(nk_blk) => { + let w_nk = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [nk_blk], + 1700000105U, + rand_a, + ) + let (_, d_nk) = bob_mgr.decrypt_incoming(w_nk) + assert_eq(d_nk, [nk_blk]) + } + None => fail("expected NextKey block on established session") + } + + // 4. Unbound New Session + let ephem_u = @ratchet.generate_elligator_keypair(rand_a) + let (ub_wire, ub_pending) = @ratchet.encrypt_new_session( + None, + bob_s.public_key, + ephem_u, + [DateTime(1700000110U), GarlicClove(delivery=Local, i2np_short=b"unbound")], + ) + assert_true(ub_pending is None) + let (ub_dec, ub_rx_pending) = @ratchet.decrypt_new_session(bob_s, ub_wire) + assert_true(ub_rx_pending is None) + assert_eq(ub_dec.length(), 2) + + // 5. Proposal 154 ECIES DatabaseLookup reply round-trip + let rkey = Bytes::make(32, b'\x91') + let rtag = Bytes::make(8, b'\x92') + let dsm_blk = @ratchet.garlic_clove_block( + Local, + 99U, + 1700000600U, + Data(data=b"dsm-ls2"), + ) + let enc_dsm = @ratchet.encrypt_ecies_lookup_reply(rkey, rtag, [dsm_blk]) + let dec_dsm = @ratchet.decrypt_ecies_lookup_reply(rkey, rtag, enc_dsm) + assert_eq(dec_dsm, [dsm_blk]) +} diff --git a/router/moon.pkg b/router/moon.pkg index 9fe5d7a..8dd1b0d 100644 --- a/router/moon.pkg +++ b/router/moon.pkg @@ -3,9 +3,13 @@ import { "experiments/moon_i2p/crypto", "experiments/moon_i2p/common", "experiments/moon_i2p/noise", + "experiments/moon_i2p/i2np", + "experiments/moon_i2p/ntcp2", "experiments/moon_i2p/ntcp2_net", "experiments/moon_i2p/netdb", "experiments/moon_i2p/tunnel", + "experiments/moon_i2p/ratchet", + "experiments/moon_i2p/streaming", "experiments/moon_i2p/sam", } diff --git a/router/netdb_protocol.mbt b/router/netdb_protocol.mbt new file mode 100644 index 0000000..50bb0b9 --- /dev/null +++ b/router/netdb_protocol.mbt @@ -0,0 +1,504 @@ +///| +/// Active Floodfill NetDB protocol handlers (`DatabaseStore`, ECIES `DatabaseLookup`, +/// and iterative `DatabaseSearchReply` Kademlia lookup crawl). + +///| +priv struct PendingNetDbLookup { + target_hash : @common.Hash + reply_key : Bytes + reply_tag : Bytes + queried_peers : Array[@common.Hash] + candidate_peers : Array[@common.Hash] + started_ms : UInt64 + kind : Int32 // 0 = NAMING LOOKUP (.b32), 1 = STREAM CONNECT awaiting LeaseSet2 + client_idx : Int32 + req_name : String + session_id : String + silent : Bool +} + +///| +fn is_hash_in(h : @common.Hash, list : Array[@common.Hash]) -> Bool { + for item in list { + if item == h { + return true + } + } + false +} + +///| +fn Router::build_session_leaseset2( + self : Router, + sess : SamSession, + now_sec : UInt32, +) -> @common.LeaseSet2? { + let seed = match sess.ed_seed { + Some(s) => s + None => return None + } + let leases : Array[@common.Lease2] = [] + let max_leases = 3 + for t in self.tunnels.inbound { + if t.expires_sec > now_sec && + t.hops.length() > 0 && + leases.length() < max_leases { + leases.push({ + tunnel_gw: t.hops[0].router_hash, + tunnel_id: t.hops[0].receive_tunnel_id, + end_date_sec: t.expires_sec, + }) + } + } + if leases.length() == 0 { + leases.push({ + tunnel_gw: self.router_hash(), + tunnel_id: sess.virtual_tid, + end_date_sec: now_sec + 600U, + }) + } + let ls2 : @common.LeaseSet2 = { + destination: sess.dest, + published_sec: now_sec, + expires_offset: 600U, + flags: 0U, + offline_sig: None, + options: @common.Mapping::new(), + encryption_keys: [ + { key_type: X25519, key_data: sess.dest.inner.crypto_public_key(), }, + ], + leases, + signature: b"", + } + let signed = ls2.sign_ed25519(seed) catch { _ => return None } + let _ = self.netdb.store_lease_set2(signed, now_sec) catch { _ => false } + Some(signed) +} + +///| +fn Router::publish_session_leaseset2(self : Router, sess : SamSession) -> Unit { + let now_sec = @ntcp2_net.unix_time_sec() + let ls2 = match self.build_session_leaseset2(sess, now_sec) { + Some(l) => l + None => return + } + let raw = ls2.to_bytes() catch { _ => return } + let utc_date = @netdb.format_utc_date(now_sec.to_uint64()) + let floodfills = self.netdb.closest_peers( + sess.hash, + utc_date, + 3, + floodfills_only=true, + excluded=[self.router_hash()], + ) + let payload : @i2np.I2npPayload = DatabaseStore( + key=sess.hash, + store_type=b'\x03', + reply_token=0U, + reply_tunnel_id=0U, + reply_gateway=None, + data=raw, + ) + for ff in floodfills { + let _ = self.send_i2np_to_peer(ff.identity.hash(), payload) + } +} + +///| +fn Router::republish_all_sessions(self : Router) -> Unit { + for sess in self.sessions { + self.publish_session_leaseset2(sess) + } +} + +///| +fn Router::select_lookup_peers( + self : Router, + target_hash : @common.Hash, + excluded : Array[@common.Hash], + now_sec : UInt32, + limit : Int32, +) -> Array[@common.Hash] { + let utc_date = @netdb.format_utc_date(now_sec.to_uint64()) + let excl : Array[@common.Hash] = [self.router_hash()] + for e in excluded { + excl.push(e) + } + let ffs = self.netdb.closest_peers( + target_hash, + utc_date, + limit, + floodfills_only=true, + excluded=excl, + ) + let peers = if ffs.length() > 0 { + ffs + } else { + self.netdb.closest_peers( + target_hash, + utc_date, + limit, + floodfills_only=false, + excluded=excl, + ) + } + let out : Array[@common.Hash] = [] + for p in peers { + out.push(p.identity.hash()) + } + out +} + +///| +fn Router::send_lookup_query( + self : Router, + lk : PendingNetDbLookup, + peer_hash : @common.Hash, +) -> Unit { + if !is_hash_in(peer_hash, lk.queried_peers) { + lk.queried_peers.push(peer_hash) + } + // Proposal 154 ECIES encrypted reply (0x10) + LeaseSet lookup type (0x04) + let lookup : @i2np.I2npPayload = DatabaseLookup( + key=lk.target_hash, + from=self.router_hash(), + flags=b'\x14', + reply_tunnel_id=None, + excluded_peers=lk.queried_peers, + reply_key=Some(lk.reply_key), + reply_tags=[lk.reply_tag], + ) + let _ = self.send_i2np_to_peer(peer_hash, lookup) +} + +///| +fn Router::start_netdb_lookup( + self : Router, + target_hash : @common.Hash, + kind : Int32, + client_idx : Int32, + req_name : String, + session_id : String, + silent : Bool, +) -> Bool { + let now_sec = @ntcp2_net.unix_time_sec() + let initial_peers = self.select_lookup_peers(target_hash, [], now_sec, 3) + if initial_peers.length() == 0 { + return false + } + let reply_key = next_rand_32() + let tag_rand = @ntcp2_net.random_bytes(8) catch { + _ => Bytes::make(8, b'\x77') + } + let lk : PendingNetDbLookup = { + target_hash, + reply_key, + reply_tag: tag_rand, + queried_peers: [], + candidate_peers: [], + started_ms: @ntcp2_net.unix_time_ms(), + kind, + client_idx, + req_name, + session_id, + silent, + } + self.pending_lookups.push(lk) + self.send_lookup_query(lk, initial_peers[0]) + for i = 1; i < initial_peers.length(); i = i + 1 { + lk.candidate_peers.push(initial_peers[i]) + } + true +} + +///| +fn Router::handle_database_store_msg( + self : Router, + from_peer : @common.Hash?, + key : @common.Hash, + store_type : Byte, + reply_token : UInt32, + reply_tunnel_id : UInt32, + reply_gateway : @common.Hash?, + data : Bytes, + now_sec : UInt32, +) -> Unit { + let stored = self.netdb.handle_database_store(store_type, key, data, now_sec) catch { + _ => false + } + if stored && (store_type.to_int() & 0x0F) == 3 { + self.complete_lookups_for_hash(key, now_sec) + } + if reply_token != 0U { + let status : @i2np.I2npPayload = DeliveryStatus( + msg_id=reply_token, + timestamp_ms=@ntcp2_net.unix_time_ms(), + ) + match reply_gateway { + Some(gw) => + if reply_tunnel_id != 0U { + let std = @i2np.encode_standard_message( + self.alloc_msg_id(), + @ntcp2_net.unix_time_ms() + 60000UL, + status, + ) catch { + _ => return + } + let _ = self.send_i2np_to_peer( + gw, + TunnelGateway(tunnel_id=reply_tunnel_id, data=std), + ) + } else { + let _ = self.send_i2np_to_peer(gw, status) + } + None => + match from_peer { + Some(ph) => { + let _ = self.send_i2np_to_peer(ph, status) + } + None => () + } + } + } +} + +///| +fn Router::handle_database_lookup_msg( + self : Router, + from_peer : @common.Hash?, + key : @common.Hash, + from : @common.Hash, + flags : Byte, + reply_tunnel_id : UInt32?, + excluded_peers : Array[@common.Hash], + reply_key : Bytes?, + reply_tags : Array[Bytes], + now_sec : UInt32, +) -> Unit { + let reply = self.netdb.handle_database_lookup( + self.router_hash(), + key, + flags, + excluded_peers, + now_sec, + ) catch { + _ => return + } + let enc_ecies = (flags.to_int() & 0x10) != 0 + let wire_reply : @i2np.I2npPayload = if enc_ecies && + reply is DatabaseStore(..) { + match reply_key { + Some(rk) if reply_tags.length() > 0 => { + let exp_sec = now_sec + 60U + let clove = @ratchet.garlic_clove_block( + Local, + self.alloc_msg_id(), + exp_sec, + reply, + ) catch { + _ => return + } + let enc = @ratchet.encrypt_ecies_lookup_reply(rk, reply_tags[0], [clove]) catch { + _ => return + } + Garlic(data=enc) + } + _ => reply + } + } else { + reply + } + if (flags.to_int() & 0x01) != 0 { + match reply_tunnel_id { + Some(tid) => { + let std = @i2np.encode_standard_message( + self.alloc_msg_id(), + @ntcp2_net.unix_time_ms() + 60000UL, + wire_reply, + ) catch { + _ => return + } + let _ = self.send_i2np_to_peer( + from, + TunnelGateway(tunnel_id=tid, data=std), + ) + return + } + None => () + } + } + let dest_peer = match self.netdb.get_router_info(from) { + Some(_) => from + None => + match from_peer { + Some(p) => p + None => from + } + } + let _ = self.send_i2np_to_peer(dest_peer, wire_reply) +} + +///| +fn Router::handle_database_search_reply_msg( + self : Router, + key : @common.Hash, + peer_hashes : Array[@common.Hash], + from : @common.Hash, +) -> Unit { + for lk in self.pending_lookups { + if lk.target_hash == key { + if !is_hash_in(from, lk.queried_peers) { + lk.queried_peers.push(from) + } + for ph in peer_hashes { + if ph != self.router_hash() && + !is_hash_in(ph, lk.queried_peers) && + !is_hash_in(ph, lk.candidate_peers) && + self.netdb.get_router_info(ph) is Some(_) { + lk.candidate_peers.push(ph) + } + } + while lk.candidate_peers.length() > 0 && lk.queried_peers.length() < 8 { + let next_peer = lk.candidate_peers.remove(0) + if !is_hash_in(next_peer, lk.queried_peers) { + self.send_lookup_query(lk, next_peer) + break + } + } + } + } +} + +///| +fn Router::try_handle_lookup_garlic_reply( + self : Router, + garlic_data : Bytes, + now_sec : UInt32, +) -> Bool { + if garlic_data.length() < 24 { + return false + } + let wire_tag = garlic_data[:8].to_owned() + let mut matched_idx = -1 + for i = 0; i < self.pending_lookups.length(); i = i + 1 { + if @crypto.ct_eq(wire_tag, self.pending_lookups[i].reply_tag) { + matched_idx = i + break + } + } + if matched_idx < 0 { + return false + } + let lk = self.pending_lookups[matched_idx] + let blocks = @ratchet.decrypt_ecies_lookup_reply( + lk.reply_key, + lk.reply_tag, + garlic_data, + ) catch { + _ => return false + } + for blk in blocks { + match blk { + GarlicClove(i2np_short~, ..) => { + let decoded = Some(@ratchet.decode_garlic_clove_i2np(i2np_short)) catch { + _ => None + } + match decoded { + Some((hdr, inner)) => self.handle_i2np_message(None, hdr, inner) + None => () + } + } + _ => () + } + } + let _ = now_sec + true +} + +///| +fn Router::complete_lookups_for_hash( + self : Router, + key : @common.Hash, + now_sec : UInt32, +) -> Unit { + let ls2 = match self.netdb.get_lease_set2(key, now_sec) { + Some(l) => l + None => return + } + let mut i = 0 + while i < self.pending_lookups.length() { + let lk = self.pending_lookups[i] + if lk.target_hash == key { + let _ = self.pending_lookups.remove(i) + if lk.client_idx < self.sam_clients.length() { + let c = self.sam_clients[lk.client_idx] + if !c.closed { + if lk.kind == 0 { + let val = ls2.destination.to_base64() + let _ = send_sam_line( + c.sock, + "NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{val}", + ) + } else { + self.finish_remote_stream_connect(lk, ls2) + } + } + } + } else { + i += 1 + } + } +} + +///| +fn Router::poll_netdb_lookups(self : Router) -> Unit { + let now_ms = @ntcp2_net.unix_time_ms() + let now_sec = (now_ms / 1000UL).to_uint() + let mut i = 0 + while i < self.pending_lookups.length() { + let lk = self.pending_lookups[i] + match self.netdb.get_lease_set2(lk.target_hash, now_sec) { + Some(ls2) => { + let _ = self.pending_lookups.remove(i) + if lk.client_idx < self.sam_clients.length() && + !self.sam_clients[lk.client_idx].closed { + if lk.kind == 0 { + let _ = send_sam_line( + self.sam_clients[lk.client_idx].sock, + "NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{ls2.destination.to_base64()}", + ) + } else { + self.finish_remote_stream_connect(lk, ls2) + } + } + continue + } + None => () + } + if now_ms > lk.started_ms + 8000UL { + let _ = self.pending_lookups.remove(i) + if lk.client_idx < self.sam_clients.length() { + let c = self.sam_clients[lk.client_idx] + if !c.closed { + if lk.kind == 0 { + let _ = send_sam_line( + c.sock, + "NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{lk.req_name}", + ) + } else { + if !lk.silent { + let _ = send_sam_line( + c.sock, + "STREAM STATUS RESULT=CANT_REACH_PEER", + ) + } + c.closed = true + c.sock.close() + } + } + } + } else { + i += 1 + } + } +} diff --git a/router/ntcp2_peers.mbt b/router/ntcp2_peers.mbt new file mode 100644 index 0000000..d3da1e7 --- /dev/null +++ b/router/ntcp2_peers.mbt @@ -0,0 +1,412 @@ +///| +/// Non-blocking NTCP2 peer pool, outbound dialer, and Data Phase frame dispatcher. + +///| +priv struct PendingPeerDial { + peer_hash : @common.Hash + dial : @ntcp2_net.PendingNtcp2Dial +} + +///| +priv struct PeerSession { + hash : @common.Hash + conn : @ntcp2_net.Ntcp2Conn + mut last_active_ms : UInt64 +} + +///| +priv struct PendingPeerSend { + target_hash : @common.Hash + msg_id : UInt32 + expiration_sec : UInt32 + payload : @i2np.I2npPayload + queued_ms : UInt64 +} + +///| +pub fn Router::peer_count(self : Router) -> Int32 { + self.peers.length() +} + +///| +fn Router::find_peer_hash_by_static( + self : Router, + static_pub : Bytes, +) -> @common.Hash? { + for entry in self.netdb.routers { + for addr in entry.1.addresses { + if addr.transport_style == "NTCP2" { + match addr.options.get("s") { + Some(s_b64) => { + let s_bytes = @encoding.base64_decode(s_b64) catch { _ => b"" } + if s_bytes.length() == 32 && @crypto.ct_eq(s_bytes, static_pub) { + return Some(entry.0) + } + } + None => () + } + } + } + } + None +} + +///| +fn Router::has_pending_dial(self : Router, target_hash : @common.Hash) -> Bool { + for pd in self.pending_dials { + if pd.peer_hash == target_hash { + return true + } + } + false +} + +///| +fn Router::ensure_peer_dial(self : Router, target_hash : @common.Hash) -> Unit { + if target_hash == self.router_hash() || self.has_pending_dial(target_hash) { + return + } + let ri = match self.netdb.get_router_info(target_hash) { + Some(r) => r + None => return + } + let peer_info = @ntcp2_net.extract_ntcp2_peer(ri) catch { _ => return } + let dial = @ntcp2_net.PendingNtcp2Dial::start( + peer_info, + self.static_key, + self.router_info, + check_clock_skew=self.check_clock_skew, + remote_ri=Some(ri), + ) catch { + _ => return + } + self.pending_dials.push({ peer_hash: target_hash, dial, }) +} + +///| +fn Router::send_i2np_to_peer( + self : Router, + target_hash : @common.Hash, + payload : @i2np.I2npPayload, + msg_id_override~ : UInt32? = None, +) -> UInt32 { + let mid = match msg_id_override { + Some(id) => id + None => self.alloc_msg_id() + } + let now_ms = @ntcp2_net.unix_time_ms() + let exp_sec = (now_ms / 1000UL).to_uint() + 60U + if target_hash == self.router_hash() { + self.pending_sends.push({ + target_hash, + msg_id: mid, + expiration_sec: exp_sec, + payload, + queued_ms: now_ms, + }) + return mid + } + // Prefer most recently active live session for target_hash + let mut idx = self.peers.length() - 1 + while idx >= 0 { + if self.peers[idx].hash == target_hash { + let ok = try { + self.peers[idx].conn.send_i2np(mid, exp_sec, payload) + true + } catch { + _ => false + } + if ok { + self.peers[idx].last_active_ms = now_ms + return mid + } + self.peers[idx].conn.close() + let _ = self.peers.remove(idx) + } + idx -= 1 + } + self.pending_sends.push({ + target_hash, + msg_id: mid, + expiration_sec: exp_sec, + payload, + queued_ms: now_ms, + }) + self.ensure_peer_dial(target_hash) + mid +} + +///| +fn Router::send_routed_i2np( + self : Router, + target_gw : @common.Hash, + target_tid : UInt32?, + payload : @i2np.I2npPayload, +) -> Unit { + if self.tunnels.outbound.length() > 0 { + let out_t = self.tunnels.outbound[0] + let target : @tunnel.DeliveryTarget = match target_tid { + Some(tid) => Tunnel(tunnel_id=tid, gateway=target_gw) + None => Router(router_hash=target_gw) + } + let routed = try { + self.send_through_tunnel(out_t.id, target, payload) + true + } catch { + _ => false + } + if routed { + return + } + } + match target_tid { + Some(tid) => { + let mid = self.alloc_msg_id() + let exp_ms = @ntcp2_net.unix_time_ms() + 60000UL + let std_bytes = @i2np.encode_standard_message(mid, exp_ms, payload) catch { + _ => return + } + let _ = self.send_i2np_to_peer( + target_gw, + TunnelGateway(tunnel_id=tid, data=std_bytes), + ) + } + None => { + let _ = self.send_i2np_to_peer(target_gw, payload) + } + } +} + +///| +fn Router::flush_pending_sends_for( + self : Router, + target_hash : @common.Hash, + peer : PeerSession, +) -> Bool { + let mut i = 0 + while i < self.pending_sends.length() { + let ps = self.pending_sends[i] + if ps.target_hash == target_hash { + let ok = try { + peer.conn.send_i2np(ps.msg_id, ps.expiration_sec, ps.payload) + true + } catch { + _ => false + } + if !ok { + return false + } + peer.last_active_ms = @ntcp2_net.unix_time_ms() + let _ = self.pending_sends.remove(i) + } else { + i += 1 + } + } + true +} + +///| +fn Router::handle_peer_blocks( + self : Router, + peer_hash : @common.Hash, + blocks : Array[@ntcp2.Ntcp2Block], +) -> Bool { + let mut should_close = false + for blk in blocks { + match blk { + I2np(short_bytes) => { + let decoded = Some( + @i2np.decode_short_message(@encoding.Reader::new(short_bytes)), + ) catch { + _ => None + } + match decoded { + Some((hdr, payload)) => + self.handle_i2np_message(Some(peer_hash), hdr, payload) + None => () + } + } + RouterInfo(router_info~, ..) => { + let ri = @common.RouterInfo::decode(@encoding.Reader::new(router_info)) catch { + _ => continue + } + let _ = self.netdb.store_router_info(ri) catch { _ => false } + } + Termination(..) => should_close = true + _ => () + } + } + should_close +} + +///| +fn Router::step_ntcp2_peers(self : Router) -> Bool { + let now_ms = @ntcp2_net.unix_time_ms() + let mut did_work = false + + // 1. Accept any newly arrived TCP sockets into non-blocking responder handshakes + for _a = 0; _a < 8; _a = _a + 1 { + match (self.ntcp2_listener.accept_nonblocking() catch { _ => None }) { + Some(sock) => { + let pa_opt = Some( + @ntcp2_net.PendingNtcp2Accept::start( + sock, + self.static_key, + self.router_hash().as_bytes(), + self.ntcp2_iv, + replay_cache=Some(self.replay_cache), + check_clock_skew=self.check_clock_skew, + ), + ) catch { + _ => None + } + match pa_opt { + Some(pa) => { + self.pending_accepts.push(pa) + did_work = true + } + None => () + } + } + None => break + } + } + + // 2. Step pending inbound NTCP2 handshakes + let mut ai = 0 + while ai < self.pending_accepts.length() { + let pa = self.pending_accepts[ai] + if now_ms > pa.started_at_ms() + 10000UL { + pa.close() + let _ = self.pending_accepts.remove(ai) + did_work = true + continue + } + let stepped = (pa.step(), false) catch { _ => (None, true) } + if stepped.1 { + pa.close() + let _ = self.pending_accepts.remove(ai) + did_work = true + continue + } + match stepped.0 { + Some(conn) => { + did_work = true + let _ = self.pending_accepts.remove(ai) + let mut peer_hash : @common.Hash? = None + match conn.remote_router_info { + Some(ri) => { + let _ = self.netdb.store_router_info(ri) catch { _ => false } + peer_hash = Some(ri.identity.hash()) + } + None => + peer_hash = self.find_peer_hash_by_static( + conn.session.remote_static(), + ) + } + match peer_hash { + Some(ph) => { + let ps : PeerSession = { hash: ph, conn, last_active_ms: now_ms, } + self.peers.push(ps) + let _ = self.flush_pending_sends_for(ph, ps) + } + None => conn.close() + } + } + None => ai += 1 + } + } + + // 3. Step pending outbound NTCP2 dials + let mut di = 0 + while di < self.pending_dials.length() { + let pd = self.pending_dials[di] + if now_ms > pd.dial.started_at_ms() + 10000UL { + pd.dial.close() + let _ = self.pending_dials.remove(di) + did_work = true + continue + } + let stepped = (pd.dial.step(), false) catch { _ => (None, true) } + if stepped.1 { + pd.dial.close() + let _ = self.pending_dials.remove(di) + did_work = true + continue + } + match stepped.0 { + Some(conn) => { + did_work = true + let _ = self.pending_dials.remove(di) + let ps : PeerSession = { + hash: pd.peer_hash, + conn, + last_active_ms: now_ms, + } + self.peers.push(ps) + let _ = self.flush_pending_sends_for(pd.peer_hash, ps) + } + None => di += 1 + } + } + + // 4. Deliver any local loopback sends or retry/expire orphaned pending sends + let local_msgs : Array[PendingPeerSend] = [] + let mut si = 0 + while si < self.pending_sends.length() { + let ps = self.pending_sends[si] + if ps.target_hash == self.router_hash() { + local_msgs.push(ps) + let _ = self.pending_sends.remove(si) + did_work = true + } else if now_ms > ps.queued_ms + 15000UL { + let _ = self.pending_sends.remove(si) + } else { + si += 1 + } + } + for ps in local_msgs { + self.handle_i2np_message( + Some(self.router_hash()), + { + msg_type: ps.payload.msg_type(), + msg_id: ps.msg_id, + expiration_sec: ps.expiration_sec, + }, + ps.payload, + ) + } + + // 5. Non-blocking read & dispatch on all active NTCP2 peer sessions + let mut pi = 0 + while pi < self.peers.length() { + let peer = self.peers[pi] + let mut alive = true + for _frame = 0; _frame < 32; _frame = _frame + 1 { + let recv_opt = peer.conn.try_recv_blocks() catch { + _ => { + alive = false + None + } + } + match recv_opt { + Some(blocks) => { + did_work = true + peer.last_active_ms = now_ms + if self.handle_peer_blocks(peer.hash, blocks) { + alive = false + break + } + } + None => break + } + } + if !alive || now_ms > peer.last_active_ms + 120000UL { + peer.conn.close() + let _ = self.peers.remove(pi) + } else { + pi += 1 + } + } + did_work +} diff --git a/router/router.mbt b/router/router.mbt index 35e2855..6b0a491 100644 --- a/router/router.mbt +++ b/router/router.mbt @@ -1,6 +1,7 @@ ///| -/// Native MoonBit I2P Router Core with transient identity, NetDB, TunnelManager, -/// NTCP2 TCP listener, and embedded SAMv3 TCP bridge (single-threaded poll loop). +/// Native MoonBit I2P Router Core with transient/persistent SAM sessions, NetDB floodfill +/// protocol, Proposal 157 multi-hop TunnelManager, non-blocking NTCP2 peer pool, +/// Proposal 144 ECIES-X25519-AEAD-Ratchet Garlic, and Ed25519 I2P Streaming. ///| #derive(Eq, Debug) @@ -10,6 +11,9 @@ pub suberror RouterError { Common(@common.CommonError) Noise(@noise.NoiseError) NetDb(@netdb.NetDbError) + I2np(@i2np.I2npError) + Tunnel(@tunnel.TunnelError) + Protocol(String) } ///| @@ -31,31 +35,6 @@ pub fn RouterConfig::default() -> RouterConfig { } } -///| -priv struct SamSession { - id : String - pub_b64 : String - b32 : String -} - -///| -priv struct SamClientConn { - sock : @ntcp2_net.TcpSocket - mut session_id : String? - mut mode : Int32 // 0 = command, 1 = waiting_accept, 2 = bridged - mut accept_session_id : String - mut accept_silent : Bool - mut closed : Bool -} - -///| -priv struct StreamBridge { - a : @ntcp2_net.TcpSocket - b : @ntcp2_net.TcpSocket - mut a_eof : Bool - mut b_eof : Bool -} - ///| /// Live MoonBit I2P Router Core instance. pub struct Router { @@ -67,45 +46,93 @@ pub struct Router { tunnels : @tunnel.TunnelManager ntcp2_listener : @ntcp2_net.TcpListener sam_listener : @ntcp2_net.TcpListener + check_clock_skew : Bool + priv mut next_msg_id : UInt32 + priv mut next_tunnel_id : UInt32 + priv mut next_stream_id : UInt32 + priv replay_cache : @ntcp2.EphemeralReplayCache + priv pending_accepts : Array[@ntcp2_net.PendingNtcp2Accept] + priv pending_dials : Array[PendingPeerDial] + priv peers : Array[PeerSession] + priv pending_sends : Array[PendingPeerSend] + priv pending_lookups : Array[PendingNetDbLookup] + priv pending_builds : Array[PendingTunnelBuild] + priv reassembler : @tunnel.FragmentReassembler priv sessions : Array[SamSession] priv sam_clients : Array[SamClientConn] priv bridges : Array[StreamBridge] + priv remote_bridges : Array[RemoteStreamBridge] priv aliases : Array[(String, String)] // hostname -> pub_b64 } ///| -/// Generates a valid transient 391-byte X25519+Ed25519 I2P Destination and -/// returns `(dest, pub_b64, priv_b64, ed_seed)`. -fn generate_transient_destination() -> ( - @common.Destination, - String, - String, - Bytes, -) raise RouterError { - let ed_seed = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } - let ed_pub = @crypto.ed25519_public_key(ed_seed) catch { - e => raise Crypto(e) +fn u32_from_be_prefix(b : Bytes) -> UInt32 { + ( + (b[0].to_uint() << 24) | + (b[1].to_uint() << 16) | + (b[2].to_uint() << 8) | + b[3].to_uint() + ) & + 0x7FFFFFFFU +} + +///| +fn Router::alloc_msg_id(self : Router) -> UInt32 { + let mut id = self.next_msg_id + if id == 0U { + id = 1U } - let x_priv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } - let x_pub = @crypto.x25519_public_key(x_priv) catch { e => raise Crypto(e) } - let pad = @ntcp2_net.random_bytes(320) catch { e => raise Net(e) } - let dest = @common.Destination::new_x25519_ed25519(x_pub, ed_pub, padding=pad) catch { - e => raise Common(e) + self.next_msg_id = id + 1U + id +} + +///| +fn Router::alloc_tunnel_id(self : Router) -> UInt32 { + let mut id = self.next_tunnel_id + if id == 0U { + id = 1U } - let pub_bytes = dest.to_bytes() - let priv_w = @encoding.Writer::new(capacity=pub_bytes.length() + 64) - priv_w.write_bytes(pub_bytes) - priv_w.write_bytes(x_priv) - priv_w.write_bytes(ed_seed) - let pub_b64 = @encoding.base64_encode(pub_bytes) - let priv_b64 = @encoding.base64_encode(priv_w.to_bytes()) - (dest, pub_b64, priv_b64, ed_seed) + self.next_tunnel_id = id + 1U + id +} + +///| +fn Router::alloc_stream_id(self : Router) -> UInt32 { + let mut id = self.next_stream_id + if id == 0U { + id = 1U + } + self.next_stream_id = id + 1U + id +} + +///| +fn next_rand_32() -> Bytes { + @ntcp2_net.random_bytes(32) catch { + _ => Bytes::make(32, b'\x42') + } +} + +///| +fn non_zero_random_bytes(n : Int32) -> Bytes { + let raw = @ntcp2_net.random_bytes(n) catch { + _ => return Bytes::make(n, b'\x01') + } + let out = FixedArray::make(n, b'\x01') + for i = 0; i < raw.length(); i = i + 1 { + out[i] = if raw[i] == b'\x00' { b'\x01' } else { raw[i] } + } + Bytes::from_array(out) } ///| /// Starts the MoonBit I2P Router Core with transient keys, self-signed `RouterInfo`, /// NTCP2 TCP listener, and embedded SAMv3 TCP bridge. -pub fn Router::start(config : RouterConfig) -> Router raise RouterError { +pub fn Router::start( + config : RouterConfig, + floodfill~ : Bool = false, + check_clock_skew~ : Bool = true, +) -> Router raise RouterError { let ed_seed = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } let ed_pub = @crypto.ed25519_public_key(ed_seed) catch { e => raise Crypto(e) @@ -143,12 +170,13 @@ pub fn Router::start(config : RouterConfig) -> Router raise RouterError { ("s", @encoding.base64_encode(static_key.public_key)), ("v", "2"), ]) + let caps = if floodfill { "LRf" } else { "LR" } let ri : @common.RouterInfo = { identity: id, published: @ntcp2_net.unix_time_ms(), addresses: [@common.RouterAddress::new(b'\x03', "NTCP2", addr_opts)], options: @common.Mapping::from_entries([ - ("caps", "LR"), + ("caps", caps), ("netId", "2"), ("router.version", "0.9.64"), ]), @@ -157,7 +185,13 @@ pub fn Router::start(config : RouterConfig) -> Router raise RouterError { let signed_ri = ri.sign_ed25519(ed_seed) catch { e => raise Common(e) } let netdb = @netdb.NetDb::new() let _ = netdb.store_router_info(signed_ri) catch { e => raise NetDb(e) } - let router : Router = { + let rseed = @ntcp2_net.random_bytes(12) catch { + _ => Bytes::make(12, b'\x01') + } + let m0 = u32_from_be_prefix(rseed[:4].to_owned()) | 1U + let t0 = u32_from_be_prefix(rseed[4:8].to_owned()) % 0x0FFFFFFFU + 10000U + let s0 = u32_from_be_prefix(rseed[8:12].to_owned()) % 0x0FFFFFFFU + 100U + { ed_seed, static_key, ntcp2_iv, @@ -166,12 +200,24 @@ pub fn Router::start(config : RouterConfig) -> Router raise RouterError { tunnels: @tunnel.TunnelManager::new(), ntcp2_listener, sam_listener, + check_clock_skew, + next_msg_id: m0, + next_tunnel_id: t0, + next_stream_id: s0, + replay_cache: @ntcp2.EphemeralReplayCache::new(max_entries=1024), + pending_accepts: [], + pending_dials: [], + peers: [], + pending_sends: [], + pending_lookups: [], + pending_builds: [], + reassembler: @tunnel.FragmentReassembler::new(), sessions: [], sam_clients: [], bridges: [], + remote_bridges: [], aliases: [], } - router } ///| @@ -220,6 +266,69 @@ pub fn Router::load_peer_file( ri } +///| +/// Scans a directory of `.dat` `RouterInfo` files, verifies Ed25519 signatures, +/// and returns how many peer entries were loaded into `self.netdb`. +pub fn Router::load_peer_dir( + self : Router, + dir_path : String, +) -> Int32 raise RouterError { + let files = @ntcp2_net.list_dir_files(dir_path) catch { e => raise Net(e) } + let mut loaded = 0 + let sep = if dir_path.has_suffix("/") { "" } else { "/" } + for fname in files { + let full_path = "\{dir_path}\{sep}\{fname}" + let ok = try { + let _ = self.load_peer_file(full_path) + true + } catch { + _ => false + } + if ok { + loaded += 1 + } + } + loaded +} + +///| +/// Parses raw `.su3` reseed bytes, verifies each contained `RouterInfo`'s Ed25519 +/// signature, and stores valid peers in `self.netdb`. +pub fn Router::load_reseed_su3_bytes( + self : Router, + su3_bytes : Bytes, +) -> Int32 raise RouterError { + let ris = @common.parse_reseed_su3(su3_bytes) catch { e => raise Common(e) } + let mut count = 0 + for ri in ris { + let stored = self.netdb.store_router_info(ri) catch { _ => false } + if stored { + count += 1 + } + } + count +} + +///| +/// Loads a local `.su3` reseed file into `self.netdb`. +pub fn Router::load_reseed_su3_file( + self : Router, + path : String, +) -> Int32 raise RouterError { + let raw = @ntcp2_net.read_file_bytes(path) catch { e => raise Net(e) } + self.load_reseed_su3_bytes(raw) +} + +///| +/// Fetches an HTTPS `.su3` reseed bundle via system `curl` and imports verified peers. +pub fn Router::reseed_from_url( + self : Router, + url : String, +) -> Int32 raise RouterError { + let raw = @ntcp2_net.fetch_https_bytes(url) catch { e => raise Net(e) } + self.load_reseed_su3_bytes(raw) +} + ///| pub fn Router::close(self : Router) -> Unit { for c in self.sam_clients { @@ -232,440 +341,124 @@ pub fn Router::close(self : Router) -> Unit { b.a.close() b.b.close() } + for rb in self.remote_bridges { + if !rb.closed { + rb.sock.close() + rb.closed = true + } + } + for pa in self.pending_accepts { + pa.close() + } + for pd in self.pending_dials { + pd.dial.close() + } + for p in self.peers { + p.conn.close() + } self.sam_listener.close() self.ntcp2_listener.close() } ///| -fn Router::find_session_by_id(self : Router, id : String) -> SamSession? { - for s in self.sessions { - if s.id == id { - return Some(s) - } - } - None -} - -///| -fn Router::find_session_by_pub(self : Router, pub_b64 : String) -> SamSession? { - for s in self.sessions { - if s.pub_b64 == pub_b64 { - return Some(s) - } - } - None -} - -///| -fn Router::resolve_name( +fn Router::handle_i2np_message( self : Router, - name : String, - client_session_id : String?, -) -> String? { - if name == "ME" { - match client_session_id { - Some(sid) => - match self.find_session_by_id(sid) { - Some(s) => return Some(s.pub_b64) - None => () - } - None => () - } - return None - } - let lower = name.to_lower() - // Check local aliases - for entry in self.aliases { - if entry.0 == lower { - return Some(entry.1) - } - } - // Check active local sessions by .b32.i2p - for s in self.sessions { - if s.b32 == lower { - return Some(s.pub_b64) - } - } - // Check NetDB LeaseSet2 entries by .b32.i2p - let now_sec = @ntcp2_net.unix_time_sec() - match self.netdb.get_lease_set2_by_b32(lower, now_sec) { - Some(ls2) => return Some(ls2.destination.to_base64()) - None => () - } - None -} - -///| -fn send_sam_line(sock : @ntcp2_net.TcpSocket, line : String) -> Bool { - sock.write_all(@encoding.string_to_utf8_bytes(line + "\n")) catch { - _ => return false - } - true -} - -///| -fn Router::handle_sam_command( - self : Router, - client_idx : Int32, - line : String, + from_peer : @common.Hash?, + hdr : @i2np.ShortHeader, + payload : @i2np.I2npPayload, ) -> Unit { - let client = self.sam_clients[client_idx] - let msg = @sam.SamMessage::parse(line) catch { - _ => { - let _ = send_sam_line( - client.sock, - "HELLO REPLY RESULT=I2P_ERROR MESSAGE=parse_error", + let now_sec = @ntcp2_net.unix_time_sec() + match payload { + DatabaseStore( + key~, + store_type~, + reply_token~, + reply_tunnel_id~, + reply_gateway~, + data~ + ) => + self.handle_database_store_msg( + from_peer, key, store_type, reply_token, reply_tunnel_id, reply_gateway, + data, now_sec, ) - return - } - } - match (msg.verb, msg.subcommand) { - ("HELLO", Some("VERSION")) => { - let _ = send_sam_line(client.sock, "HELLO REPLY RESULT=OK VERSION=3.3") - } - ("DEST", Some("GENERATE")) => { - let (_dest, pub_b64, priv_b64, _seed) = generate_transient_destination() catch { - _ => { - let _ = send_sam_line(client.sock, "DEST REPLY RESULT=I2P_ERROR") - return - } - } - let _ = send_sam_line( - client.sock, - "DEST REPLY PUB=\{pub_b64} PRIV=\{priv_b64}", - ) - } - ("NAMING", Some("LOOKUP")) => { - let name = match msg.get("NAME") { - Some(n) => n - None => { - let _ = send_sam_line( - client.sock, - "NAMING REPLY RESULT=INVALID_KEY NAME=", - ) - return - } - } - match self.resolve_name(name, client.session_id) { - Some(val) => { - let _ = send_sam_line( - client.sock, - "NAMING REPLY RESULT=OK NAME=\{name} VALUE=\{val}", - ) - } - None => { - let _ = send_sam_line( - client.sock, - "NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{name}", - ) - } - } - } - ("SESSION", Some("CREATE")) => { - let sid = match msg.get("ID") { - Some(id) => id - None => { - let _ = send_sam_line( - client.sock, - "SESSION STATUS RESULT=I2P_ERROR MESSAGE=missing_id", - ) - return - } - } - if self.find_session_by_id(sid) is Some(_) { - let _ = send_sam_line( - client.sock, - "SESSION STATUS RESULT=DUPLICATED_ID", - ) - return - } - let dest_param = match msg.get("DESTINATION") { - Some(d) => d - None => "TRANSIENT" - } - let (dest, pub_b64, priv_b64, opt_seed) = if dest_param == "TRANSIENT" { - let (d, pb, prb, seed) = generate_transient_destination() catch { - _ => { - let _ = send_sam_line( - client.sock, - "SESSION STATUS RESULT=I2P_ERROR", - ) - return - } - } - (d, pb, prb, Some(seed)) - } else { - let raw = @encoding.base64_decode(dest_param) catch { - _ => { - let _ = send_sam_line( - client.sock, - "SESSION STATUS RESULT=INVALID_KEY", - ) - return - } - } - let d = @common.Destination::decode(@encoding.Reader::new(raw)) catch { - _ => { - let _ = send_sam_line( - client.sock, - "SESSION STATUS RESULT=INVALID_KEY", - ) - return - } - } - (d, d.to_base64(), dest_param, None) - } - let b32 = dest.b32_address() - // Publish a signed LeaseSet2 for transient destinations into our NetDB - match opt_seed { - Some(seed) => { - let now_sec = @ntcp2_net.unix_time_sec() - let ls2 : @common.LeaseSet2 = { - destination: dest, - published_sec: now_sec, - expires_offset: 600U, - flags: 0U, - options: @common.Mapping::new(), - encryption_keys: [ - { key_type: X25519, key_data: dest.inner.crypto_public_key(), }, - ], - leases: [ - { - tunnel_gw: self.router_hash(), - tunnel_id: (10000 + self.sessions.length()).reinterpret_as_uint(), - end_date_sec: now_sec + 600U, - }, - ], - signature: b"", - } - let signed_ls2 = ls2.sign_ed25519(seed) catch { _ => ls2 } - let _ = self.netdb.store_lease_set2(signed_ls2, now_sec) catch { - _ => false - } - } - None => () - } - self.sessions.push({ id: sid, pub_b64, b32, }) - client.session_id = Some(sid) - let _ = send_sam_line( - client.sock, - "SESSION STATUS RESULT=OK DESTINATION=\{priv_b64}", - ) - } - ("STREAM", Some("ACCEPT")) => { - let sid = match msg.get("ID") { - Some(id) => id - None => { - let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID") - return - } - } - if self.find_session_by_id(sid) is None { - let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID") - return - } - let silent = match msg.get("SILENT") { - Some(v) => v.to_lower() == "true" - None => false - } - client.mode = 1 - client.accept_session_id = sid - client.accept_silent = silent - if !silent { - let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK") - } - } - ("STREAM", Some("CONNECT")) => { - let sid = match msg.get("ID") { - Some(id) => id - None => { - let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID") - return - } - } - let caller_sess = match self.find_session_by_id(sid) { - Some(s) => s - None => { - let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID") - return - } - } - let dest_b64 = match msg.get("DESTINATION") { - Some(d) => d - None => { - let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_KEY") - return - } - } - let silent = match msg.get("SILENT") { - Some(v) => v.to_lower() == "true" - None => false - } - let target_sess = match self.find_session_by_pub(dest_b64) { - Some(s) => s - None => { - if !silent { - let _ = send_sam_line( - client.sock, - "STREAM STATUS RESULT=CANT_REACH_PEER", - ) - } - client.closed = true - client.sock.close() - return - } - } - // Find a waiting STREAM ACCEPT client for target_sess.id - let mut acceptor_idx = -1 - for i = 0; i < self.sam_clients.length(); i = i + 1 { - let c = self.sam_clients[i] - if !c.closed && c.mode == 1 && c.accept_session_id == target_sess.id { - acceptor_idx = i - break - } - } - if acceptor_idx < 0 { - if !silent { - let _ = send_sam_line( - client.sock, - "STREAM STATUS RESULT=CANT_REACH_PEER", - ) - } - client.closed = true - client.sock.close() - return - } - let acceptor = self.sam_clients[acceptor_idx] - if !silent { - let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK") - } - if !acceptor.accept_silent { - let _ = send_sam_line(acceptor.sock, caller_sess.pub_b64) - } - // Promote both sockets into a bidirectional raw stream bridge - client.mode = 2 - acceptor.mode = 2 - self.bridges.push({ - a: client.sock, - b: acceptor.sock, - a_eof: false, - b_eof: false, - }) - } - _ => { - let _ = send_sam_line( - client.sock, - "HELLO REPLY RESULT=I2P_ERROR MESSAGE=unsupported_command", + DatabaseLookup( + key~, + from~, + flags~, + reply_tunnel_id~, + excluded_peers~, + reply_key~, + reply_tags~ + ) => + self.handle_database_lookup_msg( + from_peer, key, from, flags, reply_tunnel_id, excluded_peers, reply_key, + reply_tags, now_sec, ) - } + DatabaseSearchReply(key~, peer_hashes~, from~) => + self.handle_database_search_reply_msg(key, peer_hashes, from) + ShortTunnelBuild(records~) => + self.handle_short_tunnel_build(hdr.msg_id, records, now_sec) + ShortTunnelBuildReply(records~) => + self.handle_short_tunnel_build_reply(hdr.msg_id, records) + TunnelData(tunnel_id~, data~) => self.handle_tunnel_data(tunnel_id, data) + TunnelGateway(tunnel_id~, data~) => + self.handle_tunnel_gateway(tunnel_id, data, now_sec) + Garlic(data~) => + if !self.try_handle_lookup_garlic_reply(data, now_sec) { + self.handle_incoming_garlic(data, now_sec) + } + _ => () } } +///| +fn Router::push_sam_client(self : Router, sock : @ntcp2_net.TcpSocket) -> Unit { + self.sam_clients.push({ + sock, + recv_buf: [], + session_id: None, + mode: 0, + accept_session_id: "", + accept_silent: false, + closed: false, + }) +} + ///| /// Runs one non-blocking event-loop tick (accepting SAMv3 & NTCP2 connections, -/// processing SAMv3 commands, and pumping bridged stream relays). +/// stepping handshakes & peer sessions, servicing NetDB/tunnel/Garlic/Streaming, +/// and pumping SAMv3 stream relays). Sleeps up to `poll_ms` only when idle. pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit { - // 1. Accept any pending SAMv3 TCP connection - match (self.sam_listener.accept(timeout_ms=poll_ms) catch { _ => None }) { - Some(sock) => - self.sam_clients.push({ - sock, - session_id: None, - mode: 0, - accept_session_id: "", - accept_silent: false, - closed: false, - }) - None => () - } - - // 2. Accept any pending incoming NTCP2 TCP connection (non-blocking) - match (self.ntcp2_listener.accept(timeout_ms=0) catch { _ => None }) { - Some(sock) => { - let res = try { - let conn = @ntcp2_net.accept_ntcp2( - sock, - self.static_key, - self.router_hash().as_bytes(), - self.ntcp2_iv, - timeout_ms=2000, - ) - match conn.remote_router_info { - Some(peer_ri) => { - let _ = self.netdb.store_router_info(peer_ri) catch { _ => false } - } - None => () - } - conn.close() - true - } catch { - _ => { - sock.close() - false - } - } - let _ = res - } - None => () - } - - // 3. Process readable SAMv3 command sockets - for i = 0; i < self.sam_clients.length(); i = i + 1 { - let c = self.sam_clients[i] - if c.closed || c.mode != 0 { - continue - } - let ready = c.sock.poll_readable(0) catch { _ => false } - if !ready { - continue - } - match (c.sock.read_line() catch { _ => None }) { - Some(line) => if line.length() > 0 { self.handle_sam_command(i, line) } - None => { - c.closed = true - c.sock.close() + let mut did_work = false + for _i = 0; _i < 8; _i = _i + 1 { + match (self.sam_listener.accept(timeout_ms=0) catch { _ => None }) { + Some(sock) => { + self.push_sam_client(sock) + did_work = true } + None => break } } - // 4. Pump bidirectional raw byte bridges for active STREAM connections - let mut bi = 0 - while bi < self.bridges.length() { - let br = self.bridges[bi] - if !br.a_eof { - let r = br.a.poll_readable(0) catch { _ => false } - if r { - let data = br.a.read_some(4096) catch { _ => b"" } - if data.length() == 0 { - br.a_eof = true - br.b.shutdown_write() - } else { - br.b.write_all(data) catch { - _ => br.b_eof = true - } - } - } - } - if !br.b_eof { - let r = br.b.poll_readable(0) catch { _ => false } - if r { - let data = br.b.read_some(4096) catch { _ => b"" } - if data.length() == 0 { - br.b_eof = true - br.a.shutdown_write() - } else { - br.a.write_all(data) catch { - _ => br.a_eof = true - } - } - } - } - if br.a_eof && br.b_eof { - br.a.close() - br.b.close() - let _ = self.bridges.remove(bi) - } else { - bi += 1 + if self.step_ntcp2_peers() { + did_work = true + } + if self.step_sam_clients() { + did_work = true + } + self.poll_netdb_lookups() + self.poll_tunnel_builds() + if self.step_bridges() { + did_work = true + } + if self.step_remote_bridges() { + did_work = true + } + + if !did_work && poll_ms > 0 { + match (self.sam_listener.accept(timeout_ms=poll_ms) catch { _ => None }) { + Some(sock) => self.push_sam_client(sock) + None => () } } } diff --git a/router/router_test.mbt b/router/router_test.mbt index d5a6ec9..4c2e0c5 100644 --- a/router/router_test.mbt +++ b/router/router_test.mbt @@ -1,3 +1,52 @@ +///| +fn step_routers(rs : Array[@router.Router], count : Int32) -> Unit { + for _i = 0; _i < count; _i = _i + 1 { + for r in rs { + r.step(poll_ms=1) + } + } +} + +///| +fn pump_read_line( + sock : @ntcp2_net.TcpSocket, + rs : Array[@router.Router], + max_ticks~ : Int32 = 1000, +) -> String raise { + for _i = 0; _i < max_ticks; _i = _i + 1 { + step_routers(rs, 1) + if sock.poll_readable(0) { + match sock.read_line() { + Some(l) => return l + None => fail("unexpected EOF while waiting for SAM line") + } + } + } + fail("timed out waiting for SAM line") +} + +///| +fn pump_read_until_eof( + sock : @ntcp2_net.TcpSocket, + rs : Array[@router.Router], + max_ticks~ : Int32 = 1500, +) -> Bytes raise { + let out : Array[Byte] = [] + for _i = 0; _i < max_ticks; _i = _i + 1 { + step_routers(rs, 1) + while sock.poll_readable(0) { + let chunk = sock.read_some(4096) + if chunk.length() == 0 { + return Bytes::from_array(out) + } + for j = 0; j < chunk.length(); j = j + 1 { + out.push(chunk[j]) + } + } + } + fail("timed out waiting for EOF on stream socket") +} + ///| test "Router transient startup, self-signed RouterInfo, and embedded SAMv3 bridge" { let r = @router.Router::start({ @@ -16,36 +65,237 @@ test "Router transient startup, self-signed RouterInfo, and embedded SAMv3 bridg r.step(poll_ms=50) sock.write_all(b"HELLO VERSION MIN=3.1 MAX=3.3\n") - r.step(poll_ms=50) - assert_eq(sock.read_line(), Some("HELLO REPLY RESULT=OK VERSION=3.3")) + assert_eq(pump_read_line(sock, [r]), "HELLO REPLY RESULT=OK VERSION=3.3") sock.write_all(b"DEST GENERATE SIGNATURE_TYPE=7\n") - r.step(poll_ms=50) - let dest_line = match sock.read_line() { - Some(l) => l - None => fail("expected DEST REPLY") - } + let dest_line = pump_read_line(sock, [r]) assert_true(dest_line.has_prefix("DEST REPLY PUB=")) sock.write_all( b"SESSION CREATE STYLE=STREAM ID=test1 DESTINATION=TRANSIENT\n", ) - r.step(poll_ms=50) - let sess_line = match sock.read_line() { - Some(l) => l - None => fail("expected SESSION STATUS") - } + let sess_line = pump_read_line(sock, [r]) assert_true(sess_line.has_prefix("SESSION STATUS RESULT=OK DESTINATION=")) assert_eq(r.netdb.leaseset_count(), 1) sock.write_all(b"NAMING LOOKUP NAME=ME\n") - r.step(poll_ms=50) - let lookup_line = match sock.read_line() { - Some(l) => l - None => fail("expected NAMING REPLY") - } + let lookup_line = pump_read_line(sock, [r]) assert_true(lookup_line.has_prefix("NAMING REPLY RESULT=OK NAME=ME VALUE=")) sock.close() r.close() } + +///| +fn sam_connect_and_hello( + port : Int32, + rs : Array[@router.Router], +) -> @ntcp2_net.TcpSocket raise { + let sock = @ntcp2_net.TcpSocket::connect("127.0.0.1", port) + sock.write_all(b"HELLO VERSION MIN=3.1 MAX=3.3\n") + let reply = pump_read_line(sock, rs) + assert_eq(reply, "HELLO REPLY RESULT=OK VERSION=3.3") + sock +} + +///| +fn extract_kv(line : String, key : String) -> String { + let prefix = key + "=" + let tokens = line.split(" ").collect() + for t in tokens { + let ts = t.to_owned() + if ts.has_prefix(prefix) { + return ts[prefix.length():].to_owned() + } + } + "" +} + +///| +test "Two live routers end-to-end: NTCP2 + ECIES NetDB + Garlic Ratchet + Ed25519 Streaming" { + let router_b = @router.Router::start( + { + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }, + floodfill=true, + ) + defer router_b.close() + let router_a = @router.Router::start({ + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }) + defer router_a.close() + let _ = router_a.netdb.store_router_info(router_b.router_info) + let _ = router_b.netdb.store_router_info(router_a.router_info) + let rs = [router_a, router_b] + + // Bob opens SAM control session + STREAM ACCEPT on router B + let bob_ctrl = sam_connect_and_hello(router_b.sam_port(), rs) + defer bob_ctrl.close() + bob_ctrl.write_all( + b"SESSION CREATE STYLE=STREAM ID=bob DESTINATION=TRANSIENT\n", + ) + let bob_sess = pump_read_line(bob_ctrl, rs) + assert_true(bob_sess.has_prefix("SESSION STATUS RESULT=OK")) + bob_ctrl.write_all(b"NAMING LOOKUP NAME=ME\n") + let bob_me = pump_read_line(bob_ctrl, rs) + let bob_pub_b64 = extract_kv(bob_me, "VALUE") + let bob_dest = @common.Destination::from_base64(bob_pub_b64) + let bob_b32 = bob_dest.b32_address() + + let bob_acc = sam_connect_and_hello(router_b.sam_port(), rs) + defer bob_acc.close() + bob_acc.write_all(b"STREAM ACCEPT ID=bob SILENT=false\n") + assert_eq(pump_read_line(bob_acc, rs), "STREAM STATUS RESULT=OK") + + // Alice creates SAM control session on router A and looks up Bob's .b32.i2p via live NTCP2 ECIES NetDB + let alice_ctrl = sam_connect_and_hello(router_a.sam_port(), rs) + defer alice_ctrl.close() + alice_ctrl.write_all( + b"SESSION CREATE STYLE=STREAM ID=alice DESTINATION=TRANSIENT\n", + ) + let alice_sess = pump_read_line(alice_ctrl, rs) + assert_true(alice_sess.has_prefix("SESSION STATUS RESULT=OK")) + + alice_ctrl.write_all( + @encoding.string_to_utf8_bytes("NAMING LOOKUP NAME=\{bob_b32}\n"), + ) + let alice_lookup = pump_read_line(alice_ctrl, rs) + assert_true(alice_lookup.has_prefix("NAMING REPLY RESULT=OK")) + assert_eq(extract_kv(alice_lookup, "VALUE"), bob_pub_b64) + + // Alice connects over ECIES-X25519-AEAD-Ratchet Garlic + Ed25519 Streaming + let alice_data = sam_connect_and_hello(router_a.sam_port(), rs) + defer alice_data.close() + alice_data.write_all( + @encoding.string_to_utf8_bytes( + "STREAM CONNECT ID=alice DESTINATION=\{bob_pub_b64} SILENT=false\n", + ), + ) + assert_eq(pump_read_line(alice_data, rs), "STREAM STATUS RESULT=OK") + let seen_peer_b64 = pump_read_line(bob_acc, rs) + assert_true(seen_peer_b64.length() > 100) + + // Bidirectional Streaming payload + close exchange + alice_data.write_all(b"hello-over-ecies-streaming") + alice_data.shutdown_write() + let got_on_bob = pump_read_until_eof(bob_acc, rs) + assert_eq(got_on_bob, b"hello-over-ecies-streaming") + + bob_acc.write_all(b"ack-from-bob") + bob_acc.shutdown_write() + let got_on_alice = pump_read_until_eof(alice_data, rs) + assert_eq(got_on_alice, b"ack-from-bob") +} + +///| +test "Three-router live Proposal 157 multi-hop tunnel build and fragmented 2500B TunnelData stream" { + let router_b = @router.Router::start( + { + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }, + floodfill=true, + ) + defer router_b.close() + let router_c = @router.Router::start({ + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }) + defer router_c.close() + let router_a = @router.Router::start({ + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }) + defer router_a.close() + + for r in [router_a, router_b, router_c] { + let _ = r.netdb.store_router_info(router_a.router_info) + let _ = r.netdb.store_router_info(router_b.router_info) + let _ = r.netdb.store_router_info(router_c.router_info) + } + let rs = [router_a, router_b, router_c] + + // Router A builds 2-hop Outbound [B -> C] and 2-hop Inbound [B -> C -> A] tunnels via Proposal 157 + let out_tid = router_a.build_tunnel( + [router_b.router_hash(), router_c.router_hash()], + Outbound, + ) + let in_tid = router_a.build_tunnel( + [router_b.router_hash(), router_c.router_hash()], + Inbound, + ) + let mut built = false + for _i = 0; _i < 1000; _i = _i + 1 { + step_routers(rs, 1) + if router_a.has_tunnel(out_tid) && router_a.has_tunnel(in_tid) { + built = true + break + } + } + assert_true(built) + assert_true(router_b.tunnels.transit_count() >= 2) + assert_true(router_c.tunnels.transit_count() >= 2) + + // Router C hosts Bob; Router A hosts Alice (whose LS2 uses her Inbound [B -> C -> A] tunnel lease) + let bob_ctrl = sam_connect_and_hello(router_c.sam_port(), rs) + defer bob_ctrl.close() + bob_ctrl.write_all( + b"SESSION CREATE STYLE=STREAM ID=bob3 DESTINATION=TRANSIENT\n", + ) + assert_true( + pump_read_line(bob_ctrl, rs).has_prefix("SESSION STATUS RESULT=OK"), + ) + bob_ctrl.write_all(b"NAMING LOOKUP NAME=ME\n") + let bob_pub_b64 = extract_kv(pump_read_line(bob_ctrl, rs), "VALUE") + let bob_b32 = @common.Destination::from_base64(bob_pub_b64).b32_address() + + let bob_acc = sam_connect_and_hello(router_c.sam_port(), rs) + defer bob_acc.close() + bob_acc.write_all(b"STREAM ACCEPT ID=bob3 SILENT=false\n") + assert_eq(pump_read_line(bob_acc, rs), "STREAM STATUS RESULT=OK") + + let alice_ctrl = sam_connect_and_hello(router_a.sam_port(), rs) + defer alice_ctrl.close() + alice_ctrl.write_all( + b"SESSION CREATE STYLE=STREAM ID=alice3 DESTINATION=TRANSIENT\n", + ) + assert_true( + pump_read_line(alice_ctrl, rs).has_prefix("SESSION STATUS RESULT=OK"), + ) + alice_ctrl.write_all( + @encoding.string_to_utf8_bytes("NAMING LOOKUP NAME=\{bob_b32}\n"), + ) + assert_eq(extract_kv(pump_read_line(alice_ctrl, rs), "VALUE"), bob_pub_b64) + + let alice_data = sam_connect_and_hello(router_a.sam_port(), rs) + defer alice_data.close() + alice_data.write_all( + @encoding.string_to_utf8_bytes( + "STREAM CONNECT ID=alice3 DESTINATION=\{bob_pub_b64} SILENT=false\n", + ), + ) + assert_eq(pump_read_line(alice_data, rs), "STREAM STATUS RESULT=OK") + let _ = pump_read_line(bob_acc, rs) + + // Send 2500 bytes (spanning multiple Streaming packets & fragmented 1024B TunnelData cells) + let big_payload = Bytes::make(2500, b'\x41') + alice_data.write_all(big_payload) + alice_data.shutdown_write() + assert_eq(pump_read_until_eof(bob_acc, rs), big_payload) + + bob_acc.write_all(b"tunneled-ok") + bob_acc.shutdown_write() + assert_eq(pump_read_until_eof(alice_data, rs), b"tunneled-ok") +} diff --git a/router/sam_handler.mbt b/router/sam_handler.mbt new file mode 100644 index 0000000..0658b28 --- /dev/null +++ b/router/sam_handler.mbt @@ -0,0 +1,1146 @@ +///| +/// Embedded SAMv3 bridge wired to Proposal 144 ECIES Garlic + Ed25519 I2P Streaming +/// (plus fast loopback bridge for co-hosted local SAM sessions). + +///| +priv struct SamSession { + id : String + dest : @common.Destination + hash : @common.Hash + pub_b64 : String + b32 : String + virtual_tid : UInt32 + ed_seed : Bytes? + ratchet : @ratchet.RatchetSessionManager? + stream_mgr : @streaming.StreamManager? +} + +///| +priv struct SamClientConn { + sock : @ntcp2_net.TcpSocket + recv_buf : Array[Byte] + mut session_id : String? + mut mode : Int32 // 0 = command, 1 = waiting_accept, 2 = bridged + mut accept_session_id : String + mut accept_silent : Bool + mut closed : Bool +} + +///| +priv struct StreamBridge { + a : @ntcp2_net.TcpSocket + b : @ntcp2_net.TcpSocket + mut a_eof : Bool + mut b_eof : Bool +} + +///| +priv struct RemoteStreamBridge { + sock : @ntcp2_net.TcpSocket + session_id : String + peer_hash : @common.Hash + peer_static_pub : Bytes + lease_gw : @common.Hash + lease_tid : UInt32 + send_stream_id : UInt32 + mut state : Int32 // 0 = waiting_syn_ack, 1 = open + silent : Bool + mut local_eof : Bool + mut remote_eof_sent : Bool + mut closed : Bool + started_ms : UInt64 + pending_buf : Array[Byte] +} + +///| +/// Generates a valid transient 391-byte X25519+Ed25519 I2P Destination and +/// returns `(dest, pub_b64, priv_b64, x_keypair, ed_seed)`. +fn generate_transient_destination() -> ( + @common.Destination, + String, + String, + @noise.KeyPair, + Bytes, +) raise RouterError { + let ed_seed = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } + let ed_pub = @crypto.ed25519_public_key(ed_seed) catch { + e => raise Crypto(e) + } + let x_priv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } + let x_kp = @noise.KeyPair::from_private(x_priv) catch { e => raise Noise(e) } + let pad = @ntcp2_net.random_bytes(320) catch { e => raise Net(e) } + let dest = @common.Destination::new_x25519_ed25519( + x_kp.public_key, + ed_pub, + padding=pad, + ) catch { + e => raise Common(e) + } + let pub_bytes = dest.to_bytes() + let priv_w = @encoding.Writer::new(capacity=pub_bytes.length() + 64) + priv_w.write_bytes(pub_bytes) + priv_w.write_bytes(x_priv) + priv_w.write_bytes(ed_seed) + let pub_b64 = @encoding.base64_encode(pub_bytes) + let priv_b64 = @encoding.base64_encode(priv_w.to_bytes()) + (dest, pub_b64, priv_b64, x_kp, ed_seed) +} + +///| +fn Router::find_session_by_id(self : Router, id : String) -> SamSession? { + for s in self.sessions { + if s.id == id { + return Some(s) + } + } + None +} + +///| +fn Router::find_session_by_pub(self : Router, pub_b64 : String) -> SamSession? { + for s in self.sessions { + if s.pub_b64 == pub_b64 { + return Some(s) + } + } + None +} + +///| +fn parse_b32_hash(name : String) -> @common.Hash? { + let lower = name.to_lower() + if !lower.has_suffix(".b32.i2p") { + return None + } + let prefix = lower[:lower.length() - 8].to_owned() + let raw = @encoding.base32_decode(prefix) catch { _ => return None } + if raw.length() != 32 { + return None + } + Some(@common.Hash::from_bytes(raw) catch { _ => return None }) +} + +///| +fn extract_x25519_key(ls2 : @common.LeaseSet2) -> Bytes? { + for ek in ls2.encryption_keys { + if ek.key_type == X25519 && ek.key_data.length() == 32 { + return Some(ek.key_data) + } + } + let fallback = ls2.destination.inner.crypto_public_key() + if fallback.length() == 32 { + Some(fallback) + } else { + None + } +} + +///| +fn Router::resolve_name_local( + self : Router, + name : String, + client_session_id : String?, +) -> String? { + if name == "ME" { + match client_session_id { + Some(sid) => + match self.find_session_by_id(sid) { + Some(s) => return Some(s.pub_b64) + None => () + } + None => () + } + return None + } + let lower = name.to_lower() + for entry in self.aliases { + if entry.0 == lower { + return Some(entry.1) + } + } + for s in self.sessions { + if s.b32 == lower { + return Some(s.pub_b64) + } + } + let now_sec = @ntcp2_net.unix_time_sec() + match self.netdb.get_lease_set2_by_b32(lower, now_sec) { + Some(ls2) => return Some(ls2.destination.to_base64()) + None => () + } + None +} + +///| +fn send_sam_line(sock : @ntcp2_net.TcpSocket, line : String) -> Bool { + sock.write_all(@encoding.string_to_utf8_bytes(line + "\n")) catch { + _ => return false + } + true +} + +///| +fn Router::flush_stream_outbound( + self : Router, + sess : SamSession, + conn : @streaming.StreamConnection, + peer_hash : @common.Hash, + peer_static_pub : Bytes, + fallback_gw : @common.Hash, + fallback_tid : UInt32, + send_ls2~ : Bool = false, +) -> Unit { + let packets = conn.drain_outbound() + if packets.length() == 0 { + return + } + let ratchet = match sess.ratchet { + Some(r) => r + None => return + } + let now_sec = @ntcp2_net.unix_time_sec() + let mut gw = fallback_gw + let mut tid = fallback_tid + match self.netdb.get_lease_set2(peer_hash, now_sec) { + Some(ls2) if ls2.leases.length() > 0 => { + gw = ls2.leases[0].tunnel_gw + tid = ls2.leases[0].tunnel_id + } + _ => () + } + let exp_sec = now_sec + 60U + for idx = 0; idx < packets.length(); idx = idx + 1 { + let blocks : Array[@ratchet.RatchetBlock] = [] + if send_ls2 && idx == 0 { + match self.build_session_leaseset2(sess, now_sec) { + Some(ls2) => { + let ls_bytes = ls2.to_bytes() catch { _ => b"" } + if ls_bytes.length() > 0 { + let ls_blk = @ratchet.garlic_clove_block( + Local, + self.alloc_msg_id(), + exp_sec, + DatabaseStore( + key=sess.hash, + store_type=b'\x03', + reply_token=0U, + reply_tunnel_id=0U, + reply_gateway=None, + data=ls_bytes, + ), + ) catch { + _ => continue + } + blocks.push(ls_blk) + } + } + None => () + } + } + let clove = @ratchet.garlic_clove_block( + Destination(peer_hash), + self.alloc_msg_id(), + exp_sec, + Data(data=packets[idx]), + ) catch { + _ => continue + } + blocks.push(clove) + let wire = ratchet.encrypt_to_peer( + peer_static_pub, blocks, now_sec, next_rand_32, + ) catch { + _ => continue + } + self.send_routed_i2np(gw, Some(tid), Garlic(data=wire)) + } +} + +///| +fn Router::initiate_remote_stream( + self : Router, + client_idx : Int32, + caller_sess : SamSession, + target_dest : @common.Destination, + ls2 : @common.LeaseSet2, + silent : Bool, +) -> Unit { + let c = self.sam_clients[client_idx] + if c.closed { + return + } + let mgr = match caller_sess.stream_mgr { + Some(m) => m + None => { + if !silent { + let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=I2P_ERROR") + } + c.closed = true + c.sock.close() + return + } + } + let peer_static = match extract_x25519_key(ls2) { + Some(k) => k + None => { + if !silent { + let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=CANT_REACH_PEER") + } + c.closed = true + c.sock.close() + return + } + } + if ls2.leases.length() == 0 { + if !silent { + let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=CANT_REACH_PEER") + } + c.closed = true + c.sock.close() + return + } + let lease = ls2.leases[0] + let now_ms = @ntcp2_net.unix_time_ms() + let peer_hash = target_dest.hash() + let conn = mgr.connect(peer_hash, now_ms) catch { + _ => { + if !silent { + let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=I2P_ERROR") + } + c.closed = true + c.sock.close() + return + } + } + c.mode = 2 + let left_bytes = Bytes::from_array(c.recv_buf) + c.recv_buf.clear() + let pending_buf : Array[Byte] = [] + for i = 0; i < left_bytes.length(); i = i + 1 { + pending_buf.push(left_bytes[i]) + } + self.remote_bridges.push({ + sock: c.sock, + session_id: caller_sess.id, + peer_hash, + peer_static_pub: peer_static, + lease_gw: lease.tunnel_gw, + lease_tid: lease.tunnel_id, + send_stream_id: conn.send_stream_id, + state: 0, + silent, + local_eof: false, + remote_eof_sent: false, + closed: false, + started_ms: now_ms, + pending_buf, + }) + self.flush_stream_outbound( + caller_sess, + conn, + peer_hash, + peer_static, + lease.tunnel_gw, + lease.tunnel_id, + send_ls2=true, + ) +} + +///| +fn Router::finish_remote_stream_connect( + self : Router, + lk : PendingNetDbLookup, + ls2 : @common.LeaseSet2, +) -> Unit { + let caller_sess = match self.find_session_by_id(lk.session_id) { + Some(s) => s + None => { + let c = self.sam_clients[lk.client_idx] + if !lk.silent && !c.closed { + let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=INVALID_ID") + } + c.closed = true + c.sock.close() + return + } + } + self.initiate_remote_stream( + lk.client_idx, + caller_sess, + ls2.destination, + ls2, + lk.silent, + ) +} + +///| +fn Router::handle_incoming_garlic( + self : Router, + garlic_data : Bytes, + now_sec : UInt32, +) -> Unit { + let now_ms = @ntcp2_net.unix_time_ms() + for sess in self.sessions { + let ratchet = match sess.ratchet { + Some(r) => r + None => continue + } + let res = Some(ratchet.decrypt_incoming(garlic_data)) catch { _ => None } + match res { + Some((_remote_static, blocks)) => { + // 1. Apply DatabaseStore cloves first so peer LeaseSet2 is cached for reply + for blk in blocks { + match blk { + GarlicClove(i2np_short~, ..) => { + let decoded = Some(@ratchet.decode_garlic_clove_i2np(i2np_short)) catch { + _ => None + } + match decoded { + Some((_h, DatabaseStore(key~, store_type~, data~, ..))) => { + let _ = self.netdb.handle_database_store( + store_type, key, data, now_sec, + ) catch { + _ => false + } + } + _ => () + } + } + _ => () + } + } + // 2. Deliver Data (I2CP Streaming/Datagram) & other cloves + for blk in blocks { + match blk { + GarlicClove(i2np_short~, ..) => { + let decoded = Some(@ratchet.decode_garlic_clove_i2np(i2np_short)) catch { + _ => None + } + match decoded { + Some((hdr, inner)) => + match inner { + Data(data~) => + match sess.stream_mgr { + Some(mgr) => { + let conn_opt = mgr.handle_incoming_i2cp(data, now_ms) catch { + _ => None + } + match conn_opt { + Some(conn) => + // Immediately send any generated SYN-ACK or ACK back if peer LeaseSet2 is known + match + self.netdb.get_lease_set2( + conn.remote_hash, + now_sec, + ) { + Some(ls2) if ls2.leases.length() > 0 => + match extract_x25519_key(ls2) { + Some(pstat) => + self.flush_stream_outbound( + sess, + conn, + conn.remote_hash, + pstat, + ls2.leases[0].tunnel_gw, + ls2.leases[0].tunnel_id, + send_ls2=true, + ) + None => () + } + _ => () + } + None => () + } + } + None => () + } + DatabaseStore(..) => () + _ => self.handle_i2np_message(None, hdr, inner) + } + None => () + } + } + _ => () + } + } + return + } + None => () + } + } +} + +///| +fn Router::handle_sam_command( + self : Router, + client_idx : Int32, + line : String, +) -> Unit { + let client = self.sam_clients[client_idx] + let msg = @sam.SamMessage::parse(line) catch { + _ => { + let _ = send_sam_line( + client.sock, + "HELLO REPLY RESULT=I2P_ERROR MESSAGE=parse_error", + ) + return + } + } + match (msg.verb, msg.subcommand) { + ("HELLO", Some("VERSION")) => { + let _ = send_sam_line(client.sock, "HELLO REPLY RESULT=OK VERSION=3.3") + } + ("PING", _) => { + let pong = @sam.SamMessage::new( + "PONG", + subcommand=msg.subcommand, + params=msg.params, + ) + let _ = client.sock.write_all( + @encoding.string_to_utf8_bytes(pong.serialize()), + ) catch { + _ => () + } + } + ("DEST", Some("GENERATE")) => { + let (_dest, pub_b64, priv_b64, _xkp, _seed) = generate_transient_destination() catch { + _ => { + let _ = send_sam_line(client.sock, "DEST REPLY RESULT=I2P_ERROR") + return + } + } + let _ = send_sam_line( + client.sock, + "DEST REPLY PUB=\{pub_b64} PRIV=\{priv_b64}", + ) + } + ("NAMING", Some("LOOKUP")) => { + let name = match msg.get("NAME") { + Some(n) => n + None => { + let _ = send_sam_line( + client.sock, + "NAMING REPLY RESULT=INVALID_KEY NAME=", + ) + return + } + } + match self.resolve_name_local(name, client.session_id) { + Some(val) => { + let _ = send_sam_line( + client.sock, + "NAMING REPLY RESULT=OK NAME=\{name} VALUE=\{val}", + ) + } + None => + match parse_b32_hash(name) { + Some(target_hash) => { + let sid = match client.session_id { + Some(s) => s + None => "" + } + if !self.start_netdb_lookup( + target_hash, 0, client_idx, name, sid, false, + ) { + let _ = send_sam_line( + client.sock, + "NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{name}", + ) + } + } + None => { + let _ = send_sam_line( + client.sock, + "NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{name}", + ) + } + } + } + } + ("SESSION", Some("CREATE")) => { + let sid = match msg.get("ID") { + Some(id) => id + None => { + let _ = send_sam_line( + client.sock, + "SESSION STATUS RESULT=I2P_ERROR MESSAGE=missing_id", + ) + return + } + } + if self.find_session_by_id(sid) is Some(_) { + let _ = send_sam_line( + client.sock, + "SESSION STATUS RESULT=DUPLICATED_ID", + ) + return + } + let dest_param = match msg.get("DESTINATION") { + Some(d) => d + None => "TRANSIENT" + } + let (dest, pub_b64, priv_b64, opt_xkp, opt_seed) = if dest_param == + "TRANSIENT" { + let (d, pb, prb, xkp, seed) = generate_transient_destination() catch { + _ => { + let _ = send_sam_line( + client.sock, + "SESSION STATUS RESULT=I2P_ERROR", + ) + return + } + } + (d, pb, prb, Some(xkp), Some(seed)) + } else { + let raw = @encoding.base64_decode(dest_param) catch { + _ => { + let _ = send_sam_line( + client.sock, + "SESSION STATUS RESULT=INVALID_KEY", + ) + return + } + } + let r = @encoding.Reader::new(raw) + let d = @common.Destination::decode(r) catch { + _ => { + let _ = send_sam_line( + client.sock, + "SESSION STATUS RESULT=INVALID_KEY", + ) + return + } + } + let tail = r.read_remaining() + if tail.length() >= 64 { + let x_priv = tail[:32].to_owned() + let ed_seed = tail[32:64].to_owned() + let xkp = @noise.KeyPair::from_private(x_priv) catch { + _ => { + let _ = send_sam_line( + client.sock, + "SESSION STATUS RESULT=INVALID_KEY", + ) + return + } + } + (d, d.to_base64(), dest_param, Some(xkp), Some(ed_seed)) + } else { + (d, d.to_base64(), dest_param, None, None) + } + } + let b32 = dest.b32_address() + let hash = dest.hash() + let ratchet = match opt_xkp { + Some(xkp) => Some(@ratchet.RatchetSessionManager::new(xkp)) + None => None + } + let stream_mgr = match opt_seed { + Some(seed) => + Some( + @streaming.StreamManager::new( + dest, + seed, + initial_stream_id=self.alloc_stream_id(), + ), + ) + None => None + } + let sess : SamSession = { + id: sid, + dest, + hash, + pub_b64, + b32, + virtual_tid: self.alloc_tunnel_id(), + ed_seed: opt_seed, + ratchet, + stream_mgr, + } + self.sessions.push(sess) + self.publish_session_leaseset2(sess) + client.session_id = Some(sid) + let _ = send_sam_line( + client.sock, + "SESSION STATUS RESULT=OK DESTINATION=\{priv_b64}", + ) + } + ("STREAM", Some("ACCEPT")) => { + let sid = match msg.get("ID") { + Some(id) => id + None => { + let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID") + return + } + } + if self.find_session_by_id(sid) is None { + let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID") + return + } + let silent = match msg.get("SILENT") { + Some(v) => v.to_lower() == "true" + None => false + } + client.mode = 1 + client.accept_session_id = sid + client.accept_silent = silent + if !silent { + let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK") + } + } + ("STREAM", Some("CONNECT")) => { + let sid = match msg.get("ID") { + Some(id) => id + None => { + let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID") + return + } + } + let caller_sess = match self.find_session_by_id(sid) { + Some(s) => s + None => { + let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID") + return + } + } + let dest_b64 = match msg.get("DESTINATION") { + Some(d) => d + None => { + let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_KEY") + return + } + } + let silent = match msg.get("SILENT") { + Some(v) => v.to_lower() == "true" + None => false + } + // 1. Check co-hosted local session fast path first + match self.find_session_by_pub(dest_b64) { + Some(target_sess) => { + let mut acceptor_idx = -1 + for i = 0; i < self.sam_clients.length(); i = i + 1 { + let c = self.sam_clients[i] + if !c.closed && c.mode == 1 && c.accept_session_id == target_sess.id { + acceptor_idx = i + break + } + } + if acceptor_idx < 0 { + if !silent { + let _ = send_sam_line( + client.sock, + "STREAM STATUS RESULT=CANT_REACH_PEER", + ) + } + client.closed = true + client.sock.close() + return + } + let acceptor = self.sam_clients[acceptor_idx] + if !silent { + let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK") + } + if !acceptor.accept_silent { + let _ = send_sam_line(acceptor.sock, caller_sess.pub_b64) + } + client.mode = 2 + acceptor.mode = 2 + self.bridges.push({ + a: client.sock, + b: acceptor.sock, + a_eof: false, + b_eof: false, + }) + return + } + None => () + } + // 2. Remote destination over ECIES Garlic + Ed25519 I2P Streaming + let target_dest = @common.Destination::from_base64(dest_b64) catch { + _ => { + if !silent { + let _ = send_sam_line( + client.sock, + "STREAM STATUS RESULT=INVALID_KEY", + ) + } + client.closed = true + client.sock.close() + return + } + } + let target_hash = target_dest.hash() + let now_sec = @ntcp2_net.unix_time_sec() + match self.netdb.get_lease_set2(target_hash, now_sec) { + Some(ls2) => + self.initiate_remote_stream( + client_idx, caller_sess, target_dest, ls2, silent, + ) + None => + if !self.start_netdb_lookup( + target_hash, + 1, + client_idx, + "", + caller_sess.id, + silent, + ) { + if !silent { + let _ = send_sam_line( + client.sock, + "STREAM STATUS RESULT=CANT_REACH_PEER", + ) + } + client.closed = true + client.sock.close() + } + } + } + _ => { + let _ = send_sam_line( + client.sock, + "HELLO REPLY RESULT=I2P_ERROR MESSAGE=unsupported_command", + ) + } + } +} + +///| +fn pop_line_from_buf(buf : Array[Byte]) -> String? { + let mut nl_idx = -1 + for i = 0; i < buf.length(); i = i + 1 { + if buf[i] == b'\n' { + nl_idx = i + break + } + } + if nl_idx < 0 { + return None + } + let end = if nl_idx > 0 && buf[nl_idx - 1] == b'\r' { + nl_idx - 1 + } else { + nl_idx + } + let line_bytes = Bytes::from_array(buf[:end]) + for _k = 0; _k <= nl_idx; _k = _k + 1 { + let _ = buf.remove(0) + } + Some(@encoding.utf8_bytes_to_string(line_bytes) catch { _ => "" }) +} + +///| +fn Router::step_sam_clients(self : Router) -> Bool { + let mut did_work = false + for i = 0; i < self.sam_clients.length(); i = i + 1 { + let c = self.sam_clients[i] + if c.closed || c.mode != 0 { + continue + } + let prev_len = c.recv_buf.length() + let eof = try { + let _ = c.sock.pump_nonblocking(c.recv_buf, 4096) + false + } catch { + _ => true + } + if c.recv_buf.length() != prev_len { + did_work = true + } + if eof { + c.closed = true + c.sock.close() + did_work = true + continue + } + while !c.closed && c.mode == 0 { + match pop_line_from_buf(c.recv_buf) { + Some(line) => + if line.length() > 0 { + did_work = true + self.handle_sam_command(i, line) + } + None => break + } + } + } + did_work +} + +///| +fn Router::step_bridges(self : Router) -> Bool { + let mut did_work = false + let mut bi = 0 + while bi < self.bridges.length() { + let br = self.bridges[bi] + if !br.a_eof { + let r = br.a.poll_readable(0) catch { _ => false } + if r { + did_work = true + let data = br.a.read_some(4096) catch { _ => b"" } + if data.length() == 0 { + br.a_eof = true + br.b.shutdown_write() + } else { + br.b.write_all(data) catch { + _ => br.b_eof = true + } + } + } + } + if !br.b_eof { + let r = br.b.poll_readable(0) catch { _ => false } + if r { + did_work = true + let data = br.b.read_some(4096) catch { _ => b"" } + if data.length() == 0 { + br.b_eof = true + br.a.shutdown_write() + } else { + br.a.write_all(data) catch { + _ => br.a_eof = true + } + } + } + } + if br.a_eof && br.b_eof { + did_work = true + br.a.close() + br.b.close() + let _ = self.bridges.remove(bi) + } else { + bi += 1 + } + } + did_work +} + +///| +fn find_stream_by_id( + mgr : @streaming.StreamManager, + sid : UInt32, +) -> @streaming.StreamConnection? { + for s in mgr.streams { + if s.send_stream_id == sid { + return Some(s) + } + } + None +} + +///| +fn Router::step_remote_bridges(self : Router) -> Bool { + let now_ms = @ntcp2_net.unix_time_ms() + let now_sec = (now_ms / 1000UL).to_uint() + let mut did_work = false + + // 1. Pair incoming Streaming SYN connections with waiting SAM STREAM ACCEPT sockets + for sess in self.sessions { + let mgr = match sess.stream_mgr { + Some(m) => m + None => continue + } + for i = 0; i < self.sam_clients.length(); i = i + 1 { + let c = self.sam_clients[i] + if c.closed || c.mode != 1 || c.accept_session_id != sess.id { + continue + } + match mgr.accept_next() { + Some(conn) => { + let peer_dest = match conn.remote_dest { + Some(d) => d + None => continue + } + let peer_ls2 = self.netdb.get_lease_set2(conn.remote_hash, now_sec) + let (gw, tid, peer_static) = match peer_ls2 { + Some(l) if l.leases.length() > 0 => + ( + l.leases[0].tunnel_gw, + l.leases[0].tunnel_id, + extract_x25519_key(l).unwrap_or( + peer_dest.inner.crypto_public_key(), + ), + ) + _ => (self.router_hash(), 0U, peer_dest.inner.crypto_public_key()) + } + if !c.accept_silent { + let _ = send_sam_line(c.sock, peer_dest.to_base64()) + } + c.mode = 2 + let left_bytes = Bytes::from_array(c.recv_buf) + c.recv_buf.clear() + let pending_buf : Array[Byte] = [] + for j = 0; j < left_bytes.length(); j = j + 1 { + pending_buf.push(left_bytes[j]) + } + self.remote_bridges.push({ + sock: c.sock, + session_id: sess.id, + peer_hash: conn.remote_hash, + peer_static_pub: peer_static, + lease_gw: gw, + lease_tid: tid, + send_stream_id: conn.send_stream_id, + state: 1, + silent: c.accept_silent, + local_eof: false, + remote_eof_sent: false, + closed: false, + started_ms: now_ms, + pending_buf, + }) + did_work = true + self.flush_stream_outbound( + sess, + conn, + conn.remote_hash, + peer_static, + gw, + tid, + send_ls2=true, + ) + } + None => break + } + } + } + + // 2. Pump retransmits & flush outbound packets (ACKs, SYN-ACKs, retransmissions) + for sess in self.sessions { + let mgr = match sess.stream_mgr { + Some(m) => m + None => continue + } + for conn in mgr.streams { + let _ = conn.poll_retransmits(now_ms, rto_ms=1500UL) catch { _ => () } + match self.netdb.get_lease_set2(conn.remote_hash, now_sec) { + Some(ls2) if ls2.leases.length() > 0 => + match extract_x25519_key(ls2) { + Some(pstat) => + self.flush_stream_outbound( + sess, + conn, + conn.remote_hash, + pstat, + ls2.leases[0].tunnel_gw, + ls2.leases[0].tunnel_id, + send_ls2=false, + ) + None => () + } + _ => () + } + } + } + + // 3. Pump bidirectional SAM socket <-> StreamConnection I/O + let mut ri = 0 + while ri < self.remote_bridges.length() { + let br = self.remote_bridges[ri] + let sess = match self.find_session_by_id(br.session_id) { + Some(s) => s + None => { + br.sock.close() + br.closed = true + let _ = self.remote_bridges.remove(ri) + continue + } + } + let mgr = match sess.stream_mgr { + Some(m) => m + None => { + br.sock.close() + br.closed = true + let _ = self.remote_bridges.remove(ri) + continue + } + } + let conn = match find_stream_by_id(mgr, br.send_stream_id) { + Some(c) => c + None => { + br.sock.close() + br.closed = true + let _ = self.remote_bridges.remove(ri) + continue + } + } + if br.state == 0 { + if conn.state == Established || + conn.state == Closing || + conn.state == Closed { + br.state = 1 + did_work = true + if !br.silent { + let _ = send_sam_line(br.sock, "STREAM STATUS RESULT=OK") + } + } else if conn.state == Reset || now_ms > br.started_ms + 12000UL { + did_work = true + if !br.silent { + let _ = send_sam_line(br.sock, "STREAM STATUS RESULT=CANT_REACH_PEER") + } + br.sock.close() + br.closed = true + let _ = self.remote_bridges.remove(ri) + continue + } + } + if br.state == 1 { + let avail = conn.read_available() + if avail.length() > 0 { + did_work = true + br.sock.write_all(avail) catch { + _ => { + br.local_eof = true + let _ = conn.close(now_ms) catch { _ => () } + } + } + } + if conn.is_eof() && !br.remote_eof_sent { + did_work = true + br.sock.shutdown_write() + br.remote_eof_sent = true + } + if br.pending_buf.length() > 0 { + did_work = true + let pbytes = Bytes::from_array(br.pending_buf) + let wrote = conn.write(pbytes, now_ms) catch { _ => 0 } + for _w = 0; _w < wrote; _w = _w + 1 { + let _ = br.pending_buf.remove(0) + } + } + if !br.local_eof { + let readable = br.sock.poll_readable(0) catch { _ => false } + if readable { + did_work = true + let chunk = br.sock.read_some(4096) catch { _ => b"" } + if chunk.length() == 0 { + br.local_eof = true + let _ = conn.close(now_ms) catch { _ => () } + } else { + let wrote = conn.write(chunk, now_ms) catch { _ => 0 } + for k = wrote; k < chunk.length(); k = k + 1 { + br.pending_buf.push(chunk[k]) + } + } + } + } + self.flush_stream_outbound( + sess, + conn, + br.peer_hash, + br.peer_static_pub, + br.lease_gw, + br.lease_tid, + send_ls2=false, + ) + if br.local_eof && conn.is_eof() && !conn.has_unacked() { + did_work = true + br.sock.close() + br.closed = true + let _ = self.remote_bridges.remove(ri) + continue + } + } + ri += 1 + } + did_work +} diff --git a/router/tunnel_protocol.mbt b/router/tunnel_protocol.mbt new file mode 100644 index 0000000..cbb1b43 --- /dev/null +++ b/router/tunnel_protocol.mbt @@ -0,0 +1,480 @@ +///| +/// Live Proposal 157 ShortTunnelBuild engine and AES-256-CBC `TunnelData`/`TunnelGateway` relay. + +///| +priv struct PendingTunnelBuild { + tunnel_id : UInt32 + direction : @tunnel.TunnelDirection + hops : Array[@tunnel.TunnelHop] + hop_slots_and_keys : Array[(Int32, @tunnel.HopKeys)] + build_msg_id : UInt32 + created_sec : UInt32 + expires_sec : UInt32 + started_ms : UInt64 +} + +///| +/// Returns `true` if `tunnel_id` has completed building and is active in `self.tunnels`. +pub fn Router::has_tunnel(self : Router, tunnel_id : UInt32) -> Bool { + for t in self.tunnels.inbound { + if t.id == tunnel_id { + return true + } + } + for t in self.tunnels.outbound { + if t.id == tunnel_id { + return true + } + } + false +} + +///| +/// Initiates a Proposal 157 `ShortTunnelBuild` along `hop_hashes` (1..8 routers). +/// Returns the allocated local tunnel ID; drive completion with `Router::step()` +/// and check readiness via `Router::has_tunnel(tid)`. +pub fn Router::build_tunnel( + self : Router, + hop_hashes : Array[@common.Hash], + direction : @tunnel.TunnelDirection, + expiration_sec~ : UInt32 = 600U, +) -> UInt32 raise RouterError { + let hop_count = hop_hashes.length() + if hop_count < 1 || hop_count > 8 { + raise Protocol("tunnel hop count must be 1..8, got \{hop_count}") + } + let now_ms = @ntcp2_net.unix_time_ms() + let now_sec = (now_ms / 1000UL).to_uint() + let req_time_min = now_sec / 60U + let local_tid = self.alloc_tunnel_id() + let build_msg_id = self.alloc_msg_id() + + let hop_recv_tids : Array[UInt32] = Array(capacity=hop_count) + let hop_static_pubs : Array[Bytes] = Array(capacity=hop_count) + for h in hop_hashes { + let ri = match self.netdb.get_router_info(h) { + Some(r) => r + None => raise Protocol("missing RouterInfo for tunnel hop") + } + let x_pub = ri.identity.inner.crypto_public_key() + if x_pub.length() != 32 { + raise Protocol("tunnel hop lacks X25519 identity key") + } + hop_static_pubs.push(x_pub) + hop_recv_tids.push(self.alloc_tunnel_id()) + } + + let total_slots = if hop_count <= 4 { 4 } else { 8 } + let specs : Array[@tunnel.ShortHopBuildSpec] = Array(capacity=hop_count) + let next_tids : Array[UInt32] = Array(capacity=hop_count) + for i = 0; i < hop_count; i = i + 1 { + let next_tid = if i + 1 < hop_count { + hop_recv_tids[i + 1] + } else if direction == Inbound { + local_tid + } else { + 0U + } + next_tids.push(next_tid) + let next_ident = if i + 1 < hop_count { + hop_hashes[i + 1] + } else { + self.router_hash() + } + let flag : Byte = if direction == Inbound && i == 0 { + b'\x80' + } else if direction == Outbound && i == hop_count - 1 { + b'\x40' + } else { + b'\x00' + } + let epriv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } + let ephem = @noise.KeyPair::from_private(epriv) catch { + e => raise Noise(e) + } + let pad = @ntcp2_net.random_bytes(8) catch { _ => b"" } + specs.push({ + slot_idx: i, + hop_ident: hop_hashes[i], + hop_static_pub: hop_static_pubs[i], + ephemeral: ephem, + record: { + receive_tunnel_id: hop_recv_tids[i], + next_tunnel_id: next_tid, + next_ident, + flag, + layer_enc_type: b'\x00', + request_time_min: req_time_min, + request_expiration_sec: expiration_sec, + send_message_id: build_msg_id, + options: @common.Mapping::new(), + }, + padding: pad, + }) + } + + let dummies : Array[Bytes] = [] + for _d = hop_count; _d < total_slots; _d = _d + 1 { + let dummy = @ntcp2_net.random_bytes(218) catch { + _ => Bytes::make(218, b'\x5a') + } + dummies.push(dummy) + } + let (records, hop_slots_and_keys) = @tunnel.build_short_tunnel_request( + total_slots, specs, dummies, + ) catch { + e => raise Tunnel(e) + } + + let tunnel_hops : Array[@tunnel.TunnelHop] = Array(capacity=hop_count) + for i = 0; i < hop_count; i = i + 1 { + let keys = hop_slots_and_keys[i].1 + tunnel_hops.push({ + router_hash: hop_hashes[i], + receive_tunnel_id: hop_recv_tids[i], + next_tunnel_id: next_tids[i], + layer_key: keys.layer_key, + iv_key: keys.iv_key, + }) + } + self.pending_builds.push({ + tunnel_id: local_tid, + direction, + hops: tunnel_hops, + hop_slots_and_keys, + build_msg_id, + created_sec: now_sec, + expires_sec: now_sec + expiration_sec, + started_ms: now_ms, + }) + let _ = self.send_i2np_to_peer( + hop_hashes[0], + ShortTunnelBuild(records~), + msg_id_override=Some(build_msg_id), + ) + local_tid +} + +///| +/// Sends an I2NP message encrypted through a built active `Outbound` tunnel. +pub fn Router::send_through_tunnel( + self : Router, + outbound_tunnel_id : UInt32, + target : @tunnel.DeliveryTarget, + payload : @i2np.I2npPayload, +) -> Unit raise RouterError { + let mut out_tun : @tunnel.Tunnel? = None + for t in self.tunnels.outbound { + if t.id == outbound_tunnel_id { + out_tun = Some(t) + break + } + } + let tun = match out_tun { + Some(t) => t + None => raise Protocol("unknown outbound tunnel \{outbound_tunnel_id}") + } + if tun.hops.length() == 0 { + raise Protocol("outbound tunnel has zero hops") + } + let now_ms = @ntcp2_net.unix_time_ms() + let inner_mid = self.alloc_msg_id() + let std_bytes = @i2np.encode_standard_message( + inner_mid, + now_ms + 60000UL, + payload, + ) catch { + e => raise I2np(e) + } + let base_iv = @ntcp2_net.random_bytes(16) catch { e => raise Net(e) } + let pad = non_zero_random_bytes(1024) + let cells = @tunnel.fragment_message_to_cells( + target, + self.alloc_msg_id(), + std_bytes, + base_iv, + padding=pad, + ) catch { + e => raise Tunnel(e) + } + let first_hop = tun.hops[0] + for cell in cells { + let enc_cell = tun.prepare_outbound_cell(cell) catch { + e => raise Tunnel(e) + } + let _ = self.send_i2np_to_peer( + first_hop.router_hash, + TunnelData(tunnel_id=first_hop.receive_tunnel_id, data=enc_cell), + ) + } +} + +///| +fn Router::try_complete_pending_tunnel_build( + self : Router, + build_msg_id : UInt32, + records : Array[Bytes], +) -> Bool { + let mut idx = -1 + for i = 0; i < self.pending_builds.length(); i = i + 1 { + if self.pending_builds[i].build_msg_id == build_msg_id { + idx = i + break + } + } + if idx < 0 { + return false + } + let pb = self.pending_builds.remove(idx) + let codes = @tunnel.decrypt_short_tunnel_replies( + records, + pb.hop_slots_and_keys, + ) catch { + _ => return true + } + for c in codes { + if c != b'\x00' { + return true + } + } + let dir = pb.direction + self.tunnels.add_tunnel({ + id: pb.tunnel_id, + direction: dir, + hops: pb.hops, + created_sec: pb.created_sec, + expires_sec: pb.expires_sec, + }) + if dir == Inbound { + self.republish_all_sessions() + } + true +} + +///| +fn Router::handle_short_tunnel_build( + self : Router, + msg_id : UInt32, + records : Array[Bytes], + now_sec : UInt32, +) -> Unit { + if self.try_complete_pending_tunnel_build(msg_id, records) { + return + } + let reply_pad = @ntcp2_net.random_bytes(8) catch { _ => b"" } + let (rec, keys, _slot, out_records) = @tunnel.process_short_tunnel_build_hop( + records, + self.router_hash(), + self.static_key, + b'\x00', + reply_padding=reply_pad, + ) catch { + _ => return + } + let is_obep = (rec.flag.to_int() & 0x40) != 0 + let exp_sec = now_sec + + (if rec.request_expiration_sec > 0U { + rec.request_expiration_sec + } else { + 600U + }) + self.tunnels.add_transit_hop({ + receive_tunnel_id: rec.receive_tunnel_id, + next_tunnel_id: rec.next_tunnel_id, + next_router: rec.next_ident, + layer_key: keys.layer_key, + iv_key: keys.iv_key, + is_obep, + expires_sec: exp_sec, + }) + if is_obep { + let reply_payload : @i2np.I2npPayload = ShortTunnelBuildReply( + records=out_records, + ) + if rec.next_tunnel_id != 0U { + let std = @i2np.encode_standard_message( + rec.send_message_id, + @ntcp2_net.unix_time_ms() + 60000UL, + reply_payload, + ) catch { + _ => return + } + let _ = self.send_i2np_to_peer( + rec.next_ident, + TunnelGateway(tunnel_id=rec.next_tunnel_id, data=std), + ) + } else { + let _ = self.send_i2np_to_peer( + rec.next_ident, + reply_payload, + msg_id_override=Some(rec.send_message_id), + ) + } + } else { + let _ = self.send_i2np_to_peer( + rec.next_ident, + ShortTunnelBuild(records=out_records), + msg_id_override=Some(rec.send_message_id), + ) + } +} + +///| +fn Router::handle_short_tunnel_build_reply( + self : Router, + msg_id : UInt32, + records : Array[Bytes], +) -> Unit { + let _ = self.try_complete_pending_tunnel_build(msg_id, records) +} + +///| +fn Router::deliver_reassembled_payload( + self : Router, + target : @tunnel.DeliveryTarget, + full_payload : Bytes, + now_sec : UInt32, +) -> Unit { + let (hdr, inner_payload) = @i2np.decode_standard_message( + @encoding.Reader::new(full_payload), + ) catch { + _ => return + } + match target { + Local => + self.handle_i2np_message( + None, + { + msg_type: hdr.msg_type, + msg_id: hdr.msg_id, + expiration_sec: now_sec + 60U, + }, + inner_payload, + ) + Router(router_hash~) => { + let _ = self.send_i2np_to_peer( + router_hash, + inner_payload, + msg_id_override=Some(hdr.msg_id), + ) + } + Tunnel(tunnel_id~, gateway~) => { + let _ = self.send_i2np_to_peer( + gateway, + TunnelGateway(tunnel_id~, data=full_payload), + ) + } + } +} + +///| +fn Router::consume_cleartext_cell( + self : Router, + cleartext_cell : Bytes, + now_sec : UInt32, +) -> Unit { + let frags = @tunnel.unpack_tunnel_cell(cleartext_cell) catch { _ => return } + for frag in frags { + match self.reassembler.push(frag) { + Some((target, full_payload)) => + self.deliver_reassembled_payload(target, full_payload, now_sec) + None => () + } + } +} + +///| +fn Router::handle_tunnel_data( + self : Router, + tunnel_id : UInt32, + data : Bytes, +) -> Unit { + let now_sec = @ntcp2_net.unix_time_sec() + // 1. Check if we are the inbound tunnel endpoint (IBEP) + for in_t in self.tunnels.inbound { + if in_t.id == tunnel_id { + let clear = in_t.decrypt_inbound_cell(data) catch { _ => return } + self.consume_cleartext_cell(clear, now_sec) + return + } + } + // 2. Otherwise check transit hops (IBGW / intermediate / OBEP) + let relay_res = self.tunnels.relay_cell(tunnel_id, data) catch { _ => None } + match relay_res { + Some((next_router, next_tid, next_cell, is_obep)) => + if is_obep { + self.consume_cleartext_cell(next_cell, now_sec) + } else { + let _ = self.send_i2np_to_peer( + next_router, + TunnelData(tunnel_id=next_tid, data=next_cell), + ) + } + None => () + } +} + +///| +fn Router::handle_tunnel_gateway( + self : Router, + tunnel_id : UInt32, + data : Bytes, + now_sec : UInt32, +) -> Unit { + // Check if tunnel_id corresponds to a transit hop where we act as IBGW + let mut is_transit = false + for hop in self.tunnels.transit { + if hop.receive_tunnel_id == tunnel_id { + is_transit = true + break + } + } + if is_transit { + let base_iv = @ntcp2_net.random_bytes(16) catch { _ => return } + let pad = non_zero_random_bytes(1024) + let cells = @tunnel.fragment_message_to_cells( + Local, + self.alloc_msg_id(), + data, + base_iv, + padding=pad, + ) catch { + _ => return + } + for cell in cells { + let relay_res = self.tunnels.relay_cell(tunnel_id, cell) catch { + _ => None + } + match relay_res { + Some((next_router, next_tid, next_cell, is_obep)) => + if is_obep { + self.consume_cleartext_cell(next_cell, now_sec) + } else { + let _ = self.send_i2np_to_peer( + next_router, + TunnelData(tunnel_id=next_tid, data=next_cell), + ) + } + None => () + } + } + return + } + // Direct 0-hop session delivery or forwarded standard I2NP message + self.deliver_reassembled_payload(Local, data, now_sec) +} + +///| +fn Router::poll_tunnel_builds(self : Router) -> Unit { + let now_ms = @ntcp2_net.unix_time_ms() + let now_sec = (now_ms / 1000UL).to_uint() + let _ = self.tunnels.prune_expired(now_sec) + let mut i = 0 + while i < self.pending_builds.length() { + if now_ms > self.pending_builds[i].started_ms + 10000UL { + let _ = self.pending_builds.remove(i) + } else { + i += 1 + } + } +} diff --git a/sam_client/client.mbt b/sam_client/client.mbt index d427c37..e861125 100644 --- a/sam_client/client.mbt +++ b/sam_client/client.mbt @@ -124,6 +124,15 @@ pub fn SamConfig::with_address( { ..self, host, port, } } +///| +/// Sets the SAM `DESTINATION` parameter (`"TRANSIENT"` or Base64 private keys). +pub fn SamConfig::with_destination( + self : SamConfig, + destination : String, +) -> SamConfig { + { ..self, destination, } +} + ///| fn parse_port(s : String) -> Int32 raise SamClientError { if s.length() == 0 { @@ -194,6 +203,26 @@ fn ensure_ok(reply : @sam.SamMessage) -> Unit raise SamClientError { } } +///| +fn read_sam_reply_handling_ping( + conn : TcpConn, +) -> @sam.SamMessage raise SamClientError { + while true { + let reply = parse_sam_reply(conn.read_line()) + if reply.verb == "PING" { + let pong = @sam.SamMessage::new( + "PONG", + subcommand=reply.subcommand, + params=reply.params, + ) + conn.write_string(pong.serialize()) + continue + } + return reply + } + raise Closed +} + ///| fn perform_hello( conn : TcpConn, @@ -201,7 +230,7 @@ fn perform_hello( ) -> String raise SamClientError { let cmd = @sam.hello_version(min=config.min_version, max=config.max_version) conn.write_string(cmd.serialize()) - let reply = parse_sam_reply(conn.read_line()) + let reply = read_sam_reply_handling_ping(conn) if reply.verb != "HELLO" || reply.subcommand != Some("REPLY") { raise ProtocolError("expected HELLO REPLY, got '\{reply.verb}'") } @@ -264,7 +293,7 @@ pub fn SamClient::dest_generate( } let cmd = @sam.dest_generate(signature_type=sig.to_string()) self.conn.write_string(cmd.serialize()) - let reply = parse_sam_reply(self.conn.read_line()) + let reply = read_sam_reply_handling_ping(self.conn) if reply.verb != "DEST" || reply.subcommand != Some("REPLY") { raise ProtocolError("expected DEST REPLY, got '\{reply.verb}'") } @@ -300,7 +329,7 @@ fn naming_lookup_on_conn( ) -> SamDestination raise SamClientError { let cmd = @sam.naming_lookup(name) conn.write_string(cmd.serialize()) - let reply = parse_sam_reply(conn.read_line()) + let reply = read_sam_reply_handling_ping(conn) if reply.verb != "NAMING" || reply.subcommand != Some("REPLY") { raise ProtocolError("expected NAMING REPLY, got '\{reply.verb}'") } @@ -344,7 +373,7 @@ pub fn SamClient::session_create( options=opts, ) self.conn.write_string(cmd.serialize()) - let reply = parse_sam_reply(self.conn.read_line()) + let reply = read_sam_reply_handling_ping(self.conn) if reply.verb != "SESSION" || reply.subcommand != Some("STATUS") { raise ProtocolError("expected SESSION STATUS, got '\{reply.verb}'") } @@ -431,7 +460,7 @@ pub fn SamSession::stream_connect( let _ = perform_hello(data_conn, self.config) let cmd = @sam.stream_connect(self.id, dest_b64, silent=false) data_conn.write_string(cmd.serialize()) - let reply = parse_sam_reply(data_conn.read_line()) + let reply = read_sam_reply_handling_ping(data_conn) if reply.verb != "STREAM" || reply.subcommand != Some("STATUS") { raise ProtocolError("expected STREAM STATUS, got '\{reply.verb}'") } @@ -454,7 +483,7 @@ pub fn SamSession::stream_accept( let _ = perform_hello(data_conn, self.config) let cmd = @sam.stream_accept(self.id, silent=false) data_conn.write_string(cmd.serialize()) - let reply = parse_sam_reply(data_conn.read_line()) + let reply = read_sam_reply_handling_ping(data_conn) if reply.verb != "STREAM" || reply.subcommand != Some("STATUS") { raise ProtocolError("expected STREAM STATUS, got '\{reply.verb}'") } diff --git a/sam_client/tcp.mbt b/sam_client/tcp.mbt index 6178e8c..c8f33a9 100644 --- a/sam_client/tcp.mbt +++ b/sam_client/tcp.mbt @@ -47,12 +47,74 @@ extern "C" fn c_read_stdin(buf : FixedArray[Byte], max_len : Int32) -> Int32 = " ///| extern "C" fn c_flush_stdout() -> Unit = "moon_i2p_flush_stdout" +///| +#borrow(path) +extern "C" fn c_file_size(path : Bytes, path_len : Int32) -> Int32 = "moon_i2p_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_read_file" + ///| /// Flushes standard output (useful before blocking on `stream_accept`). pub fn flush_stdout() -> Unit { c_flush_stdout() } +///| +/// Returns `true` if `path` exists as a regular file. +pub fn file_exists(path : String) -> Bool { + let pb = @encoding.string_to_utf8_bytes(path) + c_file_size(pb, pb.length()) >= 0 +} + +///| +/// Reads a UTF-8 text file and strips leading/trailing ASCII whitespace. +pub fn read_trimmed_text_file(path : String) -> String raise SamClientError { + let pb = @encoding.string_to_utf8_bytes(path) + let sz = c_file_size(pb, pb.length()) + if sz < 0 { + raise IoError("failed to stat '\{path}': \{last_os_error()}") + } + let bytes = if sz == 0 { + b"" + } else { + let buf = FixedArray::make(sz, b'\x00') + let n = c_read_file(pb, pb.length(), buf, sz) + if n < 0 { + raise IoError("failed to read '\{path}': \{last_os_error()}") + } + Bytes::from_array(buf)[:n].to_owned() + } + let text = @encoding.utf8_bytes_to_string(bytes) catch { + _ => raise IoError("invalid UTF-8 in '\{path}'") + } + let mut start = 0 + let mut end = text.length() + while start < end { + let c = text[start].to_int() + if c == 32 || c == 9 || c == 13 || c == 10 { + start += 1 + } else { + break + } + } + while end > start { + let c = text[end - 1].to_int() + if c == 32 || c == 9 || c == 13 || c == 10 { + end -= 1 + } else { + break + } + } + text[start:end].to_owned() +} + ///| fn last_os_error() -> String { let n = c_last_error_len() diff --git a/sam_client/tcp_stub.c b/sam_client/tcp_stub.c index 8b4665f..5679e62 100644 --- a/sam_client/tcp_stub.c +++ b/sam_client/tcp_stub.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -192,3 +193,52 @@ MOONBIT_FFI_EXPORT void moon_i2p_flush_stdout(void) { fflush(stdout); } + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_file_size(moonbit_bytes_t path_bytes, int32_t path_len) { + if (path_len <= 0 || path_len >= 1024) { + set_last_error("invalid file path"); + 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) { + set_last_error(strerror(errno)); + return -1; + } + if (!S_ISREG(st.st_mode)) { + set_last_error("not a regular file"); + return -1; + } + return (int32_t)st.st_size; +} + +MOONBIT_FFI_EXPORT +int32_t moon_i2p_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) { + set_last_error("invalid file path"); + return -1; + } + char path[1024]; + memcpy(path, path_bytes, (size_t)path_len); + path[path_len] = '\0'; + FILE *f = fopen(path, "rb"); + if (!f) { + set_last_error(strerror(errno)); + return -1; + } + size_t n = fread(dst, 1, (size_t)max_len, f); + if (ferror(f)) { + set_last_error(strerror(errno)); + fclose(f); + return -1; + } + fclose(f); + return (int32_t)n; +} diff --git a/streaming/datagram.mbt b/streaming/datagram.mbt new file mode 100644 index 0000000..bf61f14 --- /dev/null +++ b/streaming/datagram.mbt @@ -0,0 +1,122 @@ +///| +/// Canonical I2P Repliable Datagrams (I2CP protocol 17) and Raw Datagrams (I2CP protocol 18). + +///| +#derive(Eq, Debug) +pub(all) struct RepliableDatagram { + sender : @common.Destination + signature : Bytes + payload : Bytes +} + +///| +/// Signs `payload` directly with Ed25519 `seed` (per I2P Repliable Datagram spec for non-DSA_SHA1). +pub fn RepliableDatagram::sign_ed25519( + sender : @common.Destination, + seed : Bytes, + payload : Bytes, +) -> RepliableDatagram raise StreamingError { + if sender.inner.signing_type() != EdDsaSha512Ed25519 { + raise InvalidFormat( + "RepliableDatagram sender signing type must be EdDsaSha512Ed25519", + ) + } + let signature = @crypto.ed25519_sign(seed, payload) catch { + e => raise Crypto(e) + } + { sender, signature, payload, } +} + +///| +pub fn RepliableDatagram::verify(self : RepliableDatagram) -> Bool { + match self.sender.inner.signing_type() { + EdDsaSha512Ed25519 => + @crypto.ed25519_verify( + self.sender.inner.signing_public_key(), + self.payload, + self.signature, + ) + _ => false + } +} + +///| +pub fn RepliableDatagram::encode(self : RepliableDatagram) -> Bytes { + let w = @encoding.Writer::new( + capacity=391 + self.signature.length() + self.payload.length(), + ) + self.sender.encode(w) + w.write_bytes(self.signature) + w.write_bytes(self.payload) + w.to_bytes() +} + +///| +pub fn RepliableDatagram::decode( + data : Bytes, +) -> RepliableDatagram raise StreamingError { + let r = @encoding.Reader::new(data) + let sender = @common.Destination::decode(r) catch { e => raise Common(e) } + let sig_len = sender.inner.signing_type().signature_length() + if sig_len <= 0 { + raise InvalidFormat("unsupported RepliableDatagram signing type") + } + let signature = r.read_bytes(sig_len) catch { e => raise Encoding(e) } + let payload = r.read_remaining() + { sender, signature, payload, } +} + +///| +pub fn RepliableDatagram::to_i2cp_bytes( + self : RepliableDatagram, + from_port~ : UInt32 = 0U, + to_port~ : UInt32 = 0U, +) -> Bytes { + @encoding.i2cp_gzip_wrap( + self.encode(), + from_port~, + to_port~, + protocol=b'\x11', + ) +} + +///| +pub fn RepliableDatagram::from_i2cp_bytes( + i2cp_bytes : Bytes, +) -> (@encoding.I2cpGzipHeader, RepliableDatagram) raise StreamingError { + let (hdr, raw) = @encoding.i2cp_gzip_unwrap(i2cp_bytes) catch { + e => raise Encoding(e) + } + if hdr.protocol != b'\x11' { + raise InvalidFormat( + "expected I2CP protocol 17 (Repliable Datagram), got \{hdr.protocol.to_int()}", + ) + } + (hdr, RepliableDatagram::decode(raw)) +} + +///| +/// Wraps a raw (non-repliable) datagram in an I2CP Gzip envelope (`protocol = 18`). +pub fn encode_raw_datagram( + payload : Bytes, + from_port~ : UInt32 = 0U, + to_port~ : UInt32 = 0U, +) -> Bytes { + @encoding.i2cp_gzip_wrap(payload, from_port~, to_port~, protocol=b'\x12') +} + +///| +/// Unwraps an I2CP Gzip raw datagram (`protocol = 18`). +pub fn decode_raw_datagram( + i2cp_bytes : Bytes, +) -> (@encoding.I2cpGzipHeader, Bytes) raise StreamingError { + let (hdr, raw) = @encoding.i2cp_gzip_unwrap(i2cp_bytes) catch { + e => raise Encoding(e) + } + if hdr.protocol != b'\x12' { + raise InvalidFormat( + "expected I2CP protocol 18 (Raw Datagram), got \{hdr.protocol.to_int()}", + ) + } + (hdr, raw) +} diff --git a/streaming/moon.pkg b/streaming/moon.pkg new file mode 100644 index 0000000..72abb26 --- /dev/null +++ b/streaming/moon.pkg @@ -0,0 +1,5 @@ +import { + "experiments/moon_i2p/encoding", + "experiments/moon_i2p/crypto", + "experiments/moon_i2p/common", +} diff --git a/streaming/packet.mbt b/streaming/packet.mbt new file mode 100644 index 0000000..63cf4cf --- /dev/null +++ b/streaming/packet.mbt @@ -0,0 +1,354 @@ +///| +/// Canonical I2P Streaming Protocol Packet codec (protocol 6 inside I2CP Gzip envelope). + +///| +#derive(Eq, Debug) +pub suberror StreamingError { + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + Crypto(@crypto.CryptoError) + InvalidFormat(String) + InvalidLength(String) + InvalidSignature + ProtocolError(String) +} + +///| +pub let flag_synchronize : UInt32 = 0x0001U + +///| +pub let flag_close : UInt32 = 0x0002U + +///| +pub let flag_reset : UInt32 = 0x0004U + +///| +pub let flag_signature_included : UInt32 = 0x0008U + +///| +pub let flag_signature_requested : UInt32 = 0x0010U + +///| +pub let flag_from_included : UInt32 = 0x0020U + +///| +pub let flag_delay_requested : UInt32 = 0x0040U + +///| +pub let flag_max_packet_size_included : UInt32 = 0x0080U + +///| +pub let flag_profile_interactive : UInt32 = 0x0100U + +///| +pub let flag_echo : UInt32 = 0x0200U + +///| +pub let flag_no_ack : UInt32 = 0x0400U + +///| +pub let flag_offline_signature : UInt32 = 0x0800U + +///| +/// Canonical I2P Streaming Packet. +#derive(Eq, Debug) +pub(all) struct StreamingPacket { + send_stream_id : UInt32 + recv_stream_id : UInt32 + sequence_num : UInt32 + ack_through : UInt32 + nacks : Array[UInt32] + resend_delay : Byte + flags : UInt32 + delay_requested : UInt32? // Option Order 1 (0x0040) + from_dest : @common.Destination? // Option Order 2 (0x0020) + max_packet_size : UInt32? // Option Order 3 (0x0080) + offline_sig : @common.OfflineSignature? // Option Order 4 (0x0800) + signature : Bytes? // Option Order 5 (0x0008) + payload : Bytes +} + +///| +fn serialize_options( + pkt : StreamingPacket, + zero_sig_len~ : Int32 = -1, +) -> Bytes raise StreamingError { + let ow = @encoding.Writer::new(capacity=512) + if (pkt.flags & flag_delay_requested) != 0U { + let d = match pkt.delay_requested { + Some(v) => v + None => + raise InvalidFormat("DELAY_REQUESTED flag set without delay_requested") + } + ow.write_u16_be(d) + } + if (pkt.flags & flag_from_included) != 0U { + let dest = match pkt.from_dest { + Some(d) => d + None => raise InvalidFormat("FROM_INCLUDED flag set without from_dest") + } + dest.encode(ow) + } + if (pkt.flags & flag_max_packet_size_included) != 0U { + let m = match pkt.max_packet_size { + Some(v) => v + None => + raise InvalidFormat( + "MAX_PACKET_SIZE_INCLUDED flag set without max_packet_size", + ) + } + ow.write_u16_be(m) + } + if (pkt.flags & flag_offline_signature) != 0U { + let os = match pkt.offline_sig { + Some(o) => o + None => + raise InvalidFormat("OFFLINE_SIGNATURE flag set without offline_sig") + } + os.encode(ow) + } + if (pkt.flags & flag_signature_included) != 0U { + if zero_sig_len > 0 { + ow.write_bytes(Bytes::make(zero_sig_len, b'\x00')) + } else { + let sig = match pkt.signature { + Some(s) => s + None => + raise InvalidFormat("SIGNATURE_INCLUDED flag set without signature") + } + ow.write_bytes(sig) + } + } + ow.to_bytes() +} + +///| +fn encode_with_opt_zero_sig( + pkt : StreamingPacket, + zero_sig_len~ : Int32 = -1, +) -> Bytes raise StreamingError { + let opts = serialize_options(pkt, zero_sig_len~) + if pkt.nacks.length() > 255 { + raise InvalidLength("StreamingPacket nacks exceed 255") + } + let w = @encoding.Writer::new( + capacity=22 + pkt.nacks.length() * 4 + opts.length() + pkt.payload.length(), + ) + w.write_u32_be(pkt.send_stream_id) + w.write_u32_be(pkt.recv_stream_id) + w.write_u32_be(pkt.sequence_num) + w.write_u32_be(pkt.ack_through) + w.write_u8(pkt.nacks.length().to_byte()) + for n in pkt.nacks { + w.write_u32_be(n) + } + w.write_u8(pkt.resend_delay) + w.write_u16_be(pkt.flags) + w.write_u16_be(opts.length().reinterpret_as_uint()) + w.write_bytes(opts) + w.write_bytes(pkt.payload) + w.to_bytes() +} + +///| +pub fn StreamingPacket::encode( + self : StreamingPacket, +) -> Bytes raise StreamingError { + encode_with_opt_zero_sig(self) +} + +///| +/// Signs the `StreamingPacket` using an Ed25519 32-byte `seed` (over the full packet +/// with the 64-byte signature slot zeroed out). +pub fn StreamingPacket::sign_ed25519( + self : StreamingPacket, + seed : Bytes, +) -> StreamingPacket raise StreamingError { + let with_flag : StreamingPacket = { + send_stream_id: self.send_stream_id, + recv_stream_id: self.recv_stream_id, + sequence_num: self.sequence_num, + ack_through: self.ack_through, + nacks: self.nacks, + resend_delay: self.resend_delay, + flags: self.flags | flag_signature_included, + delay_requested: self.delay_requested, + from_dest: self.from_dest, + max_packet_size: self.max_packet_size, + offline_sig: self.offline_sig, + signature: Some(Bytes::make(64, b'\x00')), + payload: self.payload, + } + let to_sign = encode_with_opt_zero_sig(with_flag, zero_sig_len=64) + let sig = @crypto.ed25519_sign(seed, to_sign) catch { e => raise Crypto(e) } + { + send_stream_id: with_flag.send_stream_id, + recv_stream_id: with_flag.recv_stream_id, + sequence_num: with_flag.sequence_num, + ack_through: with_flag.ack_through, + nacks: with_flag.nacks, + resend_delay: with_flag.resend_delay, + flags: with_flag.flags, + delay_requested: with_flag.delay_requested, + from_dest: with_flag.from_dest, + max_packet_size: with_flag.max_packet_size, + offline_sig: with_flag.offline_sig, + signature: Some(sig), + payload: with_flag.payload, + } +} + +///| +/// Verifies the Ed25519 signature of a `StreamingPacket` against `sender_dest` +/// (or the embedded `offline_sig.transient_pub_key` when `FLAG_OFFLINE_SIGNATURE` is set). +pub fn StreamingPacket::verify_signature( + self : StreamingPacket, + sender_dest : @common.Destination, +) -> Bool { + if (self.flags & flag_signature_included) == 0U { + return false + } + let sig = match self.signature { + Some(s) => s + None => return false + } + let verify_key = if (self.flags & flag_offline_signature) != 0U { + match self.offline_sig { + Some(os) => { + if os.transient_sig_type != EdDsaSha512Ed25519 || + sender_dest.inner.signing_type() != EdDsaSha512Ed25519 { + return false + } + if !os.verify_ed25519(sender_dest.inner.signing_public_key()) { + return false + } + os.transient_pub_key + } + None => return false + } + } else { + if sender_dest.inner.signing_type() != EdDsaSha512Ed25519 { + return false + } + sender_dest.inner.signing_public_key() + } + let to_verify = encode_with_opt_zero_sig(self, zero_sig_len=sig.length()) catch { + _ => return false + } + @crypto.ed25519_verify(verify_key, to_verify, sig) +} + +///| +/// Decodes a canonical I2P Streaming Packet. +/// Pass `peer_sig_type` if `FROM_INCLUDED` is not set in the packet so the signature length is known. +pub fn StreamingPacket::decode( + data : Bytes, + peer_sig_type~ : @common.SigningPublicKeyType = EdDsaSha512Ed25519, +) -> StreamingPacket raise StreamingError { + if data.length() < 22 { + raise InvalidLength( + "StreamingPacket shorter than 22 bytes: \{data.length()}", + ) + } + let r = @encoding.Reader::new(data) + let send_stream_id = r.read_u32_be() catch { e => raise Encoding(e) } + let recv_stream_id = r.read_u32_be() catch { e => raise Encoding(e) } + let sequence_num = r.read_u32_be() catch { e => raise Encoding(e) } + let ack_through = r.read_u32_be() catch { e => raise Encoding(e) } + let nack_count = (r.read_u8() catch { e => raise Encoding(e) }).to_int() + let nacks : Array[UInt32] = Array(capacity=nack_count) + for _i = 0; _i < nack_count; _i = _i + 1 { + nacks.push(r.read_u32_be() catch { e => raise Encoding(e) }) + } + let resend_delay = r.read_u8() catch { e => raise Encoding(e) } + let flags = r.read_u16_be() catch { e => raise Encoding(e) } + let opt_size = (r.read_u16_be() catch { e => raise Encoding(e) }).reinterpret_as_int() + let opt_bytes = r.read_bytes(opt_size) catch { e => raise Encoding(e) } + let payload = r.read_remaining() + + let or = @encoding.Reader::new(opt_bytes) + let delay_requested = if (flags & flag_delay_requested) != 0U { + Some(or.read_u16_be() catch { e => raise Encoding(e) }) + } else { + None + } + let from_dest = if (flags & flag_from_included) != 0U { + Some(@common.Destination::decode(or) catch { e => raise Common(e) }) + } else { + None + } + let max_packet_size = if (flags & flag_max_packet_size_included) != 0U { + Some(or.read_u16_be() catch { e => raise Encoding(e) }) + } else { + None + } + let effective_sig_type = match from_dest { + Some(d) => d.inner.signing_type() + None => peer_sig_type + } + let offline_sig = if (flags & flag_offline_signature) != 0U { + Some( + @common.OfflineSignature::decode(or, effective_sig_type) catch { + e => raise Common(e) + }, + ) + } else { + None + } + let signature = if (flags & flag_signature_included) != 0U { + let sig_len = match offline_sig { + Some(os) => os.transient_sig_type.signature_length() + None => effective_sig_type.signature_length() + } + if sig_len <= 0 { + Some(or.read_remaining()) + } else { + Some(or.read_bytes(sig_len) catch { e => raise Encoding(e) }) + } + } else { + None + } + { + send_stream_id, + recv_stream_id, + sequence_num, + ack_through, + nacks, + resend_delay, + flags, + delay_requested, + from_dest, + max_packet_size, + offline_sig, + signature, + payload, + } +} + +///| +/// Wraps a `StreamingPacket` inside an I2CP Gzip envelope (`protocol = 6`). +pub fn encode_i2cp_streaming( + pkt : StreamingPacket, + from_port~ : UInt32 = 0U, + to_port~ : UInt32 = 0U, +) -> Bytes raise StreamingError { + let raw = pkt.encode() + @encoding.i2cp_gzip_wrap(raw, from_port~, to_port~, protocol=b'\x06') +} + +///| +/// Unwraps an I2CP Gzip envelope and decodes a `StreamingPacket` (verifying `protocol == 6`). +pub fn decode_i2cp_streaming( + i2cp_bytes : Bytes, + peer_sig_type~ : @common.SigningPublicKeyType = EdDsaSha512Ed25519, +) -> (@encoding.I2cpGzipHeader, StreamingPacket) raise StreamingError { + let (hdr, raw) = @encoding.i2cp_gzip_unwrap(i2cp_bytes) catch { + e => raise Encoding(e) + } + if hdr.protocol != b'\x06' { + raise InvalidFormat( + "expected I2CP protocol 6 (Streaming), got \{hdr.protocol.to_int()}", + ) + } + (hdr, StreamingPacket::decode(raw, peer_sig_type~)) +} diff --git a/streaming/pkg.generated.mbti b/streaming/pkg.generated.mbti new file mode 100644 index 0000000..94d847b --- /dev/null +++ b/streaming/pkg.generated.mbti @@ -0,0 +1,151 @@ +// Generated using `moon info`, DON'T EDIT IT +package "experiments/moon_i2p/streaming" + +import { + "experiments/moon_i2p/common", + "experiments/moon_i2p/crypto", + "experiments/moon_i2p/encoding", + "moonbitlang/core/debug", +} + +// Values +pub fn decode_i2cp_streaming(Bytes, peer_sig_type? : @common.SigningPublicKeyType) -> (@encoding.I2cpGzipHeader, StreamingPacket) raise StreamingError + +pub fn decode_raw_datagram(Bytes) -> (@encoding.I2cpGzipHeader, Bytes) raise StreamingError + +pub fn encode_i2cp_streaming(StreamingPacket, from_port? : UInt32, to_port? : UInt32) -> Bytes raise StreamingError + +pub fn encode_raw_datagram(Bytes, from_port? : UInt32, to_port? : UInt32) -> Bytes + +pub let flag_close : UInt32 + +pub let flag_delay_requested : UInt32 + +pub let flag_echo : UInt32 + +pub let flag_from_included : UInt32 + +pub let flag_max_packet_size_included : UInt32 + +pub let flag_no_ack : UInt32 + +pub let flag_offline_signature : UInt32 + +pub let flag_profile_interactive : UInt32 + +pub let flag_reset : UInt32 + +pub let flag_signature_included : UInt32 + +pub let flag_signature_requested : UInt32 + +pub let flag_synchronize : UInt32 + +// Errors +#derive(Eq, @debug.Debug) +pub suberror StreamingError { + Encoding(@encoding.EncodingError) + Common(@common.CommonError) + Crypto(@crypto.CryptoError) + InvalidFormat(String) + InvalidLength(String) + InvalidSignature + ProtocolError(String) +} + +// Types and methods +#derive(Eq, @debug.Debug) +pub(all) struct RepliableDatagram { + sender : @common.Destination + signature : Bytes + payload : Bytes +} +pub fn RepliableDatagram::decode(Bytes) -> Self raise StreamingError +pub fn RepliableDatagram::encode(Self) -> Bytes +pub fn RepliableDatagram::from_i2cp_bytes(Bytes) -> (@encoding.I2cpGzipHeader, Self) raise StreamingError +pub fn RepliableDatagram::sign_ed25519(@common.Destination, Bytes, Bytes) -> Self raise StreamingError +pub fn RepliableDatagram::to_i2cp_bytes(Self, from_port? : UInt32, to_port? : UInt32) -> Bytes +pub fn RepliableDatagram::verify(Self) -> Bool + +pub struct StreamConnection { + local_dest : @common.Destination + local_ed_seed : Bytes + mut remote_dest : @common.Destination? + mut remote_hash : @common.Hash + from_port : UInt32 + to_port : UInt32 + send_stream_id : UInt32 + mut recv_stream_id : UInt32 + mut state : StreamState + mut next_send_seq : UInt32 + mut highest_acked_seq : UInt32 + mut has_acked : Bool + mut next_recv_seq : UInt32 + mut ack_through : UInt32 + mut has_recv_syn : Bool + mut max_packet_size : UInt32 + window_size : Int32 + ooo_recv : Array[(UInt32, Bytes)] + recv_buf : Array[Byte] + mut peer_closed : Bool + out_queue : Array[Bytes] + // private fields +} +pub fn StreamConnection::accept_syn(@common.Destination, Bytes, StreamingPacket, UInt32, UInt64, from_port? : UInt32, to_port? : UInt32) -> Self raise StreamingError +pub fn StreamConnection::close(Self, UInt64) -> Unit raise StreamingError +pub fn StreamConnection::connect(@common.Destination, Bytes, @common.Hash, UInt32, UInt64, from_port? : UInt32, to_port? : UInt32, max_packet_size? : UInt32) -> Self raise StreamingError +pub fn StreamConnection::drain_outbound(Self) -> Array[Bytes] +pub fn StreamConnection::has_unacked(Self) -> Bool +pub fn StreamConnection::is_eof(Self) -> Bool +pub fn StreamConnection::on_packet(Self, StreamingPacket, UInt64) -> Unit raise StreamingError +pub fn StreamConnection::poll_retransmits(Self, UInt64, rto_ms? : UInt64) -> Unit raise StreamingError +pub fn StreamConnection::read_available(Self) -> Bytes +pub fn StreamConnection::write(Self, Bytes, UInt64) -> Int32 raise StreamingError + +pub struct StreamManager { + local_dest : @common.Destination + local_ed_seed : Bytes + mut next_stream_id : UInt32 + streams : Array[StreamConnection] + pending_accept : Array[StreamConnection] + incoming_datagrams : Array[RepliableDatagram] +} +pub fn StreamManager::accept_next(Self) -> StreamConnection? +pub fn StreamManager::connect(Self, @common.Hash, UInt64, from_port? : UInt32, to_port? : UInt32) -> StreamConnection raise StreamingError +pub fn StreamManager::handle_incoming_i2cp(Self, Bytes, UInt64) -> StreamConnection? raise StreamingError +pub fn StreamManager::new(@common.Destination, Bytes, initial_stream_id? : UInt32) -> Self + +#derive(Eq, @debug.Debug) +pub(all) enum StreamState { + SynSent + SynReceived + Established + Closing + Closed + Reset +} + +#derive(Eq, @debug.Debug) +pub(all) struct StreamingPacket { + send_stream_id : UInt32 + recv_stream_id : UInt32 + sequence_num : UInt32 + ack_through : UInt32 + nacks : Array[UInt32] + resend_delay : Byte + flags : UInt32 + delay_requested : UInt32? + from_dest : @common.Destination? + max_packet_size : UInt32? + offline_sig : @common.OfflineSignature? + signature : Bytes? + payload : Bytes +} +pub fn StreamingPacket::decode(Bytes, peer_sig_type? : @common.SigningPublicKeyType) -> Self raise StreamingError +pub fn StreamingPacket::encode(Self) -> Bytes raise StreamingError +pub fn StreamingPacket::sign_ed25519(Self, Bytes) -> Self raise StreamingError +pub fn StreamingPacket::verify_signature(Self, @common.Destination) -> Bool + +// Type aliases + +// Traits diff --git a/streaming/stream.mbt b/streaming/stream.mbt new file mode 100644 index 0000000..0de8ec0 --- /dev/null +++ b/streaming/stream.mbt @@ -0,0 +1,673 @@ +///| +/// Reliable sliding-window I2P Streaming connection & session stream manager. + +///| +#derive(Eq, Debug) +pub(all) enum StreamState { + SynSent + SynReceived + Established + Closing + Closed + Reset +} + +///| +priv struct UnackedPacket { + seq : UInt32 + pkt : StreamingPacket + mut last_sent_ms : UInt64 +} + +///| +/// Single reliable bidirectional I2P Streaming connection. +pub struct StreamConnection { + local_dest : @common.Destination + local_ed_seed : Bytes + mut remote_dest : @common.Destination? + mut remote_hash : @common.Hash + from_port : UInt32 + to_port : UInt32 + send_stream_id : UInt32 + mut recv_stream_id : UInt32 + mut state : StreamState + mut next_send_seq : UInt32 + mut highest_acked_seq : UInt32 + mut has_acked : Bool + mut next_recv_seq : UInt32 + mut ack_through : UInt32 + mut has_recv_syn : Bool + mut max_packet_size : UInt32 + window_size : Int32 + priv unacked : Array[UnackedPacket] + ooo_recv : Array[(UInt32, Bytes)] + recv_buf : Array[Byte] + mut peer_closed : Bool + out_queue : Array[Bytes] +} + +///| +fn slice_bytes(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 StreamConnection::queue_packet( + self : StreamConnection, + pkt : StreamingPacket, + now_ms : UInt64, + track_unacked~ : Bool = true, +) -> Unit raise StreamingError { + if track_unacked { + self.unacked.push({ seq: pkt.sequence_num, pkt, last_sent_ms: now_ms, }) + } + self.out_queue.push( + encode_i2cp_streaming(pkt, from_port=self.from_port, to_port=self.to_port), + ) +} + +///| +fn StreamConnection::current_nacks(self : StreamConnection) -> Array[UInt32] { + if self.ooo_recv.length() == 0 { + return [] + } + let mut max_seen = self.next_recv_seq + for entry in self.ooo_recv { + if entry.0 > max_seen { + max_seen = entry.0 + } + } + let nacks : Array[UInt32] = [] + let mut s = self.next_recv_seq + while s < max_seen && nacks.length() < 32 { + let mut found = false + for entry in self.ooo_recv { + if entry.0 == s { + found = true + break + } + } + if !found { + nacks.push(s) + } + s = s + 1U + } + nacks +} + +///| +/// Creates a new outbound `StreamConnection` and queues its signed `SYN` packet. +pub fn StreamConnection::connect( + local_dest : @common.Destination, + local_ed_seed : Bytes, + remote_hash : @common.Hash, + send_stream_id : UInt32, + now_ms : UInt64, + from_port~ : UInt32 = 0U, + to_port~ : UInt32 = 0U, + max_packet_size~ : UInt32 = 1730U, +) -> StreamConnection raise StreamingError { + let conn : StreamConnection = { + local_dest, + local_ed_seed, + remote_dest: None, + remote_hash, + from_port, + to_port, + send_stream_id, + recv_stream_id: 0U, + state: SynSent, + next_send_seq: 1U, + highest_acked_seq: 0U, + has_acked: false, + next_recv_seq: 0U, + ack_through: 0U, + has_recv_syn: false, + max_packet_size, + window_size: 16, + unacked: [], + ooo_recv: [], + recv_buf: [], + peer_closed: false, + out_queue: [], + } + let syn : StreamingPacket = { + send_stream_id, + recv_stream_id: 0U, + sequence_num: 0U, + ack_through: 0U, + nacks: [], + resend_delay: b'\x00', + flags: flag_synchronize | + flag_from_included | + flag_signature_included | + flag_max_packet_size_included | + flag_no_ack, + delay_requested: None, + from_dest: Some(local_dest), + max_packet_size: Some(max_packet_size), + offline_sig: None, + signature: None, + payload: b"", + } + let signed_syn = syn.sign_ed25519(local_ed_seed) + conn.queue_packet(signed_syn, now_ms) + conn +} + +///| +/// Creates an inbound `StreamConnection` from a verified incoming `SYN` packet and queues `SYN-ACK`. +pub fn StreamConnection::accept_syn( + local_dest : @common.Destination, + local_ed_seed : Bytes, + syn_pkt : StreamingPacket, + send_stream_id : UInt32, + now_ms : UInt64, + from_port~ : UInt32 = 0U, + to_port~ : UInt32 = 0U, +) -> StreamConnection raise StreamingError { + let peer_dest = match syn_pkt.from_dest { + Some(d) => d + None => raise InvalidFormat("incoming SYN missing FROM_INCLUDED") + } + if !syn_pkt.verify_signature(peer_dest) { + raise InvalidSignature + } + let peer_mtu = match syn_pkt.max_packet_size { + Some(m) if m >= 512U && m <= 1730U => m + _ => 1730U + } + let conn : StreamConnection = { + local_dest, + local_ed_seed, + remote_dest: Some(peer_dest), + remote_hash: peer_dest.hash(), + from_port, + to_port, + send_stream_id, + recv_stream_id: syn_pkt.send_stream_id, + state: Established, + next_send_seq: 1U, + highest_acked_seq: 0U, + has_acked: false, + next_recv_seq: 1U, + ack_through: 0U, + has_recv_syn: true, + max_packet_size: peer_mtu, + window_size: 16, + unacked: [], + ooo_recv: [], + recv_buf: [], + peer_closed: false, + out_queue: [], + } + if syn_pkt.payload.length() > 0 { + for i = 0; i < syn_pkt.payload.length(); i = i + 1 { + conn.recv_buf.push(syn_pkt.payload[i]) + } + } + let syn_ack : StreamingPacket = { + send_stream_id, + recv_stream_id: syn_pkt.send_stream_id, + sequence_num: 0U, + ack_through: 0U, + nacks: [], + resend_delay: b'\x00', + flags: flag_synchronize | + flag_from_included | + flag_signature_included | + flag_max_packet_size_included, + delay_requested: None, + from_dest: Some(local_dest), + max_packet_size: Some(peer_mtu), + offline_sig: None, + signature: None, + payload: b"", + } + let signed_ack = syn_ack.sign_ed25519(local_ed_seed) + conn.queue_packet(signed_ack, now_ms) + conn +} + +///| +fn StreamConnection::process_acks( + self : StreamConnection, + pkt : StreamingPacket, + now_ms : UInt64, +) -> Unit raise StreamingError { + if (pkt.flags & flag_no_ack) != 0U { + return + } + let ack_through = pkt.ack_through + if !self.has_acked || ack_through > self.highest_acked_seq { + self.has_acked = true + self.highest_acked_seq = ack_through + } + let mut i = 0 + while i < self.unacked.length() { + let seq = self.unacked[i].seq + if seq <= ack_through { + let mut is_nacked = false + for n in pkt.nacks { + if n == seq { + is_nacked = true + break + } + } + if !is_nacked { + let _ = self.unacked.remove(i) + continue + } + } + i += 1 + } + // Retransmit explicitly NACKed packets immediately + for n in pkt.nacks { + for u in self.unacked { + if u.seq == n { + u.last_sent_ms = now_ms + self.out_queue.push( + encode_i2cp_streaming( + u.pkt, + from_port=self.from_port, + to_port=self.to_port, + ), + ) + break + } + } + } +} + +///| +fn StreamConnection::drain_ooo_in_order(self : StreamConnection) -> Unit { + while true { + let mut matched = -1 + for i = 0; i < self.ooo_recv.length(); i = i + 1 { + if self.ooo_recv[i].0 == self.next_recv_seq { + matched = i + break + } + } + if matched < 0 { + break + } + let chunk = self.ooo_recv[matched].1 + let _ = self.ooo_recv.remove(matched) + for j = 0; j < chunk.length(); j = j + 1 { + self.recv_buf.push(chunk[j]) + } + self.ack_through = self.next_recv_seq + self.next_recv_seq = self.next_recv_seq + 1U + } +} + +///| +fn StreamConnection::send_ack( + self : StreamConnection, + now_ms : UInt64, +) -> Unit raise StreamingError { + let ack_pkt : StreamingPacket = { + send_stream_id: self.send_stream_id, + recv_stream_id: self.recv_stream_id, + sequence_num: 0U, + ack_through: self.ack_through, + nacks: self.current_nacks(), + resend_delay: b'\x00', + flags: 0U, + delay_requested: None, + from_dest: None, + max_packet_size: None, + offline_sig: None, + signature: None, + payload: b"", + } + self.queue_packet(ack_pkt, now_ms, track_unacked=false) +} + +///| +/// Processes an incoming decoded `StreamingPacket` addressed to this stream. +pub fn StreamConnection::on_packet( + self : StreamConnection, + pkt : StreamingPacket, + now_ms : UInt64, +) -> Unit raise StreamingError { + if (pkt.flags & flag_reset) != 0U { + match self.remote_dest { + Some(d) => + if (pkt.flags & flag_signature_included) != 0U && + !pkt.verify_signature(d) { + raise InvalidSignature + } + None => () + } + self.state = Reset + self.peer_closed = true + return + } + if (pkt.flags & flag_synchronize) != 0U && self.state == SynSent { + let peer_dest = match pkt.from_dest { + Some(d) => d + None => raise InvalidFormat("SYN-ACK missing FROM_INCLUDED") + } + if !pkt.verify_signature(peer_dest) { + raise InvalidSignature + } + self.remote_dest = Some(peer_dest) + self.remote_hash = peer_dest.hash() + self.recv_stream_id = pkt.send_stream_id + match pkt.max_packet_size { + Some(m) if m >= 512U && m < self.max_packet_size => + self.max_packet_size = m + _ => () + } + self.has_recv_syn = true + self.ack_through = 0U + self.next_recv_seq = 1U + self.state = Established + self.process_acks(pkt, now_ms) + if pkt.payload.length() > 0 { + for i = 0; i < pkt.payload.length(); i = i + 1 { + self.recv_buf.push(pkt.payload[i]) + } + } + self.send_ack(now_ms) + return + } + + self.process_acks(pkt, now_ms) + + if (pkt.flags & flag_close) != 0U { + match self.remote_dest { + Some(d) => if !pkt.verify_signature(d) { raise InvalidSignature } + None => () + } + self.peer_closed = true + if self.state == Closing { + self.state = Closed + } + } + + let seq = pkt.sequence_num + let has_data = pkt.payload.length() > 0 || (pkt.flags & flag_close) != 0U + if seq > 0U && has_data { + if seq == self.next_recv_seq { + for i = 0; i < pkt.payload.length(); i = i + 1 { + self.recv_buf.push(pkt.payload[i]) + } + self.ack_through = seq + self.next_recv_seq = seq + 1U + self.drain_ooo_in_order() + self.send_ack(now_ms) + } else if seq > self.next_recv_seq { + let mut dup = false + for e in self.ooo_recv { + if e.0 == seq { + dup = true + break + } + } + if !dup { + self.ooo_recv.push((seq, pkt.payload)) + } + self.send_ack(now_ms) + } else { + // Duplicate old seq: re-ACK so sender stops retransmitting + self.send_ack(now_ms) + } + } else if (pkt.flags & flag_close) != 0U { + self.send_ack(now_ms) + } +} + +///| +/// Queues application `data` split into `max_packet_size` Streaming packets. +pub fn StreamConnection::write( + self : StreamConnection, + data : Bytes, + now_ms : UInt64, +) -> Int32 raise StreamingError { + if self.state != Established && self.state != SynSent { + raise ProtocolError("cannot write on closed or reset stream") + } + if data.length() == 0 { + return 0 + } + let mtu = self.max_packet_size.reinterpret_as_int() + let mut off = 0 + while off < data.length() && self.unacked.length() < self.window_size { + let rem = data.length() - off + let take = if rem < mtu { rem } else { mtu } + let chunk = slice_bytes(data, off, take) + let seq = self.next_send_seq + self.next_send_seq = seq + 1U + let flags = if self.has_recv_syn { 0U } else { flag_no_ack } + let pkt : StreamingPacket = { + send_stream_id: self.send_stream_id, + recv_stream_id: self.recv_stream_id, + sequence_num: seq, + ack_through: self.ack_through, + nacks: self.current_nacks(), + resend_delay: b'\x00', + flags, + delay_requested: None, + from_dest: None, + max_packet_size: None, + offline_sig: None, + signature: None, + payload: chunk, + } + self.queue_packet(pkt, now_ms) + off += take + } + off +} + +///| +/// Drains all in-order received bytes available for the application. +pub fn StreamConnection::read_available(self : StreamConnection) -> Bytes { + if self.recv_buf.length() == 0 { + return b"" + } + let out = Bytes::from_array(self.recv_buf) + self.recv_buf.clear() + out +} + +///| +/// Returns `true` if the peer has closed/reset and all buffered incoming bytes have been read. +pub fn StreamConnection::is_eof(self : StreamConnection) -> Bool { + self.peer_closed && self.recv_buf.length() == 0 +} + +///| +/// Queues a signed `CLOSE` packet. +pub fn StreamConnection::close( + self : StreamConnection, + now_ms : UInt64, +) -> Unit raise StreamingError { + if self.state == Closed || self.state == Reset { + return + } + let seq = self.next_send_seq + self.next_send_seq = seq + 1U + let pkt : StreamingPacket = { + send_stream_id: self.send_stream_id, + recv_stream_id: self.recv_stream_id, + sequence_num: seq, + ack_through: self.ack_through, + nacks: self.current_nacks(), + resend_delay: b'\x00', + flags: flag_close | + flag_signature_included | + (if self.has_recv_syn { 0U } else { flag_no_ack }), + delay_requested: None, + from_dest: None, + max_packet_size: None, + offline_sig: None, + signature: None, + payload: b"", + } + let signed = pkt.sign_ed25519(self.local_ed_seed) + self.queue_packet(signed, now_ms) + self.state = if self.peer_closed { Closed } else { Closing } +} + +///| +/// Re-queues any unacked packets whose RTO has expired. +pub fn StreamConnection::poll_retransmits( + self : StreamConnection, + now_ms : UInt64, + rto_ms~ : UInt64 = 1500UL, +) -> Unit raise StreamingError { + for u in self.unacked { + if now_ms >= u.last_sent_ms + rto_ms { + u.last_sent_ms = now_ms + self.out_queue.push( + encode_i2cp_streaming( + u.pkt, + from_port=self.from_port, + to_port=self.to_port, + ), + ) + } + } +} + +///| +/// Drains all outbound I2CP-wrapped Streaming packets queued by this connection. +pub fn StreamConnection::drain_outbound( + self : StreamConnection, +) -> Array[Bytes] { + let out : Array[Bytes] = Array(capacity=self.out_queue.length()) + for p in self.out_queue { + out.push(p) + } + self.out_queue.clear() + out +} + +///| +/// Per-destination stream & repliable datagram multiplexer. +pub struct StreamManager { + local_dest : @common.Destination + local_ed_seed : Bytes + mut next_stream_id : UInt32 + streams : Array[StreamConnection] + pending_accept : Array[StreamConnection] + incoming_datagrams : Array[RepliableDatagram] +} + +///| +pub fn StreamManager::new( + local_dest : @common.Destination, + local_ed_seed : Bytes, + initial_stream_id~ : UInt32 = 1000U, +) -> StreamManager { + { + local_dest, + local_ed_seed, + next_stream_id: initial_stream_id, + streams: [], + pending_accept: [], + incoming_datagrams: [], + } +} + +///| +fn StreamManager::alloc_stream_id(self : StreamManager) -> UInt32 { + let id = self.next_stream_id + self.next_stream_id = id + 1U + if self.next_stream_id == 0U { + self.next_stream_id = 1U + } + id +} + +///| +/// Returns `true` if any unacknowledged outbound packets remain pending. +pub fn StreamConnection::has_unacked(self : StreamConnection) -> Bool { + self.unacked.length() > 0 +} + +///| +pub fn StreamManager::connect( + self : StreamManager, + remote_hash : @common.Hash, + now_ms : UInt64, + from_port~ : UInt32 = 0U, + to_port~ : UInt32 = 0U, +) -> StreamConnection raise StreamingError { + let sid = self.alloc_stream_id() + let conn = StreamConnection::connect( + self.local_dest, + self.local_ed_seed, + remote_hash, + sid, + now_ms, + from_port~, + to_port~, + ) + self.streams.push(conn) + conn +} + +///| +pub fn StreamManager::accept_next(self : StreamManager) -> StreamConnection? { + if self.pending_accept.length() == 0 { + return None + } + Some(self.pending_accept.remove(0)) +} + +///| +/// Dispatches an incoming I2CP Gzip-wrapped payload (Streaming proto 6 or Repliable Datagram proto 17) +/// and returns the matching `StreamConnection` if it belongs to a stream. +pub fn StreamManager::handle_incoming_i2cp( + self : StreamManager, + i2cp_bytes : Bytes, + now_ms : UInt64, +) -> StreamConnection? raise StreamingError { + let (hdr, raw) = @encoding.i2cp_gzip_unwrap(i2cp_bytes) catch { + e => raise Encoding(e) + } + if hdr.protocol == b'\x11' { + let dg = RepliableDatagram::decode(raw) + if dg.verify() { + self.incoming_datagrams.push(dg) + } + return None + } + if hdr.protocol != b'\x06' { + return None + } + let pkt = StreamingPacket::decode(raw) + if pkt.recv_stream_id != 0U { + for s in self.streams { + if s.send_stream_id == pkt.recv_stream_id { + s.on_packet(pkt, now_ms) + return Some(s) + } + } + } + if (pkt.flags & flag_synchronize) != 0U && pkt.recv_stream_id == 0U { + let sid = self.alloc_stream_id() + let conn = StreamConnection::accept_syn( + self.local_dest, + self.local_ed_seed, + pkt, + sid, + now_ms, + from_port=hdr.to_port, + to_port=hdr.from_port, + ) + self.streams.push(conn) + self.pending_accept.push(conn) + return Some(conn) + } + None +} diff --git a/streaming/streaming_test.mbt b/streaming/streaming_test.mbt new file mode 100644 index 0000000..f6560e3 --- /dev/null +++ b/streaming/streaming_test.mbt @@ -0,0 +1,163 @@ +///| +fn make_test_identity(seed_byte : Byte) -> (@common.Destination, Bytes) { + let ed_seed = Bytes::make(32, seed_byte) + let ed_pub = try! @crypto.ed25519_public_key(ed_seed) + let x_pub = try! @crypto.x25519_public_key( + Bytes::make(32, (seed_byte.to_int() ^ 0x33).to_byte()), + ) + let dest = try! @common.Destination::new_x25519_ed25519(x_pub, ed_pub) + (dest, ed_seed) +} + +///| +test "StreamingPacket Ed25519 sign/verify, option order, and I2CP gzip wrap" { + let (dest, ed_seed) = make_test_identity(b'\x11') + let pkt : @streaming.StreamingPacket = { + send_stream_id: 100U, + recv_stream_id: 200U, + sequence_num: 0U, + ack_through: 0U, + nacks: [1U, 3U], + resend_delay: b'\x02', + flags: @streaming.flag_synchronize | + @streaming.flag_from_included | + @streaming.flag_delay_requested | + @streaming.flag_max_packet_size_included | + @streaming.flag_no_ack, + delay_requested: Some(50U), + from_dest: Some(dest), + max_packet_size: Some(1730U), + offline_sig: None, + signature: None, + payload: b"syn-payload", + } + let signed = pkt.sign_ed25519(ed_seed) + assert_eq(signed.verify_signature(dest), true) + + let i2cp = @streaming.encode_i2cp_streaming( + signed, + from_port=4000U, + to_port=8080U, + ) + let (hdr, dec) = @streaming.decode_i2cp_streaming(i2cp) + assert_eq(hdr.from_port, 4000U) + assert_eq(hdr.to_port, 8080U) + assert_eq(hdr.protocol, b'\x06') + assert_eq(dec, signed) + assert_eq(dec.verify_signature(dest), true) + + // Tampering payload invalidates signature + let tampered : @streaming.StreamingPacket = { + send_stream_id: dec.send_stream_id, + recv_stream_id: dec.recv_stream_id, + sequence_num: dec.sequence_num, + ack_through: dec.ack_through, + nacks: dec.nacks, + resend_delay: dec.resend_delay, + flags: dec.flags, + delay_requested: dec.delay_requested, + from_dest: dec.from_dest, + max_packet_size: dec.max_packet_size, + offline_sig: dec.offline_sig, + signature: dec.signature, + payload: b"tampered!", + } + assert_eq(tampered.verify_signature(dest), false) +} + +///| +test "Streaming full SYN -> SYN-ACK -> Data with drop/NACK/retransmit -> CLOSE" { + let (alice_dest, alice_seed) = make_test_identity(b'\x21') + let (bob_dest, bob_seed) = make_test_identity(b'\x22') + let alice_mgr = @streaming.StreamManager::new( + alice_dest, + alice_seed, + initial_stream_id=100U, + ) + let bob_mgr = @streaming.StreamManager::new( + bob_dest, + bob_seed, + initial_stream_id=200U, + ) + + let a_stream = alice_mgr.connect( + bob_dest.hash(), + 1000UL, + from_port=1111U, + to_port=80U, + ) + // Deliver SYN to Bob + for msg in a_stream.drain_outbound() { + let _ = bob_mgr.handle_incoming_i2cp(msg, 1010UL) + } + let b_stream = match bob_mgr.accept_next() { + Some(s) => s + None => fail("expected Bob to accept incoming SYN stream") + } + assert_eq(b_stream.remote_hash, alice_dest.hash()) + + // Deliver SYN-ACK to Alice, then Alice's ACK back to Bob + for msg in b_stream.drain_outbound() { + let _ = alice_mgr.handle_incoming_i2cp(msg, 1020UL) + } + assert_eq(a_stream.state, Established) + for msg in a_stream.drain_outbound() { + let _ = bob_mgr.handle_incoming_i2cp(msg, 1025UL) + } + + // Alice writes 4000 bytes (3 packets at 1730B MTU); drop packet #1 to force NACK & retransmit! + let buf = FixedArray::make(4000, b'\x00') + for i = 0; i < 4000; i = i + 1 { + buf[i] = ((i * 17 + 3) & 0xFF).to_byte() + } + let msg_data = Bytes::from_array(buf) + let written = a_stream.write(msg_data, 1030UL) + assert_eq(written, 4000) + let pkts = a_stream.drain_outbound() + assert_eq(pkts.length(), 3) + // Deliver packet 0 and packet 2 (drop packet 1) + let _ = bob_mgr.handle_incoming_i2cp(pkts[0], 1040UL) + let _ = bob_mgr.handle_incoming_i2cp(pkts[2], 1041UL) + // Bob emits ACK+NACK for seq 2; deliver to Alice so Alice retransmits seq 2 + for ack in b_stream.drain_outbound() { + let _ = alice_mgr.handle_incoming_i2cp(ack, 1050UL) + } + for retx in a_stream.drain_outbound() { + let _ = bob_mgr.handle_incoming_i2cp(retx, 1060UL) + } + assert_eq(b_stream.read_available(), msg_data) + + // Bob replies and closes + assert_eq(b_stream.write(b"HTTP/1.1 200 OK\r\n\r\n", 1070UL), 19) + b_stream.close(1071UL) + for msg in b_stream.drain_outbound() { + let _ = alice_mgr.handle_incoming_i2cp(msg, 1080UL) + } + assert_eq(a_stream.read_available(), b"HTTP/1.1 200 OK\r\n\r\n") + assert_eq(a_stream.is_eof(), true) +} + +///| +test "RepliableDatagram (Ed25519 raw payload) and RawDatagram I2CP round-trip" { + let (dest, seed) = make_test_identity(b'\x33') + let dg = @streaming.RepliableDatagram::sign_ed25519( + dest, seed, b"ping-datagram", + ) + assert_eq(dg.verify(), true) + let i2cp = dg.to_i2cp_bytes(from_port=5000U, to_port=5001U) + let (hdr, dec) = @streaming.RepliableDatagram::from_i2cp_bytes(i2cp) + assert_eq(hdr.from_port, 5000U) + assert_eq(hdr.to_port, 5001U) + assert_eq(hdr.protocol, b'\x11') + assert_eq(dec, dg) + assert_eq(dec.verify(), true) + + let raw_i2cp = @streaming.encode_raw_datagram( + b"unauth-raw", + from_port=9U, + to_port=10U, + ) + let (rh, rbody) = @streaming.decode_raw_datagram(raw_i2cp) + assert_eq(rh.protocol, b'\x12') + assert_eq(rbody, b"unauth-raw") +} diff --git a/tunnel/build.mbt b/tunnel/build.mbt index 2374510..a46ecd0 100644 --- a/tunnel/build.mbt +++ b/tunnel/build.mbt @@ -5,6 +5,7 @@ pub suberror TunnelError { Crypto(@crypto.CryptoError) Encoding(@encoding.EncodingError) Common(@common.CommonError) + Noise(@noise.NoiseError) InvalidLength(String) InvalidFormat(String) ChecksumMismatch @@ -36,14 +37,27 @@ fn t_concat(a : Bytes, b : Bytes) -> Bytes { Bytes::from_array(out) } +///| +/// Creates a 12-byte ChaCha20/AEAD nonce with 4 zero bytes followed by 64-bit LE `slot_idx`. +pub fn make_slot_nonce(slot_idx : Int32) -> Bytes { + let buf = FixedArray::make(12, b'\x00') + let v = slot_idx.to_uint64() + for i = 0; i < 8; i = i + 1 { + buf[4 + i] = ((v >> (i * 8)) & 0xFFUL).to_byte() + } + Bytes::from_array(buf) +} + ///| /// 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 + reply_key : Bytes // 32-byte ChaCha20-Poly1305 key for ShortBuildReplyRecord & sibling slots 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 + garlic_key : Bytes? // 32-byte OBEP reply Garlic key (when OBEP flag 0x40 set) + garlic_tag : Bytes? // 8-byte OBEP reply Garlic tag (when OBEP flag 0x40 set) } ///| @@ -64,6 +78,7 @@ pub(all) struct ShortBuildRequestRecord { ///| pub fn ShortBuildRequestRecord::encode_154( self : ShortBuildRequestRecord, + padding~ : Bytes = b"", ) -> Bytes raise TunnelError { let w = @encoding.Writer::new(capacity=154) w.write_u32_be(self.receive_tunnel_id) @@ -88,6 +103,11 @@ pub fn ShortBuildRequestRecord::encode_154( for i = 0; i < prefix.length(); i = i + 1 { out[i] = prefix[i] } + let rem = 154 - prefix.length() + let pad_copy = if padding.length() < rem { padding.length() } else { rem } + for i = 0; i < pad_copy; i = i + 1 { + out[prefix.length() + i] = padding[i] + } Bytes::from_array(out) } @@ -125,41 +145,54 @@ pub fn ShortBuildRequestRecord::decode_154( } ///| -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 { +/// Canonical Proposal 157 chained HKDF key derivation: +/// `SMTunnelReplyKey` -> `SMTunnelLayerKey` -> `TunnelLayerIVKey` (-> `RGarlicKeyAndTag` for OBEP). +fn derive_hop_keys( + ck : Bytes, + h : Bytes, + is_obep : Bool, +) -> HopKeys raise TunnelError { + let kd1 = @crypto.hkdf(ck, b"", b"SMTunnelReplyKey", 64) 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, + let ck1 = t_slice(kd1, 0, 32) + let reply_key = t_slice(kd1, 32, 32) + + let kd2 = @crypto.hkdf(ck1, b"", b"SMTunnelLayerKey", 64) catch { + e => raise Crypto(e) } + let ck2 = t_slice(kd2, 0, 32) + let layer_key = t_slice(kd2, 32, 32) + + let kd3 = @crypto.hkdf(ck2, b"", b"TunnelLayerIVKey", 64) catch { + e => raise Crypto(e) + } + let ck3 = t_slice(kd3, 0, 32) + let iv_key = t_slice(kd3, 32, 32) + + let (garlic_key, garlic_tag) = if is_obep { + let kd4 = @crypto.hkdf(ck3, b"", b"RGarlicKeyAndTag", 64) catch { + e => raise Crypto(e) + } + (Some(t_slice(kd4, 0, 32)), Some(t_slice(kd4, 32, 8))) + } else { + (None, None) + } + { reply_key, layer_key, iv_key, handshake_hash: h, garlic_key, garlic_tag, } } ///| -fn stbm_init_state( +fn stbm_init_sym( hop_static_pub : Bytes, ephem_pub : Bytes, dh : Bytes, -) -> (Bytes, Bytes, Bytes) { +) -> @noise.SymmetricState { let sym = @noise.SymmetricState::initialize(stbm_protocol_name) - sym.mix_hash(b"") // prologue + sym.mix_hash(b"") // null 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) + sym } ///| @@ -171,25 +204,19 @@ pub fn encrypt_short_build_record( hop_ident_hash : @common.Hash, hop_static_pub : Bytes, ephemeral : @noise.KeyPair, + padding~ : Bytes = b"", ) -> (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 pt = record.encode_154(padding~) 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) + let sym = stbm_init_sym(hop_static_pub, ephemeral.public_key, dh) + let ct = sym.encrypt_and_hash(pt) catch { e => raise Noise(e) } + let is_obep = (record.flag.to_int() & 0x40) != 0 + let keys = derive_hop_keys(sym.chaining_key(), sym.handshake_hash(), is_obep) // 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) @@ -219,27 +246,30 @@ pub fn decrypt_short_build_record( 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 sym = stbm_init_sym(local_static.public_key, ephem_pub, dh) + let pt = sym.decrypt_and_hash(ct) catch { e => raise Noise(e) } let rec = ShortBuildRequestRecord::decode_154(pt) + let is_obep = (rec.flag.to_int() & 0x40) != 0 + let keys = derive_hop_keys(sym.chaining_key(), sym.handshake_hash(), is_obep) (rec, keys) } ///| -/// Encrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` (`reply_code`: `0` = accept, `30` = reject). +/// Encrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` at `slot_idx` (`reply_code`: `0` = accept, `30` = reject). pub fn encrypt_short_build_reply( keys : HopKeys, + slot_idx : Int32, reply_code : Byte, + padding~ : Bytes = b"", ) -> Bytes raise TunnelError { let pt = FixedArray::make(202, b'\x00') // 2-byte empty options mapping (0x00, 0x00) + padding + final reply byte at index 201 + let copy_len = if padding.length() < 199 { padding.length() } else { 199 } + for i = 0; i < copy_len; i = i + 1 { + pt[2 + i] = padding[i] + } pt[201] = reply_code - let nonce = Bytes::make(12, b'\x00') + let nonce = make_slot_nonce(slot_idx) @crypto.aead_chacha20_poly1305_encrypt( keys.reply_key, nonce, @@ -251,9 +281,10 @@ pub fn encrypt_short_build_reply( } ///| -/// Decrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` and returns its `reply_code` byte (`0` = accept). +/// Decrypts a 218-byte Proposal 157 `ShortBuildReplyRecord` at `slot_idx` and returns its `reply_code` byte (`0` = accept). pub fn decrypt_short_build_reply( keys : HopKeys, + slot_idx : Int32, reply_218 : Bytes, ) -> Byte raise TunnelError { if reply_218.length() != 218 { @@ -261,7 +292,7 @@ pub fn decrypt_short_build_reply( "ShortBuildReplyRecord must be 218 bytes, got \{reply_218.length()}", ) } - let nonce = Bytes::make(12, b'\x00') + let nonce = make_slot_nonce(slot_idx) let pt = @crypto.aead_chacha20_poly1305_decrypt( keys.reply_key, nonce, @@ -272,3 +303,168 @@ pub fn decrypt_short_build_reply( } pt[201] } + +///| +/// Build specification for a single hop inside a multi-hop Proposal 157 `ShortTunnelBuild`. +#derive(Eq, Debug) +pub(all) struct ShortHopBuildSpec { + slot_idx : Int32 + hop_ident : @common.Hash + hop_static_pub : Bytes + ephemeral : @noise.KeyPair + record : ShortBuildRequestRecord + padding : Bytes +} + +///| +/// Constructs a multi-hop Proposal 157 `ShortTunnelBuild` record array of length `total_slots`, +/// applying ChaCha20 onion pre-encryption for downstream hops so each hop unwraps +/// its record in cleartext as the build message traverses the tunnel. +pub fn build_short_tunnel_request( + total_slots : Int32, + hops : Array[ShortHopBuildSpec], + dummy_records : Array[Bytes], +) -> (Array[Bytes], Array[(Int32, HopKeys)]) raise TunnelError { + if total_slots < hops.length() || total_slots <= 0 { + raise InvalidLength("total_slots must be >= hops.length()") + } + let records : Array[Bytes] = Array(capacity=total_slots) + for i = 0; i < total_slots; i = i + 1 { + if i < dummy_records.length() && dummy_records[i].length() == 218 { + records.push(dummy_records[i]) + } else { + records.push(Bytes::make(218, b'\x00')) + } + } + let hop_keys : Array[(Int32, HopKeys)] = Array(capacity=hops.length()) + let used_slots : Array[Int32] = [] + for spec in hops { + if spec.slot_idx < 0 || spec.slot_idx >= total_slots { + raise InvalidLength("hop slot_idx out of range: \{spec.slot_idx}") + } + for prev in used_slots { + if prev == spec.slot_idx { + raise InvalidFormat("duplicate hop slot_idx: \{spec.slot_idx}") + } + } + used_slots.push(spec.slot_idx) + let (enc, keys) = encrypt_short_build_record( + spec.record, + spec.hop_ident, + spec.hop_static_pub, + spec.ephemeral, + padding=spec.padding, + ) + records[spec.slot_idx] = enc + hop_keys.push((spec.slot_idx, keys)) + } + // Pre-XOR downstream hop slots with earlier hops' reply keys + for m = 1; m < hops.length(); m = m + 1 { + let slot_m = hops[m].slot_idx + let mut rec = records[slot_m] + for k = 0; k < m; k = k + 1 { + let keys_k = hop_keys[k].1 + rec = @crypto.chacha20_xor( + keys_k.reply_key, + 0U, + make_slot_nonce(slot_m), + rec, + ) catch { + e => raise Crypto(e) + } + } + records[slot_m] = rec + } + (records, hop_keys) +} + +///| +/// Participating router handler for a Proposal 157 `ShortTunnelBuild`: +/// finds the slot matching `local_ident[0..16]`, decrypts the record, writes the +/// AEAD-encrypted `ShortBuildReplyRecord` into that slot, and ChaCha20-XORs all other slots. +pub fn process_short_tunnel_build_hop( + records : Array[Bytes], + local_ident : @common.Hash, + local_static : @noise.KeyPair, + reply_code : Byte, + reply_padding~ : Bytes = b"", +) -> (ShortBuildRequestRecord, HopKeys, Int32, Array[Bytes]) raise TunnelError { + let mut matched_slot = -1 + let mut matched_rec : ShortBuildRequestRecord? = None + let mut matched_keys : HopKeys? = None + for idx = 0; idx < records.length(); idx = idx + 1 { + let res = Some( + decrypt_short_build_record(records[idx], local_ident, local_static), + ) catch { + RecordNotForUs => None + e => raise e + } + match res { + Some((rec, keys)) => { + matched_slot = idx + matched_rec = Some(rec) + matched_keys = Some(keys) + break + } + None => () + } + } + let rec = match matched_rec { + Some(r) => r + None => raise RecordNotForUs + } + let keys = match matched_keys { + Some(k) => k + None => raise RecordNotForUs + } + let out : Array[Bytes] = Array(capacity=records.length()) + for j = 0; j < records.length(); j = j + 1 { + if j == matched_slot { + out.push( + encrypt_short_build_reply( + keys, + matched_slot, + reply_code, + padding=reply_padding, + ), + ) + } else { + out.push( + @crypto.chacha20_xor(keys.reply_key, 0U, make_slot_nonce(j), records[j]) catch { + e => raise Crypto(e) + }, + ) + } + } + (rec, keys, matched_slot, out) +} + +///| +/// Originator handler for a completed multi-hop Proposal 157 `ShortTunnelBuildReply`: +/// peels outer ChaCha20 layers and AEAD-decrypts each hop's reply status byte (`0` = accept). +pub fn decrypt_short_tunnel_replies( + records : Array[Bytes], + hop_slots_and_keys : Array[(Int32, HopKeys)], +) -> Array[Byte] raise TunnelError { + let reply_codes : Array[Byte] = Array(capacity=hop_slots_and_keys.length()) + for m = 0; m < hop_slots_and_keys.length(); m = m + 1 { + let (slot_m, keys_m) = hop_slots_and_keys[m] + if slot_m < 0 || slot_m >= records.length() { + raise InvalidLength("reply slot index out of bounds: \{slot_m}") + } + let mut rec = records[slot_m] + for k = m + 1; k < hop_slots_and_keys.length(); k = k + 1 { + let keys_k = hop_slots_and_keys[k].1 + rec = @crypto.chacha20_xor( + keys_k.reply_key, + 0U, + make_slot_nonce(slot_m), + rec, + ) catch { + e => raise Crypto(e) + } + } + reply_codes.push(decrypt_short_build_reply(keys_m, slot_m, rec)) + } + reply_codes +} diff --git a/tunnel/crypto.mbt b/tunnel/crypto.mbt index eaf5edc..b89f10c 100644 --- a/tunnel/crypto.mbt +++ b/tunnel/crypto.mbt @@ -119,10 +119,12 @@ fn encode_fragment(frag : TunnelFragment) -> 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. +/// with its 16-byte `iv`, 4-byte SHA-256 checksum, non-zero padding (using caller-provided +/// random `padding` with any `0x00` replaced by `0x01`, or deterministic fallback), and `0x00` delimiter. pub fn pack_tunnel_cell( iv : Bytes, fragments : Array[TunnelFragment], + padding~ : Bytes = b"", ) -> Bytes raise TunnelError { if iv.length() != 16 { raise InvalidLength("TunnelData IV must be 16 bytes, got \{iv.length()}") @@ -147,9 +149,18 @@ pub fn pack_tunnel_cell( for i = 0; i < 4; i = i + 1 { cell[16 + i] = checksum[i] } - // Non-zero deterministic padding bytes + // Strictly non-zero padding bytes for i = 0; i < pad_len; i = i + 1 { - cell[20 + i] = (i % 254 + 1).to_byte() + let b = if i < padding.length() { + if padding[i] == b'\x00' { + b'\x01' + } else { + padding[i] + } + } else { + (i % 254 + 1).to_byte() + } + cell[20 + i] = b } // Zero delimiter at 20 + pad_len cell[20 + pad_len] = b'\x00' @@ -238,6 +249,7 @@ pub fn fragment_message_to_cells( msg_id : UInt32, payload : Bytes, base_iv : Bytes, + padding~ : Bytes = b"", ) -> Array[Bytes] raise TunnelError { if base_iv.length() != 16 { raise InvalidLength("base_iv must be 16 bytes") @@ -249,18 +261,22 @@ pub fn fragment_message_to_cells( } 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), - ]) + let cell = pack_tunnel_cell( + base_iv, + [First(target~, fragmented=false, msg_id=0U, data=payload)], + padding~, + ) 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), - ]), + pack_tunnel_cell( + base_iv, + [First(target~, fragmented=true, msg_id~, data=first_chunk)], + padding~, + ), ) let mut off = first_max let mut frag_num = 1 @@ -276,9 +292,11 @@ pub fn fragment_message_to_cells( 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), - ]), + pack_tunnel_cell( + Bytes::from_array(cell_iv), + [FollowOn(frag_num~, is_last~, msg_id~, data=chunk)], + padding~, + ), ) off += take frag_num += 1 @@ -289,13 +307,13 @@ pub fn fragment_message_to_cells( ///| priv struct PendingReassembly { msg_id : UInt32 - target : DeliveryTarget + mut target : DeliveryTarget? chunks : Array[(Int32, Bytes)] mut last_num : Int32 } ///| -/// Stateful reassembler for fragmented `TunnelData` messages. +/// Stateful reassembler for fragmented `TunnelData` messages (supports out-of-order fragments). pub struct FragmentReassembler { priv pending : Array[PendingReassembly] } @@ -305,6 +323,65 @@ pub fn FragmentReassembler::new() -> FragmentReassembler { { pending: [], } } +///| +fn FragmentReassembler::find_or_insert( + self : FragmentReassembler, + msg_id : UInt32, +) -> PendingReassembly { + for p in self.pending { + if p.msg_id == msg_id { + return p + } + } + if self.pending.length() >= 64 { + let _ = self.pending.remove(0) + } + let created : PendingReassembly = { + msg_id, + target: None, + chunks: [], + last_num: -1, + } + self.pending.push(created) + created +} + +///| +fn FragmentReassembler::try_finish( + self : FragmentReassembler, + msg_id : UInt32, +) -> (DeliveryTarget, Bytes)? { + for idx = 0; idx < self.pending.length(); idx = idx + 1 { + let p = self.pending[idx] + if p.msg_id == msg_id { + match p.target { + None => return None + Some(target) => + 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 { + let mut found = false + for ch in p.chunks { + if ch.0 == n { + w.write_bytes(ch.1) + found = true + break + } + } + if !found { + return None + } + } + let _ = self.pending.remove(idx) + return Some((target, w.to_bytes())) + } + } + return None + } + } + None +} + ///| /// Feeds a decoded `TunnelFragment` into the reassembler. /// Returns `Some((target, full_payload))` once all fragments of a message have arrived. @@ -317,35 +394,36 @@ pub fn FragmentReassembler::push( 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 + let p = self.find_or_insert(msg_id) + p.target = Some(target) + let mut dup = false + for ch in p.chunks { + if ch.0 == 0 { + dup = true + break } } - None + if !dup { + p.chunks.push((0, data)) + } + self.try_finish(msg_id) + } + FollowOn(frag_num~, is_last~, msg_id~, data~) => { + let p = self.find_or_insert(msg_id) + let mut dup = false + for ch in p.chunks { + if ch.0 == frag_num { + dup = true + break + } + } + if !dup { + p.chunks.push((frag_num, data)) + } + if is_last { + p.last_num = frag_num + } + self.try_finish(msg_id) } } } diff --git a/tunnel/pkg.generated.mbti b/tunnel/pkg.generated.mbti index e9c9ad3..ac0d379 100644 --- a/tunnel/pkg.generated.mbti +++ b/tunnel/pkg.generated.mbti @@ -10,17 +10,25 @@ import { } // Values +pub fn build_short_tunnel_request(Int32, Array[ShortHopBuildSpec], Array[Bytes]) -> (Array[Bytes], Array[(Int32, HopKeys)]) raise TunnelError + 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 decrypt_short_build_reply(HopKeys, Int32, Bytes) -> Byte raise TunnelError -pub fn encrypt_short_build_record(ShortBuildRequestRecord, @common.Hash, Bytes, @noise.KeyPair) -> (Bytes, HopKeys) raise TunnelError +pub fn decrypt_short_tunnel_replies(Array[Bytes], Array[(Int32, HopKeys)]) -> Array[Byte] raise TunnelError -pub fn encrypt_short_build_reply(HopKeys, Byte) -> Bytes raise TunnelError +pub fn encrypt_short_build_record(ShortBuildRequestRecord, @common.Hash, Bytes, @noise.KeyPair, padding? : Bytes) -> (Bytes, HopKeys) raise TunnelError -pub fn fragment_message_to_cells(DeliveryTarget, UInt32, Bytes, Bytes) -> Array[Bytes] raise TunnelError +pub fn encrypt_short_build_reply(HopKeys, Int32, Byte, padding? : Bytes) -> Bytes raise TunnelError -pub fn pack_tunnel_cell(Bytes, Array[TunnelFragment]) -> Bytes raise TunnelError +pub fn fragment_message_to_cells(DeliveryTarget, UInt32, Bytes, Bytes, padding? : Bytes) -> Array[Bytes] raise TunnelError + +pub fn make_slot_nonce(Int32) -> Bytes + +pub fn pack_tunnel_cell(Bytes, Array[TunnelFragment], padding? : Bytes) -> Bytes raise TunnelError + +pub fn process_short_tunnel_build_hop(Array[Bytes], @common.Hash, @noise.KeyPair, Byte, reply_padding? : Bytes) -> (ShortBuildRequestRecord, HopKeys, Int32, Array[Bytes]) raise TunnelError pub fn tunnel_layer_decrypt(Bytes, Bytes, Bytes) -> Bytes raise TunnelError @@ -34,6 +42,7 @@ pub suberror TunnelError { Crypto(@crypto.CryptoError) Encoding(@encoding.EncodingError) Common(@common.CommonError) + Noise(@noise.NoiseError) InvalidLength(String) InvalidFormat(String) ChecksumMismatch @@ -60,6 +69,8 @@ pub(all) struct HopKeys { layer_key : Bytes iv_key : Bytes handshake_hash : Bytes + garlic_key : Bytes? + garlic_tag : Bytes? } #derive(Eq, @debug.Debug) @@ -75,7 +86,17 @@ pub(all) struct ShortBuildRequestRecord { options : @common.Mapping } pub fn ShortBuildRequestRecord::decode_154(Bytes) -> Self raise TunnelError -pub fn ShortBuildRequestRecord::encode_154(Self) -> Bytes raise TunnelError +pub fn ShortBuildRequestRecord::encode_154(Self, padding? : Bytes) -> Bytes raise TunnelError + +#derive(Eq, @debug.Debug) +pub(all) struct ShortHopBuildSpec { + slot_idx : Int32 + hop_ident : @common.Hash + hop_static_pub : Bytes + ephemeral : @noise.KeyPair + record : ShortBuildRequestRecord + padding : Bytes +} #derive(Eq, @debug.Debug) pub(all) struct TransitHop { diff --git a/tunnel/tunnel_test.mbt b/tunnel/tunnel_test.mbt index d2449bb..8d5af6f 100644 --- a/tunnel/tunnel_test.mbt +++ b/tunnel/tunnel_test.mbt @@ -42,10 +42,103 @@ test "Proposal 157 ShortTunnelBuild 218-byte record & reply round-trip" { 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') + // Hop encrypts 218-byte accept reply (code 0) at slot 0; creator decrypts it + let reply = @tunnel.encrypt_short_build_reply(hop_keys, 0, b'\x00') assert_eq(reply.length(), 218) - assert_eq(@tunnel.decrypt_short_build_reply(creator_keys, reply), b'\x00') + assert_eq(@tunnel.decrypt_short_build_reply(creator_keys, 0, reply), b'\x00') +} + +///| +test "Proposal 157 multi-hop ShortTunnelBuild onion build, hop relay, OBEP garlic keys, and reply decrypt" { + let hops : Array[@tunnel.ShortHopBuildSpec] = [] + let hop_statics : Array[@noise.KeyPair] = [] + let hop_idents : Array[@common.Hash] = [] + for i = 0; i < 3; i = i + 1 { + let sp = Bytes::make(32, (0x10 + i).to_byte()) + let skp = @noise.KeyPair::from_private(sp) + let ep = Bytes::make(32, (0x20 + i).to_byte()) + let ekp = @noise.KeyPair::from_private(ep) + let ident = @common.Hash::sha256(Bytes::make(4, (0x30 + i).to_byte())) + let next_ident = @common.Hash::sha256(Bytes::make(4, (0x31 + i).to_byte())) + let flag = if i == 0 { + b'\x80' // IBGW + } else if i == 2 { + b'\x40' // OBEP + } else { + b'\x00' + } + let rec : @tunnel.ShortBuildRequestRecord = { + receive_tunnel_id: (100 + i).reinterpret_as_uint(), + next_tunnel_id: (200 + i).reinterpret_as_uint(), + next_ident, + flag, + layer_enc_type: b'\x00', + request_time_min: 28333333U, + request_expiration_sec: 600U, + send_message_id: (500 + i).reinterpret_as_uint(), + options: @common.Mapping::new(), + } + hop_statics.push(skp) + hop_idents.push(ident) + hops.push({ + slot_idx: (i + 1) % 4, // scrambled slot positions (1, 2, 3) with slot 0 dummy + hop_ident: ident, + hop_static_pub: skp.public_key, + ephemeral: ekp, + record: rec, + padding: Bytes::make(16, (0x40 + i).to_byte()), + }) + } + let (req_records, creator_hop_keys) = @tunnel.build_short_tunnel_request( + 4, + hops, + [Bytes::make(218, b'\xde')], + ) + assert_eq(req_records.length(), 4) + assert_true(creator_hop_keys[0].1.garlic_key is None) + assert_true(creator_hop_keys[2].1.garlic_key is Some(_)) + assert_true(creator_hop_keys[2].1.garlic_tag is Some(_)) + + let mut wire_records = req_records + for i = 0; i < 3; i = i + 1 { + let (rec, keys, slot, next_records) = @tunnel.process_short_tunnel_build_hop( + wire_records, + hop_idents[i], + hop_statics[i], + b'\x00', + reply_padding=Bytes::make(16, b'\x77'), + ) + assert_eq(slot, hops[i].slot_idx) + assert_eq(rec, hops[i].record) + assert_eq(keys, creator_hop_keys[i].1) + wire_records = next_records + } + let codes = @tunnel.decrypt_short_tunnel_replies( + wire_records, creator_hop_keys, + ) + assert_eq(codes, [b'\x00', b'\x00', b'\x00']) +} + +///| +test "TunnelData FragmentReassembler handles out-of-order FollowOn before First" { + let iv = Bytes::make(16, b'\x33') + let payload = Bytes::make(2200, b'\xab') + let cells = @tunnel.fragment_message_to_cells( + Local, + 777U, + payload, + iv, + padding=Bytes::make(64, b'\x00'), // zeros sanitized to 0x01 + ) + assert_eq(cells.length(), 3) + let r = @tunnel.FragmentReassembler::new() + // Deliver cell 2, then cell 1, then cell 0 + assert_eq(r.push(@tunnel.unpack_tunnel_cell(cells[2])[0]), None) + assert_eq(r.push(@tunnel.unpack_tunnel_cell(cells[1])[0]), None) + assert_eq( + r.push(@tunnel.unpack_tunnel_cell(cells[0])[0]), + Some((Local, payload)), + ) } ///|