diff --git a/crates/rns-interface/src/backbone.rs b/crates/rns-interface/src/backbone.rs index 0772b27..bf4a5c5 100644 --- a/crates/rns-interface/src/backbone.rs +++ b/crates/rns-interface/src/backbone.rs @@ -137,8 +137,8 @@ pub struct BackboneClientConfig { /// Retries allowed within one outage; `None` retries forever. pub max_reconnect_tries: Option, pub mode: InterfaceMode, - /// Identity used to request a signed tunnel synthesis for each connection. - /// `None`, or an identity without signing material, sends no synthesis. + /// Set when each connection asks transport for a tunnel synthesis; + /// transport signs it with its own wire identity. pub tunnel_identity: Option, /// Bitrate the hardware MTU is optimised for. pub bitrate: u64, @@ -1064,11 +1064,8 @@ pub async fn spawn_backbone_client_observed( task_diagnostics.connected(); // Python synthesizes on every connection (BackboneInterface.py, // :1019). - let synthesis = config - .tunnel_identity - .as_ref() - .and_then(|identity| identity.synthesis(&python_name)); - open_client_connection(&rx, &transport_tx, synthesis, &online2).await; + let synthesize = config.tunnel_identity.is_some(); + open_client_connection(&rx, &transport_tx, synthesize, &online2).await; let ended = { let mut outbound = rx.lock().await; diff --git a/crates/rns-interface/src/i2p.rs b/crates/rns-interface/src/i2p.rs index 9a1a20a..9535a7c 100644 --- a/crates/rns-interface/src/i2p.rs +++ b/crates/rns-interface/src/i2p.rs @@ -549,8 +549,8 @@ pub struct I2PClientConfig { pub max_reconnect_tries: Option, pub reconnect_delay: u64, pub mode: InterfaceMode, - /// Identity used to request a signed tunnel synthesis for each connection. - /// `None`, or an identity without signing material, sends no synthesis. + /// Set when each connection asks transport for a tunnel synthesis; + /// transport signs it with its own wire identity. pub tunnel_identity: Option, } @@ -782,11 +782,8 @@ pub async fn spawn_i2p_client( pacer.reset(); // Python synthesizes on every connection (I2PInterface.py, // :533). - let synthesis = config - .tunnel_identity - .as_ref() - .and_then(|identity| identity.synthesis(&python_name)); - open_client_connection(&rx, &transport_tx, synthesis, &online_task).await; + let synthesize = config.tunnel_identity.is_some(); + open_client_connection(&rx, &transport_tx, synthesize, &online_task).await; // BufReader may have prefetched past the handshake; flush its tail first. let buffered = stream_buf_reader.buffer().to_vec(); diff --git a/crates/rns-interface/src/tcp.rs b/crates/rns-interface/src/tcp.rs index 651ed60..ca8bb91 100644 --- a/crates/rns-interface/src/tcp.rs +++ b/crates/rns-interface/src/tcp.rs @@ -195,8 +195,8 @@ pub struct TcpClientConfig { pub bitrate: u64, /// IFAC size in bytes; frames may exceed the hardware MTU by this much. pub ifac_size: usize, - /// Identity used to request a signed tunnel synthesis for each non-KISS - /// connection. `None`, or an identity without signing material, sends none. + /// Set when each non-KISS connection asks transport for a tunnel + /// synthesis; transport signs it with its own wire identity. pub tunnel_identity: Option, } @@ -735,12 +735,8 @@ pub async fn spawn_tcp_client_observed( task_diagnostics.connected(); // Python synthesizes on every non-KISS connection // (TCPInterface.py). - let synthesis = config - .tunnel_identity - .as_ref() - .filter(|_| !kiss_framing) - .and_then(|identity| identity.synthesis(&python_name)); - open_client_connection(&rx, &transport_tx, synthesis, &online2).await; + let synthesize = config.tunnel_identity.is_some() && !kiss_framing; + open_client_connection(&rx, &transport_tx, synthesize, &online2).await; let (reader, writer) = stream.into_split(); diff --git a/crates/rns-interface/src/traits.rs b/crates/rns-interface/src/traits.rs index 0458b4d..4ee8b35 100644 --- a/crates/rns-interface/src/traits.rs +++ b/crates/rns-interface/src/traits.rs @@ -95,23 +95,12 @@ pub(crate) async fn handoff_accepted_interface( } } -/// The transport identity a client signs its tunnel syntheses with (Python -/// `Transport.identity`). Debug shows only its hash. +/// The wire transport identity (Python `Transport.identity`). A client given +/// one asks transport for a tunnel synthesis on each connection; transport +/// signs it with the identity from `SetTunnelIdentity`. Debug shows only its hash. #[derive(Clone)] pub struct TunnelIdentity(pub Arc); -impl TunnelIdentity { - /// Build a fresh synthesis using `python_name` as the Python-compatible - /// interface name. Returns `None` when the identity cannot sign. - pub fn synthesis(&self, python_name: &str) -> Option { - rns_transport::tunnel::build_tunnel_synthesis_packet( - &self.0, - rns_transport::tunnel::interface_hash(python_name), - ) - .map(Bytes::from) - } -} - impl std::fmt::Debug for TunnelIdentity { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("TunnelIdentity") @@ -137,19 +126,18 @@ pub(crate) fn python_host(host: &str) -> std::borrow::Cow<'_, str> { pub(crate) async fn open_client_connection( outbound: &tokio::sync::Mutex>, transport_tx: &rns_transport::messages::InterfaceTransportSender, - synthesis: Option, + synthesize: bool, online: &AtomicBool, ) { if !online.load(std::sync::atomic::Ordering::SeqCst) { let mut queued = outbound.lock().await; while queued.try_recv().is_ok() {} } - if let Some(raw_packet) = synthesis { + if synthesize { let _ = transport_tx .send( rns_transport::messages::TransportMessage::SynthesizeTunnel { interface_id: transport_tx.interface_id(), - raw_packet, }, ) .await; @@ -391,7 +379,7 @@ mod tests { let transport_tx = rns_transport::messages::InterfaceTransportSender::new(7, actor_tx); let online = AtomicBool::new(false); - open_client_connection(&outbound, &transport_tx, None, &online).await; + open_client_connection(&outbound, &transport_tx, false, &online).await; assert!( outbound.lock().await.try_recv().is_err(), @@ -409,7 +397,7 @@ mod tests { let online = AtomicBool::new(true); frame_tx.send(Bytes::from_static(b"first")).await.unwrap(); - open_client_connection(&outbound, &transport_tx, None, &online).await; + open_client_connection(&outbound, &transport_tx, false, &online).await; assert_eq!( outbound.lock().await.try_recv().ok(), @@ -418,6 +406,31 @@ mod tests { ); } + /// Each connection asks transport for its synthesis before it reports + /// online; transport builds and signs it. + #[tokio::test] + async fn a_connection_asks_for_its_synthesis_before_it_is_online() { + let (_frame_tx, frame_rx) = mpsc::channel::(4); + let outbound = tokio::sync::Mutex::new(frame_rx); + let (actor_tx, mut actor_rx) = mpsc::channel(4); + let transport_tx = rns_transport::messages::InterfaceTransportSender::new(7, actor_tx); + let owner = transport_tx.owner(); + owner.mark_registered(); + let online = AtomicBool::new(false); + + open_client_connection(&outbound, &transport_tx, true, &online).await; + + let message = match actor_rx.try_recv().unwrap() { + rns_transport::messages::TransportMessage::InterfaceEvent { message, .. } => *message, + message => message, + }; + assert!(matches!( + message, + rns_transport::messages::TransportMessage::SynthesizeTunnel { interface_id: 7 } + )); + assert!(online.load(Ordering::SeqCst)); + } + #[test] fn test_interface_mode_repr() { assert_eq!(InterfaceMode::Full as u8, 0x01); diff --git a/crates/rns-runtime/src/reticulum.rs b/crates/rns-runtime/src/reticulum.rs index 815c7c2..fd809d8 100644 --- a/crates/rns-runtime/src/reticulum.rs +++ b/crates/rns-runtime/src/reticulum.rs @@ -2406,11 +2406,62 @@ impl ReticulumHandle { } async fn detach_running_interface(&self, name: &str) -> Option { - use rns_transport::messages::InterfaceRole; let Some((entry, spawned)) = self.running_interface(name).await else { tracing::warn!("Attempt to detach non-existing interface \"{name}\""); return None; }; + if !self.detach_entry(&entry, spawned).await { + return Some(false); + } + // Upstream's detach is synchronous: a reload attaches straight after it. + let gone_by = tokio::time::Instant::now() + Duration::from_secs(5); + while self.running_interface(name).await.is_some() && tokio::time::Instant::now() < gone_by + { + tokio::time::sleep(Duration::from_millis(10)).await; + } + rns_transport::notice!("Interface \"{name}\" was detached"); + Some(true) + } + + /// Python `_detach_interface(..., internal_forced=True)`, which transport + /// calls for a bad or blackholed tunnel peer: it ignores + /// `enable_interface_management`, and a client so detached stays down until + /// restart or attach (Reticulum.py:976-1015). + pub(crate) async fn detach_interface_by_id( + &self, + id: rns_transport::messages::InterfaceId, + ) -> Option { + let Ok(TransportQueryResponse::InterfaceStats(entries)) = self + .query_transport_result(TransportQuery::GetInterfaceStats) + .await + else { + return None; + }; + let entry = entries.iter().find(|entry| entry.id == id)?.clone(); + let spawned = entries + .iter() + .filter(|child| child.parent_id == Some(id)) + .map(|child| child.id) + .collect(); + if !self.detach_entry(&entry, spawned).await { + return Some(false); + } + let name = entry + .identity + .as_ref() + .map_or(entry.name.as_str(), |identity| identity.name.as_str()); + rns_transport::notice!("Interface {name} was detached"); + Some(true) + } + + /// Tear down an interface and those it spawned; I2P listeners and local + /// interfaces refuse (Reticulum.py). + async fn detach_entry( + &self, + entry: &rns_transport::messages::InterfaceStatRpcEntry, + spawned: Vec, + ) -> bool { + use rns_transport::messages::InterfaceRole; let i2p = entry .identity .as_ref() @@ -2423,7 +2474,7 @@ impl ReticulumHandle { .iter() .any(|role| role.as_str() == entry.role); if i2p || local { - return Some(false); + return false; } self.discovery .bootstrap_interfaces @@ -2439,14 +2490,7 @@ impl ReticulumHandle { teardown_interface(self, id).await; } teardown_interface(self, entry.id).await; - // Upstream's detach is synchronous: a reload attaches straight after it. - let gone_by = tokio::time::Instant::now() + Duration::from_secs(5); - while self.running_interface(name).await.is_some() && tokio::time::Instant::now() < gone_by - { - tokio::time::sleep(Duration::from_millis(10)).await; - } - rns_transport::notice!("Interface \"{name}\" was detached"); - Some(true) + true } async fn attach_configured_interface(&self, name: &str) -> Option { @@ -3936,6 +3980,13 @@ pub async fn init_with_policy( Some(ephemeral) => Arc::new(ephemeral), None => transport_identity.clone(), }; + let _ = transport_tx.try_send(TransportMessage::SetTunnelIdentity { + identity: wire_transport_identity.clone(), + }); + let (interface_control_tx, interface_control_rx) = mpsc::unbounded_channel(); + let _ = transport_tx.try_send(TransportMessage::SetInterfaceControl { + tx: interface_control_tx, + }); let network_identity = rc .network_identity_path @@ -4654,6 +4705,7 @@ pub async fn init_with_policy( .into()); } let _ = interface_manager.set(handle.clone()); + tokio::spawn(run_interface_control(handle.clone(), interface_control_rx)); let mut management_announces = Vec::new(); let mut blackhole_announce = None; @@ -10942,6 +10994,33 @@ async fn spawn_configured_interface_driver( } } +/// Carry out the transport actor's interface requests until it stops or the +/// runtime shuts down. +async fn run_interface_control( + handle: ReticulumHandle, + mut requests: mpsc::UnboundedReceiver, +) { + use rns_transport::messages::InterfaceControl; + let shutdown = handle.shutdown.clone(); + loop { + let request = tokio::select! { + request = requests.recv() => request, + () = shutdown.wait() => None, + }; + match request { + Some(InterfaceControl::Detach { + interface_id, + reason, + }) => { + tracing::debug!(interface_id, ?reason, "transport asked for a detach"); + let _ = handle.detach_interface_by_id(interface_id).await; + } + Some(_) => {} + None => return, + } + } +} + /// Return the first successfully initialized runtime retained in the /// process-wide cell. Later `init` calls still construct separate runtimes; /// this reference is not replaced or cleared on shutdown. Prefer the handle diff --git a/crates/rns-runtime/src/reticulum/tests/tunnels.rs b/crates/rns-runtime/src/reticulum/tests/tunnels.rs index 13ba3d2..76c6bee 100644 --- a/crates/rns-runtime/src/reticulum/tests/tunnels.rs +++ b/crates/rns-runtime/src/reticulum/tests/tunnels.rs @@ -855,22 +855,26 @@ fn synthesis_in(frame: &[u8]) -> Option { && header.flags.destination_type == DestinationType::Plain && header.flags.packet_type == PacketType::Data && header.hops == 0 - && header.context == PacketContext::None - && frame.len() == offset + 176; + && header.context == PacketContext::None; shape .then(|| TunnelSynthesisData::unpack(&frame[offset..])) .flatten() } +/// Python 1.6.1 signs the extension too, and a Rust node sends it always. fn assert_signed(synthesis: &TunnelSynthesisData) { let signer = Identity::from_public_key(&synthesis.public_key).unwrap(); let mut signed = synthesis.public_key.to_vec(); signed.extend_from_slice(&synthesis.interface_hash); signed.extend_from_slice(&synthesis.random_hash); + signed.extend_from_slice(&synthesis.ext); assert!( signer.verify(&signed, &synthesis.signature), "the synthesis verifies under its own Ed25519 key" ); + let ext = rns_transport::tunnel::RemoteTransportInfo::decode(&synthesis.ext) + .expect("an extended synthesis"); + assert_eq!(ext.implementation, "rsRNS"); } /// Python `Interface.get_hash()`: the full hash of `str(interface)`. @@ -1211,3 +1215,113 @@ async fn a_rust_hub_restores_a_reconnecting_rust_clients_paths() { let _ = std::fs::remove_dir_all(client_dir); let _ = std::fs::remove_dir_all(hub_dir); } + +fn hub_answer(identity: &Identity) -> Vec { + rns_transport::tunnel::build_tunnel_synthesis_packet_with_ext( + identity, + python_interface_hash("TCPInterface[Client on Hub/127.0.0.1:4242]"), + &rns_transport::tunnel::TunnelExt::local(true, 23.5, 15.8), + ) + .unwrap() +} + +fn tcp_client_config(port: u16) -> String { + format!( + "[reticulum]\n share_instance = No\n\n[interfaces]\n [[Uplink]]\n type = TCPClientInterface\n enabled = yes\n target_host = 127.0.0.1\n target_port = {port}\n" + ) +} + +/// A Rust client learns its hub from the hub's answer, and its own synthesis +/// names the tunnel (Transport.py:3205, :3290-3292). +#[tokio::test] +async fn a_tcp_client_records_the_hub_that_answers_its_synthesis() { + let hub = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = hub.local_addr().unwrap().port(); + let dir = config_dir("tcp-answer", &tcp_client_config(port)); + let handle = start(&dir).await; + + let mut connection = Frames::accept(&hub, false).await; + let opening = connection + .next(Duration::from_secs(5)) + .await + .and_then(|frame| synthesis_in(&frame)) + .expect("the client synthesizes"); + let hub_identity = Identity::new(); + connection + .reader + .get_mut() + .write_all(&rns_interface::hdlc::frame(&hub_answer(&hub_identity))) + .await + .unwrap(); + let entry = wait_for_interface(&handle, |entry| { + entry.name == "Uplink" && entry.remote_transport_id == Some(hub_identity.hash) + }) + .await + .expect("the client records its hub"); + assert_eq!(entry.tunnel_id, Some(opening.tunnel_id())); + assert_eq!( + entry.remote_transport.map(|remote| remote.implementation), + Some("rsRNS".to_string()) + ); + + handle.shutdown_and_wait().await; + let _ = std::fs::remove_dir_all(dir); +} + +/// An answer with a bad signature tears the client down for good, with +/// interface management off (Transport.py:3245-3248, Reticulum.py:976-1015). +#[tokio::test] +async fn a_client_answered_with_a_bad_signature_is_torn_down() { + let hub = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = hub.local_addr().unwrap().port(); + let dir = config_dir( + "tcp-bad-answer", + &tcp_client_config(port).replace( + "share_instance = No\n", + "share_instance = No\n enable_interface_management = No\n", + ), + ); + let handle = start(&dir).await; + assert!(!handle.config.enable_interface_management); + + let mut connection = Frames::accept(&hub, false).await; + assert!( + connection + .next(Duration::from_secs(5)) + .await + .is_some_and(|frame| synthesis_in(&frame).is_some()) + ); + let mut answer = hub_answer(&Identity::new()); + answer[rns_wire::constants::HEADER_MINSIZE + 120] ^= 0x01; + connection + .reader + .get_mut() + .write_all(&rns_interface::hdlc::frame(&answer)) + .await + .unwrap(); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(10); + while interfaces(&handle) + .await + .iter() + .any(|entry| entry.name == "Uplink") + { + assert!( + tokio::time::Instant::now() < deadline, + "the client is detached" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!( + tokio::time::timeout( + Duration::from_secs(rns_interface::tcp::RECONNECT_WAIT + 2), + hub.accept() + ) + .await + .is_err(), + "a detached client does not reconnect" + ); + + handle.shutdown_and_wait().await; + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/rns-transport/src/actor/inbound.rs b/crates/rns-transport/src/actor/inbound.rs index b27e22b..3cfc764 100644 --- a/crates/rns-transport/src/actor/inbound.rs +++ b/crates/rns-transport/src/actor/inbound.rs @@ -163,6 +163,9 @@ impl TransportActor { origin: InboundOrigin, ) { let (interface_id, len) = (packet.interface_id, packet.raw.len() as u64); + if self.is_detaching(interface_id) { + return; + } let outer = std::mem::take(&mut self.inbound_verdict); self.on_inbound_inner(packet, origin); let verdict = std::mem::replace(&mut self.inbound_verdict, outer); @@ -1353,31 +1356,9 @@ impl TransportActor { return; } - // Tunnel synthesis: install the tunnel, and replay its cached paths, - // once the signature verifies (Transport.py). if header.destination_hash == tunnel_synth_dest { if let Some(payload_start) = self.data_payload_offset(raw, header) { - match crate::tunnel::TunnelSynthesisData::unpack(&raw[payload_start..]) - .filter(crate::tunnel::TunnelSynthesisData::is_signed) - { - Some(synthesis) => { - let tunnel_id = synthesis.tunnel_id(); - debug!( - tunnel_id = hex::encode(&tunnel_id[..16]), - interface_id, "tunnel synthesis request validated" - ); - crate::tunnel::handle_tunnel( - &mut self.tunnel_table, - tunnel_id, - interface_id, - ); - self.state_dirty = true; - self.restore_tunnel_paths(&tunnel_id, interface_id); - } - // Wrong length or a bad signature is a silent drop - // (Transport.py). - None => debug!(interface_id, "invalid tunnel synthesis"), - } + self.tunnel_synthesize_handler(&raw[payload_start..], interface_id); } return; } diff --git a/crates/rns-transport/src/actor/mod.rs b/crates/rns-transport/src/actor/mod.rs index 1a98da6..3e5c383 100644 --- a/crates/rns-transport/src/actor/mod.rs +++ b/crates/rns-transport/src/actor/mod.rs @@ -37,6 +37,7 @@ mod persistence; mod recursive_discovery; mod rpc; mod store_worker; +mod tunnel_synthesis; pub use options::{StorageRole, TransportActorOptions}; use rpc::InterfaceEvent; @@ -126,6 +127,12 @@ pub struct TransportActor { traffic_count: rpc::TrafficCount, /// Python `preprocess_inbound`'s verdict on the frame being processed. inbound_verdict: inbound::InboundVerdict, + /// Python `Transport.identity`, which signs tunnel syntheses. + tunnel_identity: Option>, + /// Where detach requests go; without one the actor deregisters itself. + interface_control: Option>, + /// Interfaces asked to detach; their frames are dropped until they go. + detaching: HashSet, /// Python's `local_client_rssi_cache`, `_snr_cache` and `_q_cache`: one /// 512-entry list per metric, first match wins (Transport.py). pub(crate) packet_rssi_cache: VecDeque<([u8; 32], f32)>, @@ -528,6 +535,9 @@ impl TransportActor { blackhole_table: BlackholeTable::new(), traffic_count: rpc::TrafficCount::default(), inbound_verdict: inbound::InboundVerdict::default(), + tunnel_identity: None, + interface_control: None, + detaching: HashSet::new(), packet_rssi_cache: VecDeque::new(), packet_snr_cache: VecDeque::new(), packet_q_cache: VecDeque::new(), @@ -1171,17 +1181,17 @@ impl TransportActor { self.is_shared_instance = true; self.request_announces_from_local_destinations(); } - TransportMessage::SynthesizeTunnel { - interface_id, - raw_packet, - } => { - debug!( - interface_id, - len = raw_packet.len(), - "sending tunnel synthesis packet" - ); - // The driver queues the synthesis just before it reports online. - self.send_to_interface_unchecked(interface_id, &raw_packet); + TransportMessage::SynthesizeTunnel { interface_id } => { + if let Some(entry) = self.interfaces.get_mut(&interface_id) { + entry.tunnel.reconnect(); + } + self.synthesize_tunnel(interface_id, false); + } + TransportMessage::SetTunnelIdentity { identity } => { + self.tunnel_identity = Some(identity); + } + TransportMessage::SetInterfaceControl { tx } => { + self.interface_control = Some(tx); } TransportMessage::RegisterInterface { id, entry } => { if !entry.owner.is_current() { @@ -1784,6 +1794,7 @@ impl TransportActor { online.store(false, std::sync::atomic::Ordering::SeqCst); } self.void_tunnel_interface(id); + self.detaching.remove(&id); let dropped = self.path_table.drop_all_via(id); if dropped > 0 { debug!(id, dropped, "dropped paths via deregistered interface"); @@ -3344,20 +3355,6 @@ mod tests { ); } - #[test] - fn tunnel_synthesis_is_queued_before_the_interface_reports_online() { - let (mut actor, _tx) = TransportActor::new(); - let (mut entry, mut rx) = make_test_interface("TCPClient"); - entry.online = Some(Arc::new(AtomicBool::new(false))); - actor.interfaces.insert(45, entry); - - actor.handle_message(TransportMessage::SynthesizeTunnel { - interface_id: 45, - raw_packet: Bytes::from_static(&[0x08, 0x00]), - }); - assert_eq!(rx.try_recv().unwrap(), Bytes::from_static(&[0x08, 0x00])); - } - #[test] fn test_register_local_client_does_not_replay_cached_announces() { let (mut actor, _tx) = TransportActor::new(); diff --git a/crates/rns-transport/src/actor/persistence.rs b/crates/rns-transport/src/actor/persistence.rs index 3cd065b..b01f670 100644 --- a/crates/rns-transport/src/actor/persistence.rs +++ b/crates/rns-transport/src/actor/persistence.rs @@ -984,6 +984,7 @@ impl TransportActor { } if count > 0 { self.publish_blackhole_snapshot(); + self.detach_blackholed_tunnel_peers(); debug!(count, "loaded Python blackhole files"); } } diff --git a/crates/rns-transport/src/actor/rpc.rs b/crates/rns-transport/src/actor/rpc.rs index 9126c63..2bc946a 100644 --- a/crates/rns-transport/src/actor/rpc.rs +++ b/crates/rns-transport/src/actor/rpc.rs @@ -177,6 +177,12 @@ impl TransportActor { radio: inspection.radio, last_connect_error: inspection.last_connect_error.map(str::to_string), connect_failures: inspection.connect_failures, + tunnel_id: self + .tunnel_table + .interface_tunnel(iface_id) + .or(entry.tunnel.local_tunnel_id), + remote_transport_id: entry.tunnel.remote_transport, + remote_transport: entry.tunnel.remote_info.clone(), }) }) .collect(); @@ -456,6 +462,7 @@ impl TransportActor { for dest in dropped { self.path_table.remove(&dest); } + self.detach_blackholed_tunnel_peers(); self.state_dirty = true; self.publish_blackhole_snapshot(); TransportQueryResponse::OptBoolResult(Some(true)) diff --git a/crates/rns-transport/src/actor/tests/tunnels.rs b/crates/rns-transport/src/actor/tests/tunnels.rs index 5a6c5b0..2305308 100644 --- a/crates/rns-transport/src/actor/tests/tunnels.rs +++ b/crates/rns-transport/src/actor/tests/tunnels.rs @@ -63,10 +63,93 @@ fn cache_announce(dir: &std::path::Path, raw: &[u8], interface: Option<&str>) -> packet_hash } +/// A hub-side child of a TCP listener, which Python lets take a synthesis. +fn attach_child(actor: &mut TransportActor, id: InterfaceId, name: &str) -> mpsc::Receiver { + attach_class(actor, id, name, "TCPClientInterface") +} + +fn attach_class( + actor: &mut TransportActor, + id: InterfaceId, + name: &str, + class: &str, +) -> mpsc::Receiver { + let (mut entry, rx) = make_test_interface(name); + entry.inspection = Some(InterfaceInspectionSource::identified( + crate::messages::InterfaceIdentity::new(name, name, class), + )); + actor.interfaces.insert(id, entry); + rx +} + +/// A node whose wire identity can sign, with a control channel for detaches. +fn signing( + mut actor: TransportActor, +) -> ( + TransportActor, + Arc, + mpsc::UnboundedReceiver, +) { + let identity = Arc::new(Identity::new()); + actor.transport_identity_hash = Some(identity.hash); + actor.handle_message(TransportMessage::SetTunnelIdentity { + identity: identity.clone(), + }); + let (tx, rx) = mpsc::unbounded_channel(); + actor.handle_message(TransportMessage::SetInterfaceControl { tx }); + (actor, identity, rx) +} + +fn extended(identity: &Identity, interface: &str) -> (Bytes, [u8; 32]) { + let ext = crate::tunnel::TunnelExt::local(true, 8.0, 4.5); + let raw = crate::tunnel::build_tunnel_synthesis_packet_with_ext( + identity, + crate::tunnel::interface_hash(interface), + &ext, + ) + .unwrap(); + let tunnel_id = TunnelSynthesisData::unpack(&raw[rns_wire::constants::HEADER_MINSIZE..]) + .unwrap() + .tunnel_id(); + (Bytes::from(raw), tunnel_id) +} + +/// A PLAIN broadcast to `rnstransport.tunnel.synthesize` carrying `payload`. +fn synthesis_packet(payload: &[u8]) -> Bytes { + let mut raw = PacketHeader { + flags: PacketFlags { + header_type: HeaderType::Header1, + context_flag: false, + transport_type: TransportType::Broadcast, + destination_type: DestinationType::Plain, + packet_type: PacketType::Data, + }, + hops: 0, + transport_id: None, + destination_hash: named_hash("rnstransport.tunnel.synthesize"), + context: PacketContext::None, + } + .pack(); + raw.extend_from_slice(payload); + Bytes::from(raw) +} + +/// The synthesis in a frame the actor sent, if it is one. +fn sent_synthesis(frame: &[u8]) -> Option { + let (header, offset) = PacketHeader::unpack(frame).ok()?; + (header.destination_hash == named_hash("rnstransport.tunnel.synthesize")) + .then(|| TunnelSynthesisData::unpack(&frame[offset..])) + .flatten() +} + +fn violations(actor: &TransportActor, id: InterfaceId) -> u64 { + actor.interfaces[&id].protocol_violations +} + #[test] fn valid_synthesis_installs_a_tunnel_that_collects_announces() { let mut actor = hub(); - let _rx = attach(&mut actor, 1, "hub/client_1"); + let _rx = attach_child(&mut actor, 1, "hub/client_1"); let (raw, tunnel_id) = synthesis(&Identity::new(), "TCPInterface[Uplink/127.0.0.1:4242]"); inbound(&mut actor, raw, 1); assert!( @@ -82,62 +165,318 @@ fn valid_synthesis_installs_a_tunnel_that_collects_announces() { ); } +/// Python 1.6.1 runs the handler on its own verdict table; each case is +/// signed here and must hash to Python's payload (Transport.py:3208-3297). #[test] -fn synthesis_with_a_bad_signature_or_extra_bytes_installs_nothing() { - let mut actor = hub(); - let _rx: Vec<_> = (1..=3) - .map(|id| attach(&mut actor, id, &format!("hub/client_{id}"))) - .collect(); - let (valid, valid_id) = synthesis(&Identity::new(), "uplink-a"); - inbound(&mut actor, valid, 1); - assert!( - actor.tunnel_table.get(&valid_id).is_some(), - "control: a valid synthesis installs" - ); +fn the_handler_reaches_python_verdicts() { + use crate::tunnel::python_vectors::{HANDLER_CASES, identity, payload}; + for (name, verdict, ext, digest) in HANDLER_CASES { + let data = payload(name, ext); + assert_eq!( + hex::encode(rns_crypto::sha::sha256(&data)), + *digest, + "{name}: signed as Python signs it" + ); + let (mut actor, _, mut control) = signing(hub()); + let mut rx = attach_child(&mut actor, 1, "hub/client_1"); + inbound(&mut actor, synthesis_packet(&data), 1); - let (raw, tampered_id) = synthesis(&Identity::new(), "uplink-b"); - let mut tampered = raw.to_vec(); - *tampered.last_mut().unwrap() ^= 0x01; - inbound(&mut actor, Bytes::from(tampered), 2); - assert!( - actor.tunnel_table.get(&tampered_id).is_none(), - "a flipped signature bit is rejected" - ); - - let (raw, trailing_id) = synthesis(&Identity::new(), "uplink-c"); - let mut trailing = raw.to_vec(); - trailing.push(0); - inbound(&mut actor, Bytes::from(trailing), 3); - assert!( - actor.tunnel_table.get(&trailing_id).is_none(), - "a payload longer than 176 bytes is rejected (Transport.py:2791)" - ); - assert_eq!(actor.tunnel_table.len(), 1); + let tunnel_id = TunnelSynthesisData::unpack(&data[..176]) + .unwrap() + .tunnel_id(); + let mut outcome = Vec::new(); + if rx + .try_recv() + .ok() + .as_deref() + .and_then(sent_synthesis) + .is_some() + { + outcome.push("reply"); + } + if actor.tunnel_table.get(&tunnel_id).is_some() { + outcome.push("tunnel"); + } + if control.try_recv().is_ok() { + outcome.push("detach"); + } + if actor + .interfaces + .get(&1) + .is_some_and(|entry| entry.protocol_violations > 0) + { + outcome.push("violation"); + } + if actor + .interfaces + .get(&1) + .is_some_and(|entry| entry.tunnel.remote_transport == Some(identity().hash)) + { + outcome.push("remote"); + } + let expected = match *name { + // Lead decision: costs may be ints. + "cost_int" => "reply,tunnel,remote", + _ => verdict, + }; + assert_eq!(outcome.join(","), expected, "{name}"); + } } +/// UDP, RNode, serial, KISS, pipe, AX.25, Auto and local interfaces never +/// take a synthesis (Transport.py:3211-3212). #[test] -fn the_newer_synthesis_on_an_interface_takes_its_later_announces() { +fn an_interface_without_tunnels_ignores_a_synthesis() { let mut actor = hub(); - let _rx = attach(&mut actor, 1, "hub/client_1"); - let (older, older_id) = synthesis(&Identity::new(), "uplink"); - let (newer, newer_id) = synthesis(&Identity::new(), "uplink"); - inbound(&mut actor, older, 1); - inbound(&mut actor, newer, 1); - assert!( - actor.tunnel_table.get(&older_id).is_some() && actor.tunnel_table.get(&newer_id).is_some(), - "both syntheses install" - ); + let _rx = attach_class(&mut actor, 1, "udp", "UDPInterface"); + let (raw, tunnel_id) = extended(&Identity::new(), "uplink"); + inbound(&mut actor, raw, 1); + assert!(actor.tunnel_table.get(&tunnel_id).is_none()); + assert_eq!(violations(&actor, 1), 0, "ignored silently"); + assert!(actor.interfaces[&1].tunnel.remote_transport.is_none()); +} - let (announce, dest) = make_valid_announce("tunnel.newer", 0); +/// One synthesis per connection: a second is a violation whether or not the +/// first established a tunnel, and a malformed first one uses up the chance. +#[test] +fn a_connection_takes_one_synthesis() { + let mut actor = hub(); + let _rx: Vec<_> = (1..=2) + .map(|id| attach_child(&mut actor, id, &format!("hub/client_{id}"))) + .collect(); + let (first, first_id) = synthesis(&Identity::new(), "uplink"); + let (second, second_id) = synthesis(&Identity::new(), "uplink"); + inbound(&mut actor, first, 1); + inbound(&mut actor, second, 1); + assert!(actor.tunnel_table.get(&first_id).is_some()); + assert!(actor.tunnel_table.get(&second_id).is_none()); + assert_eq!(violations(&actor, 1), 1, "already established"); + + inbound(&mut actor, synthesis_packet(&[0; 175]), 2); + assert_eq!(violations(&actor, 2), 1, "undersize"); + let (valid, valid_id) = synthesis(&Identity::new(), "uplink-b"); + inbound(&mut actor, valid, 2); + assert_eq!(violations(&actor, 2), 2, "the chance is spent"); + assert!(actor.tunnel_table.get(&valid_id).is_none()); +} + +/// A bad signature tears the interface down (Transport.py:3245-3248); with no +/// one to ask, the actor drops it itself. +#[test] +fn a_bad_signature_tears_the_interface_down() { + let (mut actor, _, mut control) = signing(hub()); + let _rx = attach_child(&mut actor, 1, "hub/client_1"); + let (raw, tunnel_id) = extended(&Identity::new(), "uplink"); + let mut tampered = raw.to_vec(); + *tampered.last_mut().unwrap() ^= 0x01; + inbound(&mut actor, Bytes::from(tampered), 1); + assert_eq!( + control.try_recv().unwrap(), + crate::messages::InterfaceControl::Detach { + interface_id: 1, + reason: crate::messages::DetachReason::InvalidSynthesis, + } + ); + assert!(actor.tunnel_table.get(&tunnel_id).is_none()); + + let (announce, dest) = make_valid_announce("tunnel.detaching", 0); inbound(&mut actor, announce, 1); assert!( - carries(&actor, &newer_id, &dest), - "the last synthesis owns the interface (Transport.py:2827, :2834)" + !actor.path_table.has_path(&dest), + "frames from a detaching interface are dropped" ); + actor.deregister_interface(1); + assert!(!actor.is_detaching(1)); + + let mut alone = hub(); + let _rx = attach_child(&mut alone, 2, "hub/client_2"); + let (raw, _) = synthesis(&Identity::new(), "uplink"); + let mut tampered = raw.to_vec(); + tampered[rns_wire::constants::HEADER_MINSIZE + 120] ^= 0x01; + inbound(&mut alone, Bytes::from(tampered), 2); + assert!(!alone.interfaces.contains_key(&2)); +} + +/// A blackholed transport node is torn down at its synthesis, and when it is +/// blackholed later (Transport.py:3249-3252, :4832-4839). +#[test] +fn a_blackholed_tunnel_peer_is_torn_down() { + let (mut actor, _, mut control) = signing(hub()); + let _rx: Vec<_> = (1..=3) + .map(|id| attach_child(&mut actor, id, &format!("hub/client_{id}"))) + .collect(); + let blackholed = Identity::new(); + actor.blackhole_table.add(blackholed.hash, None); + let (raw, tunnel_id) = extended(&blackholed, "uplink"); + inbound(&mut actor, raw, 1); + assert_eq!( + control.try_recv().unwrap(), + crate::messages::InterfaceControl::Detach { + interface_id: 1, + reason: crate::messages::DetachReason::BlackholedTransport, + } + ); + assert!(actor.tunnel_table.get(&tunnel_id).is_none()); + + let (later, other) = (Identity::new(), Identity::new()); + inbound(&mut actor, extended(&later, "uplink-2").0, 2); + inbound(&mut actor, extended(&other, "uplink-3").0, 3); + assert!(control.try_recv().is_err()); + actor.handle_query(crate::messages::TransportQuery::BlackholeIdentity { + hash: later.hash, + ttl: None, + reason: crate::blackhole::BlackholeReason::Manual, + reason_label: None, + }); + assert_eq!( + control.try_recv().unwrap(), + crate::messages::InterfaceControl::Detach { + interface_id: 2, + reason: crate::messages::DetachReason::BlackholedTransport, + } + ); + assert!(control.try_recv().is_err(), "only the blackholed peer"); +} + +/// A receiver answers an extended synthesis once, signed with its own wire +/// identity and with its own costs; a legacy synthesis gets no answer +/// (Transport.py:3286). +#[test] +fn a_receiver_answers_an_extended_synthesis_once() { + let (mut actor, hub_identity, _control) = signing(hub()); + let mut rx = attach_child(&mut actor, 1, "hub/client_1"); + actor.interfaces.get_mut(&1).unwrap().destination_cost = Some(12.0); + let client = Identity::new(); + let (raw, tunnel_id) = extended(&client, "uplink"); + inbound(&mut actor, raw, 1); + let reply = sent_synthesis(&rx.try_recv().unwrap()).expect("a reverse synthesis"); + assert!(reply.is_signed()); + assert_eq!(reply.transport_identity_hash(), hub_identity.hash); + assert_eq!( + reply.interface_hash, + crate::tunnel::interface_hash("hub/client_1") + ); + let info = crate::tunnel::RemoteTransportInfo::decode(&reply.ext).unwrap(); + assert_eq!(info.implementation, "rsRNS"); + assert!(info.transport); + assert_eq!(info.destination_cost, 12.0); + assert_eq!( + info.pr_cost, + rns_identity::stamps::quantize_cost(15.8).unwrap() + ); + assert!(actor.tunnel_table.get(&tunnel_id).is_some()); + assert!(rx.try_recv().is_err(), "answered once"); + + let stats = interface_stats(&mut actor, 1); + assert_eq!(stats.tunnel_id, Some(tunnel_id)); + assert_eq!(stats.remote_transport_id, Some(client.hash)); + let remote = stats.remote_transport.expect("the client's extension"); + assert_eq!( + (remote.implementation.as_str(), remote.version.clone()), + ( + "rsRNS", + crate::discovery::constants::IMPLEMENTATION_VERSION + .split('.') + .map(|part| part.parse().unwrap()) + .collect::>() + ) + ); + assert_eq!((remote.destination_cost, remote.pr_cost), (8.0, 4.5)); + + let mut legacy_rx = attach_child(&mut actor, 2, "hub/client_2"); + inbound(&mut actor, synthesis(&Identity::new(), "uplink").0, 2); assert!( - !carries(&actor, &older_id, &dest), - "the superseded tunnel takes no new paths" + legacy_rx.try_recv().is_err(), + "no answer to the legacy form" ); + let legacy = interface_stats(&mut actor, 2); + assert!(legacy.remote_transport_id.is_some() && legacy.remote_transport.is_none()); +} + +/// An initiator sends the extended form, names its tunnel, records the hub's +/// answer without binding a tunnel or answering back, and forgets the hub on +/// its next connection (Transport.py:3205, :3290-3292). +#[test] +fn an_initiator_records_its_hub_without_binding_a_tunnel() { + let (mut actor, client_identity, _control) = signing(hub()); + let name = "TCPInterface[Uplink/127.0.0.1:4242]"; + let mut rx = attach_class(&mut actor, 1, name, "TCPClientInterface"); + actor.interfaces.get_mut(&1).unwrap().online = + Some(Arc::new(std::sync::atomic::AtomicBool::new(false))); + actor.handle_message(TransportMessage::SynthesizeTunnel { interface_id: 1 }); + let sent = sent_synthesis(&rx.try_recv().unwrap()) + .expect("queued before the interface reports online"); + assert!(sent.is_signed()); + assert_eq!(sent.transport_identity_hash(), client_identity.hash); + assert_eq!(sent.interface_hash, crate::tunnel::interface_hash(name)); + let info = crate::tunnel::RemoteTransportInfo::decode(&sent.ext).unwrap(); + assert_eq!( + (info.destination_cost, info.pr_cost), + (23.5, rns_identity::stamps::quantize_cost(15.8).unwrap()) + ); + assert_eq!( + interface_stats(&mut actor, 1).tunnel_id, + Some(sent.tunnel_id()) + ); + + let hub_identity = Identity::new(); + let (reply, reply_tunnel) = + extended(&hub_identity, "TCPInterface[Client on Hub/10.0.0.1:5000]"); + inbound(&mut actor, reply, 1); + assert!(rx.try_recv().is_err(), "an initiator never answers"); + assert!(actor.tunnel_table.get(&reply_tunnel).is_none()); + assert!(actor.tunnel_table.is_empty()); + let stats = interface_stats(&mut actor, 1); + assert_eq!(stats.remote_transport_id, Some(hub_identity.hash)); + assert_eq!(stats.tunnel_id, Some(sent.tunnel_id())); + + actor.handle_message(TransportMessage::SynthesizeTunnel { interface_id: 1 }); + assert!( + rx.try_recv() + .ok() + .as_deref() + .and_then(sent_synthesis) + .is_some() + ); + assert!(interface_stats(&mut actor, 1).remote_transport_id.is_none()); + let (again, _) = extended(&hub_identity, "TCPInterface[Client on Hub/10.0.0.1:5001]"); + inbound(&mut actor, again, 1); + assert_eq!( + violations(&actor, 1), + 0, + "a new connection takes a new answer" + ); + assert_eq!( + interface_stats(&mut actor, 1).remote_transport_id, + Some(hub_identity.hash) + ); +} + +/// Python skips a synthesis without `Transport.identity`; the actor also +/// refuses to sign with an identity that is not its visible one. +#[test] +fn no_synthesis_without_the_wire_identity() { + let mut actor = hub(); + let mut rx = attach_child(&mut actor, 1, "uplink"); + actor.handle_message(TransportMessage::SynthesizeTunnel { interface_id: 1 }); + assert!(rx.try_recv().is_err()); + actor.handle_message(TransportMessage::SetTunnelIdentity { + identity: Arc::new(Identity::new()), + }); + actor.handle_message(TransportMessage::SynthesizeTunnel { interface_id: 1 }); + assert!(rx.try_recv().is_err(), "its hash is not the transport hash"); +} + +fn interface_stats( + actor: &mut TransportActor, + id: InterfaceId, +) -> crate::messages::InterfaceStatRpcEntry { + let crate::messages::TransportQueryResponse::InterfaceStats(entries) = + actor.handle_query(crate::messages::TransportQuery::GetInterfaceStats) + else { + panic!("unexpected interface stats response"); + }; + entries.into_iter().find(|entry| entry.id == id).unwrap() } #[test] @@ -617,3 +956,22 @@ fn shared_owner_ingress_bypasses_the_plain_hop_filter() { "the shared instance already filtered this packet (Transport.py:1627)" ); } + +/// The answer leaves through transport, so it carries the interface's IFAC +/// (Transport.py `packet.send()`). +#[test] +fn a_reverse_synthesis_carries_ifac() { + let (mut actor, _, _control) = signing(hub()); + let mut rx = attach_child(&mut actor, 1, "hub/client_1"); + let key = rns_identity::ifac::IfacKey::derive(Some("tunnels"), Some("ifac")).unwrap(); + let entry = actor.interfaces.get_mut(&1).unwrap(); + entry.ifac_key = Some(key.clone()); + entry.ifac_size = 16; + let (raw, tunnel_id) = extended(&Identity::new(), "uplink"); + let masked = crate::ifac::try_ifac_sign(&raw, &key, 16).unwrap(); + inbound(&mut actor, Bytes::from(masked), 1); + assert!(actor.tunnel_table.get(&tunnel_id).is_some()); + let reply = rx.try_recv().unwrap(); + let clear = crate::ifac::ifac_verify(&reply, &key, 16).expect("IFAC-valid"); + assert!(sent_synthesis(&clear).is_some_and(|synthesis| synthesis.is_signed())); +} diff --git a/crates/rns-transport/src/actor/tunnel_synthesis.rs b/crates/rns-transport/src/actor/tunnel_synthesis.rs new file mode 100644 index 0000000..fc0b67f --- /dev/null +++ b/crates/rns-transport/src/actor/tunnel_synthesis.rs @@ -0,0 +1,174 @@ +use super::*; +use crate::messages::{DetachReason, InterfaceControl}; +use crate::tunnel::{RemoteTransportInfo, TunnelExt, TunnelSynthesisData}; + +impl TransportActor { + /// Python 1.6.1 `Transport.synthesize_tunnel` (Transport.py:3170-3206). An + /// initiator sends while still offline and names its tunnel; a receiver's + /// reverse synthesis answers a peer's extension. + pub(super) fn synthesize_tunnel(&mut self, interface_id: InterfaceId, reverse: bool) { + let Some(identity) = self + .tunnel_identity + .clone() + .filter(|identity| Some(identity.hash) == self.transport_identity_hash) + else { + debug!( + interface_id, + "no transport identity to sign a tunnel synthesis" + ); + return; + }; + let Some(entry) = self.interfaces.get(&interface_id) else { + return; + }; + let interface_hash = crate::tunnel::interface_hash(entry.upstream_name()); + let ext = TunnelExt::local( + self.is_transport_enabled, + self.interface_destination_cost(interface_id), + self.interface_pr_cost(interface_id), + ); + let Some(raw) = + crate::tunnel::build_tunnel_synthesis_packet_with_ext(&identity, interface_hash, &ext) + else { + return; + }; + let tunnel_id = TunnelSynthesisData::unpack(&raw[rns_wire::constants::HEADER_MINSIZE..]) + .map(|synthesis| synthesis.tunnel_id()); + if let Some(entry) = self.interfaces.get_mut(&interface_id) { + entry.tunnel.synthesis_emitted = true; + if !reverse { + entry.tunnel.local_tunnel_id = tunnel_id; + } + } + debug!( + interface_id, + reverse, + len = raw.len(), + "sending tunnel synthesis" + ); + if reverse { + self.send_to_interface(interface_id, &raw); + } else { + // The driver queues it just before the interface reports online. + self.send_to_interface_unchecked(interface_id, &raw); + } + } + + /// Python 1.6.1 `Transport.tunnel_synthesize_handler` (Transport.py:3208-3297). + pub(super) fn tunnel_synthesize_handler(&mut self, data: &[u8], interface_id: InterfaceId) { + let Some(entry) = self.interfaces.get_mut(&interface_id) else { + return; + }; + if !entry.tunnels_allowed() { + return; + } + if entry.tunnel.remote_transport.is_some() || entry.tunnel.synthesis_received { + debug!(interface_id, "additional tunnel synthesis"); + self.protocol_violation(interface_id); + return; + } + // One chance per connection, spent before any check. + entry.tunnel.synthesis_received = true; + let Some(synthesis) = TunnelSynthesisData::unpack(data) else { + debug!( + interface_id, + len = data.len(), + "tunnel synthesis of invalid size" + ); + self.protocol_violation(interface_id); + return; + }; + if !synthesis.is_signed() { + self.request_detach(interface_id, DetachReason::InvalidSynthesis); + return; + } + let remote_transport = synthesis.transport_identity_hash(); + if self.blackhole_table.is_blackholed(&remote_transport) { + self.request_detach(interface_id, DetachReason::BlackholedTransport); + return; + } + let remote_info = if synthesis.ext.is_empty() { + None + } else { + match RemoteTransportInfo::decode(&synthesis.ext) { + Ok(info) => Some(info), + Err(error) => { + debug!(interface_id, ?error, "invalid tunnel synthesis extension"); + self.protocol_violation(interface_id); + return; + } + } + }; + // Only an extension asks for an answer; the answer never asks again. + if remote_info.is_some() + && self + .interfaces + .get(&interface_id) + .is_some_and(|entry| !entry.tunnel.synthesis_emitted) + { + self.synthesize_tunnel(interface_id, true); + } + let Some(entry) = self.interfaces.get_mut(&interface_id) else { + return; + }; + entry.tunnel.remote_transport = Some(remote_transport); + entry.tunnel.remote_info = remote_info; + // An initiator learns its peer; only a receiver binds the tunnel. + if entry.tunnel.local_tunnel_id.is_some() { + return; + } + let tunnel_id = synthesis.tunnel_id(); + debug!( + tunnel_id = hex::encode(&tunnel_id[..16]), + interface_id, "tunnel synthesis validated" + ); + crate::tunnel::handle_tunnel(&mut self.tunnel_table, tunnel_id, interface_id); + self.state_dirty = true; + self.restore_tunnel_paths(&tunnel_id, interface_id); + } + + /// Python `_detach_interface(None, interface_instance=..., internal_forced=True)`. + /// The embedder stops the driver; without one, the actor drops the + /// interface itself. Frames from it are ignored until it is gone. + pub(super) fn request_detach(&mut self, interface_id: InterfaceId, reason: DetachReason) { + if !self.interfaces.contains_key(&interface_id) || !self.detaching.insert(interface_id) { + return; + } + tracing::info!(interface_id, ?reason, "tearing down tunnel interface"); + let sent = self.interface_control.as_ref().is_some_and(|control| { + control + .send(InterfaceControl::Detach { + interface_id, + reason, + }) + .is_ok() + }); + if !sent { + self.deregister_interface(interface_id); + } + } + + /// Python 1.6.1 `remove_blackholed_paths` also tears down every interface + /// whose tunnel peer is blackholed (Transport.py:4832-4839). + pub(super) fn detach_blackholed_tunnel_peers(&mut self) { + let blackholed: Vec = self + .interfaces + .iter() + .filter(|(_, entry)| { + entry + .tunnel + .remote_transport + .is_some_and(|remote| self.blackhole_table.is_blackholed(&remote)) + }) + .map(|(id, _)| *id) + .collect(); + for interface_id in blackholed { + self.request_detach(interface_id, DetachReason::BlackholedTransport); + } + } + + /// Frames from an interface transport asked to detach. + pub(super) fn is_detaching(&self, interface_id: InterfaceId) -> bool { + self.detaching.contains(&interface_id) + } +} diff --git a/crates/rns-transport/src/discovery/autoconnect.rs b/crates/rns-transport/src/discovery/autoconnect.rs index e0fbca2..055426a 100644 --- a/crates/rns-transport/src/discovery/autoconnect.rs +++ b/crates/rns-transport/src/discovery/autoconnect.rs @@ -43,7 +43,7 @@ pub fn qualifies(info: &DiscoveryInfo, allow_unverified: bool) -> bool { /// Python's `version_tuple`: the leading digits of each dot-separated /// component, up to the first without any (Discovery.py). -fn version_tuple(version: &str) -> Option> { +pub(crate) fn version_tuple(version: &str) -> Option> { let components: Vec = version .trim() .split('.') diff --git a/crates/rns-transport/src/messages.rs b/crates/rns-transport/src/messages.rs index db88810..22db0de 100644 --- a/crates/rns-transport/src/messages.rs +++ b/crates/rns-transport/src/messages.rs @@ -437,6 +437,7 @@ pub struct InterfaceEntry { /// Python 1.6.1 `rxb` and `frxb`: inbound frame bytes transport accepted /// or filtered, a spawned child's included in its parent's. pub(crate) received: ReceivedBytes, + pub(crate) tunnel: crate::tunnel::InterfaceTunnel, } /// Inbound frame bytes, counted once each as Python's `Transport.inbound` @@ -522,9 +523,21 @@ impl InterfaceEntry { destination_cost: None, pr_cost: None, received: ReceivedBytes::default(), + tunnel: crate::tunnel::InterfaceTunnel::default(), } } + /// Python 1.6.1 `tunnels_allowed`: only TCP, Backbone and I2P interfaces, + /// named by their driver, take a tunnel synthesis. + pub fn tunnels_allowed(&self) -> bool { + self.inspection + .as_ref() + .and_then(InterfaceInspectionSource::identity) + .is_some_and(|identity| { + crate::tunnel::TUNNEL_INTERFACE_CLASSES.contains(&identity.class_name.as_str()) + }) + } + /// Replace admission capacity without changing the separately reported `mtu`. pub fn with_packet_capacity(mut self, capacity: InterfacePacketCapacity) -> Self { self.packet_capacity = capacity; @@ -914,12 +927,22 @@ pub enum TransportMessage { SharedConnectionRestored { interface_id: InterfaceId, }, - /// Driver-built tunnel synthesis packet ready for transmission on the - /// given interface. The actor does not build these because it does not - /// hold the signing identity. + /// A client opened a connection: forget its tunnel peer and send its + /// synthesis, signed with the `SetTunnelIdentity` identity, before the + /// interface reports online (Python 1.6.1 `connect()`). SynthesizeTunnel { interface_id: InterfaceId, - raw_packet: Bytes, + }, + /// The wire-facing transport identity that signs tunnel syntheses (Python + /// `Transport.identity`). It signs only while its hash is the actor's + /// visible transport hash. + SetTunnelIdentity { + identity: Arc, + }, + /// Where the actor asks its embedder to stop an interface, as Python's + /// transport calls `_detach_interface(..., internal_forced=True)`. + SetInterfaceControl { + tx: mpsc::UnboundedSender, }, /// Register a legacy receipt for later proof matching and destination fan-out. /// An existing entry with the same truncated hash is replaced. The caller must @@ -1020,6 +1043,8 @@ pub fn msg_variant_name(msg: &TransportMessage) -> &'static str { TransportMessage::SharedConnectionLost => "SharedConnectionLost", TransportMessage::SharedConnectionRestored { .. } => "SharedConnectionRestored", TransportMessage::SynthesizeTunnel { .. } => "SynthesizeTunnel", + TransportMessage::SetTunnelIdentity { .. } => "SetTunnelIdentity", + TransportMessage::SetInterfaceControl { .. } => "SetInterfaceControl", TransportMessage::RegisterReceipt { .. } => "RegisterReceipt", TransportMessage::RegisterReceiptWithProof { .. } => "RegisterReceiptWithProof", TransportMessage::RegisterLink { .. } => "RegisterLink", @@ -1029,6 +1054,28 @@ pub fn msg_variant_name(msg: &TransportMessage) -> &'static str { } } +/// A request from the actor to the interface owner. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum InterfaceControl { + /// Stop the interface and those it spawned, whatever the interface + /// management setting; I2P listeners and local interfaces stay. + Detach { + interface_id: InterfaceId, + reason: DetachReason, + }, +} + +/// Why transport asked for a detach (Transport.py:3245-3252, :4832-4839). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum DetachReason { + /// A tunnel synthesis with an invalid signature. + InvalidSynthesis, + /// The tunnel peer's transport identity is blackholed. + BlackholedTransport, +} + /// Local introspection and mutation operations carried by `TransportMessage::Rpc`. /// These variants are not an access-control boundary. Responses describe local /// state and command results, not remote presence or persistence guarantees. @@ -1415,6 +1462,14 @@ pub struct InterfaceStatRpcEntry { pub speeds: Option<[f64; 6]>, /// Python `current_frx_speed` and `current_ftx_speed`, sampled with `speeds`. pub filtered_speeds: Option<[f64; 2]>, + /// Python `tunnel_id or local_tunnel_id`: the tunnel a peer's synthesis + /// named, or the one this client's own synthesis names. + pub tunnel_id: Option<[u8; 32]>, + /// Python `remote_transport.hash`: the transport identity of the tunnel peer. + pub remote_transport_id: Option<[u8; 16]>, + /// Python `rem_impl`, `rem_vers`, `rem_is_tn`, `rem_dst_cost` and + /// `rem_pr_cost`, from the peer's synthesis extension. + pub remote_transport: Option, /// Python `arxb`, `atxb`, `prxb` and `ptxb`. pub announce_rx_bytes: u64, pub announce_tx_bytes: u64, @@ -1761,10 +1816,15 @@ impl std::fmt::Debug for TransportMessage { .debug_struct("SharedConnectionRestored") .field("interface_id", interface_id) .finish(), - Self::SynthesizeTunnel { interface_id, .. } => f + Self::SynthesizeTunnel { interface_id } => f .debug_struct("SynthesizeTunnel") .field("interface_id", interface_id) .finish(), + Self::SetTunnelIdentity { identity } => f + .debug_struct("SetTunnelIdentity") + .field("identity_hash", &hex::encode(identity.hash)) + .finish(), + Self::SetInterfaceControl { .. } => f.write_str("SetInterfaceControl"), Self::RegisterReceipt { truncated_hash, msg_id, diff --git a/crates/rns-transport/src/tunnel.rs b/crates/rns-transport/src/tunnel.rs index abf0325..5f14d0f 100644 --- a/crates/rns-transport/src/tunnel.rs +++ b/crates/rns-transport/src/tunnel.rs @@ -83,6 +83,12 @@ impl TunnelTable { self.entries.iter_mut() } + /// Python `interface.tunnel_id`: the tunnel this interface's latest + /// synthesis named, which may since have moved or expired. + pub fn interface_tunnel(&self, interface_id: InterfaceId) -> Option<[u8; 32]> { + self.by_interface.get(&interface_id).copied() + } + /// Resolve the cached association for this interface. It can return None /// for a removed record, or a record now bound to another interface; /// neither current binding nor expiry is checked here. @@ -157,7 +163,14 @@ fn is_stale(entry: &TunnelEntry, now: f64) -> bool { entry.expires <= now || entry.expires > now + 2.0 * crate::constants::TUNNEL_TIMEOUT as f64 } -/// The 176-byte tunnel-synthesis payload, excluding the Reticulum packet header. +/// Length of the legacy synthesis payload: `public_key(64) || interface_hash(32) +/// || random_hash(16) || signature(64)`. +pub const SYNTHESIS_LEGACY_LEN: usize = 176; +/// Longest synthesis payload Python 1.6.1 accepts (`Packet.MDU`). +pub const SYNTHESIS_MAX_LEN: usize = rns_wire::constants::MDU; + +/// A tunnel-synthesis payload, excluding the Reticulum packet header: the +/// legacy 176 bytes, then Python 1.6.1's signed extension when present. #[derive(Debug, Clone)] pub struct TunnelSynthesisData { /// Transport identity key: `X25519(32) || Ed25519(32)`. @@ -167,25 +180,30 @@ pub struct TunnelSynthesisData { /// Random bytes included in the signed payload. This type does not track /// or reject replayed synthesis packets. pub random_hash: [u8; 16], - /// Ed25519 signature over `public_key || interface_hash || random_hash`. + /// Ed25519 signature over `public_key || interface_hash || random_hash || + /// ext`; it precedes `ext` on the wire. pub signature: [u8; 64], + /// The extension exactly as received; empty in the legacy form. + pub ext: Vec, } impl TunnelSynthesisData { - /// `public_key(64) || interface_hash(32) || random_hash(16) || signature(64) = 176 bytes`. + /// `public_key || interface_hash || random_hash || signature || ext`. pub fn pack(&self) -> Vec { - let mut data = Vec::with_capacity(176); + let mut data = Vec::with_capacity(SYNTHESIS_LEGACY_LEN + self.ext.len()); data.extend_from_slice(&self.public_key); data.extend_from_slice(&self.interface_hash); data.extend_from_slice(&self.random_hash); data.extend_from_slice(&self.signature); + data.extend_from_slice(&self.ext); data } - /// Parse exactly 176 bytes without verifying the signature. Call - /// [`Self::is_signed`] before treating the payload as signed. + /// Parse 176 to 464 bytes without verifying the signature, as Python + /// 1.6.1 bounds it (Transport.py:3218-3222). Call [`Self::is_signed`] + /// before treating the payload as signed. pub fn unpack(data: &[u8]) -> Option { - if data.len() != 176 { + if !(SYNTHESIS_LEGACY_LEN..=SYNTHESIS_MAX_LEN).contains(&data.len()) { return None; } let mut public_key = [0u8; 64]; @@ -202,6 +220,7 @@ impl TunnelSynthesisData { interface_hash, random_hash, signature, + ext: data[SYNTHESIS_LEGACY_LEN..].to_vec(), }) } @@ -214,20 +233,244 @@ impl TunnelSynthesisData { sha256(&tunnel_id_data) } + /// The signer's transport identity hash (Python `remote_transport.hash`). + pub fn transport_identity_hash(&self) -> [u8; 16] { + rns_crypto::sha::truncated_hash(&self.public_key) + } + /// Verify the signature under the Ed25519 half of the embedded public key. /// This does not check an external trust policy, replay state or freshness. pub fn is_signed(&self) -> bool { let Ok(signer) = rns_identity::identity::Identity::from_public_key(&self.public_key) else { return false; }; - let mut signed = Vec::with_capacity(112); + signer.verify(&self.signed_data(), &self.signature) + } + + fn signed_data(&self) -> Vec { + let mut signed = Vec::with_capacity(112 + self.ext.len()); signed.extend_from_slice(&self.public_key); signed.extend_from_slice(&self.interface_hash); signed.extend_from_slice(&self.random_hash); - signer.verify(&signed, &self.signature) + signed.extend_from_slice(&self.ext); + signed } } +/// Python 1.6.1 discovery keys of the synthesis extension (Discovery.py:50-57). +const EXT_IMPLEMENTATION: u8 = 0xFD; +const EXT_VERSION: u8 = 0xFC; +const EXT_TRANSPORT: u8 = 0x01; +const EXT_DESTINATION_COST: u8 = 0xFB; +const EXT_PR_COST: u8 = 0xFA; + +/// What a synthesis extension says about its sender (Transport.py:3172-3178). +#[derive(Debug, Clone, PartialEq)] +pub struct TunnelExt { + pub implementation: String, + pub version: String, + pub transport: bool, + pub destination_cost: f64, + pub pr_cost: f64, +} + +impl TunnelExt { + /// This stack's extension: `rsRNS`, its crate version, and the costs given. + pub fn local(transport: bool, destination_cost: f64, pr_cost: f64) -> Self { + Self { + implementation: crate::discovery::constants::IMPLEMENTATION_NAME.to_string(), + version: crate::discovery::constants::IMPLEMENTATION_VERSION.to_string(), + transport, + destination_cost, + pr_cost, + } + } + + /// Python's `umsgpack.packb(ext_info)`: a map in its insertion order, with + /// the costs as unquantized float64. + pub fn encode(&self) -> Vec { + use rmpv::Value; + let map = Value::Map(vec![ + ( + Value::from(EXT_IMPLEMENTATION), + Value::from(self.implementation.as_str()), + ), + (Value::from(EXT_VERSION), Value::from(self.version.as_str())), + (Value::from(EXT_TRANSPORT), Value::from(self.transport)), + ( + Value::from(EXT_DESTINATION_COST), + Value::F64(self.destination_cost), + ), + (Value::from(EXT_PR_COST), Value::F64(self.pr_cost)), + ]); + let mut encoded = Vec::with_capacity(48); + rmpv::encode::write_value(&mut encoded, &map).expect("writing to a Vec cannot fail"); + encoded + } +} + +/// A tunnel peer's extension as Python 1.6.1 keeps it: `remote_impl`, +/// `remote_vers`, `remote_is_tn`, and the costs quantized. +#[derive(Debug, Clone, PartialEq)] +#[non_exhaustive] +pub struct RemoteTransportInfo { + pub implementation: String, + pub version: Vec, + pub transport: bool, + pub destination_cost: f64, + pub pr_cost: f64, +} + +/// Why Python 1.6.1 counts an extension as a protocol violation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[non_exhaustive] +pub enum TunnelExtError { + Undecodable, + NotAMap, + MissingKey(u8), + InvalidImplementation, + InvalidVersion, + InvalidCost, + InvalidTransport, +} + +impl RemoteTransportInfo { + /// Python 1.6.1's extension checks (Transport.py:3255-3288), except that + /// integer costs are accepted: Python sends one for a clamped cost. + pub fn decode(ext: &[u8]) -> Result { + use rmpv::Value; + let value = + rmpv::decode::read_value(&mut &ext[..]).map_err(|_| TunnelExtError::Undecodable)?; + if !python_decodable(&value) { + return Err(TunnelExtError::Undecodable); + } + let Value::Map(entries) = value else { + return Err(TunnelExtError::NotAMap); + }; + let field = |key: u8| { + entries + .iter() + .find(|(k, _)| k.as_u64() == Some(u64::from(key))) + .map(|(_, v)| v) + .ok_or(TunnelExtError::MissingKey(key)) + }; + let (implementation, version, transport, destination_cost, pr_cost) = ( + field(EXT_IMPLEMENTATION)?, + field(EXT_VERSION)?, + field(EXT_TRANSPORT)?, + field(EXT_DESTINATION_COST)?, + field(EXT_PR_COST)?, + ); + let version = version + .as_str() + .and_then(crate::discovery::autoconnect::version_tuple) + .ok_or(TunnelExtError::InvalidVersion)?; + let implementation = implementation + .as_str() + .filter(|name| { + !name.is_empty() && crate::discovery::app_data::sanitize_name(name) == *name + }) + .ok_or(TunnelExtError::InvalidImplementation)? + .to_string(); + let cost = |value: &Value| { + let cost = match value { + Value::F64(cost) => *cost, + Value::F32(cost) => f64::from(*cost), + Value::Integer(cost) => cost.as_f64().ok_or(TunnelExtError::InvalidCost)?, + _ => return Err(TunnelExtError::InvalidCost), + }; + rns_identity::stamps::quantize_cost(cost).map_err(|_| TunnelExtError::InvalidCost) + }; + let (destination_cost, pr_cost) = (cost(destination_cost)?, cost(pr_cost)?); + let Value::Boolean(transport) = *transport else { + return Err(TunnelExtError::InvalidTransport); + }; + Ok(Self { + implementation, + version, + transport, + destination_cost, + pr_cost, + }) + } +} + +/// Whether upstream's umsgpack unpacks the value: it rejects invalid UTF-8, +/// unhashable or duplicate map keys, and timestamps of unsupported length. +fn python_decodable(value: &rmpv::Value) -> bool { + use rmpv::Value; + fn hashable(key: &Value) -> bool { + match key { + Value::Map(_) => false, + Value::Array(items) => items.iter().all(hashable), + _ => true, + } + } + // Python's dict equality: `1 == 1.0 == True`. + fn same_key(a: &Value, b: &Value) -> bool { + let number = |value: &Value| match value { + Value::Boolean(b) => Some(f64::from(u8::from(*b))), + Value::Integer(n) => n.as_f64(), + Value::F32(f) => Some(f64::from(*f)), + Value::F64(f) => Some(*f), + _ => None, + }; + match (number(a), number(b)) { + (Some(a), Some(b)) => a == b, + _ => a == b, + } + } + match value { + Value::String(s) => s.as_str().is_some(), + Value::Array(items) => items.iter().all(python_decodable), + Value::Map(entries) => entries.iter().enumerate().all(|(i, (key, item))| { + hashable(key) + && python_decodable(key) + && python_decodable(item) + && !entries[..i] + .iter() + .any(|(earlier, _)| same_key(earlier, key)) + }), + Value::Ext(-1, data) => matches!(data.len(), 4 | 8 | 12), + _ => true, + } +} + +/// Python 1.6.1's per-interface synthesis state (Interface.py:132-149), +/// kept by the transport actor. +#[derive(Debug, Clone, Default)] +pub(crate) struct InterfaceTunnel { + pub(crate) synthesis_received: bool, + pub(crate) synthesis_emitted: bool, + /// Python `local_tunnel_id`: this side initiated the tunnel. + pub(crate) local_tunnel_id: Option<[u8; 32]>, + /// Python `remote_transport`: the peer's transport identity hash. + pub(crate) remote_transport: Option<[u8; 16]>, + /// Python `remote_impl` and the rest, from the peer's extension. + pub(crate) remote_info: Option, +} + +impl InterfaceTunnel { + /// Python's `connect()`: a new connection starts without a peer, and a + /// synthesis may arrive again (TCPInterface.py:259-264). + pub(crate) fn reconnect(&mut self) { + self.synthesis_received = false; + self.remote_transport = None; + self.remote_info = None; + } +} + +/// Classes of upstream interfaces that set `tunnels_allowed` (TCPInterface.py, +/// BackboneInterface.py, I2PInterface.py). +pub const TUNNEL_INTERFACE_CLASSES: &[&str] = &[ + "TCPClientInterface", + "TCPServerInterface", + "BackboneInterface", + "BackboneClientInterface", + "I2PInterface", + "I2PInterfacePeer", +]; + /// Insert or refresh a tunnel's interface binding and eight-hour expiry, /// retaining an existing path set. The caller must validate the synthesis /// packet first; this helper accepts IDs without cryptographic checks. It @@ -255,34 +498,47 @@ pub fn handle_tunnel( } } -/// Build a tunnel-synthesis packet addressed to the well-known tunnel -/// synthesize PLAIN destination, with fresh random bytes and a signature. -/// Return `None` if the identity cannot sign. The result is a complete inner -/// Reticulum packet; interface-specific IFAC and framing remain separate. -/// The receiving transport validates the signature before installing the tunnel. +/// Build a legacy (176-byte) tunnel-synthesis packet addressed to the +/// well-known tunnel synthesize PLAIN destination, with fresh random bytes +/// and a signature. Return `None` if the identity cannot sign. The result is +/// a complete inner Reticulum packet; IFAC and framing remain separate. pub fn build_tunnel_synthesis_packet( identity: &rns_identity::identity::Identity, interface_hash: [u8; 32], ) -> Option> { - let public_key = identity.get_public_key(); + build_synthesis(identity, interface_hash, random_hash(), &[]) +} - let random_vec = rns_crypto::random::random_bytes(16); +/// Build Python 1.6.1's synthesis: the legacy fields, the signature over +/// them and `ext`, then `ext` (Transport.py:3170-3206). +pub fn build_tunnel_synthesis_packet_with_ext( + identity: &rns_identity::identity::Identity, + interface_hash: [u8; 32], + ext: &TunnelExt, +) -> Option> { + build_synthesis(identity, interface_hash, random_hash(), &ext.encode()) +} + +fn random_hash() -> [u8; 16] { let mut random_hash = [0u8; 16]; - random_hash.copy_from_slice(&random_vec); + random_hash.copy_from_slice(&rns_crypto::random::random_bytes(16)); + random_hash +} - let mut signed_data = Vec::with_capacity(112); - signed_data.extend_from_slice(&public_key); - signed_data.extend_from_slice(&interface_hash); - signed_data.extend_from_slice(&random_hash); - - let signature = identity.sign(&signed_data)?; - - let synth_data = TunnelSynthesisData { - public_key, +fn build_synthesis( + identity: &rns_identity::identity::Identity, + interface_hash: [u8; 32], + random_hash: [u8; 16], + ext: &[u8], +) -> Option> { + let mut synth_data = TunnelSynthesisData { + public_key: identity.get_public_key(), interface_hash, random_hash, - signature, + signature: [0; 64], + ext: ext.to_vec(), }; + synth_data.signature = identity.sign(&synth_data.signed_data())?; let payload = synth_data.pack(); let dest_hash = rns_identity::destination::Destination::hash_from_name_and_identity( @@ -315,6 +571,178 @@ pub fn interface_hash(name: &str) -> [u8; 32] { rns_crypto::sha::sha256(name.as_bytes()) } +/// Vectors from upstream RNS 1.6.1 (`upstream/candidate/Reticulum`, +/// `cff4d03f`): `Transport.synthesize_tunnel` with `Transport.identity` set to +/// `Identity.from_bytes(sha256(b"k4 synthesis x25519") || sha256(b"k4 +/// synthesis ed25519"))`, `Identity.get_random_hash` returning 0x01..=0x10 and +/// `Packet.send` capturing `raw`, on an interface named [`INTERFACE`]; +/// `Discovery.IMPLEMENTATION_NAME`, `RNS_VERSION` and the transport switch set +/// per vector. Handler verdicts are `Transport.tunnel_synthesize_handler` on +/// that identity's syntheses, the extension packed by `umsgpack.packb`, with +/// `handle_tunnel`, `synthesize_tunnel` and `_detach_interface` recording. +#[cfg(test)] +pub(crate) mod python_vectors { + use rns_identity::identity::Identity; + + pub(crate) const INTERFACE: &str = "TCPInterface[Uplink/127.0.0.1:4242]"; + pub(crate) const RANDOM_HASH: [u8; 16] = [ + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, + 0x10, + ]; + /// RNS 1.6.1, transport off, costs 23.5 and 15.8. + pub(crate) const PYTHON_DEFAULT: &str = "080091bf0910267b59b0e864e0d4c91602ca0008f0794e97fbd6eedd9df04166e5c30c198b130c74\ + fdd4895666a40021346a1c9fdd19fff7e6509a77783c1a531009d4f020c2ec2883533db73042a08e\ + 51f560e19a67596cb3250476ffe12dc6de8280bab299151bb67904ea30f1585377afec0102030405\ + 060708090a0b0c0d0e0f1002ef4f3c52397835b7488f72862f8ea51fc2dcf75e70b6461246d2b549\ + 9947cfd7110d6136aa867b2eba7c1fefc0d01a1be201ab41aa384d0656b9bc5bb42f0c85ccfda352\ + 4e53ccfca5312e362e3101c2ccfbcb4037800000000000ccfacb402f99999999999a"; + /// `rsRNS` 1.5.1, transport on, costs 23.5 and 15.8: what this crate sends. + pub(crate) const RUST_FORM: &str = "080091bf0910267b59b0e864e0d4c91602ca0008f0794e97fbd6eedd9df04166e5c30c198b130c74\ + fdd4895666a40021346a1c9fdd19fff7e6509a77783c1a531009d4f020c2ec2883533db73042a08e\ + 51f560e19a67596cb3250476ffe12dc6de8280bab299151bb67904ea30f1585377afec0102030405\ + 060708090a0b0c0d0e0f1027b84f07dda1787f8c9e7e2db2f5c319c1635b5035387b7fd346fcc212\ + bc7f48c368b4922ab2f06a2069e093d316c1fe656f12d14789f019c89c59c12f1d550e85ccfda572\ + 73524e53ccfca5312e352e3101c3ccfbcb4037800000000000ccfacb402f99999999999a"; + /// RNS 1.6.1, transport on, costs clamped to the ints 100 and 0 + /// (Reticulum.py:1082-1087). + pub(crate) const CLAMPED_INT_COSTS: &str = "080091bf0910267b59b0e864e0d4c91602ca0008f0794e97fbd6eedd9df04166e5c30c198b130c74\ + fdd4895666a40021346a1c9fdd19fff7e6509a77783c1a531009d4f020c2ec2883533db73042a08e\ + 51f560e19a67596cb3250476ffe12dc6de8280bab299151bb67904ea30f1585377afec0102030405\ + 060708090a0b0c0d0e0f108006150d385d236d44c722337891b3d967dada9dfd3c8bbe5fed1df450\ + fa111f91489bb4396514c41af90c38fce07e94ddc511c93cf32675b77a0c2a10acef0585ccfda352\ + 4e53ccfca5312e362e3101c3ccfb64ccfa00"; + /// `(case, Python verdict, extension, SHA-256 of the whole payload)`; the + /// `bad_signature` payload carries 64 zero bytes as its signature. + pub(crate) const HANDLER_CASES: &[(&str, &str, &str, &str)] = &[ + ( + "legacy", + "tunnel,remote", + "", + "c27ead28b4079539a2db20cc44fc4ed6faf93ae22b7f486166c8ec956532e635", + ), + ( + "extended", + "reply,tunnel,remote", + "85ccfda3524e53ccfca5312e362e3101c3ccfbcb4037800000000000ccfacb402f99999999999a", + "9564e4e54674fcba802649079accbde6a54ad79794cefa24f2a8c4c2f1f30c57", + ), + ( + "trailing_bytes", + "reply,tunnel,remote", + "85ccfda3524e53ccfca5312e362e3101c3ccfbcb4037800000000000ccfacb402f99999999999a0001", + "244394deda58b5c26b0cc7329dc71bde7147cc62f0ec0ce2a2c0b1db2fc6edb3", + ), + ( + "extra_key", + "reply,tunnel,remote", + "86ccfda3524e53ccfca5312e362e3101c3ccfbcb4037800000000000ccfacb402f99999999999a00b2544350536572766572496e74657266616365", + "2756e2841e6a0eaf6f22ab174f3fd85029f2837af8fb792faaa3d03f7d895766", + ), + ( + "missing_pr_cost", + "violation", + "84ccfda3524e53ccfca5312e362e3101c3ccfbcb4037800000000000", + "c23fe2d5db0a45de3ef5c025b19961a409d916e647401f016b05e5b42dad3826", + ), + ( + "impl_not_str", + "violation", + "85ccfdc403524e53ccfca5312e362e3101c3ccfbcb4037800000000000ccfacb402f99999999999a", + "7de2e05d50cbfb8b8cb8a182b2d4a323582dd91db1453f5fe4cad0dca66f2249", + ), + ( + "impl_unsanitary", + "violation", + "85ccfda420524e53ccfca5312e362e3101c3ccfbcb4037800000000000ccfacb402f99999999999a", + "eb57ca09b1f999f86f3cff0c66ff3fa47a1ff5cc34315ca8ca1475f1da0304ad", + ), + ( + "impl_empty", + "violation", + "85ccfda0ccfca5312e362e3101c3ccfbcb4037800000000000ccfacb402f99999999999a", + "424b4b225c5a95c27f14a4b13a171fe7ce796a705b1a06f46bb19749265daa88", + ), + ( + "version_unparsable", + "violation", + "85ccfda3524e53ccfca2763101c3ccfbcb4037800000000000ccfacb402f99999999999a", + "ecefeb8e408f6cd8001edccb739ebec9d77bf35973cdf22676421d8a670a63a0", + ), + ( + "version_prefix", + "reply,tunnel,remote", + "85ccfda3524e53ccfca5322e782e3101c3ccfbcb4037800000000000ccfacb402f99999999999a", + "e29fe380ed9b4b2f4d218e8c4627847ab1bf3223ec42411acb1b6d166402a82f", + ), + ( + "transport_int", + "violation", + "85ccfda3524e53ccfca5312e362e310101ccfbcb4037800000000000ccfacb402f99999999999a", + "978328450f982882147a148fa1be7e7445083249f602edd820e6b7e355df9993", + ), + ( + "cost_int", + "violation", + "85ccfda3524e53ccfca5312e362e3101c3ccfb64ccfacb402f99999999999a", + "342ff63da943d29d8e249ee0630b10b9bec646978e080e46c06ca00f72706f56", + ), + ( + "cost_nan", + "violation", + "85ccfda3524e53ccfca5312e362e3101c3ccfbcb4037800000000000ccfacb7ff8000000000000", + "decff860b2c53f2b0108f38fcde26d3b5cef7e52641e79e4096bfcc25fe7a2b4", + ), + ( + "ext_array", + "violation", + "920102", + "f96f2f2ac2b480f2c01d3d7b74c1489bd9bdc207d0a25bc9da5b36d764d0ad45", + ), + ( + "ext_undecodable", + "violation", + "c1", + "465b25e6078af34c7b347667fde8089769eabf58a8583f7111c6e0ebc8fdf154", + ), + ( + "duplicate_key", + "violation", + "86ccfda3524e53ccfca5312e362e3101c3ccfbcb4037800000000000ccfacb402f99999999999a01c3", + "61212eecebc63b0abbec51d26dc2be498d34802d063e1a82e14ddaad10d637b6", + ), + ( + "bad_signature", + "detach", + "85ccfda3524e53ccfca5312e362e3101c3ccfbcb4037800000000000ccfacb402f99999999999a", + "7db7d644cab200f07440b93c8e0dba96df7988366ebeaecf0e94ad2d99fe0382", + ), + ]; + + pub(crate) fn identity() -> Identity { + let key = hex::decode( + "647aa6ad267afdd5b7e0b7dd5889acd56068f5a2d93579fd37bd9f74c8d1d9e8\ + f56f0cbab4dd8721d77d087e50342fba11c40e481fab8717e83b10ef55fe5330", + ) + .unwrap(); + Identity::from_private_key(&key).unwrap() + } + + /// A case's payload as this crate signs it. + pub(crate) fn payload(name: &str, ext: &str) -> Vec { + let mut data = super::TunnelSynthesisData { + public_key: identity().get_public_key(), + interface_hash: super::interface_hash(INTERFACE), + random_hash: RANDOM_HASH, + signature: [0; 64], + ext: hex::decode(ext).unwrap(), + }; + if name != "bad_signature" { + data.signature = identity().sign(&data.signed_data()).unwrap(); + } + data.pack() + } +} + #[cfg(test)] mod tests { use super::*; @@ -334,51 +762,146 @@ mod tests { assert_eq!(table.len(), 1); } - #[test] - fn test_tunnel_synthesis_roundtrip() { - let data = TunnelSynthesisData { + fn synthesis(ext: &[u8]) -> TunnelSynthesisData { + TunnelSynthesisData { public_key: [0x42; 64], interface_hash: [0xAB; 32], random_hash: [0xCD; 16], signature: [0xEF; 64], - }; - let packed = data.pack(); - assert_eq!(packed.len(), 176); - - let unpacked = TunnelSynthesisData::unpack(&packed).unwrap(); - assert_eq!(unpacked.public_key, data.public_key); - assert_eq!(unpacked.interface_hash, data.interface_hash); - assert_eq!(unpacked.random_hash, data.random_hash); - assert_eq!(unpacked.signature, data.signature); + ext: ext.to_vec(), + } } #[test] - fn synthesis_payload_must_be_exactly_176_bytes() { - let packed = TunnelSynthesisData { - public_key: [0x42; 64], - interface_hash: [0xAB; 32], - random_hash: [0xCD; 16], - signature: [0xEF; 64], + fn test_tunnel_synthesis_roundtrip() { + for ext in [&[][..], &[0x80, 0x01, 0x02]] { + let data = synthesis(ext); + let packed = data.pack(); + assert_eq!(packed.len(), 176 + ext.len()); + let unpacked = TunnelSynthesisData::unpack(&packed).unwrap(); + assert_eq!(unpacked.public_key, data.public_key); + assert_eq!(unpacked.interface_hash, data.interface_hash); + assert_eq!(unpacked.random_hash, data.random_hash); + assert_eq!(unpacked.signature, data.signature); + assert_eq!(unpacked.ext, ext); } - .pack(); + } + + /// Python 1.6.1 takes 176 to `Packet.MDU` bytes (Transport.py:3218-3222). + #[test] + fn synthesis_payloads_run_from_176_to_464_bytes() { + let packed = synthesis(&[0; 288]).pack(); + assert_eq!(packed.len(), 464); assert!(TunnelSynthesisData::unpack(&packed).is_some()); + assert!(TunnelSynthesisData::unpack(&packed[..176]).is_some()); assert!(TunnelSynthesisData::unpack(&packed[..175]).is_none()); - let mut trailing = packed.clone(); - trailing.push(0); + let mut long = packed.clone(); + long.push(0); + assert!(TunnelSynthesisData::unpack(&long).is_none()); + } + + fn packet(hex: &str) -> (rns_wire::header::PacketHeader, TunnelSynthesisData) { + let raw = hex::decode(hex).unwrap(); + let (header, offset) = rns_wire::header::PacketHeader::unpack(&raw).unwrap(); + (header, TunnelSynthesisData::unpack(&raw[offset..]).unwrap()) + } + + /// The signature covers the extension that follows it on the wire. + #[test] + fn python_signs_the_extension_it_appends() { + let (header, mut data) = packet(python_vectors::PYTHON_DEFAULT); + assert_eq!( + header.destination_hash, + rns_identity::destination::Destination::hash_from_name_and_identity( + "rnstransport.tunnel.synthesize", + None + ) + ); + assert_eq!(data.pack().len(), 215); + assert_eq!( + hex::encode(&data.ext), + "85ccfda3524e53ccfca5312e362e3101c2ccfbcb4037800000000000ccfacb402f99999999999a" + ); + assert!(data.is_signed()); + assert_eq!( + data.transport_identity_hash(), + python_vectors::identity().hash + ); + data.ext.pop(); assert!( - TunnelSynthesisData::unpack(&trailing).is_none(), - "Python requires exactly 176 bytes (Transport.py:2791)" + !data.is_signed(), + "a truncated extension breaks the signature" + ); + } + + /// This crate's synthesis is byte for byte what upstream's encoder and + /// signer make of the same fields. + #[test] + fn rust_builds_the_synthesis_python_builds() { + let ext = TunnelExt { + implementation: "rsRNS".into(), + version: "1.5.1".into(), + transport: true, + destination_cost: 23.5, + pr_cost: 15.8, + }; + let raw = build_synthesis( + &python_vectors::identity(), + interface_hash(python_vectors::INTERFACE), + python_vectors::RANDOM_HASH, + &ext.encode(), + ) + .unwrap(); + assert_eq!(hex::encode(raw), python_vectors::RUST_FORM); + let python = TunnelExt { + implementation: "RNS".into(), + version: "1.6.1".into(), + transport: false, + ..ext + }; + let raw = build_synthesis( + &python_vectors::identity(), + interface_hash(python_vectors::INTERFACE), + python_vectors::RANDOM_HASH, + &python.encode(), + ) + .unwrap(); + assert_eq!(hex::encode(raw), python_vectors::PYTHON_DEFAULT); + assert_eq!( + TunnelExt::local(true, 1.0, 2.0).implementation, + crate::discovery::constants::IMPLEMENTATION_NAME ); } + #[test] + fn a_python_extension_decodes_to_its_remote_transport() { + let (_, data) = packet(python_vectors::PYTHON_DEFAULT); + assert_eq!( + RemoteTransportInfo::decode(&data.ext).unwrap(), + RemoteTransportInfo { + implementation: "RNS".into(), + version: vec![1, 6, 1], + transport: false, + destination_cost: rns_identity::stamps::quantize_cost(23.5).unwrap(), + pr_cost: rns_identity::stamps::quantize_cost(15.8).unwrap(), + } + ); + } + + /// Python rejects the ints its own clamp produces; costs are accepted + /// either way here (lead decision, logged as a patch candidate). + #[test] + fn integer_costs_are_accepted_and_quantized() { + let (_, data) = packet(python_vectors::CLAMPED_INT_COSTS); + assert!(data.is_signed()); + let info = RemoteTransportInfo::decode(&data.ext).unwrap(); + assert_eq!((info.destination_cost, info.pr_cost), (100.0, 0.0)); + assert!(info.transport); + } + #[test] fn test_tunnel_synthesis_id() { - let data = TunnelSynthesisData { - public_key: [0x42; 64], - interface_hash: [0xAB; 32], - random_hash: [0xCD; 16], - signature: [0xEF; 64], - }; + let data = synthesis(&[]); let id = data.tunnel_id(); assert_eq!(id.len(), 32); let id2 = data.tunnel_id();