feat: add public I2P network mode to router daemon
- Add `--public`, `--hops`, `--hosts`, and `--debug` router flags; `--public` auto-reseeds from the live network and keeps a status loop running. - Route NetDB lookups through tunnels with Noise_N garlic wrapping, fan out to two floodfills, and fetch unknown RouterInfos in the background. - Back off failed NTCP2 peers and fall back to IPv6 addresses when no IPv4 NTCP2 address is available. - Size session LeaseSet2 expiry from lease end dates and use the destination's X25519 key when present. - Add canonical Ed25519 Destination KeyCertificate constructors with round-trip tests. - Fix DatabaseStore gzip handling to honor the length prefix, and send `Wget/1.11.4` as the reseed User-Agent.
This commit is contained in:
1 parent
ae72b00323
commit
54cfb2faa9
25 files changed
+2033
-191
No files matched your search
@@ -21,7 +21,7 @@ moon-i2p/
|
||||
├── 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`, `--peer-dir`, `--su3`, `--reseed`, `--floodfill`)
|
||||
├── cmd/router/ # Native MoonBit I2P router daemon (`--public`, `--hops`, `--hosts`, `--debug`, `--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`)
|
||||
```
|
||||
@@ -36,9 +36,34 @@ Every cryptographic primitive in `crypto/` is verified against official standard
|
||||
- **X25519**: RFC 7748 Sections 5.2 & 6.1
|
||||
- **Ed25519**: RFC 8032 Section 7.1 test vectors 1–3 (+ non-canonical `S >= L` & tamper rejection)
|
||||
- **SipHash-2-4**: Official SipHash reference test vector
|
||||
- **Live I2P Interop**: Verified real `i2pd` `router.info` parsing + Ed25519 signature verification, and full live NTCP2 handshake (Msg 1 → Msg 2 → Msg 3 → Data Phase SipHash length-masked AEAD frames) against a live public I2P floodfill router.
|
||||
- **Live Public I2P Network Interop**:
|
||||
- Live `.su3` HTTPS reseed import & Ed25519 verification (`User-Agent: Wget/1.11.4`).
|
||||
- Live firewalled (`LU`) NTCP2 outbound handshakes and data-phase transport with public I2P routers.
|
||||
- Live 1-hop & 2-hop Proposal 157 `ShortTunnelBuild` Inbound and Outbound tunnels (including OBEP ECIES `RGarlicKeyAndTag` replies).
|
||||
- Live tunnel-routed Proposal 154 ECIES `DatabaseLookup` + iterative `DatabaseSearchReply` RI crawl resolving real public eepsite `LeaseSet2`s.
|
||||
- Live end-to-end `client.exe http-get` over Proposal 144 ECIES Garlic (`NS`/`NSR`/`ES`) + Ed25519 I2P Streaming (including `OFFLINE_SIGNATURE` transient keys) against live public `.b32.i2p` eepsites (`stats.i2p`, `zzz.i2p`, `tracker2.postman.i2p`).
|
||||
|
||||
## Running the Native MoonBit Router & SAMv3 Client
|
||||
## Joining the Public I2P Network
|
||||
|
||||
```bash
|
||||
# Build native router and SAMv3 client
|
||||
moon build --target native cmd/router
|
||||
moon build --target native cmd/client
|
||||
|
||||
# Join the live public I2P network behind NAT (auto-reseeds, connects NTCP2 peers, builds tunnels)
|
||||
./_build/native/debug/build/cmd/router/router.exe --public --hops 1 --debug
|
||||
|
||||
# Optional flags:
|
||||
# --hops <1..4> Tunnel length (e.g. --hops 2 for 2-hop Inbound & Outbound tunnels)
|
||||
# --hosts <hosts.txt> Load hostname=base64dest entries from a local I2P hosts.txt file
|
||||
# --debug Log peer dials, tunnel builds, NetDB lookups, and Garlic/Streaming state
|
||||
|
||||
# Once tunnels are up (`tunnels=in:2/out:2`), resolve and fetch live public eepsites:
|
||||
./_build/native/debug/build/cmd/client/client.exe lookup kqypgjpjwrphnzebod5ev3ts2vtii6e5tntrg4rnfijqc7rypldq.b32.i2p
|
||||
./_build/native/debug/build/cmd/client/client.exe http-get kqypgjpjwrphnzebod5ev3ts2vtii6e5tntrg4rnfijqc7rypldq.b32.i2p /
|
||||
```
|
||||
|
||||
## Running the Local MoonBit Router & SAMv3 Client
|
||||
|
||||
```bash
|
||||
# Build the native router and client binaries
|
||||
|
||||
+71
-3
@@ -46,10 +46,14 @@ fn main {
|
||||
let mut ntcp2_port = 0
|
||||
let mut floodfill = false
|
||||
let mut check_clock_skew = true
|
||||
let mut public_mode = false
|
||||
let mut tunnel_hops = 1
|
||||
let mut debug = false
|
||||
let peer_files : Array[String] = []
|
||||
let peer_dirs : Array[String] = []
|
||||
let su3_files : Array[String] = []
|
||||
let reseed_urls : Array[String] = []
|
||||
let hosts_files : Array[String] = []
|
||||
|
||||
let mut i = 1
|
||||
while i < args.length() {
|
||||
@@ -112,6 +116,31 @@ fn main {
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
"--hosts" =>
|
||||
if i + 1 < args.length() {
|
||||
hosts_files.push(args[i + 1])
|
||||
i += 2
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
"--hops" =>
|
||||
if i + 1 < args.length() {
|
||||
match parse_port(args[i + 1]) {
|
||||
Some(h) if h >= 1 && h <= 4 => tunnel_hops = h
|
||||
_ => println("warning: ignoring invalid --hops \{args[i + 1]}")
|
||||
}
|
||||
i += 2
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
"--public" => {
|
||||
public_mode = true
|
||||
i += 1
|
||||
}
|
||||
"--debug" => {
|
||||
debug = true
|
||||
i += 1
|
||||
}
|
||||
"--floodfill" => {
|
||||
floodfill = true
|
||||
i += 1
|
||||
@@ -128,6 +157,9 @@ fn main {
|
||||
{ sam_host, sam_port, ntcp2_host, ntcp2_port, },
|
||||
floodfill~,
|
||||
check_clock_skew~,
|
||||
public_mode~,
|
||||
tunnel_hops~,
|
||||
debug~,
|
||||
) catch {
|
||||
_ => {
|
||||
println("error: failed to start moon-i2p router")
|
||||
@@ -169,12 +201,48 @@ fn main {
|
||||
}
|
||||
println(" Reseeded \{n} peer(s) from \{url}")
|
||||
}
|
||||
if public_mode &&
|
||||
reseed_urls.length() == 0 &&
|
||||
su3_files.length() == 0 &&
|
||||
peer_files.length() == 0 &&
|
||||
peer_dirs.length() == 0 {
|
||||
println("Reseeding from public I2P network...")
|
||||
let _ = r.auto_reseed()
|
||||
}
|
||||
for hf in hosts_files {
|
||||
let n = r.load_hosts_file(hf) catch {
|
||||
_ => {
|
||||
println("warning: failed to load hosts file \{hf}")
|
||||
continue
|
||||
}
|
||||
}
|
||||
println(" Loaded \{n} host alias(es) from \{hf}")
|
||||
}
|
||||
println("moon-i2p router started (transient identity)")
|
||||
println(" Router Hash: \{r.router_hash().to_base64()}")
|
||||
println(" Router B32: \{r.router_hash().to_b32_address()}")
|
||||
println(" NTCP2: \{ntcp2_host}:\{r.ntcp2_port()}")
|
||||
println(
|
||||
" NTCP2: \{ntcp2_host}:\{r.ntcp2_port()} (public=\{public_mode}, hops=\{tunnel_hops})",
|
||||
)
|
||||
println(" SAMv3: \{sam_host}:\{r.sam_port()}")
|
||||
println(" NetDB peers: \{r.netdb.router_count()}")
|
||||
println(
|
||||
" NetDB peers: \{r.netdb.router_count()} (floodfills=\{r.netdb.floodfill_count()})",
|
||||
)
|
||||
@ntcp2_net.flush_stdout()
|
||||
r.run()
|
||||
if public_mode {
|
||||
let mut last_log_ms = @ntcp2_net.unix_time_ms()
|
||||
while true {
|
||||
r.step(poll_ms=10)
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
if now_ms >= last_log_ms + 5000UL {
|
||||
last_log_ms = now_ms
|
||||
println(
|
||||
"[public] peers=\{r.peer_count()} dials=\{r.pending_dial_count()} netdb=\{r.netdb.router_count()}(ff=\{r.netdb.floodfill_count()},ls=\{r.netdb.leaseset_count()}) tunnels=in:\{r.inbound_tunnel_count()}/out:\{r.outbound_tunnel_count()} builds=\{r.pending_build_count()}",
|
||||
)
|
||||
@ntcp2_net.flush_stdout()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
r.run()
|
||||
}
|
||||
}
|
||||
@@ -45,6 +45,28 @@ test "Destination X25519+Ed25519 key extraction, Base64, and .b32.i2p address" {
|
||||
assert_true(b32.has_suffix(".b32.i2p"))
|
||||
}
|
||||
|
||||
///|
|
||||
test "Destination Ed25519 canonical KeyCertificate (sig=7, crypto=0) round-trip" {
|
||||
let sig_pub = Bytes::make(32, b'\x37')
|
||||
let pad = Bytes::make(352, b'\x9a')
|
||||
let dest = @common.Destination::new_ed25519(sig_pub, padding=pad)
|
||||
let raw = dest.to_bytes()
|
||||
assert_eq(raw.length(), 391)
|
||||
// Trailing KeyCertificate: 05 (Key) | 00 04 (len=4) | 00 07 (Ed25519) | 00 00 (ElGamal)
|
||||
assert_eq(raw[384], b'\x05')
|
||||
assert_eq(raw[385], b'\x00')
|
||||
assert_eq(raw[386], b'\x04')
|
||||
assert_eq(raw[387], b'\x00')
|
||||
assert_eq(raw[388], b'\x07')
|
||||
assert_eq(raw[389], b'\x00')
|
||||
assert_eq(raw[390], b'\x00')
|
||||
assert_eq(dest.inner.crypto_type(), ElGamal)
|
||||
assert_eq(dest.inner.signing_type(), EdDsaSha512Ed25519)
|
||||
assert_eq(dest.inner.signing_public_key(), sig_pub)
|
||||
let decoded = @common.Destination::decode(@encoding.Reader::new(raw))
|
||||
assert_eq(decoded, dest)
|
||||
}
|
||||
|
||||
///|
|
||||
test "RouterInfo encode and decode round-trip" {
|
||||
let ri_id = @common.RouterIdentity::new_x25519_ed25519(
|
||||
|
||||
@@ -9,6 +9,33 @@ pub struct KeysAndCert {
|
||||
certificate : Certificate
|
||||
}
|
||||
|
||||
///|
|
||||
/// Constructs a modern Ed25519 `Destination` `KeysAndCert` (CryptoType=0 ElGamal, SigType=7 Ed25519).
|
||||
/// Per I2P Proposal 123/144, Destinations always use ElGamal (0) in their KeyCertificate while
|
||||
/// placing active X25519 encryption keys in `LeaseSet2.encryption_keys`:
|
||||
/// `padding` (352 bytes, or zero-filled if omitted) occupies bytes 0..352,
|
||||
/// and the Ed25519 signing public key (32 bytes) is right-aligned at bytes 352..384.
|
||||
pub fn KeysAndCert::new_destination_ed25519(
|
||||
signing_pub : Bytes,
|
||||
padding~ : Bytes = b"",
|
||||
) -> KeysAndCert raise CommonError {
|
||||
if signing_pub.length() != 32 {
|
||||
raise InvalidLength(
|
||||
"Ed25519 public key must be 32 bytes, got \{signing_pub.length()}",
|
||||
)
|
||||
}
|
||||
let buf = FixedArray::make(384, b'\x00')
|
||||
let pad_len = if padding.length() < 352 { padding.length() } else { 352 }
|
||||
for i = 0; i < pad_len; i = i + 1 {
|
||||
buf[i] = padding[i]
|
||||
}
|
||||
for i = 0; i < 32; i = i + 1 {
|
||||
buf[352 + i] = signing_pub[i]
|
||||
}
|
||||
let cert = Certificate::Key(KeyCertificate::new(EdDsaSha512Ed25519, ElGamal))
|
||||
{ key_data: Bytes::from_array(buf), certificate: cert, }
|
||||
}
|
||||
|
||||
///|
|
||||
/// Constructs a modern X25519 + Ed25519 `KeysAndCert` (CryptoType=4, SigType=7).
|
||||
/// Per I2P spec: X25519 public key (32 bytes) is placed at bytes 0..32,
|
||||
@@ -138,6 +165,14 @@ pub fn Destination::new(inner : KeysAndCert) -> Destination {
|
||||
{ inner, }
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Destination::new_ed25519(
|
||||
signing_pub : Bytes,
|
||||
padding~ : Bytes = b"",
|
||||
) -> Destination raise CommonError {
|
||||
{ inner: KeysAndCert::new_destination_ed25519(signing_pub, padding~), }
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Destination::new_x25519_ed25519(
|
||||
crypto_pub : Bytes,
|
||||
|
||||
@@ -56,6 +56,7 @@ pub fn Destination::encode(Self, @encoding.Writer) -> Unit
|
||||
pub fn Destination::from_base64(String) -> Self raise CommonError
|
||||
pub fn Destination::hash(Self) -> Hash
|
||||
pub fn Destination::new(KeysAndCert) -> Self
|
||||
pub fn Destination::new_ed25519(Bytes, padding? : Bytes) -> Self raise CommonError
|
||||
pub fn Destination::new_x25519_ed25519(Bytes, Bytes, padding? : Bytes) -> Self raise CommonError
|
||||
pub fn Destination::to_base64(Self) -> String
|
||||
pub fn Destination::to_bytes(Self) -> Bytes
|
||||
@@ -93,6 +94,7 @@ pub fn KeysAndCert::crypto_type(Self) -> CryptoPublicKeyType
|
||||
pub fn KeysAndCert::decode(@encoding.Reader) -> Self raise CommonError
|
||||
pub fn KeysAndCert::encode(Self, @encoding.Writer) -> Unit
|
||||
pub fn KeysAndCert::hash(Self) -> Hash
|
||||
pub fn KeysAndCert::new_destination_ed25519(Bytes, padding? : Bytes) -> Self raise CommonError
|
||||
pub fn KeysAndCert::new_x25519_ed25519(Bytes, Bytes, padding? : Bytes) -> Self raise CommonError
|
||||
pub fn KeysAndCert::signing_public_key(Self) -> Bytes
|
||||
pub fn KeysAndCert::signing_type(Self) -> SigningPublicKeyType
|
||||
|
||||
+13
-2
@@ -123,6 +123,17 @@ pub fn NetDb::leaseset_count(self : NetDb) -> Int32 {
|
||||
self.leasesets.length()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn NetDb::floodfill_count(self : NetDb) -> Int32 {
|
||||
let mut n = 0
|
||||
for entry in self.routers {
|
||||
if is_floodfill(entry.1) {
|
||||
n += 1
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
///|
|
||||
/// Stores a `RouterInfo` after verifying its Ed25519 signature.
|
||||
/// Returns `true` if inserted or updated (newer `published` timestamp), `false` if stale.
|
||||
@@ -333,12 +344,12 @@ pub fn NetDb::handle_database_store(
|
||||
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() {
|
||||
if gz_len <= 0 || 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 {
|
||||
@encoding.gzip_decompress(data[2:2 + gz_len].to_owned()) catch {
|
||||
_ => raise InvalidRecord("DatabaseStore RouterInfo gunzip failed")
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -34,6 +34,7 @@ pub struct NetDb {
|
||||
leasesets : Array[(@common.Hash, @common.LeaseSet2)]
|
||||
}
|
||||
pub fn NetDb::closest_peers(Self, @common.Hash, String, Int32, floodfills_only? : Bool, excluded? : Array[@common.Hash]) -> Array[@common.RouterInfo]
|
||||
pub fn NetDb::floodfill_count(Self) -> Int32
|
||||
pub fn NetDb::get_lease_set2(Self, @common.Hash, UInt32) -> @common.LeaseSet2?
|
||||
pub fn NetDb::get_lease_set2_by_b32(Self, String, UInt32) -> @common.LeaseSet2?
|
||||
pub fn NetDb::get_router_info(Self, @common.Hash) -> @common.RouterInfo?
|
||||
|
||||
@@ -586,7 +586,7 @@ int32_t moon_i2p_net_fetch_https(
|
||||
close(devnull);
|
||||
}
|
||||
char *argv[] = {
|
||||
"curl", "-fsSL", "--max-time", "15", "--max-filesize", "2097152", url, NULL
|
||||
"curl", "-fsSL", "-A", "Wget/1.11.4", "--max-time", "25", "--max-filesize", "2097152", url, NULL
|
||||
};
|
||||
execvp("curl", argv);
|
||||
_exit(127);
|
||||
|
||||
+45
-40
@@ -603,46 +603,51 @@ pub fn extract_ntcp2_peer(
|
||||
ri : @common.RouterInfo,
|
||||
host_override~ : String? = None,
|
||||
) -> Ntcp2PeerInfo raise Ntcp2NetError {
|
||||
for addr in ri.addresses {
|
||||
if addr.transport_style != "NTCP2" {
|
||||
continue
|
||||
}
|
||||
let s_b64 = match addr.options.get("s") {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
let i_b64 = match addr.options.get("i") {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
let port_str = match addr.options.get("port") {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
let host = match host_override {
|
||||
Some(h) => h
|
||||
None =>
|
||||
match addr.options.get("host") {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
}
|
||||
let port = match parse_port_str(port_str) {
|
||||
Some(p) => p
|
||||
None => continue
|
||||
}
|
||||
let static_key = @encoding.base64_decode(s_b64) catch {
|
||||
_ => raise InvalidPeer("invalid base64 in NTCP2 's' option")
|
||||
}
|
||||
let iv = @encoding.base64_decode(i_b64) catch {
|
||||
_ => raise InvalidPeer("invalid base64 in NTCP2 'i' option")
|
||||
}
|
||||
return {
|
||||
router_hash: ri.identity.hash().as_bytes(),
|
||||
static_key,
|
||||
iv,
|
||||
host,
|
||||
port,
|
||||
for pass = 0; pass < 2; pass = pass + 1 {
|
||||
let allow_ipv6 = pass == 1
|
||||
for addr in ri.addresses {
|
||||
if addr.transport_style != "NTCP2" {
|
||||
continue
|
||||
}
|
||||
let s_b64 = match addr.options.get("s") {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
let i_b64 = match addr.options.get("i") {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
let port_str = match addr.options.get("port") {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
let host = match host_override {
|
||||
Some(h) => h
|
||||
None =>
|
||||
match addr.options.get("host") {
|
||||
Some(v) => v
|
||||
None => continue
|
||||
}
|
||||
}
|
||||
if !allow_ipv6 && host.contains(":") {
|
||||
continue
|
||||
}
|
||||
let port = match parse_port_str(port_str) {
|
||||
Some(p) => p
|
||||
None => continue
|
||||
}
|
||||
let static_key = @encoding.base64_decode(s_b64) catch { _ => continue }
|
||||
let iv = @encoding.base64_decode(i_b64) catch { _ => continue }
|
||||
if static_key.length() != 32 || iv.length() != 16 {
|
||||
continue
|
||||
}
|
||||
return {
|
||||
router_hash: ri.identity.hash().as_bytes(),
|
||||
static_key,
|
||||
iv,
|
||||
host,
|
||||
port,
|
||||
}
|
||||
}
|
||||
}
|
||||
raise InvalidPeer(
|
||||
|
||||
@@ -9,6 +9,9 @@
|
||||
///|
|
||||
pub let ecies_protocol_name : Bytes = b"Noise_IKelg2+hs2_25519_ChaChaPoly_SHA256"
|
||||
|
||||
///|
|
||||
pub let router_garlic_protocol_name : Bytes = b"Noise_N_25519_ChaChaPoly_SHA256"
|
||||
|
||||
///|
|
||||
fn r_slice(data : Bytes, start : Int32, len : Int32) -> Bytes {
|
||||
let out = FixedArray::make(len, b'\x00')
|
||||
@@ -559,6 +562,56 @@ pub fn decrypt_ecies_lookup_reply(
|
||||
decode_blocks(pt)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Encrypts Garlic blocks to a router's static X25519 key using Proposal 144 `Noise_N_25519_ChaChaPoly_SHA256`
|
||||
/// (canonical `WrapECIESX25519MessageForRouter`: `raw_ephem_pub (32B) || AEAD ciphertext`).
|
||||
pub fn encrypt_router_garlic(
|
||||
remote_static_pub : Bytes,
|
||||
ephemeral : @noise.KeyPair,
|
||||
blocks : Array[RatchetBlock],
|
||||
) -> Bytes raise RatchetError {
|
||||
if remote_static_pub.length() != 32 {
|
||||
raise InvalidLength("remote_static_pub must be 32 bytes")
|
||||
}
|
||||
let sym = @noise.SymmetricState::initialize(router_garlic_protocol_name)
|
||||
sym.mix_hash(b"") // null prologue
|
||||
sym.mix_hash(remote_static_pub)
|
||||
sym.mix_hash(ephemeral.public_key)
|
||||
let dh = @crypto.x25519(ephemeral.private_key, remote_static_pub) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
sym.mix_key(dh)
|
||||
let pt = encode_blocks(blocks)
|
||||
let ct = sym.encrypt_and_hash(pt) catch { e => raise Noise(e) }
|
||||
let w = @encoding.Writer::new(capacity=32 + ct.length())
|
||||
w.write_bytes(ephemeral.public_key)
|
||||
w.write_bytes(ct)
|
||||
w.to_bytes()
|
||||
}
|
||||
|
||||
///|
|
||||
/// Decrypts a router-targeted `Noise_N_25519_ChaChaPoly_SHA256` Garlic message addressed to `local_static`.
|
||||
pub fn decrypt_router_garlic(
|
||||
local_static : @noise.KeyPair,
|
||||
data : Bytes,
|
||||
) -> Array[RatchetBlock] raise RatchetError {
|
||||
if data.length() < 48 {
|
||||
raise InvalidLength("Router Garlic shorter than 48 bytes")
|
||||
}
|
||||
let ephem_pub = r_slice(data, 0, 32)
|
||||
let ct = r_slice(data, 32, data.length() - 32)
|
||||
let sym = @noise.SymmetricState::initialize(router_garlic_protocol_name)
|
||||
sym.mix_hash(b"")
|
||||
sym.mix_hash(local_static.public_key)
|
||||
sym.mix_hash(ephem_pub)
|
||||
let dh = @crypto.x25519(local_static.private_key, ephem_pub) catch {
|
||||
e => raise Crypto(e)
|
||||
}
|
||||
sym.mix_key(dh)
|
||||
let pt = sym.decrypt_and_hash(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.
|
||||
|
||||
@@ -21,6 +21,8 @@ pub fn decrypt_new_session(@noise.KeyPair, Bytes) -> (Array[RatchetBlock], Pendi
|
||||
|
||||
pub fn decrypt_new_session_reply(@noise.KeyPair, PendingNewSession, Bytes) -> (Array[RatchetBlock], RatchetPeerSession) raise RatchetError
|
||||
|
||||
pub fn decrypt_router_garlic(@noise.KeyPair, Bytes) -> Array[RatchetBlock] raise RatchetError
|
||||
|
||||
pub fn dh_initialize(Bytes, Bytes) -> (Bytes, TagSet) raise RatchetError
|
||||
|
||||
pub let ecies_protocol_name : Bytes
|
||||
@@ -33,10 +35,14 @@ pub fn encrypt_new_session(@noise.KeyPair?, Bytes, ElligatorKeyPair, Array[Ratch
|
||||
|
||||
pub fn encrypt_new_session_reply(PendingNewSession, ElligatorKeyPair, Array[RatchetBlock]) -> (Bytes, RatchetPeerSession) raise RatchetError
|
||||
|
||||
pub fn encrypt_router_garlic(Bytes, @noise.KeyPair, Array[RatchetBlock]) -> Bytes raise RatchetError
|
||||
|
||||
pub fn garlic_clove_block(GarlicDelivery, UInt32, UInt32, @i2np.I2npPayload) -> RatchetBlock raise RatchetError
|
||||
|
||||
pub fn generate_elligator_keypair(() -> Bytes) -> ElligatorKeyPair raise RatchetError
|
||||
|
||||
pub let router_garlic_protocol_name : Bytes
|
||||
|
||||
// Errors
|
||||
#derive(Eq, @debug.Debug)
|
||||
pub suberror RatchetError {
|
||||
|
||||
@@ -162,4 +162,31 @@ test "Proposal 144 ECIES-X25519-AEAD-Ratchet NS -> NSR -> bidirectional ES + DH
|
||||
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])
|
||||
|
||||
// 6. Router-targeted Noise_N Garlic round-trip & auth check
|
||||
let router_s = @noise.KeyPair::from_private(
|
||||
@crypto.sha256(b"router-n-static"),
|
||||
)
|
||||
let ephem_n = @noise.KeyPair::from_private(@crypto.sha256(b"router-n-ephem"))
|
||||
let wrong_s = @noise.KeyPair::from_private(@crypto.sha256(b"wrong-n-static"))
|
||||
let router_clove = @ratchet.garlic_clove_block(
|
||||
Local,
|
||||
123U,
|
||||
1700000600U,
|
||||
Data(data=b"lookup-payload"),
|
||||
)
|
||||
let rg_wire = @ratchet.encrypt_router_garlic(router_s.public_key, ephem_n, [
|
||||
DateTime(1700000200U),
|
||||
router_clove,
|
||||
])
|
||||
let rg_dec = @ratchet.decrypt_router_garlic(router_s, rg_wire)
|
||||
assert_eq(rg_dec, [DateTime(1700000200U), router_clove])
|
||||
let mut wrong_failed = false
|
||||
try {
|
||||
let _ = @ratchet.decrypt_router_garlic(wrong_s, rg_wire)
|
||||
} catch {
|
||||
AuthenticationFailed => wrong_failed = true
|
||||
_ => ()
|
||||
}
|
||||
assert_eq(wrong_failed, true)
|
||||
}
|
||||
+321
-20
@@ -5,16 +5,20 @@
|
||||
///|
|
||||
priv struct PendingNetDbLookup {
|
||||
target_hash : @common.Hash
|
||||
lookup_type : Int32 // 1 = LeaseSet, 2 = RouterInfo, 3 = Exploration
|
||||
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
|
||||
mut last_query_ms : UInt64
|
||||
kind : Int32 // 0 = NAMING LOOKUP (.b32), 1 = STREAM CONNECT awaiting LeaseSet2, 2 = background RI/exploration
|
||||
client_idx : Int32
|
||||
req_name : String
|
||||
session_id : String
|
||||
silent : Bool
|
||||
from_port : UInt32
|
||||
to_port : UInt32
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -57,16 +61,39 @@ fn Router::build_session_leaseset2(
|
||||
end_date_sec: now_sec + 600U,
|
||||
})
|
||||
}
|
||||
let enc_key = match sess.x25519_pub {
|
||||
Some(k) if k.length() == 32 => k
|
||||
_ => {
|
||||
let fk = sess.dest.inner.crypto_public_key()
|
||||
if fk.length() == 32 {
|
||||
fk
|
||||
} else {
|
||||
return None
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut max_end = now_sec + 60U
|
||||
for l in leases {
|
||||
if l.end_date_sec > max_end {
|
||||
max_end = l.end_date_sec
|
||||
}
|
||||
}
|
||||
let diff = if max_end > now_sec { max_end - now_sec } else { 60U }
|
||||
let expires_offset = if diff < 60U {
|
||||
60U
|
||||
} else if diff > 660U {
|
||||
660U
|
||||
} else {
|
||||
diff
|
||||
}
|
||||
let ls2 : @common.LeaseSet2 = {
|
||||
destination: sess.dest,
|
||||
published_sec: now_sec,
|
||||
expires_offset: 600U,
|
||||
expires_offset,
|
||||
flags: 0U,
|
||||
offline_sig: None,
|
||||
options: @common.Mapping::new(),
|
||||
encryption_keys: [
|
||||
{ key_type: X25519, key_data: sess.dest.inner.crypto_public_key(), },
|
||||
],
|
||||
encryption_keys: [{ key_type: X25519, key_data: enc_key, }],
|
||||
leases,
|
||||
signature: b"",
|
||||
}
|
||||
@@ -78,6 +105,9 @@ fn Router::build_session_leaseset2(
|
||||
///|
|
||||
fn Router::publish_session_leaseset2(self : Router, sess : SamSession) -> Unit {
|
||||
let now_sec = @ntcp2_net.unix_time_sec()
|
||||
if self.public_mode && self.tunnels.inbound.length() == 0 {
|
||||
return
|
||||
}
|
||||
let ls2 = match self.build_session_leaseset2(sess, now_sec) {
|
||||
Some(l) => l
|
||||
None => return
|
||||
@@ -100,7 +130,7 @@ fn Router::publish_session_leaseset2(self : Router, sess : SamSession) -> Unit {
|
||||
data=raw,
|
||||
)
|
||||
for ff in floodfills {
|
||||
let _ = self.send_i2np_to_peer(ff.identity.hash(), payload)
|
||||
self.send_routed_i2np(ff.identity.hash(), None, payload)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,19 +188,191 @@ fn Router::send_lookup_query(
|
||||
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 now_ms = @ntcp2_net.unix_time_ms()
|
||||
let now_sec = (now_ms / 1000UL).to_uint()
|
||||
lk.last_query_ms = now_ms
|
||||
let excl : Array[@common.Hash] = []
|
||||
let excl_cap = if lk.queried_peers.length() < 8 {
|
||||
lk.queried_peers.length()
|
||||
} else {
|
||||
8
|
||||
}
|
||||
for ei = lk.queried_peers.length() - excl_cap
|
||||
ei < lk.queried_peers.length()
|
||||
ei = ei + 1 {
|
||||
excl.push(lk.queried_peers[ei])
|
||||
}
|
||||
|
||||
let has_tunnels = self.tunnels.inbound.length() > 0 &&
|
||||
self.tunnels.outbound.length() > 0
|
||||
if has_tunnels && self.tunnels.inbound[0].hops.length() > 0 {
|
||||
let in_idx = lk.queried_peers.length() % self.tunnels.inbound.length()
|
||||
let in_t = if self.tunnels.inbound[in_idx].hops.length() > 0 {
|
||||
self.tunnels.inbound[in_idx]
|
||||
} else {
|
||||
self.tunnels.inbound[0]
|
||||
}
|
||||
let out_idx = lk.queried_peers.length() % self.tunnels.outbound.length()
|
||||
let out_t = self.tunnels.outbound[out_idx]
|
||||
let ibgw = in_t.hops[0]
|
||||
let flags_int = 0x01 | (lk.lookup_type << 2) | 0x10
|
||||
let lookup : @i2np.I2npPayload = DatabaseLookup(
|
||||
key=lk.target_hash,
|
||||
from=ibgw.router_hash,
|
||||
flags=flags_int.to_byte(),
|
||||
reply_tunnel_id=Some(ibgw.receive_tunnel_id),
|
||||
excluded_peers=excl,
|
||||
reply_key=Some(lk.reply_key),
|
||||
reply_tags=[lk.reply_tag],
|
||||
)
|
||||
let mut wrapped : @i2np.I2npPayload? = None
|
||||
match self.netdb.get_router_info(peer_hash) {
|
||||
Some(ri) =>
|
||||
if ri.identity.inner.crypto_type() == X25519 {
|
||||
let xpub = ri.identity.inner.crypto_public_key()
|
||||
if xpub.length() == 32 {
|
||||
let ephem_opt = Some(@noise.KeyPair::from_private(next_rand_32())) catch {
|
||||
_ => None
|
||||
}
|
||||
match ephem_opt {
|
||||
Some(ephem) => {
|
||||
let clove_opt = Some(
|
||||
@ratchet.garlic_clove_block(
|
||||
Local,
|
||||
self.alloc_msg_id(),
|
||||
now_sec + 60U,
|
||||
lookup,
|
||||
),
|
||||
) catch {
|
||||
_ => None
|
||||
}
|
||||
match clove_opt {
|
||||
Some(clove) => {
|
||||
let enc_opt = Some(
|
||||
@ratchet.encrypt_router_garlic(xpub, ephem, [
|
||||
DateTime(now_sec),
|
||||
clove,
|
||||
]),
|
||||
) catch {
|
||||
_ => None
|
||||
}
|
||||
match enc_opt {
|
||||
Some(enc) => wrapped = Some(Garlic(data=enc))
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
let wire_payload = wrapped.unwrap_or(lookup)
|
||||
let ok = try {
|
||||
self.send_through_tunnel(
|
||||
out_t.id,
|
||||
Router(router_hash=peer_hash),
|
||||
wire_payload,
|
||||
)
|
||||
true
|
||||
} catch {
|
||||
_ => false
|
||||
}
|
||||
if ok {
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] NetDB lookup type=\{lk.lookup_type} key=\{lk.target_hash.to_b32_address()} -> peer=\{peer_hash.to_b32_address()} via tunnel \{out_t.id} (reply_ibgw=\{ibgw.router_hash.to_b32_address()}:\{ibgw.receive_tunnel_id})",
|
||||
)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback direct query (used during bootstrap when 0 tunnels exist, or in 2-router tests)
|
||||
let flags_int = (lk.lookup_type << 2) | 0x10
|
||||
let lookup : @i2np.I2npPayload = DatabaseLookup(
|
||||
key=lk.target_hash,
|
||||
from=self.router_hash(),
|
||||
flags=b'\x14',
|
||||
flags=flags_int.to_byte(),
|
||||
reply_tunnel_id=None,
|
||||
excluded_peers=lk.queried_peers,
|
||||
excluded_peers=excl,
|
||||
reply_key=Some(lk.reply_key),
|
||||
reply_tags=[lk.reply_tag],
|
||||
)
|
||||
let _ = self.send_i2np_to_peer(peer_hash, lookup)
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::has_pending_lookup(
|
||||
self : Router,
|
||||
target_hash : @common.Hash,
|
||||
lookup_type : Int32,
|
||||
) -> Bool {
|
||||
for lk in self.pending_lookups {
|
||||
if lk.target_hash == target_hash && lk.lookup_type == lookup_type {
|
||||
return true
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::start_background_lookup(
|
||||
self : Router,
|
||||
target_hash : @common.Hash,
|
||||
lookup_type : Int32,
|
||||
preferred_peer~ : @common.Hash? = None,
|
||||
) -> Unit {
|
||||
if self.has_pending_lookup(target_hash, lookup_type) {
|
||||
return
|
||||
}
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let now_sec = (now_ms / 1000UL).to_uint()
|
||||
let peers = self.select_lookup_peers(target_hash, [], now_sec, 3)
|
||||
let ordered : Array[@common.Hash] = []
|
||||
match preferred_peer {
|
||||
Some(p) if p != self.router_hash() => ordered.push(p)
|
||||
_ => ()
|
||||
}
|
||||
for p in peers {
|
||||
if !is_hash_in(p, ordered) {
|
||||
ordered.push(p)
|
||||
}
|
||||
}
|
||||
if ordered.length() == 0 {
|
||||
return
|
||||
}
|
||||
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,
|
||||
lookup_type,
|
||||
reply_key,
|
||||
reply_tag: tag_rand,
|
||||
queried_peers: [],
|
||||
candidate_peers: [],
|
||||
started_ms: now_ms,
|
||||
last_query_ms: now_ms,
|
||||
kind: 2,
|
||||
client_idx: -1,
|
||||
req_name: "",
|
||||
session_id: "",
|
||||
silent: true,
|
||||
from_port: 0U,
|
||||
to_port: 0U,
|
||||
}
|
||||
self.pending_lookups.push(lk)
|
||||
self.send_lookup_query(lk, ordered[0])
|
||||
for i = 1; i < ordered.length(); i = i + 1 {
|
||||
lk.candidate_peers.push(ordered[i])
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::start_netdb_lookup(
|
||||
self : Router,
|
||||
@@ -180,9 +382,12 @@ fn Router::start_netdb_lookup(
|
||||
req_name : String,
|
||||
session_id : String,
|
||||
silent : Bool,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
) -> Bool {
|
||||
let now_sec = @ntcp2_net.unix_time_sec()
|
||||
let initial_peers = self.select_lookup_peers(target_hash, [], now_sec, 3)
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let now_sec = (now_ms / 1000UL).to_uint()
|
||||
let initial_peers = self.select_lookup_peers(target_hash, [], now_sec, 6)
|
||||
if initial_peers.length() == 0 {
|
||||
return false
|
||||
}
|
||||
@@ -192,20 +397,31 @@ fn Router::start_netdb_lookup(
|
||||
}
|
||||
let lk : PendingNetDbLookup = {
|
||||
target_hash,
|
||||
lookup_type: 1, // LeaseSet lookup
|
||||
reply_key,
|
||||
reply_tag: tag_rand,
|
||||
queried_peers: [],
|
||||
candidate_peers: [],
|
||||
started_ms: @ntcp2_net.unix_time_ms(),
|
||||
started_ms: now_ms,
|
||||
last_query_ms: now_ms,
|
||||
kind,
|
||||
client_idx,
|
||||
req_name,
|
||||
session_id,
|
||||
silent,
|
||||
from_port,
|
||||
to_port,
|
||||
}
|
||||
self.pending_lookups.push(lk)
|
||||
self.send_lookup_query(lk, initial_peers[0])
|
||||
for i = 1; i < initial_peers.length(); i = i + 1 {
|
||||
let fanout = if self.public_mode && initial_peers.length() >= 2 {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
}
|
||||
for k = 0; k < fanout; k = k + 1 {
|
||||
self.send_lookup_query(lk, initial_peers[k])
|
||||
}
|
||||
for i = fanout; i < initial_peers.length(); i = i + 1 {
|
||||
lk.candidate_peers.push(initial_peers[i])
|
||||
}
|
||||
true
|
||||
@@ -223,11 +439,39 @@ fn Router::handle_database_store_msg(
|
||||
data : Bytes,
|
||||
now_sec : UInt32,
|
||||
) -> Unit {
|
||||
let stype = store_type.to_int() & 0x0F
|
||||
let stored = self.netdb.handle_database_store(store_type, key, data, now_sec) catch {
|
||||
_ => false
|
||||
}
|
||||
if stored && (store_type.to_int() & 0x0F) == 3 {
|
||||
if self.debug && (stype == 3 || stored) {
|
||||
println(
|
||||
"[debug] NetDB DatabaseStore type=\{stype} stored=\{stored} key=\{key.to_b32_address()} (len=\{data.length()})",
|
||||
)
|
||||
}
|
||||
if stype == 3 && stored {
|
||||
self.complete_lookups_for_hash(key, now_sec)
|
||||
} else if stype == 0 && stored {
|
||||
// Complete any background RouterInfo lookups for `key` and feed new floodfill into active LS lookups
|
||||
let mut idx = 0
|
||||
while idx < self.pending_lookups.length() {
|
||||
let lk = self.pending_lookups[idx]
|
||||
if lk.kind == 2 && lk.lookup_type == 2 && lk.target_hash == key {
|
||||
let _ = self.pending_lookups.remove(idx)
|
||||
} else {
|
||||
idx += 1
|
||||
}
|
||||
}
|
||||
match self.netdb.get_router_info(key) {
|
||||
Some(ri) if @netdb.is_floodfill(ri) =>
|
||||
for lk in self.pending_lookups {
|
||||
if lk.lookup_type == 1 &&
|
||||
!is_hash_in(key, lk.queried_peers) &&
|
||||
!is_hash_in(key, lk.candidate_peers) {
|
||||
lk.candidate_peers.push(key)
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
if reply_token != 0U {
|
||||
let status : @i2np.I2npPayload = DeliveryStatus(
|
||||
@@ -345,6 +589,13 @@ fn Router::handle_database_search_reply_msg(
|
||||
peer_hashes : Array[@common.Hash],
|
||||
from : @common.Hash,
|
||||
) -> Unit {
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] NetDB DatabaseSearchReply key=\{key.to_b32_address()} refs=\{peer_hashes.length()} from=\{from.to_b32_address()}",
|
||||
)
|
||||
}
|
||||
let max_queries = if self.public_mode { 16 } else { 8 }
|
||||
let unknown_to_fetch : Array[@common.Hash] = []
|
||||
for lk in self.pending_lookups {
|
||||
if lk.target_hash == key {
|
||||
if !is_hash_in(from, lk.queried_peers) {
|
||||
@@ -353,12 +604,18 @@ fn Router::handle_database_search_reply_msg(
|
||||
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)
|
||||
!is_hash_in(ph, lk.candidate_peers) {
|
||||
if self.netdb.get_router_info(ph) is Some(_) {
|
||||
lk.candidate_peers.push(ph)
|
||||
} else if lk.lookup_type != 2 &&
|
||||
unknown_to_fetch.length() < 4 &&
|
||||
!is_hash_in(ph, unknown_to_fetch) {
|
||||
unknown_to_fetch.push(ph)
|
||||
}
|
||||
}
|
||||
}
|
||||
while lk.candidate_peers.length() > 0 && lk.queried_peers.length() < 8 {
|
||||
while lk.candidate_peers.length() > 0 &&
|
||||
lk.queried_peers.length() < max_queries {
|
||||
let next_peer = lk.candidate_peers.remove(0)
|
||||
if !is_hash_in(next_peer, lk.queried_peers) {
|
||||
self.send_lookup_query(lk, next_peer)
|
||||
@@ -367,6 +624,9 @@ fn Router::handle_database_search_reply_msg(
|
||||
}
|
||||
}
|
||||
}
|
||||
for ph in unknown_to_fetch {
|
||||
self.start_background_lookup(ph, 2, preferred_peer=Some(from))
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -454,9 +714,28 @@ fn Router::complete_lookups_for_hash(
|
||||
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 timeout_ms = if self.public_mode { 25000UL } else { 8000UL }
|
||||
let max_queries = if self.public_mode { 16 } else { 8 }
|
||||
let mut i = 0
|
||||
while i < self.pending_lookups.length() {
|
||||
let lk = self.pending_lookups[i]
|
||||
if lk.kind == 2 {
|
||||
if lk.lookup_type == 2 &&
|
||||
self.netdb.get_router_info(lk.target_hash) is Some(_) {
|
||||
let _ = self.pending_lookups.remove(i)
|
||||
continue
|
||||
}
|
||||
if now_ms > lk.started_ms + 15000UL {
|
||||
let _ = self.pending_lookups.remove(i)
|
||||
continue
|
||||
}
|
||||
if now_ms > lk.last_query_ms + 3000UL && lk.candidate_peers.length() > 0 {
|
||||
let next_p = lk.candidate_peers.remove(0)
|
||||
self.send_lookup_query(lk, next_p)
|
||||
}
|
||||
i += 1
|
||||
continue
|
||||
}
|
||||
match self.netdb.get_lease_set2(lk.target_hash, now_sec) {
|
||||
Some(ls2) => {
|
||||
let _ = self.pending_lookups.remove(i)
|
||||
@@ -475,7 +754,29 @@ fn Router::poll_netdb_lookups(self : Router) -> Unit {
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
if now_ms > lk.started_ms + 8000UL {
|
||||
if self.public_mode &&
|
||||
lk.queried_peers.length() < max_queries &&
|
||||
now_ms > lk.last_query_ms + 2500UL {
|
||||
if lk.candidate_peers.length() > 0 {
|
||||
let next_p = lk.candidate_peers.remove(0)
|
||||
if !is_hash_in(next_p, lk.queried_peers) {
|
||||
self.send_lookup_query(lk, next_p)
|
||||
}
|
||||
} else {
|
||||
let fresh = self.select_lookup_peers(
|
||||
lk.target_hash,
|
||||
lk.queried_peers,
|
||||
now_sec,
|
||||
2,
|
||||
)
|
||||
if fresh.length() > 0 {
|
||||
self.send_lookup_query(lk, fresh[0])
|
||||
} else {
|
||||
lk.last_query_ms = now_ms
|
||||
}
|
||||
}
|
||||
}
|
||||
if now_ms > lk.started_ms + timeout_ms {
|
||||
let _ = self.pending_lookups.remove(i)
|
||||
if lk.client_idx < self.sam_clients.length() {
|
||||
let c = self.sam_clients[lk.client_idx]
|
||||
|
||||
+85
-6
@@ -28,6 +28,46 @@ pub fn Router::peer_count(self : Router) -> Int32 {
|
||||
self.peers.length()
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::mark_peer_failed(
|
||||
self : Router,
|
||||
peer_hash : @common.Hash,
|
||||
cooldown_ms : UInt64,
|
||||
) -> Unit {
|
||||
let until = @ntcp2_net.unix_time_ms() + cooldown_ms
|
||||
for i = 0; i < self.failed_peers.length(); i = i + 1 {
|
||||
if self.failed_peers[i].0 == peer_hash {
|
||||
self.failed_peers[i] = (peer_hash, until)
|
||||
return
|
||||
}
|
||||
}
|
||||
if self.failed_peers.length() >= 512 {
|
||||
let _ = self.failed_peers.remove(0)
|
||||
}
|
||||
self.failed_peers.push((peer_hash, until))
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::is_peer_backed_off(
|
||||
self : Router,
|
||||
peer_hash : @common.Hash,
|
||||
now_ms : UInt64,
|
||||
) -> Bool {
|
||||
let mut i = 0
|
||||
let mut backed_off = false
|
||||
while i < self.failed_peers.length() {
|
||||
if self.failed_peers[i].1 <= now_ms {
|
||||
let _ = self.failed_peers.remove(i)
|
||||
} else {
|
||||
if self.failed_peers[i].0 == peer_hash {
|
||||
backed_off = true
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
backed_off
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::find_peer_hash_by_static(
|
||||
self : Router,
|
||||
@@ -63,14 +103,24 @@ fn Router::has_pending_dial(self : Router, target_hash : @common.Hash) -> Bool {
|
||||
|
||||
///|
|
||||
fn Router::ensure_peer_dial(self : Router, target_hash : @common.Hash) -> Unit {
|
||||
if target_hash == self.router_hash() || self.has_pending_dial(target_hash) {
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
if target_hash == self.router_hash() ||
|
||||
self.has_pending_dial(target_hash) ||
|
||||
(self.public_mode && self.is_peer_backed_off(target_hash, now_ms)) {
|
||||
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 peer_info = @ntcp2_net.extract_ntcp2_peer(ri) catch {
|
||||
_ => {
|
||||
if self.public_mode {
|
||||
self.mark_peer_failed(target_hash, 120000UL)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
let dial = @ntcp2_net.PendingNtcp2Dial::start(
|
||||
peer_info,
|
||||
self.static_key,
|
||||
@@ -78,7 +128,12 @@ fn Router::ensure_peer_dial(self : Router, target_hash : @common.Hash) -> Unit {
|
||||
check_clock_skew=self.check_clock_skew,
|
||||
remote_ri=Some(ri),
|
||||
) catch {
|
||||
_ => return
|
||||
_ => {
|
||||
if self.public_mode {
|
||||
self.mark_peer_failed(target_hash, 60000UL)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
self.pending_dials.push({ peer_hash: target_hash, dial, })
|
||||
}
|
||||
@@ -143,8 +198,11 @@ fn Router::send_routed_i2np(
|
||||
target_tid : UInt32?,
|
||||
payload : @i2np.I2npPayload,
|
||||
) -> Unit {
|
||||
if self.tunnels.outbound.length() > 0 {
|
||||
let out_t = self.tunnels.outbound[0]
|
||||
let out_len = self.tunnels.outbound.length()
|
||||
if out_len > 0 {
|
||||
let idx = if self.outbound_rr < 0 { 0 } else { self.outbound_rr % out_len }
|
||||
self.outbound_rr = (self.outbound_rr + 1) & 0x3FFFFFFF
|
||||
let out_t = self.tunnels.outbound[idx]
|
||||
let target : @tunnel.DeliveryTarget = match target_tid {
|
||||
Some(tid) => Tunnel(tunnel_id=tid, gateway=target_gw)
|
||||
None => Router(router_hash=target_gw)
|
||||
@@ -324,6 +382,14 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool {
|
||||
if now_ms > pd.dial.started_at_ms() + 10000UL {
|
||||
pd.dial.close()
|
||||
let _ = self.pending_dials.remove(di)
|
||||
if self.public_mode {
|
||||
self.mark_peer_failed(pd.peer_hash, 60000UL)
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] NTCP2 dial timeout: \{pd.peer_hash.to_b32_address()}",
|
||||
)
|
||||
}
|
||||
}
|
||||
did_work = true
|
||||
continue
|
||||
}
|
||||
@@ -331,6 +397,14 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool {
|
||||
if stepped.1 {
|
||||
pd.dial.close()
|
||||
let _ = self.pending_dials.remove(di)
|
||||
if self.public_mode {
|
||||
self.mark_peer_failed(pd.peer_hash, 60000UL)
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] NTCP2 dial rejected: \{pd.peer_hash.to_b32_address()}",
|
||||
)
|
||||
}
|
||||
}
|
||||
did_work = true
|
||||
continue
|
||||
}
|
||||
@@ -344,6 +418,11 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool {
|
||||
last_active_ms: now_ms,
|
||||
}
|
||||
self.peers.push(ps)
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] NTCP2 connected to \{pd.peer_hash.to_b32_address()} (peers=\{self.peers.length()})",
|
||||
)
|
||||
}
|
||||
let _ = self.flush_pending_sends_for(pd.peer_hash, ps)
|
||||
}
|
||||
None => di += 1
|
||||
@@ -401,7 +480,7 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool {
|
||||
None => break
|
||||
}
|
||||
}
|
||||
if !alive || now_ms > peer.last_active_ms + 120000UL {
|
||||
if !alive || now_ms > peer.last_active_ms + 180000UL {
|
||||
peer.conn.close()
|
||||
let _ = self.peers.remove(pi)
|
||||
} else {
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
///|
|
||||
/// Autonomous public I2P network bootstrap: live `.su3` reseed, NAT-friendly
|
||||
/// Proposal 157 Inbound/Outbound tunnel pool maintenance, `hosts.txt` aliases,
|
||||
/// and periodic NetDB floodfill exploration.
|
||||
|
||||
///|
|
||||
pub let default_reseed_urls : Array[String] = [
|
||||
"https://reseed.stormycloud.org/i2pseeds.su3", "https://reseed.diva.exchange/i2pseeds.su3",
|
||||
"https://i2p.novg.net/i2pseeds.su3", "https://reseed2.i2p.net/i2pseeds.su3",
|
||||
]
|
||||
|
||||
///|
|
||||
/// Reseeds `NetDb` from verified public I2P HTTPS reseed servers until >= 20
|
||||
/// routers are imported or all built-in URLs have been tried.
|
||||
pub fn Router::auto_reseed(self : Router) -> Int32 {
|
||||
let mut total = 0
|
||||
for url in default_reseed_urls {
|
||||
let n = self.reseed_from_url(url) catch {
|
||||
_ => {
|
||||
println(" Reseed skipped (\{url})")
|
||||
continue
|
||||
}
|
||||
}
|
||||
println(" Reseeded \{n} peer(s) from \{url}")
|
||||
total += n
|
||||
if total >= 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
///|
|
||||
/// Loads `hostname=base64dest` addressbook aliases from a local `hosts.txt` file.
|
||||
pub fn Router::load_hosts_file(
|
||||
self : Router,
|
||||
path : String,
|
||||
) -> Int32 raise RouterError {
|
||||
let raw = @ntcp2_net.read_file_bytes(path) catch { e => raise Net(e) }
|
||||
let text = @encoding.utf8_bytes_to_string(raw) catch {
|
||||
_ => raise Protocol("hosts file is not valid UTF-8")
|
||||
}
|
||||
let mut count = 0
|
||||
for line_view in text.split("\n") {
|
||||
let line = line_view.to_owned().trim().to_owned()
|
||||
if line.length() == 0 || line.has_prefix("#") {
|
||||
continue
|
||||
}
|
||||
let mut eq = -1
|
||||
for i = 0; i < line.length(); i = i + 1 {
|
||||
if line[i] == '=' {
|
||||
eq = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if eq > 0 && eq + 1 < line.length() {
|
||||
let host = line[:eq].to_owned().trim().to_owned()
|
||||
let dest_b64 = line[eq + 1:].to_owned().trim().to_owned()
|
||||
if host.length() > 0 && dest_b64.length() > 100 {
|
||||
self.register_alias(host, dest_b64)
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::is_usable_public_peer(
|
||||
self : Router,
|
||||
h : @common.Hash,
|
||||
ri : @common.RouterInfo,
|
||||
now_ms : UInt64,
|
||||
) -> Bool {
|
||||
if h == self.router_hash() ||
|
||||
self.is_peer_backed_off(h, now_ms) ||
|
||||
ri.identity.inner.crypto_type() != X25519 {
|
||||
return false
|
||||
}
|
||||
let info = @ntcp2_net.extract_ntcp2_peer(ri) catch { _ => return false }
|
||||
if info.host.contains(":") ||
|
||||
info.host == "127.0.0.1" ||
|
||||
info.host == "0.0.0.0" {
|
||||
return false
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::is_inbound_build_pending(self : Router) -> Int32 {
|
||||
let mut n = 0
|
||||
for pb in self.pending_builds {
|
||||
if pb.direction == Inbound {
|
||||
n += 1
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::is_outbound_build_pending(self : Router) -> Int32 {
|
||||
let mut n = 0
|
||||
for pb in self.pending_builds {
|
||||
if pb.direction == Outbound {
|
||||
n += 1
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
///|
|
||||
fn is_peer_in_list(h : @common.Hash, list : Array[@common.Hash]) -> Bool {
|
||||
for x in list {
|
||||
if x == h {
|
||||
return true
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::pick_usable_peers(
|
||||
self : Router,
|
||||
count : Int32,
|
||||
excluded : Array[@common.Hash],
|
||||
now_ms : UInt64,
|
||||
) -> Array[@common.Hash] {
|
||||
let out : Array[@common.Hash] = []
|
||||
let total = self.netdb.routers.length()
|
||||
if total == 0 || count <= 0 {
|
||||
return out
|
||||
}
|
||||
let rbytes = @ntcp2_net.random_bytes(4) catch { _ => Bytes::make(4, b'\x01') }
|
||||
let start = u32_from_be_prefix(rbytes).reinterpret_as_int() % total
|
||||
for step = 0; step < total && out.length() < count; step = step + 1 {
|
||||
let idx = (start + step) % total
|
||||
let (h, ri) = self.netdb.routers[idx]
|
||||
if is_peer_in_list(h, excluded) || is_peer_in_list(h, out) {
|
||||
continue
|
||||
}
|
||||
if self.is_usable_public_peer(h, ri, now_ms) {
|
||||
out.push(h)
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::pick_connected_hop(
|
||||
self : Router,
|
||||
excluded : Array[@common.Hash],
|
||||
now_ms : UInt64,
|
||||
) -> @common.Hash? {
|
||||
if self.peers.length() == 0 {
|
||||
return None
|
||||
}
|
||||
let rbytes = @ntcp2_net.random_bytes(4) catch { _ => Bytes::make(4, b'\x01') }
|
||||
let start = u32_from_be_prefix(rbytes).reinterpret_as_int() %
|
||||
self.peers.length()
|
||||
for step = 0; step < self.peers.length(); step = step + 1 {
|
||||
let idx = (start + step) % self.peers.length()
|
||||
let ph = self.peers[idx].hash
|
||||
if is_peer_in_list(ph, excluded) || self.is_peer_backed_off(ph, now_ms) {
|
||||
continue
|
||||
}
|
||||
match self.netdb.get_router_info(ph) {
|
||||
Some(ri) =>
|
||||
if ri.identity.inner.crypto_type() == X25519 {
|
||||
return Some(ph)
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::step_public_bootstrap(self : Router) -> Unit {
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
if now_ms < self.last_bootstrap_ms + 1500UL {
|
||||
return
|
||||
}
|
||||
self.last_bootstrap_ms = now_ms
|
||||
|
||||
// 1. Keep up to 6 live outbound NTCP2 TCP peer sessions active
|
||||
let target_peers = 6
|
||||
if self.peers.length() + self.pending_dials.length() < target_peers {
|
||||
let excl : Array[@common.Hash] = []
|
||||
for p in self.peers {
|
||||
excl.push(p.hash)
|
||||
}
|
||||
for pd in self.pending_dials {
|
||||
excl.push(pd.peer_hash)
|
||||
}
|
||||
let need = target_peers -
|
||||
(self.peers.length() + self.pending_dials.length())
|
||||
let to_dial = self.pick_usable_peers(need, excl, now_ms)
|
||||
for ph in to_dial {
|
||||
self.ensure_peer_dial(ph)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Maintain >= 2 Inbound tunnels (behind NAT: 1-hop on connected peers first,
|
||||
// then upgrade to `tunnel_hops`-hop `[IBGW -> connected_last_hop -> self]` once Outbound exists)
|
||||
let pending_in = self.is_inbound_build_pending()
|
||||
let mut in_full = 0
|
||||
for t in self.tunnels.inbound {
|
||||
if t.hops.length() >= self.tunnel_hops {
|
||||
in_full += 1
|
||||
}
|
||||
}
|
||||
let need_in_bootstrap = self.tunnels.inbound.length() + pending_in < 2
|
||||
let need_in_upgrade = self.tunnel_hops >= 2 &&
|
||||
self.tunnels.inbound.length() >= 1 &&
|
||||
self.tunnels.outbound.length() >= 1 &&
|
||||
in_full < 2 &&
|
||||
self.tunnels.inbound.length() + pending_in < 4
|
||||
if (need_in_bootstrap || need_in_upgrade) && pending_in < 2 {
|
||||
let excl_in : Array[@common.Hash] = []
|
||||
for t in self.tunnels.inbound {
|
||||
if t.hops.length() > 0 {
|
||||
excl_in.push(t.hops[t.hops.length() - 1].router_hash)
|
||||
}
|
||||
}
|
||||
for pb in self.pending_builds {
|
||||
if pb.direction == Inbound && pb.hops.length() > 0 {
|
||||
excl_in.push(pb.hops[pb.hops.length() - 1].router_hash)
|
||||
}
|
||||
}
|
||||
match self.pick_connected_hop(excl_in, now_ms) {
|
||||
Some(h0) =>
|
||||
if self.tunnel_hops >= 2 &&
|
||||
self.tunnels.inbound.length() >= 1 &&
|
||||
self.tunnels.outbound.length() >= 1 {
|
||||
let out_t = self.tunnels.outbound[0]
|
||||
let excl_ibgw : Array[@common.Hash] = [h0]
|
||||
if out_t.hops.length() > 0 {
|
||||
excl_ibgw.push(out_t.hops[out_t.hops.length() - 1].router_hash)
|
||||
}
|
||||
let ibgw_opt = match self.pick_connected_hop(excl_ibgw, now_ms) {
|
||||
Some(c) => Some(c)
|
||||
None => {
|
||||
let usables = self.pick_usable_peers(1, excl_ibgw, now_ms)
|
||||
if usables.length() == 1 {
|
||||
Some(usables[0])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
match ibgw_opt {
|
||||
Some(ibgw) => {
|
||||
let _ = self.build_tunnel(
|
||||
[ibgw, h0],
|
||||
Inbound,
|
||||
outbound_via=Some(out_t),
|
||||
) catch {
|
||||
_ => 0U
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
} else {
|
||||
let _ = self.build_tunnel([h0], Inbound) catch { _ => 0U }
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Maintain >= 2 Outbound tunnels (replying via an active Inbound tunnel)
|
||||
let pending_out = self.is_outbound_build_pending()
|
||||
if self.tunnels.inbound.length() >= 1 &&
|
||||
self.tunnels.outbound.length() + pending_out < 2 &&
|
||||
pending_out < 3 {
|
||||
let reply_in = self.tunnels.inbound[0]
|
||||
if reply_in.hops.length() > 0 {
|
||||
let reply_ibgw = reply_in.hops[0].router_hash
|
||||
let excl_out : Array[@common.Hash] = [reply_ibgw]
|
||||
for pb in self.pending_builds {
|
||||
if pb.direction == Outbound {
|
||||
for h in pb.hops {
|
||||
excl_out.push(h.router_hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.tunnel_hops >= 2 {
|
||||
match self.pick_connected_hop(excl_out, now_ms) {
|
||||
Some(h0) => {
|
||||
excl_out.push(h0)
|
||||
let obep_opt = match self.pick_connected_hop(excl_out, now_ms) {
|
||||
Some(c) => Some(c)
|
||||
None => {
|
||||
let obeps = self.pick_usable_peers(1, excl_out, now_ms)
|
||||
if obeps.length() == 1 {
|
||||
Some(obeps[0])
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
match obep_opt {
|
||||
Some(obep) => {
|
||||
let _ = self.build_tunnel(
|
||||
[h0, obep],
|
||||
Outbound,
|
||||
reply_tunnel=Some(reply_in),
|
||||
) catch {
|
||||
_ => 0U
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
} else {
|
||||
// Prefer an OBEP peer != reply_ibgw; if connected peer available use it, else any usable peer
|
||||
match self.pick_connected_hop(excl_out, now_ms) {
|
||||
Some(h0) => {
|
||||
let _ = self.build_tunnel(
|
||||
[h0],
|
||||
Outbound,
|
||||
reply_tunnel=Some(reply_in),
|
||||
) catch {
|
||||
_ => 0U
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let obeps = self.pick_usable_peers(1, excl_out, now_ms)
|
||||
if obeps.length() == 1 {
|
||||
let _ = self.build_tunnel(
|
||||
[obeps[0]],
|
||||
Outbound,
|
||||
reply_tunnel=Some(reply_in),
|
||||
) catch {
|
||||
_ => 0U
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Periodic NetDB exploration once tunnels are up to learn additional live floodfills
|
||||
if self.tunnels.inbound.length() >= 1 &&
|
||||
self.tunnels.outbound.length() >= 1 &&
|
||||
(self.last_explore_ms == 0UL || now_ms > self.last_explore_ms + 30000UL) {
|
||||
self.last_explore_ms = now_ms
|
||||
let rkey = @common.Hash::from_bytes(next_rand_32()) catch {
|
||||
_ => self.router_hash()
|
||||
}
|
||||
self.start_background_lookup(rkey, 3)
|
||||
}
|
||||
}
|
||||
+76
-10
@@ -47,6 +47,9 @@ pub struct Router {
|
||||
ntcp2_listener : @ntcp2_net.TcpListener
|
||||
sam_listener : @ntcp2_net.TcpListener
|
||||
check_clock_skew : Bool
|
||||
public_mode : Bool
|
||||
tunnel_hops : Int32
|
||||
debug : Bool
|
||||
priv mut next_msg_id : UInt32
|
||||
priv mut next_tunnel_id : UInt32
|
||||
priv mut next_stream_id : UInt32
|
||||
@@ -63,6 +66,11 @@ pub struct Router {
|
||||
priv bridges : Array[StreamBridge]
|
||||
priv remote_bridges : Array[RemoteStreamBridge]
|
||||
priv aliases : Array[(String, String)] // hostname -> pub_b64
|
||||
priv failed_peers : Array[(@common.Hash, UInt64)] // (router_hash, retry_after_ms)
|
||||
priv mut lease_rr : Int32
|
||||
priv mut outbound_rr : Int32
|
||||
priv mut last_bootstrap_ms : UInt64
|
||||
priv mut last_explore_ms : UInt64
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -128,10 +136,15 @@ fn non_zero_random_bytes(n : Int32) -> Bytes {
|
||||
///|
|
||||
/// Starts the MoonBit I2P Router Core with transient keys, self-signed `RouterInfo`,
|
||||
/// NTCP2 TCP listener, and embedded SAMv3 TCP bridge.
|
||||
/// In `public_mode` with loopback/unspecified `ntcp2_host`, advertises an unpublished
|
||||
/// firewalled `LU` RouterInfo (required for outbound NTCP2 to live public routers behind NAT).
|
||||
pub fn Router::start(
|
||||
config : RouterConfig,
|
||||
floodfill~ : Bool = false,
|
||||
check_clock_skew~ : Bool = true,
|
||||
public_mode~ : Bool = false,
|
||||
tunnel_hops~ : Int32 = 1,
|
||||
debug~ : Bool = false,
|
||||
) -> 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 {
|
||||
@@ -142,6 +155,7 @@ pub fn Router::start(
|
||||
e => raise Noise(e)
|
||||
}
|
||||
let ntcp2_iv = @ntcp2_net.random_bytes(16) catch { e => raise Net(e) }
|
||||
let id_pad = @ntcp2_net.random_bytes(320) catch { e => raise Net(e) }
|
||||
let ntcp2_listener = @ntcp2_net.TcpListener::bind(
|
||||
config.ntcp2_host,
|
||||
config.ntcp2_port,
|
||||
@@ -160,21 +174,34 @@ pub fn Router::start(
|
||||
let id = @common.RouterIdentity::new_x25519_ed25519(
|
||||
static_key.public_key,
|
||||
ed_pub,
|
||||
padding=id_pad,
|
||||
) catch {
|
||||
e => raise Common(e)
|
||||
}
|
||||
let addr_opts = @common.Mapping::from_entries([
|
||||
("host", config.ntcp2_host),
|
||||
("i", @encoding.base64_encode(ntcp2_iv)),
|
||||
("port", "\{ntcp2_listener.local_port()}"),
|
||||
("s", @encoding.base64_encode(static_key.public_key)),
|
||||
("v", "2"),
|
||||
])
|
||||
let caps = if floodfill { "LRf" } else { "LR" }
|
||||
let is_firewalled = public_mode &&
|
||||
(config.ntcp2_host == "127.0.0.1" || config.ntcp2_host == "0.0.0.0")
|
||||
let addr_opts = if is_firewalled {
|
||||
@common.Mapping::from_entries([
|
||||
("caps", "4"),
|
||||
("s", @encoding.base64_encode(static_key.public_key)),
|
||||
("v", "2"),
|
||||
])
|
||||
} else {
|
||||
@common.Mapping::from_entries([
|
||||
("caps", "4"),
|
||||
("host", config.ntcp2_host),
|
||||
("i", @encoding.base64_encode(ntcp2_iv)),
|
||||
("port", "\{ntcp2_listener.local_port()}"),
|
||||
("s", @encoding.base64_encode(static_key.public_key)),
|
||||
("v", "2"),
|
||||
])
|
||||
}
|
||||
let addr_cost : Byte = if is_firewalled { b'\x0e' } else { b'\x03' }
|
||||
let caps = if floodfill { "LRf" } else if is_firewalled { "LU" } else { "LR" }
|
||||
let ri : @common.RouterInfo = {
|
||||
identity: id,
|
||||
published: @ntcp2_net.unix_time_ms(),
|
||||
addresses: [@common.RouterAddress::new(b'\x03', "NTCP2", addr_opts)],
|
||||
addresses: [@common.RouterAddress::new(addr_cost, "NTCP2", addr_opts)],
|
||||
options: @common.Mapping::from_entries([
|
||||
("caps", caps),
|
||||
("netId", "2"),
|
||||
@@ -191,6 +218,13 @@ pub fn Router::start(
|
||||
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
|
||||
let clamped_hops = if tunnel_hops < 1 {
|
||||
1
|
||||
} else if tunnel_hops > 4 {
|
||||
4
|
||||
} else {
|
||||
tunnel_hops
|
||||
}
|
||||
{
|
||||
ed_seed,
|
||||
static_key,
|
||||
@@ -201,6 +235,9 @@ pub fn Router::start(
|
||||
ntcp2_listener,
|
||||
sam_listener,
|
||||
check_clock_skew,
|
||||
public_mode,
|
||||
tunnel_hops: clamped_hops,
|
||||
debug,
|
||||
next_msg_id: m0,
|
||||
next_tunnel_id: t0,
|
||||
next_stream_id: s0,
|
||||
@@ -217,9 +254,34 @@ pub fn Router::start(
|
||||
bridges: [],
|
||||
remote_bridges: [],
|
||||
aliases: [],
|
||||
failed_peers: [],
|
||||
lease_rr: 0,
|
||||
outbound_rr: 0,
|
||||
last_bootstrap_ms: 0UL,
|
||||
last_explore_ms: 0UL,
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Router::inbound_tunnel_count(self : Router) -> Int32 {
|
||||
self.tunnels.inbound_count()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Router::outbound_tunnel_count(self : Router) -> Int32 {
|
||||
self.tunnels.outbound_count()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Router::pending_build_count(self : Router) -> Int32 {
|
||||
self.pending_builds.length()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Router::pending_dial_count(self : Router) -> Int32 {
|
||||
self.pending_dials.length()
|
||||
}
|
||||
|
||||
///|
|
||||
pub fn Router::sam_port(self : Router) -> Int32 {
|
||||
self.sam_listener.local_port()
|
||||
@@ -404,7 +466,8 @@ fn Router::handle_i2np_message(
|
||||
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) {
|
||||
if !self.try_handle_build_garlic_reply(data) &&
|
||||
!self.try_handle_lookup_garlic_reply(data, now_sec) {
|
||||
self.handle_incoming_garlic(data, now_sec)
|
||||
}
|
||||
_ => ()
|
||||
@@ -448,6 +511,9 @@ pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit {
|
||||
}
|
||||
self.poll_netdb_lookups()
|
||||
self.poll_tunnel_builds()
|
||||
if self.public_mode {
|
||||
self.step_public_bootstrap()
|
||||
}
|
||||
if self.step_bridges() {
|
||||
did_work = true
|
||||
}
|
||||
|
||||
@@ -299,3 +299,60 @@ test "Three-router live Proposal 157 multi-hop tunnel build and fragmented 2500B
|
||||
bob_acc.shutdown_write()
|
||||
assert_eq(pump_read_until_eof(alice_data, rs), b"tunneled-ok")
|
||||
}
|
||||
|
||||
///|
|
||||
test "Proposal 157 Outbound tunnel replying via Inbound tunnel with OBEP ECIES Garlic" {
|
||||
let router_b = @router.Router::start({
|
||||
sam_host: "127.0.0.1",
|
||||
sam_port: 0,
|
||||
ntcp2_host: "127.0.0.1",
|
||||
ntcp2_port: 0,
|
||||
})
|
||||
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]
|
||||
|
||||
let in_tid = router_a.build_tunnel([router_b.router_hash()], Inbound)
|
||||
for _i = 0; _i < 500; _i = _i + 1 {
|
||||
step_routers(rs, 1)
|
||||
if router_a.has_tunnel(in_tid) {
|
||||
break
|
||||
}
|
||||
}
|
||||
assert_true(router_a.has_tunnel(in_tid))
|
||||
|
||||
let reply_in = router_a.tunnels.inbound[0]
|
||||
let out_tid = router_a.build_tunnel(
|
||||
[router_c.router_hash()],
|
||||
Outbound,
|
||||
reply_tunnel=Some(reply_in),
|
||||
)
|
||||
let mut built_out = false
|
||||
for _i = 0; _i < 800; _i = _i + 1 {
|
||||
step_routers(rs, 1)
|
||||
if router_a.has_tunnel(out_tid) {
|
||||
built_out = true
|
||||
break
|
||||
}
|
||||
}
|
||||
assert_true(built_out)
|
||||
}
|
||||
+166
-25
@@ -10,6 +10,7 @@ priv struct SamSession {
|
||||
pub_b64 : String
|
||||
b32 : String
|
||||
virtual_tid : UInt32
|
||||
x25519_pub : Bytes?
|
||||
ed_seed : Bytes?
|
||||
ratchet : @ratchet.RatchetSessionManager?
|
||||
stream_mgr : @streaming.StreamManager?
|
||||
@@ -42,7 +43,7 @@ priv struct RemoteStreamBridge {
|
||||
peer_static_pub : Bytes
|
||||
lease_gw : @common.Hash
|
||||
lease_tid : UInt32
|
||||
send_stream_id : UInt32
|
||||
local_stream_id : UInt32
|
||||
mut state : Int32 // 0 = waiting_syn_ack, 1 = open
|
||||
silent : Bool
|
||||
mut local_eof : Bool
|
||||
@@ -53,8 +54,9 @@ priv struct RemoteStreamBridge {
|
||||
}
|
||||
|
||||
///|
|
||||
/// Generates a valid transient 391-byte X25519+Ed25519 I2P Destination and
|
||||
/// returns `(dest, pub_b64, priv_b64, x_keypair, ed_seed)`.
|
||||
/// Generates a valid canonical 391-byte Ed25519 I2P Destination (sig=7, crypto=0 ElGamal)
|
||||
/// plus paired X25519 encryption keypair for LeaseSet2, and returns
|
||||
/// `(dest, pub_b64, priv_b64, x_keypair, ed_seed)`.
|
||||
fn generate_transient_destination() -> (
|
||||
@common.Destination,
|
||||
String,
|
||||
@@ -68,12 +70,8 @@ fn generate_transient_destination() -> (
|
||||
}
|
||||
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 {
|
||||
let pad = @ntcp2_net.random_bytes(352) catch { e => raise Net(e) }
|
||||
let dest = @common.Destination::new_ed25519(ed_pub, padding=pad) catch {
|
||||
e => raise Common(e)
|
||||
}
|
||||
let pub_bytes = dest.to_bytes()
|
||||
@@ -190,6 +188,9 @@ fn Router::flush_stream_outbound(
|
||||
fallback_tid : UInt32,
|
||||
send_ls2~ : Bool = false,
|
||||
) -> Unit {
|
||||
if peer_static_pub.length() != 32 {
|
||||
return
|
||||
}
|
||||
let packets = conn.drain_outbound()
|
||||
if packets.length() == 0 {
|
||||
return
|
||||
@@ -203,8 +204,18 @@ fn Router::flush_stream_outbound(
|
||||
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 valid : Array[@common.Lease2] = []
|
||||
for l in ls2.leases {
|
||||
if l.end_date_sec > now_sec {
|
||||
valid.push(l)
|
||||
}
|
||||
}
|
||||
let pool = if valid.length() > 0 { valid } else { ls2.leases }
|
||||
let rr = if self.lease_rr < 0 { 0 } else { self.lease_rr }
|
||||
self.lease_rr = (self.lease_rr + 1) & 0x3FFFFFFF
|
||||
let chosen = pool[rr % pool.length()]
|
||||
gw = chosen.tunnel_gw
|
||||
tid = chosen.tunnel_id
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
@@ -251,6 +262,11 @@ fn Router::flush_stream_outbound(
|
||||
) catch {
|
||||
_ => continue
|
||||
}
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] send Garlic (\{wire.length()}B, ls2=\{send_ls2}) -> gw=\{gw.to_b32_address()} tid=\{tid}",
|
||||
)
|
||||
}
|
||||
self.send_routed_i2np(gw, Some(tid), Garlic(data=wire))
|
||||
}
|
||||
}
|
||||
@@ -263,6 +279,8 @@ fn Router::initiate_remote_stream(
|
||||
target_dest : @common.Destination,
|
||||
ls2 : @common.LeaseSet2,
|
||||
silent : Bool,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
) -> Unit {
|
||||
let c = self.sam_clients[client_idx]
|
||||
if c.closed {
|
||||
@@ -299,9 +317,14 @@ fn Router::initiate_remote_stream(
|
||||
return
|
||||
}
|
||||
let lease = ls2.leases[0]
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] initiating remote stream to \{target_dest.b32_address()} leases=\{ls2.leases.length()} keys=\{ls2.encryption_keys.length()} first_gw=\{lease.tunnel_gw.to_b32_address()} tid=\{lease.tunnel_id}",
|
||||
)
|
||||
}
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let peer_hash = target_dest.hash()
|
||||
let conn = mgr.connect(peer_hash, now_ms) catch {
|
||||
let conn = mgr.connect(peer_hash, now_ms, from_port~, to_port~) catch {
|
||||
_ => {
|
||||
if !silent {
|
||||
let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=I2P_ERROR")
|
||||
@@ -325,7 +348,7 @@ fn Router::initiate_remote_stream(
|
||||
peer_static_pub: peer_static,
|
||||
lease_gw: lease.tunnel_gw,
|
||||
lease_tid: lease.tunnel_id,
|
||||
send_stream_id: conn.send_stream_id,
|
||||
local_stream_id: conn.local_stream_id,
|
||||
state: 0,
|
||||
silent,
|
||||
local_eof: false,
|
||||
@@ -369,6 +392,8 @@ fn Router::finish_remote_stream_connect(
|
||||
ls2.destination,
|
||||
ls2,
|
||||
lk.silent,
|
||||
from_port=lk.from_port,
|
||||
to_port=lk.to_port,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -387,6 +412,11 @@ fn Router::handle_incoming_garlic(
|
||||
let res = Some(ratchet.decrypt_incoming(garlic_data)) catch { _ => None }
|
||||
match res {
|
||||
Some((_remote_static, blocks)) => {
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] Garlic decrypted for session \{sess.id} (\{blocks.length()} blocks)",
|
||||
)
|
||||
}
|
||||
// 1. Apply DatabaseStore cloves first so peer LeaseSet2 is cached for reply
|
||||
for blk in blocks {
|
||||
match blk {
|
||||
@@ -421,9 +451,11 @@ fn Router::handle_incoming_garlic(
|
||||
Data(data~) =>
|
||||
match sess.stream_mgr {
|
||||
Some(mgr) => {
|
||||
let prev_streams = mgr.streams.length()
|
||||
let conn_opt = mgr.handle_incoming_i2cp(data, now_ms) catch {
|
||||
_ => None
|
||||
}
|
||||
let send_ls2_now = mgr.streams.length() > prev_streams
|
||||
match conn_opt {
|
||||
Some(conn) =>
|
||||
// Immediately send any generated SYN-ACK or ACK back if peer LeaseSet2 is known
|
||||
@@ -442,7 +474,7 @@ fn Router::handle_incoming_garlic(
|
||||
pstat,
|
||||
ls2.leases[0].tunnel_gw,
|
||||
ls2.leases[0].tunnel_id,
|
||||
send_ls2=true,
|
||||
send_ls2=send_ls2_now,
|
||||
)
|
||||
None => ()
|
||||
}
|
||||
@@ -467,6 +499,40 @@ fn Router::handle_incoming_garlic(
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
// Fallback: router-targeted Noise_N Garlic message addressed to self.static_key
|
||||
let router_blocks = Some(
|
||||
@ratchet.decrypt_router_garlic(self.static_key, garlic_data),
|
||||
) catch {
|
||||
_ => None
|
||||
}
|
||||
match router_blocks {
|
||||
Some(blocks) =>
|
||||
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 => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
None =>
|
||||
if self.debug {
|
||||
let tag_hex = if garlic_data.length() >= 8 {
|
||||
@encoding.hex_encode(garlic_data[:8].to_owned())
|
||||
} else {
|
||||
""
|
||||
}
|
||||
println(
|
||||
"[debug] unhandled incoming Garlic (\{garlic_data.length()}B tag=\{tag_hex} sessions=\{self.sessions.length()})",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -645,6 +711,10 @@ fn Router::handle_sam_command(
|
||||
)
|
||||
None => None
|
||||
}
|
||||
let x25519_pub = match opt_xkp {
|
||||
Some(xkp) => Some(xkp.public_key)
|
||||
None => None
|
||||
}
|
||||
let sess : SamSession = {
|
||||
id: sid,
|
||||
dest,
|
||||
@@ -652,6 +722,7 @@ fn Router::handle_sam_command(
|
||||
pub_b64,
|
||||
b32,
|
||||
virtual_tid: self.alloc_tunnel_id(),
|
||||
x25519_pub,
|
||||
ed_seed: opt_seed,
|
||||
ratchet,
|
||||
stream_mgr,
|
||||
@@ -713,6 +784,8 @@ fn Router::handle_sam_command(
|
||||
Some(v) => v.to_lower() == "true"
|
||||
None => false
|
||||
}
|
||||
let from_port = parse_sam_port(msg.get("FROM_PORT"))
|
||||
let to_port = parse_sam_port(msg.get("TO_PORT"))
|
||||
// 1. Check co-hosted local session fast path first
|
||||
match self.find_session_by_pub(dest_b64) {
|
||||
Some(target_sess) => {
|
||||
@@ -773,7 +846,13 @@ fn Router::handle_sam_command(
|
||||
match self.netdb.get_lease_set2(target_hash, now_sec) {
|
||||
Some(ls2) =>
|
||||
self.initiate_remote_stream(
|
||||
client_idx, caller_sess, target_dest, ls2, silent,
|
||||
client_idx,
|
||||
caller_sess,
|
||||
target_dest,
|
||||
ls2,
|
||||
silent,
|
||||
from_port~,
|
||||
to_port~,
|
||||
)
|
||||
None =>
|
||||
if !self.start_netdb_lookup(
|
||||
@@ -783,6 +862,8 @@ fn Router::handle_sam_command(
|
||||
"",
|
||||
caller_sess.id,
|
||||
silent,
|
||||
from_port~,
|
||||
to_port~,
|
||||
) {
|
||||
if !silent {
|
||||
let _ = send_sam_line(
|
||||
@@ -914,19 +995,53 @@ fn Router::step_bridges(self : Router) -> Bool {
|
||||
did_work
|
||||
}
|
||||
|
||||
///|
|
||||
fn parse_sam_port(s_opt : String?) -> UInt32 {
|
||||
let s = match s_opt {
|
||||
Some(v) => v
|
||||
None => return 0U
|
||||
}
|
||||
if s.length() == 0 {
|
||||
return 0U
|
||||
}
|
||||
let mut val = 0U
|
||||
for ch in s {
|
||||
if ch < '0' || ch > '9' {
|
||||
return 0U
|
||||
}
|
||||
val = val * 10U + (ch.to_int() - '0'.to_int()).reinterpret_as_uint()
|
||||
if val > 65535U {
|
||||
return 0U
|
||||
}
|
||||
}
|
||||
val
|
||||
}
|
||||
|
||||
///|
|
||||
fn find_stream_by_id(
|
||||
mgr : @streaming.StreamManager,
|
||||
sid : UInt32,
|
||||
) -> @streaming.StreamConnection? {
|
||||
for s in mgr.streams {
|
||||
if s.send_stream_id == sid {
|
||||
if s.local_stream_id == sid {
|
||||
return Some(s)
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
///|
|
||||
fn remove_stream_by_id(mgr : @streaming.StreamManager, sid : UInt32) -> Unit {
|
||||
let mut i = 0
|
||||
while i < mgr.streams.length() {
|
||||
if mgr.streams[i].local_stream_id == sid {
|
||||
let _ = mgr.streams.remove(i)
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
@@ -951,16 +1066,19 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
None => continue
|
||||
}
|
||||
let peer_ls2 = self.netdb.get_lease_set2(conn.remote_hash, now_sec)
|
||||
let fallback_key = if peer_dest.inner.crypto_type() == X25519 {
|
||||
peer_dest.inner.crypto_public_key()
|
||||
} else {
|
||||
b""
|
||||
}
|
||||
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(),
|
||||
),
|
||||
extract_x25519_key(l).unwrap_or(fallback_key),
|
||||
)
|
||||
_ => (self.router_hash(), 0U, peer_dest.inner.crypto_public_key())
|
||||
_ => (self.router_hash(), 0U, fallback_key)
|
||||
}
|
||||
if !c.accept_silent {
|
||||
let _ = send_sam_line(c.sock, peer_dest.to_base64())
|
||||
@@ -979,7 +1097,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
peer_static_pub: peer_static,
|
||||
lease_gw: gw,
|
||||
lease_tid: tid,
|
||||
send_stream_id: conn.send_stream_id,
|
||||
local_stream_id: conn.local_stream_id,
|
||||
state: 1,
|
||||
silent: c.accept_silent,
|
||||
local_eof: false,
|
||||
@@ -1005,13 +1123,14 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
}
|
||||
|
||||
// 2. Pump retransmits & flush outbound packets (ACKs, SYN-ACKs, retransmissions)
|
||||
let rto_ms = if self.public_mode { 3500UL } else { 1500UL }
|
||||
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 { _ => () }
|
||||
let _ = conn.poll_retransmits(now_ms, rto_ms~) catch { _ => () }
|
||||
match self.netdb.get_lease_set2(conn.remote_hash, now_sec) {
|
||||
Some(ls2) if ls2.leases.length() > 0 =>
|
||||
match extract_x25519_key(ls2) {
|
||||
@@ -1023,7 +1142,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
pstat,
|
||||
ls2.leases[0].tunnel_gw,
|
||||
ls2.leases[0].tunnel_id,
|
||||
send_ls2=false,
|
||||
send_ls2=conn.state == SynSent,
|
||||
)
|
||||
None => ()
|
||||
}
|
||||
@@ -1033,6 +1152,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
}
|
||||
|
||||
// 3. Pump bidirectional SAM socket <-> StreamConnection I/O
|
||||
let connect_timeout_ms = if self.public_mode { 30000UL } else { 12000UL }
|
||||
let mut ri = 0
|
||||
while ri < self.remote_bridges.length() {
|
||||
let br = self.remote_bridges[ri]
|
||||
@@ -1054,7 +1174,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
continue
|
||||
}
|
||||
}
|
||||
let conn = match find_stream_by_id(mgr, br.send_stream_id) {
|
||||
let conn = match find_stream_by_id(mgr, br.local_stream_id) {
|
||||
Some(c) => c
|
||||
None => {
|
||||
br.sock.close()
|
||||
@@ -1069,14 +1189,26 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
conn.state == Closed {
|
||||
br.state = 1
|
||||
did_work = true
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] Streaming established to \{br.peer_hash.to_b32_address()} (local_sid=\{br.local_stream_id})",
|
||||
)
|
||||
}
|
||||
if !br.silent {
|
||||
let _ = send_sam_line(br.sock, "STREAM STATUS RESULT=OK")
|
||||
}
|
||||
} else if conn.state == Reset || now_ms > br.started_ms + 12000UL {
|
||||
} else if conn.state == Reset ||
|
||||
now_ms > br.started_ms + connect_timeout_ms {
|
||||
did_work = true
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] Streaming failed/timed out to \{br.peer_hash.to_b32_address()}",
|
||||
)
|
||||
}
|
||||
if !br.silent {
|
||||
let _ = send_sam_line(br.sock, "STREAM STATUS RESULT=CANT_REACH_PEER")
|
||||
}
|
||||
remove_stream_by_id(mgr, br.local_stream_id)
|
||||
br.sock.close()
|
||||
br.closed = true
|
||||
let _ = self.remote_bridges.remove(ri)
|
||||
@@ -1087,6 +1219,11 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
let avail = conn.read_available()
|
||||
if avail.length() > 0 {
|
||||
did_work = true
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] stream \{br.local_stream_id} recv \{avail.length()}B",
|
||||
)
|
||||
}
|
||||
br.sock.write_all(avail) catch {
|
||||
_ => {
|
||||
br.local_eof = true
|
||||
@@ -1096,6 +1233,9 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
}
|
||||
if conn.is_eof() && !br.remote_eof_sent {
|
||||
did_work = true
|
||||
if self.debug {
|
||||
println("[debug] stream \{br.local_stream_id} EOF")
|
||||
}
|
||||
br.sock.shutdown_write()
|
||||
br.remote_eof_sent = true
|
||||
}
|
||||
@@ -1134,6 +1274,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
|
||||
)
|
||||
if br.local_eof && conn.is_eof() && !conn.has_unacked() {
|
||||
did_work = true
|
||||
remove_stream_by_id(mgr, br.local_stream_id)
|
||||
br.sock.close()
|
||||
br.closed = true
|
||||
let _ = self.remote_bridges.remove(ri)
|
||||
|
||||
+246
-20
@@ -11,6 +11,8 @@ priv struct PendingTunnelBuild {
|
||||
created_sec : UInt32
|
||||
expires_sec : UInt32
|
||||
started_ms : UInt64
|
||||
obep_garlic_key : Bytes?
|
||||
obep_garlic_tag : Bytes?
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -33,11 +35,15 @@ pub fn Router::has_tunnel(self : Router, tunnel_id : UInt32) -> Bool {
|
||||
/// 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)`.
|
||||
/// When `reply_tunnel` is supplied for an `Outbound` tunnel, the OBEP encrypts the
|
||||
/// `ShortTunnelBuildReply` with `RGarlicKeyAndTag` and routes it via that Inbound tunnel.
|
||||
pub fn Router::build_tunnel(
|
||||
self : Router,
|
||||
hop_hashes : Array[@common.Hash],
|
||||
direction : @tunnel.TunnelDirection,
|
||||
expiration_sec~ : UInt32 = 600U,
|
||||
reply_tunnel~ : @tunnel.Tunnel? = None,
|
||||
outbound_via~ : @tunnel.Tunnel? = None,
|
||||
) -> UInt32 raise RouterError {
|
||||
let hop_count = hop_hashes.length()
|
||||
if hop_count < 1 || hop_count > 8 {
|
||||
@@ -56,6 +62,9 @@ pub fn Router::build_tunnel(
|
||||
Some(r) => r
|
||||
None => raise Protocol("missing RouterInfo for tunnel hop")
|
||||
}
|
||||
if ri.identity.inner.crypto_type() != X25519 {
|
||||
raise Protocol("tunnel hop lacks X25519 crypto identity type")
|
||||
}
|
||||
let x_pub = ri.identity.inner.crypto_public_key()
|
||||
if x_pub.length() != 32 {
|
||||
raise Protocol("tunnel hop lacks X25519 identity key")
|
||||
@@ -65,6 +74,20 @@ pub fn Router::build_tunnel(
|
||||
}
|
||||
|
||||
let total_slots = if hop_count <= 4 { 4 } else { 8 }
|
||||
let slot_perm : Array[Int32] = Array(capacity=total_slots)
|
||||
for s = 0; s < total_slots; s = s + 1 {
|
||||
slot_perm.push(s)
|
||||
}
|
||||
let rand_perm = @ntcp2_net.random_bytes(total_slots) catch {
|
||||
_ => Bytes::make(total_slots, b'\x01')
|
||||
}
|
||||
for k = total_slots - 1; k > 0; k = k - 1 {
|
||||
let ridx = rand_perm[k].to_int() % (k + 1)
|
||||
let tmp = slot_perm[k]
|
||||
slot_perm[k] = slot_perm[ridx]
|
||||
slot_perm[ridx] = tmp
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -73,11 +96,19 @@ pub fn Router::build_tunnel(
|
||||
} else if direction == Inbound {
|
||||
local_tid
|
||||
} else {
|
||||
0U
|
||||
match reply_tunnel {
|
||||
Some(in_t) if in_t.hops.length() > 0 => in_t.hops[0].receive_tunnel_id
|
||||
_ => 0U
|
||||
}
|
||||
}
|
||||
next_tids.push(next_tid)
|
||||
let next_ident = if i + 1 < hop_count {
|
||||
hop_hashes[i + 1]
|
||||
} else if direction == Outbound {
|
||||
match reply_tunnel {
|
||||
Some(in_t) if in_t.hops.length() > 0 => in_t.hops[0].router_hash
|
||||
_ => self.router_hash()
|
||||
}
|
||||
} else {
|
||||
self.router_hash()
|
||||
}
|
||||
@@ -93,8 +124,13 @@ pub fn Router::build_tunnel(
|
||||
e => raise Noise(e)
|
||||
}
|
||||
let pad = @ntcp2_net.random_bytes(8) catch { _ => b"" }
|
||||
let hop_send_msg_id = if i + 1 < hop_count {
|
||||
self.alloc_msg_id()
|
||||
} else {
|
||||
build_msg_id
|
||||
}
|
||||
specs.push({
|
||||
slot_idx: i,
|
||||
slot_idx: slot_perm[i],
|
||||
hop_ident: hop_hashes[i],
|
||||
hop_static_pub: hop_static_pubs[i],
|
||||
ephemeral: ephem,
|
||||
@@ -106,15 +142,15 @@ pub fn Router::build_tunnel(
|
||||
layer_enc_type: b'\x00',
|
||||
request_time_min: req_time_min,
|
||||
request_expiration_sec: expiration_sec,
|
||||
send_message_id: build_msg_id,
|
||||
send_message_id: hop_send_msg_id,
|
||||
options: @common.Mapping::new(),
|
||||
},
|
||||
padding: pad,
|
||||
})
|
||||
}
|
||||
|
||||
let dummies : Array[Bytes] = []
|
||||
for _d = hop_count; _d < total_slots; _d = _d + 1 {
|
||||
let dummies : Array[Bytes] = Array(capacity=total_slots)
|
||||
for _d = 0; _d < total_slots; _d = _d + 1 {
|
||||
let dummy = @ntcp2_net.random_bytes(218) catch {
|
||||
_ => Bytes::make(218, b'\x5a')
|
||||
}
|
||||
@@ -137,6 +173,13 @@ pub fn Router::build_tunnel(
|
||||
iv_key: keys.iv_key,
|
||||
})
|
||||
}
|
||||
let last_keys = hop_slots_and_keys[hop_count - 1].1
|
||||
let (obep_garlic_key, obep_garlic_tag) = if direction == Outbound &&
|
||||
reply_tunnel is Some(_) {
|
||||
(last_keys.garlic_key, last_keys.garlic_tag)
|
||||
} else {
|
||||
(None, None)
|
||||
}
|
||||
self.pending_builds.push({
|
||||
tunnel_id: local_tid,
|
||||
direction,
|
||||
@@ -146,12 +189,59 @@ pub fn Router::build_tunnel(
|
||||
created_sec: now_sec,
|
||||
expires_sec: now_sec + expiration_sec,
|
||||
started_ms: now_ms,
|
||||
obep_garlic_key,
|
||||
obep_garlic_tag,
|
||||
})
|
||||
let _ = self.send_i2np_to_peer(
|
||||
hop_hashes[0],
|
||||
ShortTunnelBuild(records~),
|
||||
msg_id_override=Some(build_msg_id),
|
||||
)
|
||||
let build_payload : @i2np.I2npPayload = ShortTunnelBuild(records~)
|
||||
let outer_mid = if hop_count == 1 && direction == Inbound {
|
||||
Some(build_msg_id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
match outbound_via {
|
||||
Some(out_t) if self.has_tunnel(out_t.id) => {
|
||||
let obep_differs = out_t.hops.length() == 0 ||
|
||||
out_t.hops[out_t.hops.length() - 1].router_hash != hop_hashes[0]
|
||||
if obep_differs {
|
||||
let ephem_n = @noise.KeyPair::from_private(next_rand_32()) catch {
|
||||
e => raise Noise(e)
|
||||
}
|
||||
let clove = @ratchet.garlic_clove_block(
|
||||
Local,
|
||||
build_msg_id,
|
||||
now_sec + 60U,
|
||||
build_payload,
|
||||
) catch {
|
||||
_ => raise Protocol("garlic_clove failed")
|
||||
}
|
||||
let enc = @ratchet.encrypt_router_garlic(hop_static_pubs[0], ephem_n, [
|
||||
DateTime(now_sec),
|
||||
clove,
|
||||
]) catch {
|
||||
_ => raise Protocol("encrypt_router_garlic failed")
|
||||
}
|
||||
self.send_through_tunnel(
|
||||
out_t.id,
|
||||
Router(router_hash=hop_hashes[0]),
|
||||
Garlic(data=enc),
|
||||
)
|
||||
} else {
|
||||
self.send_through_tunnel(
|
||||
out_t.id,
|
||||
Router(router_hash=hop_hashes[0]),
|
||||
build_payload,
|
||||
msg_id_override=outer_mid,
|
||||
)
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
let _ = self.send_i2np_to_peer(
|
||||
hop_hashes[0],
|
||||
build_payload,
|
||||
msg_id_override=outer_mid,
|
||||
)
|
||||
}
|
||||
}
|
||||
local_tid
|
||||
}
|
||||
|
||||
@@ -162,6 +252,7 @@ pub fn Router::send_through_tunnel(
|
||||
outbound_tunnel_id : UInt32,
|
||||
target : @tunnel.DeliveryTarget,
|
||||
payload : @i2np.I2npPayload,
|
||||
msg_id_override~ : UInt32? = None,
|
||||
) -> Unit raise RouterError {
|
||||
let mut out_tun : @tunnel.Tunnel? = None
|
||||
for t in self.tunnels.outbound {
|
||||
@@ -178,7 +269,10 @@ pub fn Router::send_through_tunnel(
|
||||
raise Protocol("outbound tunnel has zero hops")
|
||||
}
|
||||
let now_ms = @ntcp2_net.unix_time_ms()
|
||||
let inner_mid = self.alloc_msg_id()
|
||||
let inner_mid = match msg_id_override {
|
||||
Some(id) => id
|
||||
None => self.alloc_msg_id()
|
||||
}
|
||||
let std_bytes = @i2np.encode_standard_message(
|
||||
inner_mid,
|
||||
now_ms + 60000UL,
|
||||
@@ -230,13 +324,30 @@ fn Router::try_complete_pending_tunnel_build(
|
||||
records,
|
||||
pb.hop_slots_and_keys,
|
||||
) catch {
|
||||
_ => return true
|
||||
}
|
||||
for c in codes {
|
||||
if c != b'\x00' {
|
||||
_ => {
|
||||
if self.debug {
|
||||
println("[debug] tunnel build \{pb.tunnel_id} reply decrypt failed")
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
let mut all_ok = true
|
||||
for hi = 0; hi < codes.length(); hi = hi + 1 {
|
||||
if codes[hi] != b'\x00' {
|
||||
all_ok = false
|
||||
if self.public_mode && hi < pb.hops.length() {
|
||||
self.mark_peer_failed(pb.hops[hi].router_hash, 45000UL)
|
||||
}
|
||||
if self.debug {
|
||||
println(
|
||||
"[debug] tunnel build \{pb.tunnel_id} hop \{hi} rejected code=\{codes[hi].to_int()}",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !all_ok {
|
||||
return true
|
||||
}
|
||||
let dir = pb.direction
|
||||
self.tunnels.add_tunnel({
|
||||
id: pb.tunnel_id,
|
||||
@@ -245,12 +356,82 @@ fn Router::try_complete_pending_tunnel_build(
|
||||
created_sec: pb.created_sec,
|
||||
expires_sec: pb.expires_sec,
|
||||
})
|
||||
if self.debug {
|
||||
let kind_s = match dir {
|
||||
Inbound => "Inbound"
|
||||
Outbound => "Outbound"
|
||||
}
|
||||
println(
|
||||
"[debug] built \{kind_s} tunnel \{pb.tunnel_id} (\{pb.hops.length()}h) [in=\{self.tunnels.inbound_count()} out=\{self.tunnels.outbound_count()}]",
|
||||
)
|
||||
}
|
||||
if dir == Inbound {
|
||||
self.republish_all_sessions()
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::try_handle_build_garlic_reply(
|
||||
self : Router,
|
||||
garlic_data : Bytes,
|
||||
) -> Bool {
|
||||
if garlic_data.length() < 24 {
|
||||
return false
|
||||
}
|
||||
let wire_tag = garlic_data[:8].to_owned()
|
||||
for i = 0; i < self.pending_builds.length(); i = i + 1 {
|
||||
let pb = self.pending_builds[i]
|
||||
match (pb.obep_garlic_key, pb.obep_garlic_tag) {
|
||||
(Some(gk), Some(gtag)) =>
|
||||
if @crypto.ct_eq(wire_tag, gtag) {
|
||||
let blocks = @ratchet.decrypt_ecies_lookup_reply(
|
||||
gk, gtag, 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, ShortTunnelBuildReply(records~))) => {
|
||||
let _ = hdr
|
||||
let _ = self.try_complete_pending_tunnel_build(
|
||||
pb.build_msg_id,
|
||||
records,
|
||||
)
|
||||
return true
|
||||
}
|
||||
Some((hdr, inner)) => {
|
||||
let _ = self.try_complete_pending_tunnel_build(
|
||||
pb.build_msg_id,
|
||||
match inner {
|
||||
ShortTunnelBuild(records~) => records
|
||||
_ => []
|
||||
},
|
||||
)
|
||||
let _ = hdr
|
||||
return true
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
///|
|
||||
fn Router::handle_short_tunnel_build(
|
||||
self : Router,
|
||||
@@ -292,10 +473,32 @@ fn Router::handle_short_tunnel_build(
|
||||
records=out_records,
|
||||
)
|
||||
if rec.next_tunnel_id != 0U {
|
||||
let outer_payload : @i2np.I2npPayload = if rec.next_ident !=
|
||||
self.router_hash() {
|
||||
match (keys.garlic_key, keys.garlic_tag) {
|
||||
(Some(gk), Some(gt)) => {
|
||||
let clove = @ratchet.garlic_clove_block(
|
||||
Local,
|
||||
rec.send_message_id,
|
||||
now_sec + 60U,
|
||||
reply_payload,
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
let enc = @ratchet.encrypt_ecies_lookup_reply(gk, gt, [clove]) catch {
|
||||
_ => return
|
||||
}
|
||||
Garlic(data=enc)
|
||||
}
|
||||
_ => reply_payload
|
||||
}
|
||||
} else {
|
||||
reply_payload
|
||||
}
|
||||
let std = @i2np.encode_standard_message(
|
||||
rec.send_message_id,
|
||||
@ntcp2_net.unix_time_ms() + 60000UL,
|
||||
reply_payload,
|
||||
outer_payload,
|
||||
) catch {
|
||||
_ => return
|
||||
}
|
||||
@@ -373,7 +576,14 @@ fn Router::consume_cleartext_cell(
|
||||
cleartext_cell : Bytes,
|
||||
now_sec : UInt32,
|
||||
) -> Unit {
|
||||
let frags = @tunnel.unpack_tunnel_cell(cleartext_cell) catch { _ => return }
|
||||
let frags = @tunnel.unpack_tunnel_cell(cleartext_cell) catch {
|
||||
_ => {
|
||||
if self.debug {
|
||||
println("[debug] unpack_tunnel_cell checksum/format error")
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
for frag in frags {
|
||||
match self.reassembler.push(frag) {
|
||||
Some((target, full_payload)) =>
|
||||
@@ -393,7 +603,14 @@ fn Router::handle_tunnel_data(
|
||||
// 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 }
|
||||
let clear = in_t.decrypt_inbound_cell(data) catch {
|
||||
_ => {
|
||||
if self.debug {
|
||||
println("[debug] inbound tunnel \{tunnel_id} decrypt error")
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
self.consume_cleartext_cell(clear, now_sec)
|
||||
return
|
||||
}
|
||||
@@ -469,10 +686,19 @@ 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 build_timeout = if self.public_mode { 20000UL } else { 10000UL }
|
||||
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)
|
||||
if now_ms > self.pending_builds[i].started_ms + build_timeout {
|
||||
let timed_out = self.pending_builds.remove(i)
|
||||
if self.public_mode {
|
||||
for h in timed_out.hops {
|
||||
self.mark_peer_failed(h.router_hash, 30000UL)
|
||||
}
|
||||
if self.debug {
|
||||
println("[debug] tunnel build \{timed_out.tunnel_id} timed out")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
|
||||
@@ -198,6 +198,26 @@ pub fn StreamingPacket::sign_ed25519(
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Verifies the Ed25519 signature of a `StreamingPacket` directly against a 32-byte
|
||||
/// Ed25519 public key (used for follow-on packets signed by a cached offline transient key).
|
||||
pub fn StreamingPacket::verify_signature_with_key(
|
||||
self : StreamingPacket,
|
||||
signing_pub : Bytes,
|
||||
) -> Bool {
|
||||
if (self.flags & flag_signature_included) == 0U || signing_pub.length() != 32 {
|
||||
return false
|
||||
}
|
||||
let sig = match self.signature {
|
||||
Some(s) => s
|
||||
None => return false
|
||||
}
|
||||
let to_verify = encode_with_opt_zero_sig(self, zero_sig_len=sig.length()) catch {
|
||||
_ => return false
|
||||
}
|
||||
@crypto.ed25519_verify(signing_pub, to_verify, sig)
|
||||
}
|
||||
|
||||
///|
|
||||
/// Verifies the Ed25519 signature of a `StreamingPacket` against `sender_dest`
|
||||
/// (or the embedded `offline_sig.transient_pub_key` when `FLAG_OFFLINE_SIGNATURE` is set).
|
||||
|
||||
@@ -71,11 +71,12 @@ pub struct StreamConnection {
|
||||
local_dest : @common.Destination
|
||||
local_ed_seed : Bytes
|
||||
mut remote_dest : @common.Destination?
|
||||
mut remote_transient_pub : Bytes?
|
||||
mut remote_hash : @common.Hash
|
||||
from_port : UInt32
|
||||
to_port : UInt32
|
||||
send_stream_id : UInt32
|
||||
mut recv_stream_id : UInt32
|
||||
local_stream_id : UInt32
|
||||
mut remote_stream_id : UInt32
|
||||
mut state : StreamState
|
||||
mut next_send_seq : UInt32
|
||||
mut highest_acked_seq : UInt32
|
||||
@@ -145,6 +146,7 @@ pub fn StreamingPacket::decode(Bytes, peer_sig_type? : @common.SigningPublicKeyT
|
||||
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
|
||||
pub fn StreamingPacket::verify_signature_with_key(Self, Bytes) -> Bool
|
||||
|
||||
// Type aliases
|
||||
|
||||
|
||||
+140
-43
@@ -25,11 +25,12 @@ pub struct StreamConnection {
|
||||
local_dest : @common.Destination
|
||||
local_ed_seed : Bytes
|
||||
mut remote_dest : @common.Destination?
|
||||
mut remote_transient_pub : Bytes?
|
||||
mut remote_hash : @common.Hash
|
||||
from_port : UInt32
|
||||
to_port : UInt32
|
||||
send_stream_id : UInt32
|
||||
mut recv_stream_id : UInt32
|
||||
local_stream_id : UInt32
|
||||
mut remote_stream_id : UInt32
|
||||
mut state : StreamState
|
||||
mut next_send_seq : UInt32
|
||||
mut highest_acked_seq : UInt32
|
||||
@@ -55,6 +56,35 @@ fn slice_bytes(data : Bytes, start : Int32, len : Int32) -> Bytes {
|
||||
Bytes::from_array(out)
|
||||
}
|
||||
|
||||
///|
|
||||
fn hash_to_nacks(h : @common.Hash) -> Array[UInt32] {
|
||||
let b = h.as_bytes()
|
||||
let out : Array[UInt32] = Array(capacity=8)
|
||||
for i = 0; i < 8; i = i + 1 {
|
||||
let off = i * 4
|
||||
let v = (b[off].to_uint() << 24) |
|
||||
(b[off + 1].to_uint() << 16) |
|
||||
(b[off + 2].to_uint() << 8) |
|
||||
b[off + 3].to_uint()
|
||||
out.push(v)
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
///|
|
||||
fn nacks_match_hash(nacks : Array[UInt32], h : @common.Hash) -> Bool {
|
||||
if nacks.length() != 8 {
|
||||
return false
|
||||
}
|
||||
let expected = hash_to_nacks(h)
|
||||
for i = 0; i < 8; i = i + 1 {
|
||||
if nacks[i] != expected[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
///|
|
||||
fn StreamConnection::queue_packet(
|
||||
self : StreamConnection,
|
||||
@@ -100,12 +130,13 @@ fn StreamConnection::current_nacks(self : StreamConnection) -> Array[UInt32] {
|
||||
}
|
||||
|
||||
///|
|
||||
/// Creates a new outbound `StreamConnection` and queues its signed `SYN` packet.
|
||||
/// Creates a new outbound `StreamConnection` and queues its signed `SYN` packet
|
||||
/// (wire `send_stream_id = 0`, `recv_stream_id = local_stream_id`, 8-NACK anti-replay hash).
|
||||
pub fn StreamConnection::connect(
|
||||
local_dest : @common.Destination,
|
||||
local_ed_seed : Bytes,
|
||||
remote_hash : @common.Hash,
|
||||
send_stream_id : UInt32,
|
||||
local_stream_id : UInt32,
|
||||
now_ms : UInt64,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
@@ -115,11 +146,12 @@ pub fn StreamConnection::connect(
|
||||
local_dest,
|
||||
local_ed_seed,
|
||||
remote_dest: None,
|
||||
remote_transient_pub: None,
|
||||
remote_hash,
|
||||
from_port,
|
||||
to_port,
|
||||
send_stream_id,
|
||||
recv_stream_id: 0U,
|
||||
local_stream_id,
|
||||
remote_stream_id: 0U,
|
||||
state: SynSent,
|
||||
next_send_seq: 1U,
|
||||
highest_acked_seq: 0U,
|
||||
@@ -136,11 +168,11 @@ pub fn StreamConnection::connect(
|
||||
out_queue: [],
|
||||
}
|
||||
let syn : StreamingPacket = {
|
||||
send_stream_id,
|
||||
recv_stream_id: 0U,
|
||||
send_stream_id: 0U,
|
||||
recv_stream_id: local_stream_id,
|
||||
sequence_num: 0U,
|
||||
ack_through: 0U,
|
||||
nacks: [],
|
||||
nacks: hash_to_nacks(remote_hash),
|
||||
resend_delay: b'\x00',
|
||||
flags: flag_synchronize |
|
||||
flag_from_included |
|
||||
@@ -165,7 +197,7 @@ pub fn StreamConnection::accept_syn(
|
||||
local_dest : @common.Destination,
|
||||
local_ed_seed : Bytes,
|
||||
syn_pkt : StreamingPacket,
|
||||
send_stream_id : UInt32,
|
||||
local_stream_id : UInt32,
|
||||
now_ms : UInt64,
|
||||
from_port~ : UInt32 = 0U,
|
||||
to_port~ : UInt32 = 0U,
|
||||
@@ -177,19 +209,30 @@ pub fn StreamConnection::accept_syn(
|
||||
if !syn_pkt.verify_signature(peer_dest) {
|
||||
raise InvalidSignature
|
||||
}
|
||||
if syn_pkt.nacks.length() == 8 &&
|
||||
!nacks_match_hash(syn_pkt.nacks, local_dest.hash()) {
|
||||
raise ProtocolError("SYN destination hash NACK mismatch")
|
||||
}
|
||||
let peer_mtu = match syn_pkt.max_packet_size {
|
||||
Some(m) if m >= 512U && m <= 1730U => m
|
||||
_ => 1730U
|
||||
}
|
||||
let remote_transient_pub = match syn_pkt.offline_sig {
|
||||
Some(os) if (syn_pkt.flags & flag_offline_signature) != 0U =>
|
||||
Some(os.transient_pub_key)
|
||||
_ => None
|
||||
}
|
||||
let peer_sid = syn_pkt.recv_stream_id
|
||||
let conn : StreamConnection = {
|
||||
local_dest,
|
||||
local_ed_seed,
|
||||
remote_dest: Some(peer_dest),
|
||||
remote_transient_pub,
|
||||
remote_hash: peer_dest.hash(),
|
||||
from_port,
|
||||
to_port,
|
||||
send_stream_id,
|
||||
recv_stream_id: syn_pkt.send_stream_id,
|
||||
local_stream_id,
|
||||
remote_stream_id: peer_sid,
|
||||
state: Established,
|
||||
next_send_seq: 1U,
|
||||
highest_acked_seq: 0U,
|
||||
@@ -202,7 +245,7 @@ pub fn StreamConnection::accept_syn(
|
||||
unacked: [],
|
||||
ooo_recv: [],
|
||||
recv_buf: [],
|
||||
peer_closed: false,
|
||||
peer_closed: (syn_pkt.flags & flag_close) != 0U,
|
||||
out_queue: [],
|
||||
}
|
||||
if syn_pkt.payload.length() > 0 {
|
||||
@@ -211,8 +254,8 @@ pub fn StreamConnection::accept_syn(
|
||||
}
|
||||
}
|
||||
let syn_ack : StreamingPacket = {
|
||||
send_stream_id,
|
||||
recv_stream_id: syn_pkt.send_stream_id,
|
||||
send_stream_id: peer_sid,
|
||||
recv_stream_id: local_stream_id,
|
||||
sequence_num: 0U,
|
||||
ack_through: 0U,
|
||||
nacks: [],
|
||||
@@ -312,8 +355,8 @@ fn StreamConnection::send_ack(
|
||||
now_ms : UInt64,
|
||||
) -> Unit raise StreamingError {
|
||||
let ack_pkt : StreamingPacket = {
|
||||
send_stream_id: self.send_stream_id,
|
||||
recv_stream_id: self.recv_stream_id,
|
||||
send_stream_id: self.remote_stream_id,
|
||||
recv_stream_id: self.local_stream_id,
|
||||
sequence_num: 0U,
|
||||
ack_through: self.ack_through,
|
||||
nacks: self.current_nacks(),
|
||||
@@ -329,6 +372,36 @@ fn StreamConnection::send_ack(
|
||||
self.queue_packet(ack_pkt, now_ms, track_unacked=false)
|
||||
}
|
||||
|
||||
///|
|
||||
fn StreamConnection::verify_peer_signature(
|
||||
self : StreamConnection,
|
||||
pkt : StreamingPacket,
|
||||
) -> Bool {
|
||||
if (pkt.flags & flag_offline_signature) != 0U {
|
||||
match self.remote_dest {
|
||||
Some(d) =>
|
||||
if pkt.verify_signature(d) {
|
||||
self.remote_transient_pub = match pkt.offline_sig {
|
||||
Some(os) => Some(os.transient_pub_key)
|
||||
None => self.remote_transient_pub
|
||||
}
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
None => return false
|
||||
}
|
||||
}
|
||||
match self.remote_transient_pub {
|
||||
Some(tk) => if pkt.verify_signature_with_key(tk) { return true }
|
||||
None => ()
|
||||
}
|
||||
match self.remote_dest {
|
||||
Some(d) => pkt.verify_signature(d)
|
||||
None => false
|
||||
}
|
||||
}
|
||||
|
||||
///|
|
||||
/// Processes an incoming decoded `StreamingPacket` addressed to this stream.
|
||||
pub fn StreamConnection::on_packet(
|
||||
@@ -337,29 +410,35 @@ pub fn StreamConnection::on_packet(
|
||||
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 => ()
|
||||
if (pkt.flags & flag_signature_included) != 0U &&
|
||||
(self.remote_dest is Some(_) || self.remote_transient_pub is Some(_)) &&
|
||||
!self.verify_peer_signature(pkt) {
|
||||
raise InvalidSignature
|
||||
}
|
||||
self.state = Reset
|
||||
self.peer_closed = true
|
||||
return
|
||||
}
|
||||
let mut acked = false
|
||||
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")
|
||||
match pkt.from_dest {
|
||||
Some(d) => {
|
||||
self.remote_dest = Some(d)
|
||||
self.remote_hash = d.hash()
|
||||
}
|
||||
None => ()
|
||||
}
|
||||
if !pkt.verify_signature(peer_dest) {
|
||||
raise InvalidSignature
|
||||
if (pkt.flags & flag_signature_included) != 0U {
|
||||
if self.remote_dest is None && self.remote_transient_pub is None {
|
||||
raise InvalidFormat(
|
||||
"SYN-ACK SIGNATURE_INCLUDED missing peer Destination",
|
||||
)
|
||||
}
|
||||
if !self.verify_peer_signature(pkt) {
|
||||
raise InvalidSignature
|
||||
}
|
||||
}
|
||||
self.remote_dest = Some(peer_dest)
|
||||
self.remote_hash = peer_dest.hash()
|
||||
self.recv_stream_id = pkt.send_stream_id
|
||||
self.remote_stream_id = pkt.recv_stream_id
|
||||
match pkt.max_packet_size {
|
||||
Some(m) if m >= 512U && m < self.max_packet_size =>
|
||||
self.max_packet_size = m
|
||||
@@ -375,6 +454,9 @@ pub fn StreamConnection::on_packet(
|
||||
self.recv_buf.push(pkt.payload[i])
|
||||
}
|
||||
}
|
||||
if (pkt.flags & flag_close) != 0U {
|
||||
self.peer_closed = true
|
||||
}
|
||||
self.send_ack(now_ms)
|
||||
return
|
||||
}
|
||||
@@ -382,9 +464,13 @@ pub fn StreamConnection::on_packet(
|
||||
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 => ()
|
||||
if (pkt.flags & flag_signature_included) != 0U {
|
||||
if self.remote_dest is None && self.remote_transient_pub is None {
|
||||
raise InvalidFormat("CLOSE SIGNATURE_INCLUDED missing peer Destination")
|
||||
}
|
||||
if !self.verify_peer_signature(pkt) {
|
||||
raise InvalidSignature
|
||||
}
|
||||
}
|
||||
self.peer_closed = true
|
||||
if self.state == Closing {
|
||||
@@ -403,6 +489,7 @@ pub fn StreamConnection::on_packet(
|
||||
self.next_recv_seq = seq + 1U
|
||||
self.drain_ooo_in_order()
|
||||
self.send_ack(now_ms)
|
||||
acked = true
|
||||
} else if seq > self.next_recv_seq {
|
||||
let mut dup = false
|
||||
for e in self.ooo_recv {
|
||||
@@ -415,12 +502,22 @@ pub fn StreamConnection::on_packet(
|
||||
self.ooo_recv.push((seq, pkt.payload))
|
||||
}
|
||||
self.send_ack(now_ms)
|
||||
acked = true
|
||||
} else {
|
||||
// Duplicate old seq: re-ACK so sender stops retransmitting
|
||||
self.send_ack(now_ms)
|
||||
acked = true
|
||||
}
|
||||
} else if (pkt.flags & flag_close) != 0U {
|
||||
} else if (pkt.flags & flag_close) != 0U ||
|
||||
(pkt.flags & flag_synchronize) != 0U {
|
||||
self.send_ack(now_ms)
|
||||
acked = true
|
||||
}
|
||||
if !acked && (pkt.flags & flag_delay_requested) != 0U {
|
||||
match pkt.delay_requested {
|
||||
Some(d) if d == 0U => self.send_ack(now_ms)
|
||||
_ => ()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,8 +544,8 @@ pub fn StreamConnection::write(
|
||||
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,
|
||||
send_stream_id: self.remote_stream_id,
|
||||
recv_stream_id: self.local_stream_id,
|
||||
sequence_num: seq,
|
||||
ack_through: self.ack_through,
|
||||
nacks: self.current_nacks(),
|
||||
@@ -496,8 +593,8 @@ pub fn StreamConnection::close(
|
||||
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,
|
||||
send_stream_id: self.remote_stream_id,
|
||||
recv_stream_id: self.local_stream_id,
|
||||
sequence_num: seq,
|
||||
ack_through: self.ack_through,
|
||||
nacks: self.current_nacks(),
|
||||
@@ -646,15 +743,15 @@ pub fn StreamManager::handle_incoming_i2cp(
|
||||
return None
|
||||
}
|
||||
let pkt = StreamingPacket::decode(raw)
|
||||
if pkt.recv_stream_id != 0U {
|
||||
if pkt.send_stream_id != 0U {
|
||||
for s in self.streams {
|
||||
if s.send_stream_id == pkt.recv_stream_id {
|
||||
if s.local_stream_id == pkt.send_stream_id {
|
||||
s.on_packet(pkt, now_ms)
|
||||
return Some(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
if (pkt.flags & flag_synchronize) != 0U && pkt.recv_stream_id == 0U {
|
||||
if (pkt.flags & flag_synchronize) != 0U && pkt.send_stream_id == 0U {
|
||||
let sid = self.alloc_stream_id()
|
||||
let conn = StreamConnection::accept_syn(
|
||||
self.local_dest,
|
||||
|
||||
@@ -86,8 +86,14 @@ test "Streaming full SYN -> SYN-ACK -> Data with drop/NACK/retransmit -> CLOSE"
|
||||
from_port=1111U,
|
||||
to_port=80U,
|
||||
)
|
||||
// Deliver SYN to Bob
|
||||
for msg in a_stream.drain_outbound() {
|
||||
// Deliver SYN to Bob and verify canonical I2P wire polarity & 8-NACK target hash
|
||||
let syn_pkts = a_stream.drain_outbound()
|
||||
assert_eq(syn_pkts.length(), 1)
|
||||
let (_syn_hdr, syn_dec) = @streaming.decode_i2cp_streaming(syn_pkts[0])
|
||||
assert_eq(syn_dec.send_stream_id, 0U)
|
||||
assert_eq(syn_dec.recv_stream_id, 100U)
|
||||
assert_eq(syn_dec.nacks.length(), 8)
|
||||
for msg in syn_pkts {
|
||||
let _ = bob_mgr.handle_incoming_i2cp(msg, 1010UL)
|
||||
}
|
||||
let b_stream = match bob_mgr.accept_next() {
|
||||
@@ -161,3 +167,162 @@ test "RepliableDatagram (Ed25519 raw payload) and RawDatagram I2CP round-trip" {
|
||||
assert_eq(rh.protocol, b'\x12')
|
||||
assert_eq(rbody, b"unauth-raw")
|
||||
}
|
||||
|
||||
///|
|
||||
test "Streaming accepts unsigned ECIES SYN-ACK / CLOSE and honors DELAY_REQUESTED=0" {
|
||||
let (alice_dest, alice_seed) = make_test_identity(b'\x41')
|
||||
let (bob_dest, _bob_seed) = make_test_identity(b'\x42')
|
||||
let alice_mgr = @streaming.StreamManager::new(
|
||||
alice_dest,
|
||||
alice_seed,
|
||||
initial_stream_id=300U,
|
||||
)
|
||||
let a_stream = alice_mgr.connect(bob_dest.hash(), 2000UL)
|
||||
let _ = a_stream.drain_outbound()
|
||||
|
||||
// Simulated ECIES peer sends unsigned SYN-ACK (m_DontSign)
|
||||
let unsigned_syn_ack : @streaming.StreamingPacket = {
|
||||
send_stream_id: 300U,
|
||||
recv_stream_id: 900U,
|
||||
sequence_num: 0U,
|
||||
ack_through: 0U,
|
||||
nacks: [],
|
||||
resend_delay: b'\x00',
|
||||
flags: @streaming.flag_synchronize |
|
||||
@streaming.flag_from_included |
|
||||
@streaming.flag_max_packet_size_included,
|
||||
delay_requested: None,
|
||||
from_dest: Some(bob_dest),
|
||||
max_packet_size: Some(1730U),
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: b"",
|
||||
}
|
||||
let _ = alice_mgr.handle_incoming_i2cp(
|
||||
@streaming.encode_i2cp_streaming(unsigned_syn_ack),
|
||||
2010UL,
|
||||
)
|
||||
assert_eq(a_stream.state, Established)
|
||||
let _ = a_stream.drain_outbound()
|
||||
|
||||
// Peer sends empty ACK packet with DELAY_REQUESTED=0 -> must queue immediate ACK
|
||||
let probe_pkt : @streaming.StreamingPacket = {
|
||||
send_stream_id: 300U,
|
||||
recv_stream_id: 900U,
|
||||
sequence_num: 0U,
|
||||
ack_through: 0U,
|
||||
nacks: [],
|
||||
resend_delay: b'\x00',
|
||||
flags: @streaming.flag_delay_requested,
|
||||
delay_requested: Some(0U),
|
||||
from_dest: None,
|
||||
max_packet_size: None,
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: b"",
|
||||
}
|
||||
let _ = alice_mgr.handle_incoming_i2cp(
|
||||
@streaming.encode_i2cp_streaming(probe_pkt),
|
||||
2020UL,
|
||||
)
|
||||
assert_eq(a_stream.drain_outbound().length(), 1)
|
||||
|
||||
// Peer sends unsigned CLOSE with data at seq 1
|
||||
let unsigned_close : @streaming.StreamingPacket = {
|
||||
send_stream_id: 300U,
|
||||
recv_stream_id: 900U,
|
||||
sequence_num: 1U,
|
||||
ack_through: 0U,
|
||||
nacks: [],
|
||||
resend_delay: b'\x00',
|
||||
flags: @streaming.flag_close,
|
||||
delay_requested: None,
|
||||
from_dest: None,
|
||||
max_packet_size: None,
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: b"bye",
|
||||
}
|
||||
let _ = alice_mgr.handle_incoming_i2cp(
|
||||
@streaming.encode_i2cp_streaming(unsigned_close),
|
||||
2030UL,
|
||||
)
|
||||
assert_eq(a_stream.read_available(), b"bye")
|
||||
assert_eq(a_stream.is_eof(), true)
|
||||
}
|
||||
|
||||
///|
|
||||
test "Streaming caches offline transient key from SYN-ACK to verify CLOSE without OFFLINE_SIGNATURE" {
|
||||
let (alice_dest, alice_seed) = make_test_identity(b'\x51')
|
||||
let master_seed = Bytes::make(32, b'\x52')
|
||||
let master_pub = @crypto.ed25519_public_key(master_seed)
|
||||
let transient_seed = Bytes::make(32, b'\x53')
|
||||
let transient_pub = @crypto.ed25519_public_key(transient_seed)
|
||||
let bob_dest = try! @common.Destination::new_ed25519(master_pub)
|
||||
|
||||
let off_sig : @common.OfflineSignature = {
|
||||
expires_sec: 1900000000U,
|
||||
transient_sig_type: EdDsaSha512Ed25519,
|
||||
transient_pub_key: transient_pub,
|
||||
signature: b"",
|
||||
}
|
||||
let signed_off = off_sig.sign_ed25519(master_seed)
|
||||
|
||||
let alice_mgr = @streaming.StreamManager::new(
|
||||
alice_dest,
|
||||
alice_seed,
|
||||
initial_stream_id=400U,
|
||||
)
|
||||
let a_stream = alice_mgr.connect(bob_dest.hash(), 3000UL)
|
||||
let _ = a_stream.drain_outbound()
|
||||
|
||||
let syn_ack_raw : @streaming.StreamingPacket = {
|
||||
send_stream_id: 400U,
|
||||
recv_stream_id: 800U,
|
||||
sequence_num: 0U,
|
||||
ack_through: 0U,
|
||||
nacks: [],
|
||||
resend_delay: b'\x00',
|
||||
flags: @streaming.flag_synchronize |
|
||||
@streaming.flag_from_included |
|
||||
@streaming.flag_max_packet_size_included |
|
||||
@streaming.flag_offline_signature,
|
||||
delay_requested: None,
|
||||
from_dest: Some(bob_dest),
|
||||
max_packet_size: Some(1730U),
|
||||
offline_sig: Some(signed_off),
|
||||
signature: None,
|
||||
payload: b"",
|
||||
}
|
||||
let syn_ack = syn_ack_raw.sign_ed25519(transient_seed)
|
||||
let _ = alice_mgr.handle_incoming_i2cp(
|
||||
@streaming.encode_i2cp_streaming(syn_ack),
|
||||
3010UL,
|
||||
)
|
||||
assert_eq(a_stream.state, Established)
|
||||
let _ = a_stream.drain_outbound()
|
||||
|
||||
// Follow-on CLOSE signed with cached transient key without repeating OFFLINE_SIGNATURE
|
||||
let close_raw : @streaming.StreamingPacket = {
|
||||
send_stream_id: 400U,
|
||||
recv_stream_id: 800U,
|
||||
sequence_num: 1U,
|
||||
ack_through: 0U,
|
||||
nacks: [],
|
||||
resend_delay: b'\x00',
|
||||
flags: @streaming.flag_close,
|
||||
delay_requested: None,
|
||||
from_dest: None,
|
||||
max_packet_size: None,
|
||||
offline_sig: None,
|
||||
signature: None,
|
||||
payload: b"HTTP/1.0 200 OK\r\n\r\nhi",
|
||||
}
|
||||
let close_pkt = close_raw.sign_ed25519(transient_seed)
|
||||
let _ = alice_mgr.handle_incoming_i2cp(
|
||||
@streaming.encode_i2cp_streaming(close_pkt),
|
||||
3020UL,
|
||||
)
|
||||
assert_eq(a_stream.read_available(), b"HTTP/1.0 200 OK\r\n\r\nhi")
|
||||
assert_eq(a_stream.is_eof(), true)
|
||||
}
|
||||
+23
-14
@@ -146,7 +146,7 @@ pub fn ShortBuildRequestRecord::decode_154(
|
||||
|
||||
///|
|
||||
/// Canonical Proposal 157 chained HKDF key derivation:
|
||||
/// `SMTunnelReplyKey` -> `SMTunnelLayerKey` -> `TunnelLayerIVKey` (-> `RGarlicKeyAndTag` for OBEP).
|
||||
/// `SMTunnelReplyKey` -> `SMTunnelLayerKey` (-> `TunnelLayerIVKey` -> `RGarlicKeyAndTag` for OBEP).
|
||||
fn derive_hop_keys(
|
||||
ck : Bytes,
|
||||
h : Bytes,
|
||||
@@ -164,21 +164,30 @@ fn derive_hop_keys(
|
||||
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 {
|
||||
if is_obep {
|
||||
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 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)))
|
||||
// Canonical i2pd: garlic_tag = kd4[0..8], garlic_key = kd4[32..64]
|
||||
let garlic_tag = Some(t_slice(kd4, 0, 8))
|
||||
let garlic_key = Some(t_slice(kd4, 32, 32))
|
||||
{ reply_key, layer_key, iv_key, handshake_hash: h, garlic_key, garlic_tag, }
|
||||
} else {
|
||||
(None, None)
|
||||
// Non-OBEP hops use ck2 directly as iv_key (no TunnelLayerIVKey HKDF step)
|
||||
{
|
||||
reply_key,
|
||||
layer_key,
|
||||
iv_key: ck2,
|
||||
handshake_hash: h,
|
||||
garlic_key: None,
|
||||
garlic_tag: None,
|
||||
}
|
||||
}
|
||||
{ reply_key, layer_key, iv_key, handshake_hash: h, garlic_key, garlic_tag, }
|
||||
}
|
||||
|
||||
///|
|
||||
@@ -366,7 +375,7 @@ pub fn build_short_tunnel_request(
|
||||
let keys_k = hop_keys[k].1
|
||||
rec = @crypto.chacha20_xor(
|
||||
keys_k.reply_key,
|
||||
0U,
|
||||
1U,
|
||||
make_slot_nonce(slot_m),
|
||||
rec,
|
||||
) catch {
|
||||
@@ -430,7 +439,7 @@ pub fn process_short_tunnel_build_hop(
|
||||
)
|
||||
} else {
|
||||
out.push(
|
||||
@crypto.chacha20_xor(keys.reply_key, 0U, make_slot_nonce(j), records[j]) catch {
|
||||
@crypto.chacha20_xor(keys.reply_key, 1U, make_slot_nonce(j), records[j]) catch {
|
||||
e => raise Crypto(e)
|
||||
},
|
||||
)
|
||||
@@ -457,7 +466,7 @@ pub fn decrypt_short_tunnel_replies(
|
||||
let keys_k = hop_slots_and_keys[k].1
|
||||
rec = @crypto.chacha20_xor(
|
||||
keys_k.reply_key,
|
||||
0U,
|
||||
1U,
|
||||
make_slot_nonce(slot_m),
|
||||
rec,
|
||||
) catch {
|
||||
|
||||
@@ -25,6 +25,59 @@ test "Proposal 157 ShortTunnelBuild 218-byte record & reply round-trip" {
|
||||
)
|
||||
assert_eq(enc_rec.length(), 218)
|
||||
|
||||
// Verify canonical non-OBEP key derivation: iv_key == ck2 (no TunnelLayerIVKey step)
|
||||
let sym = @noise.SymmetricState::initialize(
|
||||
b"Noise_N_25519_ChaChaPoly_SHA256",
|
||||
)
|
||||
sym.mix_hash(b"")
|
||||
sym.mix_hash(hop_static.public_key)
|
||||
sym.mix_hash(ephem.public_key)
|
||||
let dh = @crypto.x25519(ephem.private_key, hop_static.public_key)
|
||||
sym.mix_key(dh)
|
||||
let pt = req.encode_154()
|
||||
let _ = sym.encrypt_and_hash(pt)
|
||||
let kd1 = @crypto.hkdf(sym.chaining_key(), b"", b"SMTunnelReplyKey", 64)
|
||||
let ck1 = kd1[:32].to_owned()
|
||||
let kd2 = @crypto.hkdf(ck1, b"", b"SMTunnelLayerKey", 64)
|
||||
let ck2 = kd2[:32].to_owned()
|
||||
assert_eq(creator_keys.iv_key, ck2)
|
||||
assert_eq(creator_keys.garlic_key, None)
|
||||
assert_eq(creator_keys.garlic_tag, None)
|
||||
|
||||
// Verify canonical OBEP key derivation: TunnelLayerIVKey + RGarlicKeyAndTag (tag=0..8, key=32..64)
|
||||
let obep_req : @tunnel.ShortBuildRequestRecord = {
|
||||
receive_tunnel_id: 1001U,
|
||||
next_tunnel_id: 2002U,
|
||||
next_ident: next_hash,
|
||||
flag: b'\x40', // OBEP
|
||||
layer_enc_type: b'\x00',
|
||||
request_time_min: 28333333U,
|
||||
request_expiration_sec: 600U,
|
||||
send_message_id: 5555U,
|
||||
options: @common.Mapping::new(),
|
||||
}
|
||||
let (_, obep_keys) = @tunnel.encrypt_short_build_record(
|
||||
obep_req,
|
||||
hop_hash,
|
||||
hop_static.public_key,
|
||||
ephem,
|
||||
)
|
||||
let sym2 = @noise.SymmetricState::initialize(
|
||||
b"Noise_N_25519_ChaChaPoly_SHA256",
|
||||
)
|
||||
sym2.mix_hash(b"")
|
||||
sym2.mix_hash(hop_static.public_key)
|
||||
sym2.mix_hash(ephem.public_key)
|
||||
sym2.mix_key(dh)
|
||||
let _ = sym2.encrypt_and_hash(obep_req.encode_154())
|
||||
let ok1 = @crypto.hkdf(sym2.chaining_key(), b"", b"SMTunnelReplyKey", 64)
|
||||
let ok2 = @crypto.hkdf(ok1[:32].to_owned(), b"", b"SMTunnelLayerKey", 64)
|
||||
let ok3 = @crypto.hkdf(ok2[:32].to_owned(), b"", b"TunnelLayerIVKey", 64)
|
||||
let ok4 = @crypto.hkdf(ok3[:32].to_owned(), b"", b"RGarlicKeyAndTag", 64)
|
||||
assert_eq(obep_keys.iv_key, ok3[32:64].to_owned())
|
||||
assert_eq(obep_keys.garlic_tag, Some(ok4[:8].to_owned()))
|
||||
assert_eq(obep_keys.garlic_key, Some(ok4[32:64].to_owned()))
|
||||
|
||||
// Wrong hop rejects with RecordNotForUs
|
||||
let mut rejected = false
|
||||
try {
|
||||
@@ -99,6 +152,22 @@ test "Proposal 157 multi-hop ShortTunnelBuild onion build, hop relay, OBEP garli
|
||||
assert_true(creator_hop_keys[2].1.garlic_key is Some(_))
|
||||
assert_true(creator_hop_keys[2].1.garlic_tag is Some(_))
|
||||
|
||||
// Verify Proposal 157 canonical ChaCha20 initial block counter 1U on downstream slot 1
|
||||
let (raw_hop1, _) = @tunnel.encrypt_short_build_record(
|
||||
hops[1].record,
|
||||
hops[1].hop_ident,
|
||||
hops[1].hop_static_pub,
|
||||
hops[1].ephemeral,
|
||||
padding=hops[1].padding,
|
||||
)
|
||||
let expected_slot1 = @crypto.chacha20_xor(
|
||||
creator_hop_keys[0].1.reply_key,
|
||||
1U,
|
||||
@tunnel.make_slot_nonce(hops[1].slot_idx),
|
||||
raw_hop1,
|
||||
)
|
||||
assert_eq(req_records[hops[1].slot_idx], expected_slot1)
|
||||
|
||||
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(
|
||||
|
||||
Reference in new issue
Block a user