Group data transports and add reverse TCP dialing and Shoes carriers
Let the elected opener invite its authenticated peer to dial back after a forward TCP attempt fails. Limit the reverse attempt, correlate failure replies with the active generation and cancel it on membership or policy changes. Only mutually enabled carriers with link-reverse v1 participate. Keep native TCP/TLS wire v2 and use the advertised TCP port with direct control-path or configured bootstrap IPs. Race candidate connects, bound handshakes, verify the Ed25519 SPKI and wake every link-close waiter. Add two separately versioned embedded Shoes profiles. VLESS runs over XHTTP stream-one with HTTP/2 and pinned TLS 1.3. Shadowsocks 2022 selects AES-128-GCM or AES-256-GCM per connection. Allocate a new credential and request path or salt for each attempt and admit it once through private mesh control. Both profiles terminate a local mesh service and retain the existing inner WireGuard tunnel. Attribute the adapted Shoes v0.3.8 wire code and keep its MIT license. Preferred ports are 9443 and 9444. Expose WireGuard, iroh, Native and Shoes as collapsible groups in the desktop and Android transport editor. A partial group's checkbox enables all its children. Keep the global protocol priority, save the concrete list per network and preserve explicitly saved choices including none. New networks enable all six carriers. Keep the existing CLI protocol names and unqualified port behavior. Advance local IPC to v30 for the catalog labels and groups. The existing network identity and encrypted data formats for the four original protocols stay compatible. Checked formatting, strict workspace Clippy and the full macOS workspace test suite (684 passed, 8 opted out by default). The initial sandbox denied loopback sockets. A full run also exposed an overly broad control dispatch check in the existing standalone AWG test; restoring the transport contract fixed it. Ran the opt-in upstream Shoes 0.3.8 reference test on loopback for HTTP/2 and both Shadowsocks methods. Checked Android arm64 and Windows GNU targets by cross-compilation. No live DPI or physical-device network measurements were performed.
This commit is contained in:
1 parent
68f19d1758
commit
16d7f82af5
42 files changed
+2695
-392
No files matched your search
@@ -3,7 +3,7 @@ use std::{sync::Arc, time::Instant};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tsunagi::{
|
||||
Agent, NetworkName, NetworkSecret,
|
||||
ipc::{DnsReport, PrivilegeReport, ProtocolReport, StatusReport},
|
||||
ipc::{DnsReport, PrivilegeReport, StatusReport},
|
||||
vip::VipStatus,
|
||||
};
|
||||
use tsunagi_ui::client::Command;
|
||||
@@ -302,10 +302,7 @@ async fn snapshot(
|
||||
cache_healthy: status.cache_healthy,
|
||||
available_protocols: tsunagi_runtime::PROTOCOLS
|
||||
.iter()
|
||||
.map(|spec| ProtocolReport {
|
||||
name: spec.name.into(),
|
||||
summary: spec.summary.into(),
|
||||
})
|
||||
.map(|spec| spec.report())
|
||||
.collect(),
|
||||
protocols: tsunagi_runtime::PROTOCOLS
|
||||
.iter()
|
||||
|
||||
@@ -449,16 +449,21 @@ fn broadcast_route_is_only_present_when_requested() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn all_four_desktop_carriers_register_and_each_network_keeps_its_preference() {
|
||||
async fn all_desktop_carriers_register_and_each_network_keeps_its_preference() {
|
||||
use tsunagi::{Agent, testing};
|
||||
use tsunagi_runtime::{Carriers, PROTOCOLS};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let names = ["wg", "awg", "wg-quic", "tcp-tls"];
|
||||
let names = ["wg", "awg", "wg-quic", "tcp-tls", "vless-xhttp", "ss2022"];
|
||||
assert_eq!(
|
||||
PROTOCOLS.iter().map(|spec| spec.group).collect::<Vec<_>>(),
|
||||
["WireGuard", "WireGuard", "iroh", "Native", "Shoes", "Shoes"]
|
||||
);
|
||||
let (network, secret) = testing::network("carriers");
|
||||
let (other, other_secret) = testing::network("other");
|
||||
for restart in [false, true] {
|
||||
let config = testing::local_config(dir.path());
|
||||
let (config, carriers) = Carriers::configure(config, &[], None, |spec| {
|
||||
if spec.name == "tcp-tls" {
|
||||
if matches!(spec.name, "tcp-tls" | "vless-xhttp" | "ss2022") {
|
||||
vec![("port".into(), "0".into())]
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -487,15 +492,24 @@ async fn all_four_desktop_carriers_register_and_each_network_keeps_its_preferenc
|
||||
let saved = agent.network_status(id).await.unwrap().protocols;
|
||||
if restart {
|
||||
assert_eq!(saved, ["tcp-tls", "wg"]);
|
||||
let second = agent.join_network(&other, &other_secret).await.unwrap();
|
||||
assert!(
|
||||
agent
|
||||
.network_status(second)
|
||||
.await
|
||||
.unwrap()
|
||||
.protocols
|
||||
.is_empty()
|
||||
);
|
||||
} else {
|
||||
assert_eq!(saved, names);
|
||||
agent
|
||||
.set_protocols(id, vec!["tcp-tls".into(), "wg".into()])
|
||||
.await
|
||||
.unwrap();
|
||||
let (other, secret) = testing::network("other");
|
||||
let second = agent.join_network(&other, &secret).await.unwrap();
|
||||
let second = agent.join_network(&other, &other_secret).await.unwrap();
|
||||
assert_eq!(agent.network_status(second).await.unwrap().protocols, names);
|
||||
agent.set_protocols(second, vec![]).await.unwrap();
|
||||
}
|
||||
agent.shutdown().await;
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ use super::status::{
|
||||
};
|
||||
use sync::{Changes, SyncKey};
|
||||
|
||||
mod reverse;
|
||||
mod selection;
|
||||
mod sync;
|
||||
|
||||
@@ -407,6 +408,7 @@ struct Runtime {
|
||||
/// Links currently being opened, so we do not start two.
|
||||
opening: HashSet<(EndpointId, String)>,
|
||||
link_tasks: HashMap<(EndpointId, String), tokio::task::AbortHandle>,
|
||||
reverse_dials: HashMap<(EndpointId, String), u64>,
|
||||
link_attempts: HashMap<(EndpointId, String), u64>,
|
||||
next_link_attempt: u64,
|
||||
link_results_tx: mpsc::Sender<LinkOutcome>,
|
||||
@@ -515,6 +517,7 @@ impl Runtime {
|
||||
announced_reach: HashSet::new(),
|
||||
opening: HashSet::new(),
|
||||
link_tasks: HashMap::new(),
|
||||
reverse_dials: HashMap::new(),
|
||||
link_attempts: HashMap::new(),
|
||||
next_link_attempt: 0,
|
||||
link_results_tx,
|
||||
@@ -2086,12 +2089,12 @@ impl Runtime {
|
||||
|
||||
/// Opens whatever data plane links are missing, and forgets dead ones.
|
||||
///
|
||||
/// Only one side dials, chosen by a rule both sides compute the same way,
|
||||
/// so two agents never open two links for the same thing.
|
||||
/// The smaller endpoint coordinates each attempt, including a reverse
|
||||
/// TCP dial if the negotiated carrier supports it.
|
||||
fn ensure_links(&mut self) {
|
||||
let Some(transport) = self.params.transport.clone() else {
|
||||
if self.params.transport.is_none() {
|
||||
return;
|
||||
};
|
||||
}
|
||||
let served = self.served_protocols();
|
||||
if served.is_empty() {
|
||||
return;
|
||||
@@ -2157,8 +2160,7 @@ impl Runtime {
|
||||
if self.no_direct_data(peer) {
|
||||
continue;
|
||||
}
|
||||
// The smaller endpoint id dials; the other side accepts. Both
|
||||
// compute this identically, so exactly one link is created.
|
||||
// The smaller endpoint tries first and can invite a peer to dial back.
|
||||
if self.local_id.as_bytes() >= peer.as_bytes() {
|
||||
continue;
|
||||
}
|
||||
@@ -2206,6 +2208,7 @@ impl Runtime {
|
||||
for key in interrupted {
|
||||
self.opening.remove(&key);
|
||||
self.link_attempts.remove(&key);
|
||||
self.reverse_dials.remove(&key);
|
||||
if let Some(task) = self.link_tasks.remove(&key) {
|
||||
task.abort();
|
||||
}
|
||||
@@ -2214,49 +2217,57 @@ impl Runtime {
|
||||
let trial = self.next_comparison(&served, now);
|
||||
wanted.extend(trial.iter().cloned());
|
||||
for (peer, protocol) in wanted {
|
||||
let key = (peer, protocol.clone());
|
||||
if self.links.contains_key(&key) || self.opening.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
self.opening.insert(key.clone());
|
||||
|
||||
let results = self.link_results_tx.clone();
|
||||
let transport = Arc::clone(&transport);
|
||||
let network = self.network_id;
|
||||
let shutdown = self.shutdown.clone();
|
||||
let background = trial.as_ref() == Some(&key);
|
||||
self.next_link_attempt = self.next_link_attempt.wrapping_add(1);
|
||||
let generation = self.next_link_attempt;
|
||||
self.link_attempts.insert(key.clone(), generation);
|
||||
let task = tokio::spawn(async move {
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => Err("network deactivated".to_string()),
|
||||
result = async {
|
||||
let dial = transport.open(network, peer, &protocol);
|
||||
if background {
|
||||
tokio::time::timeout(Duration::from_secs(30), dial).await
|
||||
.map_err(|_| "carrier comparison timed out".to_owned())?
|
||||
} else {
|
||||
dial.await
|
||||
}.map_err(|err| err.to_string())
|
||||
} => {
|
||||
result
|
||||
}
|
||||
};
|
||||
let _ = results
|
||||
.send(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol,
|
||||
result,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
self.link_tasks.insert(key, task.abort_handle());
|
||||
let background = trial.as_ref() == Some(&(peer, protocol.clone()));
|
||||
self.start_link_attempt(peer, protocol, background);
|
||||
}
|
||||
}
|
||||
|
||||
fn start_link_attempt(&mut self, peer: EndpointId, protocol: String, background: bool) {
|
||||
let Some(transport) = self.params.transport.clone() else {
|
||||
return;
|
||||
};
|
||||
let key = (peer, protocol.clone());
|
||||
if self.links.contains_key(&key) || self.opening.contains(&key) {
|
||||
return;
|
||||
}
|
||||
self.opening.insert(key.clone());
|
||||
|
||||
let results = self.link_results_tx.clone();
|
||||
|
||||
let network = self.network_id;
|
||||
let shutdown = self.shutdown.clone();
|
||||
|
||||
self.next_link_attempt = self.next_link_attempt.wrapping_add(1);
|
||||
let generation = self.next_link_attempt;
|
||||
self.link_attempts.insert(key.clone(), generation);
|
||||
let task = tokio::spawn(async move {
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => Err("network deactivated".to_string()),
|
||||
result = async {
|
||||
let dial = transport.open(network, peer, &protocol);
|
||||
if background {
|
||||
tokio::time::timeout(Duration::from_secs(30), dial).await
|
||||
.map_err(|_| "carrier comparison timed out".to_owned())?
|
||||
} else {
|
||||
dial.await
|
||||
}.map_err(|err| err.to_string())
|
||||
} => {
|
||||
result
|
||||
}
|
||||
};
|
||||
let _ = results
|
||||
.send(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol,
|
||||
result,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
self.link_tasks.insert(key, task.abort_handle());
|
||||
}
|
||||
|
||||
/// Takes in what another member knows about the rest.
|
||||
///
|
||||
/// Returns how many of them were new here, which is the only reason to
|
||||
@@ -2529,6 +2540,17 @@ impl Runtime {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if outcome.result.is_err() {
|
||||
if let Some(token) = self.reverse_dials.remove(&key) {
|
||||
if self.local_id > outcome.peer {
|
||||
self.send_reverse(outcome.peer, &outcome.protocol, token, false);
|
||||
}
|
||||
} else if self.ask_for_reverse(&outcome) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
self.reverse_dials.remove(&key);
|
||||
}
|
||||
self.link_attempts.remove(&key);
|
||||
self.opening.remove(&key);
|
||||
self.link_tasks.remove(&key);
|
||||
@@ -2586,6 +2608,21 @@ impl Runtime {
|
||||
inbound.link.close();
|
||||
return;
|
||||
}
|
||||
let key = (inbound.peer, inbound.protocol.clone());
|
||||
if self.local_id < inbound.peer
|
||||
&& self.can_reverse(inbound.peer, &inbound.protocol)
|
||||
&& !self.reverse_dials.contains_key(&key)
|
||||
{
|
||||
inbound.link.close();
|
||||
return;
|
||||
}
|
||||
if self.local_id < inbound.peer && self.reverse_dials.remove(&key).is_some() {
|
||||
self.link_attempts.remove(&key);
|
||||
self.opening.remove(&key);
|
||||
if let Some(task) = self.link_tasks.remove(&key) {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
self.record_protocol_success(inbound.peer, &inbound.protocol);
|
||||
self.adopt_link(inbound.peer, inbound.protocol, inbound.link);
|
||||
self.update_paths();
|
||||
@@ -2675,6 +2712,7 @@ impl Runtime {
|
||||
fn reset_peer_data(&mut self, peer: EndpointId, reason: &str) {
|
||||
self.comparisons.remove(&peer);
|
||||
self.data_errors.remove(&peer);
|
||||
self.reverse_dials.retain(|(id, _), _| *id != peer);
|
||||
self.link_attempts.retain(|(id, _), _| *id != peer);
|
||||
self.opening.retain(|(id, _)| *id != peer);
|
||||
self.link_tasks.retain(|(id, _), task| {
|
||||
@@ -2832,6 +2870,14 @@ impl Runtime {
|
||||
reason,
|
||||
});
|
||||
}
|
||||
if self
|
||||
.params
|
||||
.carriers
|
||||
.iter()
|
||||
.any(|c| c.supports_reverse_dial())
|
||||
{
|
||||
capabilities.push(reverse::capability());
|
||||
}
|
||||
if self.params.carriers.len() > 1 {
|
||||
capabilities.push(selection::capability());
|
||||
}
|
||||
@@ -3024,6 +3070,10 @@ impl Runtime {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if protocol == reverse::PROTOCOL {
|
||||
self.receive_reverse(peer, payload.as_bytes());
|
||||
return;
|
||||
}
|
||||
if protocol == selection::PROTOCOL {
|
||||
self.receive_choice(peer, payload.as_bytes());
|
||||
return;
|
||||
@@ -3152,6 +3202,14 @@ impl Runtime {
|
||||
|
||||
fn dispatch_capabilities(&mut self, peer: EndpointId, capabilities: &[PluginCapability]) {
|
||||
let mut errors = Vec::new();
|
||||
let ranges = self.params.routes.overlay_ranges();
|
||||
let ips: Vec<_> = self.sessions.get(&peer).into_iter()
|
||||
.flat_map(|session| snapshot_connection(&session.conn).paths)
|
||||
.filter_map(|path| match path.remote {
|
||||
PathAddr::Ip(addr) => Some(addr.ip().to_canonical()), _ => None,
|
||||
})
|
||||
.filter(|ip| !matches!(ip, std::net::IpAddr::V4(v4) if ranges.iter().any(|range| range.contains(*v4))))
|
||||
.take(self.params.limits.max_hints_per_peer).collect();
|
||||
for cap in capabilities {
|
||||
let carriers = self
|
||||
.params
|
||||
@@ -3162,7 +3220,7 @@ impl Runtime {
|
||||
(
|
||||
carrier.protocol_version(),
|
||||
if carrier.protocol_version() == cap.version {
|
||||
carrier.on_peer_capability(self.network_id, peer, cap)
|
||||
carrier.on_peer_capability_at(self.network_id, peer, cap, &ips)
|
||||
} else {
|
||||
Ok(())
|
||||
},
|
||||
@@ -3318,6 +3376,7 @@ impl Runtime {
|
||||
.iter()
|
||||
.filter(|cap| {
|
||||
cap.enabled
|
||||
&& cap.protocol != reverse::PROTOCOL
|
||||
&& cap.protocol != selection::PROTOCOL
|
||||
&& self
|
||||
.params
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The elected opener grants one bounded reverse dial over authenticated control.
|
||||
use super::{ControlMessage, EndpointId, LinkOutcome, PluginCapability, Runtime};
|
||||
use crate::dataplane::transport::{DataCarrier, PacketLink, TransportPayload};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub(super) const PROTOCOL: &str = "link-reverse";
|
||||
|
||||
pub(super) fn capability() -> PluginCapability {
|
||||
PluginCapability {
|
||||
protocol: PROTOCOL.into(),
|
||||
version: 1,
|
||||
enabled: true,
|
||||
data: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
fn mutual_carrier(&self, peer: EndpointId, name: &str) -> Option<&dyn DataCarrier> {
|
||||
let caps = &self.sessions.get(&peer)?.capabilities;
|
||||
self.params
|
||||
.carriers
|
||||
.iter()
|
||||
.find(|c| {
|
||||
c.protocol_id() == name
|
||||
&& caps.iter().any(|cap| {
|
||||
cap.enabled && cap.protocol == name && cap.version == c.protocol_version()
|
||||
})
|
||||
})
|
||||
.map(|c| c.as_ref())
|
||||
}
|
||||
|
||||
pub(super) fn can_reverse(&self, peer: EndpointId, protocol: &str) -> bool {
|
||||
self.mutual_carrier(peer, protocol)
|
||||
.is_some_and(|c| c.supports_reverse_dial())
|
||||
&& self.sessions.get(&peer).is_some_and(|s| {
|
||||
s.capabilities
|
||||
.iter()
|
||||
.any(|c| c.enabled && c.protocol == PROTOCOL && c.version == 1)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn send_reverse(
|
||||
&mut self,
|
||||
peer: EndpointId,
|
||||
protocol: &str,
|
||||
token: u64,
|
||||
request: bool,
|
||||
) -> bool {
|
||||
let Ok(bytes) = postcard::to_stdvec(&(request, token, protocol)) else {
|
||||
return false;
|
||||
};
|
||||
self.send_to(
|
||||
peer,
|
||||
ControlMessage::Transport {
|
||||
protocol: PROTOCOL.into(),
|
||||
payload: TransportPayload::new(bytes),
|
||||
},
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
pub(super) fn ask_for_reverse(&mut self, attempt: &LinkOutcome) -> bool {
|
||||
let peer = attempt.peer;
|
||||
let protocol = &attempt.protocol;
|
||||
let generation = attempt.generation;
|
||||
if self.local_id >= peer
|
||||
|| !self.can_reverse(peer, protocol)
|
||||
|| !self.send_reverse(peer, protocol, generation, true)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let key = (peer, protocol.clone());
|
||||
self.reverse_dials.insert(key.clone(), generation);
|
||||
let tx = self.link_results_tx.clone();
|
||||
let protocol = protocol.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(12)).await;
|
||||
let _ = tx
|
||||
.send(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol,
|
||||
result: Err("reverse TCP dial timed out".into()),
|
||||
})
|
||||
.await;
|
||||
});
|
||||
self.link_tasks.insert(key, task.abort_handle());
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn receive_reverse(&mut self, peer: EndpointId, payload: &[u8]) {
|
||||
let Ok((request, generation, protocol)) =
|
||||
postcard::from_bytes::<(bool, u64, &str)>(payload)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if protocol.len() > crate::dataplane::MAX_PROTOCOL_ID_LEN
|
||||
|| !self.can_reverse(peer, protocol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let key = (peer, protocol.to_owned());
|
||||
if request && peer < self.local_id {
|
||||
if self.opening.contains(&key) || self.links.get(&key).is_some_and(|l| !l.is_closed()) {
|
||||
return;
|
||||
}
|
||||
if self.no_direct_data(peer)
|
||||
|| self
|
||||
.protocol_dial_states
|
||||
.get(&key)
|
||||
.is_some_and(|s| s.cooldown_until > Instant::now())
|
||||
{
|
||||
self.send_reverse(peer, protocol, generation, false);
|
||||
return;
|
||||
}
|
||||
self.reverse_dials.insert(key, generation);
|
||||
self.start_link_attempt(peer, protocol.to_owned(), false);
|
||||
} else if !request
|
||||
&& self.local_id < peer
|
||||
&& self.reverse_dials.get(&key) == Some(&generation)
|
||||
{
|
||||
if let Some(task) = self.link_tasks.remove(&key) {
|
||||
task.abort();
|
||||
}
|
||||
self.handle_link_result(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol: protocol.into(),
|
||||
result: Err("neither TCP dial direction succeeded".into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,10 @@ pub trait DataCarrier: Send + Sync + std::fmt::Debug + 'static {
|
||||
fn protocol_id(&self) -> &str;
|
||||
/// Wire version, independent of software releases and the internal tunnel.
|
||||
fn protocol_version(&self) -> u16;
|
||||
/// Whether the peer may dial back after an unsuccessful elected dial.
|
||||
fn supports_reverse_dial(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// Supported carrier settings.
|
||||
fn options(&self) -> &'static [ProtocolOption] {
|
||||
&[]
|
||||
@@ -25,6 +29,17 @@ pub trait DataCarrier: Send + Sync + std::fmt::Debug + 'static {
|
||||
peer: EndpointId,
|
||||
capability: &PluginCapability,
|
||||
) -> Result<(), PluginError>;
|
||||
/// Adds IP hints from verified direct control paths. Their UDP ports do not
|
||||
/// identify a TCP listener. Carriers authenticate their own data path.
|
||||
fn on_peer_capability_at(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
capability: &PluginCapability,
|
||||
_ips: &[std::net::IpAddr],
|
||||
) -> Result<(), PluginError> {
|
||||
self.on_peer_capability(network, peer, capability)
|
||||
}
|
||||
/// Supplies the actual owned interface name, including kernel-assigned names.
|
||||
fn on_interface_ready(&self, _name: &str) {}
|
||||
/// Activates this carrier for one local network.
|
||||
|
||||
@@ -739,6 +739,10 @@ pub struct RangeConflictReport {
|
||||
/// A data-plane protocol available in the running agent.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProtocolReport {
|
||||
/// UI family of this transport.
|
||||
pub group: String,
|
||||
/// Human-readable protocol name.
|
||||
pub label: String,
|
||||
/// Stable protocol name used by the CLI and network negotiation.
|
||||
pub name: String,
|
||||
/// A short description of encryption and transport.
|
||||
@@ -1214,7 +1218,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
///
|
||||
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
||||
/// changes shape.
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 29]);
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 30]);
|
||||
|
||||
/// Reads one request off an accepted stream, answers it, writes the response.
|
||||
///
|
||||
|
||||
@@ -13,8 +13,16 @@ tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.10" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.10" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.10" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.10" }
|
||||
tsunagi-shoes = { path = "../tsunagi-shoes", version = "1.0.0" }
|
||||
tsunagi-vless-xhttp = { path = "../tsunagi-vless-xhttp", version = "1.0.0" }
|
||||
tsunagi-ss2022 = { path = "../tsunagi-ss2022", version = "1.0.0" }
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
data-encoding.workspace = true
|
||||
hex.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -10,7 +10,11 @@ use tsunagi::{
|
||||
iroh_types::EndpointAddr,
|
||||
};
|
||||
use tsunagi_awg::{AWG_PROTOCOL, AWG_WIRE_VERSION, AwgPlugin, AwgTransport};
|
||||
use tsunagi_tcp_tls::{TCP_TLS_PROTOCOL, TcpTlsCarrier, TcpTlsConfig, TcpTlsTransport};
|
||||
use tsunagi_shoes::ShoesTransport;
|
||||
use tsunagi_tcp_tls::{
|
||||
TCP_TLS_PROTOCOL, TcpCarrier, TcpTlsCarrier, TcpTlsConfig, TcpTlsTransport,
|
||||
candidates::TcpEndpoint,
|
||||
};
|
||||
use tsunagi_wireguard::WG_PROTOCOL;
|
||||
|
||||
pub mod report;
|
||||
@@ -23,6 +27,10 @@ pub mod report;
|
||||
pub struct ProtocolSpec {
|
||||
/// The name on the wire, which is what peers compare.
|
||||
pub name: &'static str,
|
||||
/// Display family; selection is still saved per protocol.
|
||||
pub group: &'static str,
|
||||
/// Compact user-facing name.
|
||||
pub label: &'static str,
|
||||
/// The wire version. Not the software version: two peers on different
|
||||
/// builds carry traffic for each other as long as this matches.
|
||||
pub version: u16,
|
||||
@@ -32,6 +40,27 @@ pub struct ProtocolSpec {
|
||||
pub options: &'static [tsunagi::dataplane::ProtocolOption],
|
||||
}
|
||||
|
||||
impl ProtocolSpec {
|
||||
/// UI metadata for the current local build.
|
||||
pub fn report(&self) -> tsunagi::ipc::ProtocolReport {
|
||||
tsunagi::ipc::ProtocolReport {
|
||||
name: self.name.into(),
|
||||
label: self.label.into(),
|
||||
group: self.group.into(),
|
||||
summary: self.summary.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fn tcp_port_option(port: &'static str) -> tsunagi::dataplane::ProtocolOption {
|
||||
tsunagi::dataplane::ProtocolOption {
|
||||
key: "port",
|
||||
value: "PORT",
|
||||
help: "local TCP listener port (0 for an available port)",
|
||||
default: Some(port),
|
||||
}
|
||||
}
|
||||
|
||||
const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::ProtocolOption {
|
||||
key: "port",
|
||||
value: "PORT",
|
||||
@@ -43,34 +72,59 @@ const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::
|
||||
pub const PROTOCOLS: &[ProtocolSpec] = &[
|
||||
ProtocolSpec {
|
||||
name: WG_PROTOCOL,
|
||||
group: "WireGuard",
|
||||
label: "WireGuard",
|
||||
version: tsunagi_wireguard::WG_WIRE_VERSION,
|
||||
summary: "Pure WireGuard direct UDP transport",
|
||||
options: WG_OPTIONS,
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: AWG_PROTOCOL,
|
||||
group: "WireGuard",
|
||||
label: "AmneziaWG",
|
||||
version: AWG_WIRE_VERSION,
|
||||
summary: "Pairwise Amnezia-masked UDP with fresh private profiles on every connection attempt",
|
||||
options: AwgPlugin::OPTIONS,
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: "wg-quic",
|
||||
group: "iroh",
|
||||
label: "WG over QUIC",
|
||||
version: 1,
|
||||
summary: "iroh QUIC datagram carrier with NAT traversal and relays",
|
||||
options: &[],
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: TCP_TLS_PROTOCOL,
|
||||
group: "Native",
|
||||
label: "TCP + TLS",
|
||||
version: tsunagi_tcp_tls::TCP_TLS_VERSION,
|
||||
summary: "TCP TLS 1.3 carrier",
|
||||
summary: "Direct TCP with TLS 1.3 pinned to the peer identity. Either peer can initiate the connection.",
|
||||
options: TcpTlsConfig::OPTIONS,
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: tsunagi_vless_xhttp::PROTOCOL,
|
||||
group: "Shoes",
|
||||
label: "VLESS + XHTTP",
|
||||
version: tsunagi_vless_xhttp::WIRE_VERSION,
|
||||
summary: "VLESS over XHTTP stream-one, HTTP/2 and TLS 1.3. Each attempt gets a fresh UUID and request path.",
|
||||
options: &[tcp_port_option("9443")],
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: tsunagi_ss2022::PROTOCOL,
|
||||
group: "Shoes",
|
||||
label: "Shadowsocks 2022",
|
||||
version: tsunagi_ss2022::WIRE_VERSION,
|
||||
summary: "Shadowsocks 2022 over TCP. Each attempt gets a fresh private key, salts, padding and a choice of AES-128-GCM or AES-256-GCM.",
|
||||
options: &[tcp_port_option("9444")],
|
||||
},
|
||||
];
|
||||
|
||||
/// Incoming direct connections to attach after the agent has acquired its identity.
|
||||
pub struct Carriers {
|
||||
udp: [Arc<AwgTransport>; 2],
|
||||
tls: Arc<TcpTlsTransport>,
|
||||
shoes: Vec<Arc<ShoesTransport>>,
|
||||
}
|
||||
|
||||
impl Carriers {
|
||||
@@ -142,20 +196,52 @@ impl Carriers {
|
||||
.await
|
||||
.map_err(|error| -> Box<dyn std::error::Error> { error })?,
|
||||
);
|
||||
for address in bootstrap {
|
||||
for ip in address.ip_addrs() {
|
||||
tls.set_peer_addr(address.id, *ip);
|
||||
}
|
||||
}
|
||||
let carrier = TcpTlsCarrier::with_interface(tls.clone(), config.interface_name.clone());
|
||||
if let Some(source) = underlay {
|
||||
carrier.set_underlay(source);
|
||||
carrier.set_bootstrap(bootstrap);
|
||||
if let Some(source) = &underlay {
|
||||
carrier.set_underlay(source.clone());
|
||||
}
|
||||
config = config
|
||||
.with_carrier(Arc::new(IrohCarrier))
|
||||
.with_carrier(carrier)
|
||||
.with_custom_transport(TCP_TLS_PROTOCOL, tls.clone());
|
||||
Ok((config, Self { udp, tls }))
|
||||
let vless = tsunagi_vless_xhttp::VlessXhttp::new(&identity)
|
||||
.map_err(|e| -> Box<dyn std::error::Error> { e })?;
|
||||
let wires: [(Arc<dyn tsunagi_shoes::ShoesWire>, u16); 2] = [
|
||||
(Arc::new(vless), tsunagi_vless_xhttp::PORT),
|
||||
(
|
||||
Arc::new(tsunagi_ss2022::Shadowsocks2022),
|
||||
tsunagi_ss2022::PORT,
|
||||
),
|
||||
];
|
||||
let mut shoes = Vec::new();
|
||||
for (wire, default_port) in wires {
|
||||
let name = wire.name();
|
||||
let mut port = None;
|
||||
for (key, value) in options_for(name) {
|
||||
if key != "port" {
|
||||
return Err(format!("unknown {name} option {key}").into());
|
||||
}
|
||||
port = Some(value.parse::<u16>()?);
|
||||
}
|
||||
let transport = ShoesTransport::bind(wire, port, default_port).await?;
|
||||
let carrier =
|
||||
TcpCarrier::with_interface(transport.clone(), config.interface_name.clone());
|
||||
carrier.set_bootstrap(bootstrap);
|
||||
if let Some(source) = &underlay {
|
||||
carrier.set_underlay(source.clone());
|
||||
}
|
||||
tracing::debug!(
|
||||
protocol = name,
|
||||
port = transport.bound_port(),
|
||||
"TCP listener ready"
|
||||
);
|
||||
config = config
|
||||
.with_carrier(carrier)
|
||||
.with_custom_transport(name, transport.clone());
|
||||
shoes.push(transport);
|
||||
}
|
||||
Ok((config, Self { udp, tls, shoes }))
|
||||
}
|
||||
|
||||
/// Accept incoming authenticated links until the caller drops the returned task set.
|
||||
@@ -172,6 +258,9 @@ impl Carriers {
|
||||
}
|
||||
});
|
||||
}
|
||||
for transport in self.shoes {
|
||||
tasks.spawn(transport.listen(agent.clone()));
|
||||
}
|
||||
let agent = agent.clone();
|
||||
tasks.spawn(async move {
|
||||
self.tls
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Optional interoperability against an independently built upstream Shoes server.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use std::{
|
||||
fs,
|
||||
process::{Child, Command, Stdio},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{TcpListener, TcpStream},
|
||||
};
|
||||
use tsunagi::identity::DeviceIdentity;
|
||||
use tsunagi_shoes::{Profile, ShoesWire};
|
||||
use tsunagi_tcp_tls::cert::generate_self_signed_cert;
|
||||
|
||||
struct Reference(Child);
|
||||
impl Drop for Reference {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
fn pem(label: &str, bytes: &[u8]) -> String {
|
||||
format!(
|
||||
"-----BEGIN {label}-----\n{}\n-----END {label}-----\n",
|
||||
data_encoding::BASE64.encode(bytes)
|
||||
)
|
||||
}
|
||||
#[tokio::test]
|
||||
#[ignore = "set TSUNAGI_SHOES_BIN to the upstream Shoes executable (v0.3.8)"]
|
||||
async fn upstream_server_accepts_stream_one_and_both_ss2022_methods() {
|
||||
let bin = std::env::var_os("TSUNAGI_SHOES_BIN").expect("upstream Shoes path");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let endpoint = DeviceIdentity::generate();
|
||||
let (cert, key) = generate_self_signed_cert(&endpoint.secret_bytes(), "localhost").unwrap();
|
||||
fs::write(
|
||||
dir.path().join("cert.pem"),
|
||||
pem("CERTIFICATE", cert.as_ref()),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
dir.path().join("key.pem"),
|
||||
pem("PRIVATE KEY", key.secret_der()),
|
||||
)
|
||||
.unwrap();
|
||||
for (is_vless, use_256) in [(true, false), (false, false), (false, true)] {
|
||||
let profile = Profile {
|
||||
tag: [0x34; 32],
|
||||
secret: [0x53; 32],
|
||||
variant: use_256,
|
||||
};
|
||||
let (wire, protocol): (Box<dyn ShoesWire>, String) = if is_vless {
|
||||
let path = hex::encode(profile.tag);
|
||||
(
|
||||
Box::new(tsunagi_vless_xhttp::VlessXhttp::new(&endpoint).unwrap()),
|
||||
format!(
|
||||
"type: tls\n default_target:\n cert: cert.pem\n key: key.pem\n alpn_protocols: [h2]\n protocol:\n type: xhttp\n path: /{path}/\n mode: stream-one\n protocol:\n type: vless\n user_id: 53535353-5353-4353-9353-535353535353"
|
||||
),
|
||||
)
|
||||
} else {
|
||||
let size = if use_256 { 32 } else { 16 };
|
||||
let key = data_encoding::BASE64.encode(&profile.secret[..size]);
|
||||
(
|
||||
Box::new(tsunagi_ss2022::Shadowsocks2022),
|
||||
format!(
|
||||
"type: shadowsocks\n cipher: 2022-blake3-aes-{}-gcm\n password: '{key}'",
|
||||
size * 8
|
||||
),
|
||||
)
|
||||
};
|
||||
let backend = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let backend_address = backend.local_addr().unwrap();
|
||||
let reservation = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = reservation.local_addr().unwrap();
|
||||
fs::write(dir.path().join("reference.yaml"), format!("- address: {address}\n protocol:\n {protocol}\n rules:\n - mask: 127.0.0.1:1\n action: allow\n override_address: {backend_address}\n client_chain: direct\n")).unwrap();
|
||||
drop(reservation);
|
||||
let mut server = Reference(
|
||||
Command::new(&bin)
|
||||
.current_dir(dir.path())
|
||||
.args(["-t", "1", "--no-reload", "reference.yaml"])
|
||||
.stdout(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
tokio::time::timeout(Duration::from_secs(15), async {
|
||||
let tcp = loop {
|
||||
assert!(
|
||||
server.0.try_wait().unwrap().is_none(),
|
||||
"reference server exited at startup"
|
||||
);
|
||||
if let Ok(tcp) = TcpStream::connect(address).await {
|
||||
break tcp;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
};
|
||||
let payload = vec![0x8c; 96 * 1024];
|
||||
let exchange = async {
|
||||
let mut stream = wire
|
||||
.connect(tcp, endpoint.endpoint_id(), &profile)
|
||||
.await
|
||||
.unwrap();
|
||||
if !is_vless {
|
||||
let mut first = [0; 4];
|
||||
stream.read_exact(&mut first).await.unwrap();
|
||||
assert_eq!(&first, b"mesh");
|
||||
}
|
||||
stream.write_all(&payload).await.unwrap();
|
||||
let mut returned = vec![0; payload.len()];
|
||||
stream.read_exact(&mut returned).await.unwrap();
|
||||
assert_eq!(payload, returned);
|
||||
};
|
||||
let service = async {
|
||||
let (mut socket, _) = backend.accept().await.unwrap();
|
||||
if !is_vless {
|
||||
socket.write_all(b"\0mesh").await.unwrap();
|
||||
}
|
||||
let mut bytes = vec![0; payload.len()];
|
||||
socket.read_exact(&mut bytes).await.unwrap();
|
||||
socket.write_all(&bytes).await.unwrap();
|
||||
};
|
||||
tokio::join!(service, exchange);
|
||||
})
|
||||
.await
|
||||
.expect("reference wire exchange timed out");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "tsunagi-shoes"
|
||||
version = "1.0.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license = "WTFPL"
|
||||
repository.workspace = true
|
||||
description = "Private per-attempt negotiation for Shoes mesh carriers."
|
||||
|
||||
[dependencies]
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util"] }
|
||||
rand = "0.10"
|
||||
zeroize = { version = "1.9", features = ["derive"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,281 @@
|
||||
//! Embedded peer-only TCP profiles. Control is supplied by the running mesh agent.
|
||||
mod profile;
|
||||
mod stream;
|
||||
use iroh::EndpointId;
|
||||
use profile::{Pair, rejected};
|
||||
pub use profile::{Profile, Profiles, Ticket};
|
||||
use std::{
|
||||
io,
|
||||
net::SocketAddr,
|
||||
sync::{Arc, OnceLock},
|
||||
time::Duration,
|
||||
};
|
||||
pub use stream::driven;
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncWrite},
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::{Semaphore, oneshot},
|
||||
task::JoinSet,
|
||||
time::timeout,
|
||||
};
|
||||
use tsunagi::{
|
||||
BoxFuture, NetworkId,
|
||||
dataplane::transport::{
|
||||
ControlSender, InboundLink, PacketTransport, SharedLink, TransportError, TransportPayload,
|
||||
},
|
||||
};
|
||||
use tsunagi_tcp_tls::{
|
||||
candidates::{TcpEndpoint, dial_candidates},
|
||||
transport::TcpTlsLink,
|
||||
};
|
||||
|
||||
/// A negotiated byte stream carrying length-prefixed mesh datagrams.
|
||||
pub trait ByteStream: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
impl<T: AsyncRead + AsyncWrite + Unpin + Send> ByteStream for T {}
|
||||
/// Owned stream returned by either side.
|
||||
pub type Stream = Box<dyn ByteStream>;
|
||||
/// A wire profile knows its own handshake and bytes, independent of reachability.
|
||||
pub trait ShoesWire: Send + Sync + 'static {
|
||||
/// Stable protocol identifier.
|
||||
fn name(&self) -> &'static str;
|
||||
/// Version compared between peers.
|
||||
fn version(&self) -> u16;
|
||||
/// Perform the client handshake.
|
||||
fn connect<'a>(
|
||||
&'a self,
|
||||
tcp: TcpStream,
|
||||
peer: EndpointId,
|
||||
profile: &'a Profile,
|
||||
) -> BoxFuture<'a, io::Result<Stream>>;
|
||||
/// Authenticate and consume an authorized incoming attempt.
|
||||
fn accept<'a>(
|
||||
&'a self,
|
||||
tcp: TcpStream,
|
||||
profiles: &'a Profiles,
|
||||
) -> BoxFuture<'a, io::Result<(Ticket, Stream)>>;
|
||||
}
|
||||
|
||||
/// A listening TCP carrier with private one-time, per-pair credentials.
|
||||
pub struct ShoesTransport {
|
||||
wire: Arc<dyn ShoesWire>,
|
||||
listener: TcpListener,
|
||||
port: u16,
|
||||
profiles: Profiles,
|
||||
control: OnceLock<Arc<dyn ControlSender>>,
|
||||
replies: Arc<Semaphore>,
|
||||
}
|
||||
impl std::fmt::Debug for ShoesTransport {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ShoesTransport")
|
||||
.field("name", &self.name())
|
||||
.field("port", &self.port)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
impl ShoesTransport {
|
||||
/// An explicitly requested port must bind; an occupied default can use a dynamic port.
|
||||
pub async fn bind(
|
||||
wire: Arc<dyn ShoesWire>,
|
||||
port: Option<u16>,
|
||||
default_port: u16,
|
||||
) -> io::Result<Arc<Self>> {
|
||||
let listener = match tsunagi_tcp_tls::candidates::listen(port.unwrap_or(default_port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) if port.is_none() && e.kind() == io::ErrorKind::AddrInUse => {
|
||||
tsunagi_tcp_tls::candidates::listen(0)?
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let port = listener.local_addr()?.port();
|
||||
Ok(Arc::new(Self {
|
||||
wire,
|
||||
listener,
|
||||
port,
|
||||
profiles: Default::default(),
|
||||
control: OnceLock::new(),
|
||||
replies: Arc::new(Semaphore::new(64)),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Drives incoming sockets and their installation, bounded by one task set.
|
||||
pub async fn listen(self: Arc<Self>, agent: tsunagi::Agent) {
|
||||
let mut tasks = JoinSet::new();
|
||||
let mut expire = tokio::time::interval(profile::LIFETIME);
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = expire.tick() => self.profiles.expire(),
|
||||
_ = tasks.join_next(), if !tasks.is_empty() => {},
|
||||
accepted = self.listener.accept(), if tasks.len() < 64 => {
|
||||
let Ok((tcp, address)) = accepted else { break; };
|
||||
let owner = self.clone();
|
||||
let agent = agent.clone();
|
||||
tasks.spawn(async move {
|
||||
let _ = tcp.set_nodelay(true);
|
||||
if let Ok(Ok((ticket, stream))) = timeout(Duration::from_secs(8), owner.wire.accept(tcp, &owner.profiles)).await {
|
||||
let (network, peer) = ticket.pair;
|
||||
let protocol = owner.wire.name();
|
||||
let link = Arc::new(TcpTlsLink::framed(protocol, network, peer, stream, address.to_string()));
|
||||
let _ = agent.install_inbound_link(InboundLink { network, peer, protocol: protocol.into(), link }).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn authorize(&self, pair: Pair) -> Result<Profile, TransportError> {
|
||||
let control = self.control.get().ok_or(TransportError::Closed)?;
|
||||
let profile = Profile::fresh();
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.profiles
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get_mut(&pair)
|
||||
.ok_or(TransportError::Closed)?
|
||||
.waiting = Some((profile.tag, tx));
|
||||
// Fixed lengths distinguish an offer (tag + secret + variant) from its receipt (tag).
|
||||
let mut bytes = Vec::with_capacity(65);
|
||||
bytes.extend_from_slice(&profile.tag);
|
||||
bytes.extend_from_slice(&profile.secret);
|
||||
bytes.push(u8::from(profile.variant));
|
||||
control
|
||||
.send(pair.0, pair.1, self.name(), TransportPayload::new(bytes))
|
||||
.await?;
|
||||
rx.await.map_err(|_| TransportError::Closed)?;
|
||||
Ok(profile)
|
||||
}
|
||||
}
|
||||
impl TcpEndpoint for ShoesTransport {
|
||||
fn wire_version(&self) -> u16 {
|
||||
self.wire.version()
|
||||
}
|
||||
fn bound_port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
fn set_pair_addresses(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
addresses: Option<Vec<SocketAddr>>,
|
||||
) {
|
||||
let mut slots = self.profiles.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
match addresses {
|
||||
Some(addresses) => slots.entry((network, peer)).or_default().addresses = addresses,
|
||||
None => {
|
||||
slots.remove(&(network, peer));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn clear_network(&self, network: NetworkId) {
|
||||
self.profiles
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.retain(|(n, _), _| *n != network);
|
||||
}
|
||||
}
|
||||
impl PacketTransport for ShoesTransport {
|
||||
fn name(&self) -> &str {
|
||||
self.wire.name()
|
||||
}
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn attach_control(&self, control: Arc<dyn ControlSender>) {
|
||||
let _ = self.control.set(control);
|
||||
}
|
||||
fn on_control(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
protocol: &str,
|
||||
bytes: &[u8],
|
||||
) -> Result<(), TransportError> {
|
||||
let bad = || TransportError::Declined("invalid Shoes negotiation".into());
|
||||
if protocol != self.name() {
|
||||
return Err(bad());
|
||||
}
|
||||
let pair = (network, peer);
|
||||
let tag: [u8; 32] = bytes
|
||||
.get(..32)
|
||||
.ok_or_else(bad)?
|
||||
.try_into()
|
||||
.map_err(|_| bad())?;
|
||||
match bytes.len() {
|
||||
32 => {
|
||||
let mut slots = self.profiles.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let slot = slots.get_mut(&pair).ok_or_else(bad)?;
|
||||
let (_, ack) = slot.waiting.take_if(|(id, _)| *id == tag).ok_or_else(bad)?;
|
||||
let _ = ack.send(());
|
||||
}
|
||||
65 if bytes[64] <= 1 => {
|
||||
let secret = bytes[32..64].try_into().map_err(|_| bad())?;
|
||||
let permit = self
|
||||
.replies
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| bad())?;
|
||||
let sender = self.control.get().ok_or_else(bad)?.clone();
|
||||
let name = self.wire.name();
|
||||
self.profiles
|
||||
.offer(
|
||||
pair,
|
||||
Profile {
|
||||
tag,
|
||||
secret,
|
||||
variant: bytes[64] == 1,
|
||||
},
|
||||
)
|
||||
.map_err(|_| bad())?;
|
||||
tokio::spawn(async move {
|
||||
let _permit = permit;
|
||||
let _ = timeout(
|
||||
Duration::from_secs(4),
|
||||
sender.send(network, peer, name, TransportPayload::new(tag.to_vec())),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
_ => return Err(bad()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn open<'a>(
|
||||
&'a self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
protocol: &'a str,
|
||||
) -> BoxFuture<'a, Result<SharedLink, TransportError>> {
|
||||
Box::pin(async move {
|
||||
if protocol != self.name() {
|
||||
return Err(TransportError::Declined(protocol.into()));
|
||||
}
|
||||
let pair = (network, peer);
|
||||
let addresses = self
|
||||
.profiles
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get(&pair)
|
||||
.map(|s| s.addresses.clone())
|
||||
.ok_or_else(|| TransportError::Unreachable(rejected().to_string()))?;
|
||||
dial_candidates(addresses, |tcp, addr| async move {
|
||||
let profile = self.authorize(pair).await?;
|
||||
let stream = self
|
||||
.wire
|
||||
.connect(tcp, peer, &profile)
|
||||
.await
|
||||
.map_err(|_| TransportError::Declined("Shoes handshake failed".into()))?;
|
||||
Ok(Arc::new(TcpTlsLink::framed(
|
||||
self.wire.name(),
|
||||
network,
|
||||
peer,
|
||||
stream,
|
||||
addr.to_string(),
|
||||
)) as SharedLink)
|
||||
})
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Single-use credentials scoped to an authenticated pair.
|
||||
use iroh::EndpointId;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io,
|
||||
net::SocketAddr,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::oneshot;
|
||||
use tsunagi::NetworkId;
|
||||
use zeroize::ZeroizeOnDrop;
|
||||
|
||||
pub(crate) type Pair = (NetworkId, EndpointId);
|
||||
pub(crate) const LIFETIME: Duration = Duration::from_secs(12);
|
||||
|
||||
/// An independently random public lookup value and private credential.
|
||||
#[derive(ZeroizeOnDrop)]
|
||||
pub struct Profile {
|
||||
/// Random request salt or XHTTP path component.
|
||||
pub tag: [u8; 32],
|
||||
/// Secret material, sent only on the already authenticated control session.
|
||||
pub secret: [u8; 32],
|
||||
/// Independent random selector for a wire profile with two supported methods.
|
||||
pub variant: bool,
|
||||
}
|
||||
impl Profile {
|
||||
pub(crate) fn fresh() -> Self {
|
||||
Self {
|
||||
tag: rand::random(),
|
||||
secret: rand::random(),
|
||||
variant: rand::random(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pair is supplied by authenticated control, never by the TCP client.
|
||||
#[derive(Clone)]
|
||||
pub struct Ticket {
|
||||
pub(crate) pair: Pair,
|
||||
/// Parameters of this connection attempt.
|
||||
pub profile: Arc<Profile>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Slot {
|
||||
pub(crate) addresses: Vec<SocketAddr>,
|
||||
incoming: Option<(Arc<Profile>, Instant)>,
|
||||
// A repeated private offer cannot reauthorize a previously accepted salt.
|
||||
recent: std::collections::VecDeque<([u8; 16], Instant)>,
|
||||
pub(crate) waiting: Option<([u8; 32], oneshot::Sender<()>)>,
|
||||
}
|
||||
|
||||
/// Bounded by enabled, authenticated memberships. At most one offer per pair.
|
||||
#[derive(Default)]
|
||||
pub struct Profiles(pub(crate) Mutex<HashMap<Pair, Slot>>);
|
||||
|
||||
impl Profiles {
|
||||
pub(crate) fn offer(&self, pair: Pair, profile: Profile) -> io::Result<()> {
|
||||
let mut slots = self.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
if slots.iter().any(|(other, slot)| {
|
||||
*other != pair
|
||||
&& slot.incoming.as_ref().is_some_and(|(p, until)| {
|
||||
*until > Instant::now() && p.tag[..16] == profile.tag[..16]
|
||||
})
|
||||
}) {
|
||||
return Err(rejected());
|
||||
}
|
||||
let slot = slots.get_mut(&pair).ok_or_else(rejected)?;
|
||||
let now = Instant::now();
|
||||
let prefix = profile.tag[..16].try_into().map_err(|_| rejected())?;
|
||||
slot.recent.retain(|(_, until)| *until > now);
|
||||
if slot.recent.len() >= 64 || slot.recent.iter().any(|(tag, _)| tag == &prefix) {
|
||||
return Err(rejected());
|
||||
}
|
||||
slot.recent
|
||||
.push_back((prefix, now + Duration::from_secs(60)));
|
||||
slot.incoming = Some((Arc::new(profile), now + LIFETIME));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve a bounded, public identifier before verifying the private credential.
|
||||
pub fn lookup(&self, tag: &[u8]) -> io::Result<Ticket> {
|
||||
if !matches!(tag.len(), 16 | 32) {
|
||||
return Err(rejected());
|
||||
}
|
||||
let slots = self.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
slots
|
||||
.iter()
|
||||
.find_map(|(pair, slot)| {
|
||||
let (p, expiry) = slot.incoming.as_ref()?;
|
||||
(p.tag.starts_with(tag) && *expiry > Instant::now()).then(|| Ticket {
|
||||
pair: *pair,
|
||||
profile: p.clone(),
|
||||
})
|
||||
})
|
||||
.ok_or_else(rejected)
|
||||
}
|
||||
/// Consume only after successful wire authentication and before acknowledging the client.
|
||||
pub fn claim(&self, ticket: &Ticket) -> io::Result<()> {
|
||||
let mut slots = self.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let slot = slots.get_mut(&ticket.pair).ok_or_else(rejected)?;
|
||||
slot.incoming
|
||||
.take_if(|(p, until)| Arc::ptr_eq(p, &ticket.profile) && *until > Instant::now())
|
||||
.map(|_| ())
|
||||
.ok_or_else(rejected)
|
||||
}
|
||||
pub(crate) fn expire(&self) {
|
||||
for slot in self
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.values_mut()
|
||||
{
|
||||
slot.incoming.take_if(|(_, until)| *until <= Instant::now());
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) fn rejected() -> io::Error {
|
||||
io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"unknown or expired connection attempt",
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn attempts_rotate_and_a_delayed_claim_cannot_consume_a_replacement() {
|
||||
let registry = Profiles::default();
|
||||
let pair = (
|
||||
NetworkId::from_bytes([12; 32]),
|
||||
tsunagi::identity::DeviceIdentity::generate().endpoint_id(),
|
||||
);
|
||||
registry.0.lock().unwrap().insert(pair, Slot::default());
|
||||
let a = Profile::fresh();
|
||||
let tag = a.tag;
|
||||
registry.offer(pair, a).unwrap();
|
||||
let old = registry.lookup(&tag).unwrap();
|
||||
let b = Profile::fresh();
|
||||
assert_ne!(old.profile.tag, b.tag);
|
||||
assert_ne!(old.profile.secret, b.secret);
|
||||
let tag = b.tag;
|
||||
registry.offer(pair, b).unwrap();
|
||||
assert!(registry.claim(&old).is_err());
|
||||
let current = registry.lookup(&tag).unwrap();
|
||||
registry.claim(¤t).unwrap();
|
||||
assert!(registry.claim(¤t).is_err());
|
||||
assert!(registry.lookup(&tag).is_err());
|
||||
let duplicate = Profile {
|
||||
tag,
|
||||
secret: current.profile.secret,
|
||||
variant: current.profile.variant,
|
||||
};
|
||||
assert!(registry.offer(pair, duplicate).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_network_expiry_and_retirement_reject_existing_tickets() {
|
||||
let registry = Profiles::default();
|
||||
let peer = tsunagi::identity::DeviceIdentity::generate().endpoint_id();
|
||||
let pair = (NetworkId::from_bytes([7; 32]), peer);
|
||||
let other = (NetworkId::from_bytes([8; 32]), peer);
|
||||
registry.0.lock().unwrap().insert(pair, Slot::default());
|
||||
assert!(registry.offer(other, Profile::fresh()).is_err());
|
||||
let offered = Profile::fresh();
|
||||
let tag = offered.tag;
|
||||
registry.offer(pair, offered).unwrap();
|
||||
let ticket = registry.lookup(&tag).unwrap();
|
||||
registry
|
||||
.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&pair)
|
||||
.unwrap()
|
||||
.incoming
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.1 = Instant::now();
|
||||
assert!(registry.lookup(&tag).is_err());
|
||||
assert!(registry.claim(&ticket).is_err());
|
||||
registry.expire();
|
||||
registry.0.lock().unwrap().remove(&pair);
|
||||
assert!(registry.claim(&ticket).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Tie an HTTP/2 connection or record driver to its negotiated stream.
|
||||
use crate::{ByteStream, Stream};
|
||||
use std::{
|
||||
future::Future,
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
|
||||
struct Driven<S> {
|
||||
inner: S,
|
||||
driver: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl<S> Drop for Driven<S> {
|
||||
fn drop(&mut self) {
|
||||
self.driver.abort();
|
||||
}
|
||||
}
|
||||
/// Closing a link cancels its driver even when the peer has stopped reading.
|
||||
pub fn driven<S: ByteStream + 'static>(
|
||||
inner: S,
|
||||
driver: impl Future<Output = ()> + Send + 'static,
|
||||
) -> Stream {
|
||||
Box::new(Driven {
|
||||
inner,
|
||||
driver: tokio::spawn(driver),
|
||||
})
|
||||
}
|
||||
impl<S: ByteStream> AsyncRead for Driven<S> {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
impl<S: ByteStream> AsyncWrite for Driven<S> {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "tsunagi-ss2022"
|
||||
version = "1.0.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license = "MIT"
|
||||
repository.workspace = true
|
||||
description = "Shadowsocks 2022 TCP transport for peer-to-peer mesh links."
|
||||
|
||||
[dependencies]
|
||||
tsunagi-shoes = { path = "../tsunagi-shoes" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util"] }
|
||||
rand = "0.10"
|
||||
ring = "0.17"
|
||||
blake3 = { version = "1.8", features = ["zeroize"] }
|
||||
zeroize = "1.9"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,20 @@
|
||||
Copyright (c) 2021-2023 Alex Lau <github@alau.ca>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Peer-only Shoes Shadowsocks 2022 TCP profile, adapted from cfal/shoes v0.3.8
|
||||
//! shadowsocks/{blake3_key,shadowsocks_stream,shadowsocks_tcp_handler}.rs (MIT).
|
||||
mod records;
|
||||
use iroh::EndpointId;
|
||||
use rand::Rng;
|
||||
use records::Records;
|
||||
use std::{
|
||||
io,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpStream,
|
||||
};
|
||||
use tsunagi::BoxFuture;
|
||||
use tsunagi_shoes::{Profile, Profiles, ShoesWire, Stream, Ticket, driven};
|
||||
|
||||
/// Fixed identity of the external carrier.
|
||||
pub const PROTOCOL: &str = "ss2022";
|
||||
/// Initial compatible wire format.
|
||||
pub const WIRE_VERSION: u16 = 1;
|
||||
/// Preferred physical port.
|
||||
pub const PORT: u16 = 9444;
|
||||
/// Both SIP022 AES-GCM methods are available.
|
||||
pub struct Shadowsocks2022;
|
||||
|
||||
// A service selector inside the encrypted request. No OS connection is opened.
|
||||
const TARGET: [u8; 7] = [1, 127, 0, 0, 1, 0, 1];
|
||||
const MAX_PADDING: usize = 900;
|
||||
const TAG: usize = 16;
|
||||
fn invalid() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "invalid Shadowsocks record")
|
||||
}
|
||||
fn now() -> io::Result<u64> {
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(io::Error::other)?
|
||||
.as_secs())
|
||||
}
|
||||
fn key_len(profile: &Profile) -> usize {
|
||||
// Independent of the secret; the private offer tells both endpoints which method to use.
|
||||
if profile.variant { 32 } else { 16 }
|
||||
}
|
||||
fn fixed(kind: u8, request_salt: &[u8], len: usize) -> io::Result<Vec<u8>> {
|
||||
let mut header = vec![kind];
|
||||
header.extend_from_slice(&now()?.to_be_bytes());
|
||||
header.extend_from_slice(request_salt);
|
||||
header.extend_from_slice(&u16::try_from(len).map_err(|_| invalid())?.to_be_bytes());
|
||||
Ok(header)
|
||||
}
|
||||
fn parse_fixed(header: &[u8], kind: u8, salt: &[u8], time: u64) -> io::Result<usize> {
|
||||
if header.len() != 11 + salt.len() || header[0] != kind || &header[9..9 + salt.len()] != salt {
|
||||
return Err(invalid());
|
||||
}
|
||||
let timestamp = u64::from_be_bytes(header[1..9].try_into().map_err(|_| invalid())?);
|
||||
if timestamp.abs_diff(time) > 30 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let n = 9 + salt.len();
|
||||
Ok(u16::from_be_bytes([header[n], header[n + 1]]) as usize)
|
||||
}
|
||||
fn record_stream(tcp: TcpStream, mut seal: Records, mut open: Records, early: Vec<u8>) -> Stream {
|
||||
let (stream, bridge) = tokio::io::duplex(64 * 1024);
|
||||
driven(stream, async move {
|
||||
let (mut net_in, mut net_out) = tcp.into_split();
|
||||
let (mut app_in, mut app_out) = tokio::io::split(bridge);
|
||||
let upload = async {
|
||||
let mut buf = vec![0; 16 * 1024];
|
||||
loop {
|
||||
let n = app_in.read(&mut buf).await?;
|
||||
if n == 0 {
|
||||
return Ok::<_, io::Error>(());
|
||||
}
|
||||
let mut frame = seal.seal(&(n as u16).to_be_bytes())?;
|
||||
frame.extend(seal.seal(&buf[..n])?);
|
||||
net_out.write_all(&frame).await?;
|
||||
}
|
||||
};
|
||||
let download = async {
|
||||
app_out.write_all(&early).await?;
|
||||
loop {
|
||||
let len = open.read(&mut net_in, 2).await?;
|
||||
let n = u16::from_be_bytes([len[0], len[1]]) as usize;
|
||||
if n == 0 {
|
||||
return Err::<(), _>(invalid());
|
||||
}
|
||||
app_out.write_all(&open.read(&mut net_in, n).await?).await?;
|
||||
}
|
||||
};
|
||||
tokio::select! { _ = upload => {}, _ = download => {} }
|
||||
})
|
||||
}
|
||||
|
||||
impl ShoesWire for Shadowsocks2022 {
|
||||
fn name(&self) -> &'static str {
|
||||
PROTOCOL
|
||||
}
|
||||
fn version(&self) -> u16 {
|
||||
WIRE_VERSION
|
||||
}
|
||||
fn connect<'a>(
|
||||
&'a self,
|
||||
mut tcp: TcpStream,
|
||||
_: EndpointId,
|
||||
p: &'a Profile,
|
||||
) -> BoxFuture<'a, io::Result<Stream>> {
|
||||
Box::pin(async move {
|
||||
let n = key_len(p);
|
||||
let salt = &p.tag[..n];
|
||||
let mut seal = Records::new(&p.secret[..n], salt)?;
|
||||
let pad: u16 = rand::random_range(1..=MAX_PADDING as u16);
|
||||
let mut body = TARGET.to_vec();
|
||||
body.extend_from_slice(&pad.to_be_bytes());
|
||||
body.resize(body.len() + usize::from(pad), 0);
|
||||
rand::rng().fill_bytes(&mut body[9..]);
|
||||
let mut first = salt.to_vec();
|
||||
first.extend(seal.seal(&fixed(0, &[], body.len())?)?);
|
||||
first.extend(seal.seal(&body)?);
|
||||
tcp.write_all(&first).await?;
|
||||
let mut response = vec![0; n + 11 + n + TAG];
|
||||
if tcp.read(&mut response).await? != response.len() {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut open = Records::new(&p.secret[..n], &response[..n])?;
|
||||
let header = open.open(response[n..].to_vec())?;
|
||||
let size = parse_fixed(&header, 1, salt, now()?)?;
|
||||
if size == 0 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let initial = open.read(&mut tcp, size).await?;
|
||||
let early = initial.strip_prefix(&[0]).ok_or_else(invalid)?;
|
||||
Ok(record_stream(tcp, seal, open, early.to_vec()))
|
||||
})
|
||||
}
|
||||
fn accept<'a>(
|
||||
&'a self,
|
||||
mut tcp: TcpStream,
|
||||
profiles: &'a Profiles,
|
||||
) -> BoxFuture<'a, io::Result<(Ticket, Stream)>> {
|
||||
Box::pin(async move {
|
||||
// Use a consistent reset on rejected or truncated first records (SIP022 §3.1.4).
|
||||
tcp.set_zero_linger()?;
|
||||
// SIP022 reads the salt and complete fixed header in one socket read.
|
||||
let mut prefix = [0u8; 32 + 11 + TAG];
|
||||
let used = tcp.read(&mut prefix).await?;
|
||||
if used < 16 + 11 + TAG {
|
||||
return Err(invalid());
|
||||
}
|
||||
let ticket = profiles.lookup(&prefix[..16])?;
|
||||
let p = &ticket.profile;
|
||||
let n = key_len(p);
|
||||
let end = n + 11 + TAG;
|
||||
if used < end || prefix[..n] != p.tag[..n] {
|
||||
return Err(invalid());
|
||||
}
|
||||
let salt = &prefix[..n];
|
||||
let key = &p.secret[..n];
|
||||
let mut open = Records::new(key, salt)?;
|
||||
let header = open.open(prefix[n..end].to_vec())?;
|
||||
let size = parse_fixed(&header, 0, &[], now()?)?;
|
||||
if size < 9 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut body = vec![0; size + TAG];
|
||||
let buffered = used - end;
|
||||
body[..buffered].copy_from_slice(&prefix[end..used]);
|
||||
tcp.read_exact(&mut body[buffered..]).await?;
|
||||
let body = open.open(body)?;
|
||||
let early = parse_target(&body)?;
|
||||
profiles.claim(&ticket)?;
|
||||
// Tokio deprecates positive linger times because they block on close.
|
||||
// Clearing the rejection-only reset restores the normal nonblocking close.
|
||||
#[allow(deprecated)]
|
||||
tcp.set_linger(None)?;
|
||||
let response_salt: [u8; 32] = rand::random();
|
||||
let mut seal = Records::new(key, &response_salt[..n])?;
|
||||
let mut response = response_salt[..n].to_vec();
|
||||
response.extend(seal.seal(&fixed(1, salt, 1)?)?);
|
||||
response.extend(seal.seal(&[0])?);
|
||||
tcp.write_all(&response).await?;
|
||||
Ok((ticket, record_stream(tcp, seal, open, early.to_vec())))
|
||||
})
|
||||
}
|
||||
}
|
||||
fn parse_target(body: &[u8]) -> io::Result<&[u8]> {
|
||||
if body.len() < 9 || body[..7] != TARGET {
|
||||
return Err(invalid());
|
||||
}
|
||||
let pad = u16::from_be_bytes([body[7], body[8]]) as usize;
|
||||
if pad > MAX_PADDING || body.len() == 9 {
|
||||
return Err(invalid());
|
||||
}
|
||||
body.get(9 + pad..).ok_or_else(invalid)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn reject_clock_skew_reflection_wrong_salt_and_wrong_service() {
|
||||
let header = fixed(1, &[8; 16], 512).unwrap();
|
||||
let time = now().unwrap();
|
||||
assert_eq!(parse_fixed(&header, 1, &[8; 16], time).unwrap(), 512);
|
||||
assert!(parse_fixed(&header, 0, &[8; 16], time).is_err());
|
||||
assert!(parse_fixed(&header, 1, &[7; 16], time).is_err());
|
||||
assert!(parse_fixed(&header, 1, &[8; 16], time + 31).is_err());
|
||||
let mut body = TARGET.to_vec();
|
||||
body.extend([0, 0]);
|
||||
assert!(parse_target(&body).is_err());
|
||||
body.extend([9]);
|
||||
assert_eq!(parse_target(&body).unwrap(), &[9]);
|
||||
body[8] = 2;
|
||||
assert!(parse_target(&body).is_err());
|
||||
body[8] = 1;
|
||||
body[4] = 2;
|
||||
assert!(parse_target(&body).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! The SIP022 record construction used by Shoes (MIT).
|
||||
use super::{TAG, invalid};
|
||||
use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey};
|
||||
use std::io;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt};
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
pub(super) struct Records {
|
||||
key: LessSafeKey,
|
||||
counter: u128,
|
||||
}
|
||||
impl Records {
|
||||
pub(super) fn new(key: &[u8], salt: &[u8]) -> io::Result<Self> {
|
||||
let algorithm = match (key.len(), salt.len()) {
|
||||
(16, 16) => &aead::AES_128_GCM,
|
||||
(32, 32) => &aead::AES_256_GCM,
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
let mut hasher = blake3::Hasher::new_derive_key("shadowsocks 2022 session subkey");
|
||||
hasher.update(key).update(salt);
|
||||
let mut subkey = Zeroizing::new([0; 32]);
|
||||
hasher.finalize_xof().fill(&mut subkey[..key.len()]);
|
||||
hasher.zeroize();
|
||||
let key = UnboundKey::new(algorithm, &subkey[..key.len()]).map_err(|_| invalid())?;
|
||||
Ok(Self {
|
||||
key: LessSafeKey::new(key),
|
||||
counter: 0,
|
||||
})
|
||||
}
|
||||
fn nonce(&mut self) -> io::Result<Nonce> {
|
||||
if self.counter >= 1 << 96 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut nonce = [0; 12];
|
||||
nonce.copy_from_slice(&self.counter.to_le_bytes()[..12]);
|
||||
self.counter += 1;
|
||||
Ok(Nonce::assume_unique_for_key(nonce))
|
||||
}
|
||||
pub(super) fn seal(&mut self, plaintext: &[u8]) -> io::Result<Vec<u8>> {
|
||||
let nonce = self.nonce()?;
|
||||
let mut buf = plaintext.to_vec();
|
||||
self.key
|
||||
.seal_in_place_append_tag(nonce, Aad::empty(), &mut buf)
|
||||
.map_err(|_| invalid())?;
|
||||
Ok(buf)
|
||||
}
|
||||
pub(super) fn open(&mut self, mut buf: Vec<u8>) -> io::Result<Vec<u8>> {
|
||||
let nonce = self.nonce()?;
|
||||
let size = self
|
||||
.key
|
||||
.open_in_place(nonce, Aad::empty(), &mut buf)
|
||||
.map_err(|_| invalid())?
|
||||
.len();
|
||||
buf.truncate(size);
|
||||
Ok(buf)
|
||||
}
|
||||
pub(super) async fn read(
|
||||
&mut self,
|
||||
r: &mut (impl AsyncRead + Unpin),
|
||||
len: usize,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
let mut buf = vec![0; len + TAG];
|
||||
r.read_exact(&mut buf).await?;
|
||||
self.open(buf)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn both_methods_authenticate_each_record_and_enforce_nonce_order() {
|
||||
for n in [16, 32] {
|
||||
let key = &[0x33; 32][..n];
|
||||
let salt = &[0x44; 32][..n];
|
||||
let mut tx = Records::new(key, salt).unwrap();
|
||||
let mut rx = Records::new(key, salt).unwrap();
|
||||
let a = tx.seal(b"ab").unwrap();
|
||||
let b = tx.seal(b"ab").unwrap();
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(rx.open(a.clone()).unwrap(), b"ab");
|
||||
assert_eq!(rx.open(b).unwrap(), b"ab");
|
||||
assert!(rx.open(a.clone()).is_err());
|
||||
let mut corrupt = a;
|
||||
corrupt[1] ^= 0x40;
|
||||
assert!(Records::new(key, salt).unwrap().open(corrupt).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,11 +13,13 @@ iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
||||
rustls = "0.23"
|
||||
tokio-rustls = "0.26"
|
||||
x509-parser = "0.18"
|
||||
rcgen = { version = "0.14", default-features = false, features = ["ring"] }
|
||||
bytes.workspace = true
|
||||
serde.workspace = true
|
||||
postcard.workspace = true
|
||||
tracing.workspace = true
|
||||
socket2 = "0.6"
|
||||
netdev = "0.46"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Bounded address selection shared by native TCP carriers.
|
||||
use iroh::EndpointId;
|
||||
use std::{collections::HashMap, net::SocketAddr, sync::Mutex, time::Duration};
|
||||
use tokio::{
|
||||
net::TcpStream,
|
||||
task::JoinSet,
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
use tsunagi::{
|
||||
NetworkId,
|
||||
dataplane::transport::{PacketTransport, SharedLink, TransportError},
|
||||
};
|
||||
|
||||
/// TCP service registered on its own port, using authenticated, per-network announcements.
|
||||
pub trait TcpEndpoint: PacketTransport {
|
||||
/// Independent version of the data carrier.
|
||||
fn wire_version(&self) -> u16;
|
||||
/// Actual bound TCP port.
|
||||
fn bound_port(&self) -> u16;
|
||||
/// Replace reachability for one membership; an empty list still permits reverse dialing.
|
||||
fn set_pair_addresses(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
addresses: Option<Vec<SocketAddr>>,
|
||||
);
|
||||
/// Retire candidates and negotiations belonging to this network.
|
||||
fn clear_network(&self, network: NetworkId);
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Candidates {
|
||||
pub(crate) pairs: Mutex<HashMap<(NetworkId, EndpointId), Vec<SocketAddr>>>,
|
||||
pub(crate) manual: Mutex<HashMap<EndpointId, Vec<SocketAddr>>>,
|
||||
}
|
||||
|
||||
/// Stagger TCP connects so a stale LAN address cannot hide a reachable candidate.
|
||||
/// Only one connected socket at a time negotiates a link with the remote peer.
|
||||
pub async fn dial_candidates<F, Fut>(
|
||||
addresses: Vec<SocketAddr>,
|
||||
mut authenticate: F,
|
||||
) -> Result<SharedLink, TransportError>
|
||||
where
|
||||
F: FnMut(TcpStream, SocketAddr) -> Fut,
|
||||
Fut: Future<Output = Result<SharedLink, TransportError>>,
|
||||
{
|
||||
timeout(Duration::from_secs(8), async {
|
||||
let mut connects = JoinSet::new();
|
||||
for (i, addr) in addresses.into_iter().take(32).enumerate() {
|
||||
connects.spawn(async move {
|
||||
sleep(Duration::from_millis(60 * i as u64)).await;
|
||||
let socket = timeout(Duration::from_secs(3), TcpStream::connect(addr))
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
Some((socket, addr))
|
||||
});
|
||||
}
|
||||
let mut error = TransportError::Unreachable("no reachable TCP listener for peer".into());
|
||||
while let Some(result) = connects.join_next().await {
|
||||
if let Ok(Some((socket, addr))) = result {
|
||||
let _ = socket.set_nodelay(true);
|
||||
match timeout(Duration::from_secs(4), authenticate(socket, addr)).await {
|
||||
Ok(Ok(link)) => return Ok(link),
|
||||
Ok(Err(err)) => error = err,
|
||||
Err(_) => error = TransportError::Unreachable("TCP handshake timed out".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| TransportError::Unreachable("TCP dial timed out".into()))?
|
||||
}
|
||||
|
||||
/// Bind one port for both address families where the host supports dual-stack TCP.
|
||||
pub fn listen(port: u16) -> std::io::Result<tokio::net::TcpListener> {
|
||||
use socket2::{Domain, Socket, Type};
|
||||
let ipv6 = || -> std::io::Result<std::net::TcpListener> {
|
||||
let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?;
|
||||
socket.set_only_v6(false)?;
|
||||
socket.bind(&SocketAddr::from((std::net::Ipv6Addr::UNSPECIFIED, port)).into())?;
|
||||
socket.listen(128)?;
|
||||
Ok(socket.into())
|
||||
};
|
||||
let socket =
|
||||
ipv6().or_else(|_| std::net::TcpListener::bind((std::net::Ipv4Addr::UNSPECIFIED, port)))?;
|
||||
socket.set_nonblocking(true)?;
|
||||
tokio::net::TcpListener::from_std(socket)
|
||||
}
|
||||
@@ -33,14 +33,15 @@ impl ServerCertVerifier for PinnedEndpointVerifier {
|
||||
_ocsp_response: &[u8],
|
||||
_now: UnixTime,
|
||||
) -> Result<ServerCertVerified, RustlsError> {
|
||||
// Parse the certificate's SPKI / public key
|
||||
let cert_bytes = end_entity.as_ref();
|
||||
let expected_bytes = self.expected.as_bytes();
|
||||
|
||||
// Check if the expected 32-byte Ed25519 public key is in the certificate
|
||||
if cert_bytes
|
||||
.windows(32)
|
||||
.any(|window| window == expected_bytes)
|
||||
use x509_parser::prelude::{FromDer, X509Certificate};
|
||||
let (rest, cert) = X509Certificate::from_der(end_entity.as_ref())
|
||||
.map_err(|_| RustlsError::InvalidCertificate(rustls::CertificateError::BadEncoding))?;
|
||||
let key = cert.public_key();
|
||||
if rest.is_empty()
|
||||
&& key.algorithm.algorithm == x509_parser::oid_registry::OID_SIG_ED25519
|
||||
&& key.algorithm.parameters.is_none()
|
||||
&& key.subject_public_key.unused_bits == 0
|
||||
&& key.subject_public_key.data.as_ref() == self.expected.as_bytes()
|
||||
{
|
||||
Ok(ServerCertVerified::assertion())
|
||||
} else {
|
||||
@@ -126,7 +127,7 @@ pub fn make_server_config(
|
||||
) -> Result<Arc<ServerConfig>, rustls::Error> {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let mut config = ServerConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()?
|
||||
.with_protocol_versions(&[&rustls::version::TLS13])?
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![cert], key)?;
|
||||
config.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
@@ -138,7 +139,7 @@ pub fn make_client_config(expected_peer: EndpointId) -> Result<Arc<ClientConfig>
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let verifier = Arc::new(PinnedEndpointVerifier::new(expected_peer));
|
||||
let mut config = ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()?
|
||||
.with_protocol_versions(&[&rustls::version::TLS13])?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(verifier)
|
||||
.with_no_client_auth();
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! TCP TLS 1.3 carrier for opaque, independently encrypted mesh datagrams.
|
||||
pub mod candidates;
|
||||
pub mod cert;
|
||||
pub mod plugin;
|
||||
pub mod transport;
|
||||
pub use plugin::{
|
||||
TCP_TLS_PROTOCOL, TCP_TLS_VERSION, TcpTlsCarrier, TcpTlsConfig, local_ip_candidates,
|
||||
TCP_TLS_PROTOCOL, TCP_TLS_VERSION, TcpCarrier, TcpTlsCarrier, TcpTlsConfig, local_ip_candidates,
|
||||
};
|
||||
pub use transport::TcpTlsTransport;
|
||||
@@ -1,5 +1,5 @@
|
||||
//! TLS carrier options and bounded reachability announcements. No IP cipher lives here.
|
||||
use crate::transport::TcpTlsTransport;
|
||||
use crate::{candidates::TcpEndpoint, transport::TcpTlsTransport};
|
||||
use iroh::EndpointId;
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
@@ -138,7 +138,12 @@ pub(crate) fn is_candidate_interface(iface: &netdev::Interface) -> bool {
|
||||
}
|
||||
|
||||
pub(crate) fn is_candidate_ipv4(addr: std::net::Ipv4Addr) -> bool {
|
||||
if addr.is_loopback() || addr.is_unspecified() || addr.is_link_local() || addr.is_broadcast() {
|
||||
if addr.is_multicast()
|
||||
|| addr.is_loopback()
|
||||
|| addr.is_unspecified()
|
||||
|| addr.is_link_local()
|
||||
|| addr.is_broadcast()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if addr.is_documentation() {
|
||||
@@ -151,7 +156,7 @@ pub(crate) fn is_candidate_ip(addr: std::net::IpAddr) -> bool {
|
||||
match addr {
|
||||
std::net::IpAddr::V4(v4) => is_candidate_ipv4(v4),
|
||||
std::net::IpAddr::V6(v6) => {
|
||||
if v6.is_loopback() || v6.is_unspecified() {
|
||||
if v6.is_multicast() || v6.is_loopback() || v6.is_unspecified() {
|
||||
return false;
|
||||
}
|
||||
let segments = v6.segments();
|
||||
@@ -230,71 +235,65 @@ impl TcpTlsConfig {
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
/// TLS carrier announcements and lifecycle, independent of IP encryption.
|
||||
/// Native TLS carrier, retaining the original registration API.
|
||||
pub type TcpTlsCarrier = TcpCarrier<TcpTlsTransport>;
|
||||
|
||||
/// Bounded TCP address announcements shared by carriers with independent listeners.
|
||||
#[derive(Debug)]
|
||||
pub struct TcpTlsCarrier {
|
||||
transport: Arc<TcpTlsTransport>,
|
||||
pub struct TcpCarrier<T> {
|
||||
transport: Arc<T>,
|
||||
excluded_interface: std::sync::Mutex<Option<String>>,
|
||||
bootstrap: std::sync::OnceLock<std::collections::HashMap<EndpointId, Vec<std::net::IpAddr>>>,
|
||||
underlay: std::sync::OnceLock<tokio::sync::watch::Receiver<Vec<std::net::IpAddr>>>,
|
||||
peers: std::sync::Mutex<
|
||||
std::collections::HashMap<(NetworkId, EndpointId), Vec<std::net::SocketAddr>>,
|
||||
>,
|
||||
}
|
||||
impl TcpTlsCarrier {
|
||||
/// Shares the transport's listener; creates no end-to-end cipher.
|
||||
pub fn new(transport: Arc<TcpTlsTransport>) -> Arc<Self> {
|
||||
impl<T: TcpEndpoint> TcpCarrier<T> {
|
||||
/// Announces the actual listener's port.
|
||||
pub fn new(transport: Arc<T>) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
transport,
|
||||
excluded_interface: std::sync::Mutex::new(None),
|
||||
excluded_interface: Default::default(),
|
||||
bootstrap: Default::default(),
|
||||
underlay: Default::default(),
|
||||
peers: Default::default(),
|
||||
})
|
||||
}
|
||||
/// Registers a carrier while excluding the agent's own, possibly custom-named interface.
|
||||
pub fn with_interface(transport: Arc<TcpTlsTransport>, interface: String) -> Arc<Self> {
|
||||
/// Excludes the agent's own interface from physical addresses.
|
||||
pub fn with_interface(transport: Arc<T>, interface: String) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
transport,
|
||||
excluded_interface: std::sync::Mutex::new(Some(interface)),
|
||||
bootstrap: Default::default(),
|
||||
underlay: Default::default(),
|
||||
peers: Default::default(),
|
||||
})
|
||||
}
|
||||
/// Bootstrap IPs can be candidates for this peer's separately announced TCP port.
|
||||
pub fn set_bootstrap(&self, endpoints: &[iroh::EndpointAddr]) {
|
||||
let _ = self.bootstrap.set(
|
||||
endpoints
|
||||
.iter()
|
||||
.map(|endpoint| {
|
||||
(
|
||||
endpoint.id,
|
||||
endpoint.ip_addrs().take(32).map(|a| a.ip()).collect(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
/// Use only the addresses assigned to the OS-selected physical network.
|
||||
pub fn set_underlay(&self, source: tokio::sync::watch::Receiver<Vec<std::net::IpAddr>>) {
|
||||
let _ = self.underlay.set(source);
|
||||
}
|
||||
fn update_peer(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
addrs: Option<Vec<std::net::SocketAddr>>,
|
||||
) {
|
||||
let mut peers = self.peers.lock().unwrap_or_else(|p| p.into_inner());
|
||||
match addrs {
|
||||
Some(addrs) => {
|
||||
peers.insert((network, peer), addrs);
|
||||
}
|
||||
None => {
|
||||
peers.remove(&(network, peer));
|
||||
}
|
||||
}
|
||||
let mut combined = peers
|
||||
.iter()
|
||||
.filter(|((_, id), _)| *id == peer)
|
||||
.flat_map(|(_, addrs)| addrs.iter().copied())
|
||||
.collect::<Vec<_>>();
|
||||
combined.sort_unstable();
|
||||
combined.dedup();
|
||||
combined.truncate(32);
|
||||
self.transport.replace_peer_addrs(peer, combined);
|
||||
}
|
||||
}
|
||||
impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||
|
||||
impl<T: TcpEndpoint> tsunagi::dataplane::transport::DataCarrier for TcpCarrier<T> {
|
||||
fn protocol_id(&self) -> &str {
|
||||
TCP_TLS_PROTOCOL
|
||||
self.transport.name()
|
||||
}
|
||||
fn protocol_version(&self) -> u16 {
|
||||
2
|
||||
self.transport.wire_version()
|
||||
}
|
||||
fn supports_reverse_dial(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn on_interface_ready(&self, name: &str) {
|
||||
*self
|
||||
@@ -324,10 +323,10 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||
self.transport.bound_port(),
|
||||
ips.into_iter().take(32).collect::<Vec<_>>(),
|
||||
))
|
||||
.map_err(|_| PluginError::Other("cannot encode TLS addresses".into()))?;
|
||||
.map_err(|_| PluginError::Other("cannot encode TCP addresses".into()))?;
|
||||
Ok(Some(tsunagi::dataplane::PluginCapability {
|
||||
protocol: TCP_TLS_PROTOCOL.into(),
|
||||
version: 2,
|
||||
protocol: self.protocol_id().into(),
|
||||
version: self.protocol_version(),
|
||||
enabled: true,
|
||||
data,
|
||||
}))
|
||||
@@ -338,8 +337,20 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||
peer: EndpointId,
|
||||
cap: &tsunagi::dataplane::PluginCapability,
|
||||
) -> Result<(), PluginError> {
|
||||
if !cap.enabled || cap.protocol != TCP_TLS_PROTOCOL || cap.version != 2 {
|
||||
return Err(PluginError::Rejected("unsupported TLS carrier".into()));
|
||||
self.on_peer_capability_at(network, peer, cap, &[])
|
||||
}
|
||||
fn on_peer_capability_at(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
cap: &tsunagi::dataplane::PluginCapability,
|
||||
observed: &[std::net::IpAddr],
|
||||
) -> Result<(), PluginError> {
|
||||
if !cap.enabled
|
||||
|| cap.protocol != self.protocol_id()
|
||||
|| cap.version != self.protocol_version()
|
||||
{
|
||||
return Err(PluginError::Rejected("unsupported TCP carrier".into()));
|
||||
}
|
||||
// Decode a fixed bounded array through the existing common announcement limit.
|
||||
#[derive(Deserialize)]
|
||||
@@ -348,37 +359,36 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||
#[serde(deserialize_with = "bounded_ips")] Vec<std::net::IpAddr>,
|
||||
);
|
||||
let Addresses(port, ips) = postcard::from_bytes(&cap.data)
|
||||
.map_err(|_| PluginError::Rejected("invalid TLS carrier addresses".into()))?;
|
||||
.map_err(|_| PluginError::Rejected("invalid TCP carrier addresses".into()))?;
|
||||
if port == 0 {
|
||||
return Err(PluginError::Rejected("invalid TLS carrier port".into()));
|
||||
return Err(PluginError::Rejected("invalid TCP carrier port".into()));
|
||||
}
|
||||
self.update_peer(
|
||||
network,
|
||||
peer,
|
||||
Some(
|
||||
ips.into_iter()
|
||||
.filter(|ip| is_candidate_ip(*ip))
|
||||
.map(|ip| std::net::SocketAddr::new(ip, port))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
let configured = self.bootstrap.get().and_then(|peers| peers.get(&peer));
|
||||
let mut addresses = Vec::new();
|
||||
for ip in observed
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(configured.into_iter().flatten().copied())
|
||||
.chain(ips)
|
||||
{
|
||||
let ip = ip.to_canonical();
|
||||
let addr = std::net::SocketAddr::new(ip, port);
|
||||
if is_candidate_ip(ip) && !addresses.contains(&addr) {
|
||||
addresses.push(addr);
|
||||
}
|
||||
if addresses.len() == 32 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.transport
|
||||
.set_pair_addresses(network, peer, Some(addresses));
|
||||
Ok(())
|
||||
}
|
||||
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId) {
|
||||
self.update_peer(network, peer, None);
|
||||
self.transport.set_pair_addresses(network, peer, None);
|
||||
}
|
||||
fn on_network_deactivated(&self, network: NetworkId) {
|
||||
let peers: Vec<_> = self
|
||||
.peers
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.keys()
|
||||
.filter(|(id, _)| *id == network)
|
||||
.map(|(_, peer)| *peer)
|
||||
.collect();
|
||||
for peer in peers {
|
||||
self.update_peer(network, peer, None);
|
||||
}
|
||||
self.transport.clear_network(network);
|
||||
}
|
||||
}
|
||||
fn bounded_ips<'de, D: serde::Deserializer<'de>>(
|
||||
|
||||
@@ -3,17 +3,16 @@
|
||||
//! Provides [`TcpTlsTransport`] implementing [`PacketTransport`]
|
||||
//! and [`TcpTlsLink`] implementing [`PacketLink`].
|
||||
|
||||
use std::collections::HashMap;
|
||||
use crate::candidates::{Candidates, TcpEndpoint, dial_candidates};
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use iroh::{EndpointId, Signature};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::{Notify, mpsc};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_rustls::TlsConnector;
|
||||
|
||||
use tsunagi::BoxFuture;
|
||||
@@ -116,14 +115,27 @@ pub struct TcpTlsLink {
|
||||
tx: mpsc::Sender<Bytes>,
|
||||
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
||||
tasks: [tokio::task::AbortHandle; 2],
|
||||
closed_notify: Arc<Notify>,
|
||||
is_closed: Arc<AtomicBool>,
|
||||
closed: watch::Sender<bool>,
|
||||
remote_addr: String,
|
||||
protocol: &'static str,
|
||||
}
|
||||
|
||||
impl TcpTlsLink {
|
||||
/// Creates a new `TcpTlsLink` from a stream that has already passed the TLS handshake.
|
||||
pub fn new<S>(network: NetworkId, peer: EndpointId, stream: S, remote_addr: String) -> Self
|
||||
where
|
||||
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static,
|
||||
{
|
||||
Self::framed("tcp-tls", network, peer, stream, remote_addr)
|
||||
}
|
||||
/// Frames opaque mesh datagrams on a mutually authenticated carrier stream.
|
||||
pub fn framed<S>(
|
||||
protocol: &'static str,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
stream: S,
|
||||
remote_addr: String,
|
||||
) -> Self
|
||||
where
|
||||
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static,
|
||||
{
|
||||
@@ -132,11 +144,8 @@ impl TcpTlsLink {
|
||||
let (tx_out, mut rx_out) = mpsc::channel::<Bytes>(256);
|
||||
let (tx_in, rx_in) = mpsc::channel::<Bytes>(256);
|
||||
|
||||
let is_closed = Arc::new(AtomicBool::new(false));
|
||||
let closed_notify = Arc::new(Notify::new());
|
||||
|
||||
let closed_flag_w = Arc::clone(&is_closed);
|
||||
let closed_notify_w = Arc::clone(&closed_notify);
|
||||
let (closed, _) = watch::channel(false);
|
||||
let writer_closed = closed.clone();
|
||||
let writer_task = tokio::spawn(async move {
|
||||
while let Some(msg) = rx_out.recv().await {
|
||||
if msg.len() > MAX_FRAME_SIZE {
|
||||
@@ -153,12 +162,10 @@ impl TcpTlsLink {
|
||||
break;
|
||||
}
|
||||
}
|
||||
closed_flag_w.store(true, Ordering::Release);
|
||||
closed_notify_w.notify_waiters();
|
||||
writer_closed.send_replace(true);
|
||||
});
|
||||
|
||||
let closed_flag_r = Arc::clone(&is_closed);
|
||||
let closed_notify_r = Arc::clone(&closed_notify);
|
||||
let reader_closed = closed.clone();
|
||||
let reader_task = tokio::spawn(async move {
|
||||
let mut len_buf = [0u8; 2];
|
||||
loop {
|
||||
@@ -177,8 +184,7 @@ impl TcpTlsLink {
|
||||
break;
|
||||
}
|
||||
}
|
||||
closed_flag_r.store(true, Ordering::Release);
|
||||
closed_notify_r.notify_waiters();
|
||||
reader_closed.send_replace(true);
|
||||
});
|
||||
|
||||
Self {
|
||||
@@ -187,9 +193,9 @@ impl TcpTlsLink {
|
||||
tx: tx_out,
|
||||
rx: tokio::sync::Mutex::new(rx_in),
|
||||
tasks: [writer_task.abort_handle(), reader_task.abort_handle()],
|
||||
closed_notify,
|
||||
is_closed,
|
||||
closed,
|
||||
remote_addr,
|
||||
protocol,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,8 +207,7 @@ impl Drop for TcpTlsLink {
|
||||
}
|
||||
impl PacketLink for TcpTlsLink {
|
||||
fn close(&self) {
|
||||
self.is_closed.store(true, Ordering::Release);
|
||||
self.closed_notify.notify_waiters();
|
||||
self.closed.send_replace(true);
|
||||
for task in &self.tasks {
|
||||
task.abort();
|
||||
}
|
||||
@@ -226,7 +231,7 @@ impl PacketLink for TcpTlsLink {
|
||||
limit: MAX_FRAME_SIZE,
|
||||
});
|
||||
}
|
||||
if self.is_closed.load(Ordering::Acquire) {
|
||||
if *self.closed.borrow() {
|
||||
return Err(TransportError::Closed);
|
||||
}
|
||||
self.tx
|
||||
@@ -243,19 +248,16 @@ impl PacketLink for TcpTlsLink {
|
||||
|
||||
fn closed(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
if self.is_closed.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
self.closed_notify.notified().await;
|
||||
let _ = self.closed.subscribe().wait_for(|closed| *closed).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn is_closed(&self) -> bool {
|
||||
self.is_closed.load(Ordering::Acquire)
|
||||
*self.closed.borrow()
|
||||
}
|
||||
|
||||
fn path_description(&self) -> String {
|
||||
format!("tcp-tls via {}", self.remote_addr)
|
||||
format!("{} via {}", self.protocol, self.remote_addr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,7 +267,7 @@ pub struct TcpTlsTransport {
|
||||
local_id: EndpointId,
|
||||
listen_port: u16,
|
||||
sni: String,
|
||||
peer_addresses: std::sync::RwLock<HashMap<EndpointId, Vec<SocketAddr>>>,
|
||||
peer_addresses: Candidates,
|
||||
server_config: Arc<rustls::ServerConfig>,
|
||||
listener: Option<Arc<TcpListener>>,
|
||||
}
|
||||
@@ -348,7 +350,6 @@ impl TcpTlsTransport {
|
||||
let server_config = make_server_config(cert, key)?;
|
||||
|
||||
let target_port = requested_port.unwrap_or(DEFAULT_PORT);
|
||||
let bind_addr = SocketAddr::from(([0, 0, 0, 0], target_port));
|
||||
|
||||
let bind_result = {
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -358,13 +359,11 @@ impl TcpTlsTransport {
|
||||
None
|
||||
};
|
||||
|
||||
std::net::TcpListener::bind(bind_addr)
|
||||
crate::candidates::listen(target_port)
|
||||
};
|
||||
|
||||
let listener = match bind_result {
|
||||
Ok(std_listener) => {
|
||||
std_listener.set_nonblocking(true)?;
|
||||
let l = TcpListener::from_std(std_listener)?;
|
||||
Ok(l) => {
|
||||
tracing::info!(port = target_port, "TCP TLS listening");
|
||||
Some(Arc::new(l))
|
||||
}
|
||||
@@ -391,8 +390,7 @@ impl TcpTlsTransport {
|
||||
);
|
||||
}
|
||||
|
||||
let fallback_addr = SocketAddr::from(([0, 0, 0, 0], FALLBACK_PORT));
|
||||
match TcpListener::bind(fallback_addr).await {
|
||||
match crate::candidates::listen(FALLBACK_PORT) {
|
||||
Ok(l) => {
|
||||
tracing::info!(port = FALLBACK_PORT, "TCP TLS listening on fallback port");
|
||||
Some(Arc::new(l))
|
||||
@@ -404,8 +402,7 @@ impl TcpTlsTransport {
|
||||
"Cannot bind to fallback port {FALLBACK_PORT}: {fallback_err}. \
|
||||
Falling back to ephemeral port."
|
||||
);
|
||||
let ephemeral_addr = SocketAddr::from(([0, 0, 0, 0], 0));
|
||||
let l = TcpListener::bind(ephemeral_addr).await?;
|
||||
let l = crate::candidates::listen(0)?;
|
||||
let bound = l.local_addr()?.port();
|
||||
tracing::info!(port = bound, "TCP TLS listening on ephemeral port");
|
||||
Some(Arc::new(l))
|
||||
@@ -438,7 +435,7 @@ impl TcpTlsTransport {
|
||||
local_id: identity.endpoint_id(),
|
||||
listen_port: bound_port,
|
||||
sni,
|
||||
peer_addresses: std::sync::RwLock::new(HashMap::new()),
|
||||
peer_addresses: Candidates::default(),
|
||||
server_config,
|
||||
listener,
|
||||
})
|
||||
@@ -456,7 +453,7 @@ impl TcpTlsTransport {
|
||||
|
||||
/// Records an observed TCP target address for a peer.
|
||||
pub fn set_peer_addr(&self, peer: EndpointId, addr: SocketAddr) {
|
||||
if let Ok(mut guard) = self.peer_addresses.write() {
|
||||
if let Ok(mut guard) = self.peer_addresses.manual.lock() {
|
||||
let addrs = guard.entry(peer).or_default();
|
||||
if !addrs.contains(&addr) {
|
||||
addrs.push(addr);
|
||||
@@ -466,7 +463,7 @@ impl TcpTlsTransport {
|
||||
|
||||
/// Replaces a bounded candidate set learned through an authenticated session.
|
||||
pub fn replace_peer_addrs(&self, peer: EndpointId, addresses: Vec<SocketAddr>) {
|
||||
if let Ok(mut peers) = self.peer_addresses.write() {
|
||||
if let Ok(mut peers) = self.peer_addresses.manual.lock() {
|
||||
if addresses.is_empty() {
|
||||
peers.remove(&peer);
|
||||
} else {
|
||||
@@ -487,11 +484,19 @@ impl TcpTlsTransport {
|
||||
let acceptor = tokio_rustls::TlsAcceptor::from(Arc::clone(&self.server_config));
|
||||
let local_id = self.local_id;
|
||||
|
||||
while let Ok((socket, remote_addr)) = listener.accept().await {
|
||||
let mut handshakes = tokio::task::JoinSet::new();
|
||||
loop {
|
||||
let accepted = tokio::select! {
|
||||
_ = handshakes.join_next(), if !handshakes.is_empty() => continue,
|
||||
result = listener.accept(), if handshakes.len() < 64 => result,
|
||||
};
|
||||
let Ok((socket, remote_addr)) = accepted else {
|
||||
break;
|
||||
};
|
||||
let _ = socket.set_nodelay(true);
|
||||
let acceptor = acceptor.clone();
|
||||
let on_inbound = on_inbound.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
handshakes.spawn(tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let mut tls_stream = match acceptor.accept(socket).await {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
@@ -536,7 +541,7 @@ impl TcpTlsTransport {
|
||||
protocol: "tcp-tls".into(),
|
||||
link: Arc::new(link),
|
||||
});
|
||||
});
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -561,92 +566,107 @@ impl PacketTransport for TcpTlsTransport {
|
||||
return Err(TransportError::Declined(protocol.to_string()));
|
||||
}
|
||||
|
||||
let target_addrs = {
|
||||
let guard = self
|
||||
.peer_addresses
|
||||
.read()
|
||||
.map_err(|_| TransportError::Other("lock poisoned".into()))?;
|
||||
guard.get(&peer).cloned().unwrap_or_default()
|
||||
};
|
||||
let addresses = self
|
||||
.peer_addresses
|
||||
.pairs
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get(&(network, peer))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| {
|
||||
self.peer_addresses
|
||||
.manual
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get(&peer)
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
});
|
||||
dial_candidates(addresses, |socket, addr| async move {
|
||||
let client_config = make_client_config(peer)
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
let connector = TlsConnector::from(client_config);
|
||||
|
||||
if target_addrs.is_empty() {
|
||||
return Err(TransportError::Unreachable(
|
||||
"no known TCP address for peer".into(),
|
||||
));
|
||||
}
|
||||
let server_name = rustls::pki_types::ServerName::try_from(self.sni.as_str())
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?
|
||||
.to_owned();
|
||||
|
||||
let mut connected_socket = None;
|
||||
let mut connected_addr = None;
|
||||
for addr in &target_addrs {
|
||||
if addr.ip().is_loopback() && addr.port() == self.listen_port {
|
||||
continue;
|
||||
let mut tls_stream = connector
|
||||
.connect(server_name, socket)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(format!("TLS handshake failed: {err}")))?;
|
||||
|
||||
// Send LinkHandshake (fixed 128 bytes)
|
||||
let msg = link_handshake_bytes(network, peer);
|
||||
let sig = self.identity.sign(&msg);
|
||||
let hello = LinkHandshake {
|
||||
network,
|
||||
client_id: self.local_id,
|
||||
signature: sig.to_bytes(),
|
||||
};
|
||||
let hello_bytes = hello.to_bytes();
|
||||
tls_stream
|
||||
.write_all(&hello_bytes)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
tls_stream
|
||||
.flush()
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
|
||||
// Read LinkAck (fixed 1 byte)
|
||||
let mut ack_buf = [0u8; LinkAck::LEN];
|
||||
tls_stream
|
||||
.read_exact(&mut ack_buf)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
let ack = LinkAck::from_bytes(&ack_buf)
|
||||
.ok_or_else(|| TransportError::Other("invalid link ack".into()))?;
|
||||
|
||||
if !ack.accepted {
|
||||
return Err(TransportError::Declined("link declined".into()));
|
||||
}
|
||||
match tokio::time::timeout(Duration::from_secs(3), TcpStream::connect(*addr)).await
|
||||
{
|
||||
Ok(Ok(socket)) => {
|
||||
connected_socket = Some(socket);
|
||||
connected_addr = Some(*addr);
|
||||
break;
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
|
||||
let (socket, addr) = match (connected_socket, connected_addr) {
|
||||
(Some(s), Some(a)) => (s, a),
|
||||
_ => {
|
||||
return Err(TransportError::Unreachable(
|
||||
"cannot connect to any TCP address for peer".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let client_config =
|
||||
make_client_config(peer).map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
let connector = TlsConnector::from(client_config);
|
||||
|
||||
let server_name = rustls::pki_types::ServerName::try_from(self.sni.as_str())
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?
|
||||
.to_owned();
|
||||
|
||||
let mut tls_stream = connector
|
||||
.connect(server_name, socket)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(format!("TLS handshake failed: {err}")))?;
|
||||
|
||||
// Send LinkHandshake (fixed 128 bytes)
|
||||
let msg = link_handshake_bytes(network, peer);
|
||||
let sig = self.identity.sign(&msg);
|
||||
let hello = LinkHandshake {
|
||||
network,
|
||||
client_id: self.local_id,
|
||||
signature: sig.to_bytes(),
|
||||
};
|
||||
let hello_bytes = hello.to_bytes();
|
||||
tls_stream
|
||||
.write_all(&hello_bytes)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
tls_stream
|
||||
.flush()
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
|
||||
// Read LinkAck (fixed 1 byte)
|
||||
let mut ack_buf = [0u8; LinkAck::LEN];
|
||||
tls_stream
|
||||
.read_exact(&mut ack_buf)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
let ack = LinkAck::from_bytes(&ack_buf)
|
||||
.ok_or_else(|| TransportError::Other("invalid link ack".into()))?;
|
||||
|
||||
if !ack.accepted {
|
||||
return Err(TransportError::Declined("link declined".into()));
|
||||
}
|
||||
|
||||
let link = TcpTlsLink::new(network, peer, tls_stream, addr.to_string());
|
||||
Ok(Arc::new(link) as SharedLink)
|
||||
let link = TcpTlsLink::new(network, peer, tls_stream, addr.to_string());
|
||||
Ok(Arc::new(link) as SharedLink)
|
||||
})
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TcpEndpoint for TcpTlsTransport {
|
||||
fn wire_version(&self) -> u16 {
|
||||
crate::TCP_TLS_VERSION
|
||||
}
|
||||
fn bound_port(&self) -> u16 {
|
||||
self.listen_port
|
||||
}
|
||||
fn set_pair_addresses(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
addresses: Option<Vec<SocketAddr>>,
|
||||
) {
|
||||
let mut pairs = self
|
||||
.peer_addresses
|
||||
.pairs
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner());
|
||||
match addresses {
|
||||
Some(addresses) => {
|
||||
pairs.insert((network, peer), addresses);
|
||||
}
|
||||
None => {
|
||||
pairs.remove(&(network, peer));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn clear_network(&self, network: NetworkId) {
|
||||
self.peer_addresses
|
||||
.pairs
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.retain(|(n, _), _| *n != network);
|
||||
}
|
||||
}
|
||||
@@ -51,3 +51,28 @@ fn test_make_client_and_server_config() {
|
||||
let client_config = tsunagi_tcp_tls::cert::make_client_config(peer_id);
|
||||
assert!(client_config.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_certificate_fields_cannot_satisfy_the_identity_pin() {
|
||||
let expected = DeviceIdentity::generate().endpoint_id();
|
||||
let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519).unwrap();
|
||||
let mut params = rcgen::CertificateParams::new(vec!["peer.invalid".into()]).unwrap();
|
||||
params
|
||||
.custom_extensions
|
||||
.push(rcgen::CustomExtension::from_oid_content(
|
||||
&[1, 3, 6, 1, 4, 1, 55555, 1],
|
||||
expected.as_bytes().to_vec(),
|
||||
));
|
||||
let cert = params.self_signed(&key).unwrap();
|
||||
assert!(
|
||||
PinnedEndpointVerifier::new(expected)
|
||||
.verify_server_cert(
|
||||
cert.der(),
|
||||
&[],
|
||||
&ServerName::try_from("peer.invalid").unwrap(),
|
||||
&[],
|
||||
UnixTime::now()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Shared compact network tiles, device header and join form.
|
||||
mod card;
|
||||
mod protocols;
|
||||
use crate::{
|
||||
client::{Client, Command},
|
||||
devices, exit, format,
|
||||
@@ -7,6 +8,7 @@ use crate::{
|
||||
widgets,
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
use protocols::draw_protocols;
|
||||
use std::collections::BTreeSet;
|
||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
@@ -422,81 +424,6 @@ fn draw_selected_exit(ui: &mut egui::Ui, network: &NetworkReport, via: &str, sta
|
||||
});
|
||||
}
|
||||
|
||||
fn draw_protocols(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
network: &NetworkReport,
|
||||
available: &[tsunagi::ipc::ProtocolReport],
|
||||
) {
|
||||
let summary = if network.protocols.is_empty() {
|
||||
"none".into()
|
||||
} else {
|
||||
network.protocols.join(", ")
|
||||
};
|
||||
egui::CollapsingHeader::new(format!("data transports {summary}"))
|
||||
.id_salt(("protocols", &network.network_id))
|
||||
.show(ui, |ui| {
|
||||
ui.weak("Order sets the first choice. Peers that support link comparison can switch to a faster enabled transport.");
|
||||
let mut selected = network.protocols.clone();
|
||||
let mut changed = false;
|
||||
ui.add_enabled_ui(!agent.busy(), |ui| {
|
||||
// Enabled items follow the user's preference; unchecked items
|
||||
// follow the agent's catalog. The worker refreshes after edits.
|
||||
let ordered: Vec<_> = network
|
||||
.protocols
|
||||
.iter()
|
||||
.filter_map(|name| available.iter().find(|p| &p.name == name))
|
||||
.chain(
|
||||
available
|
||||
.iter()
|
||||
.filter(|p| !network.protocols.contains(&p.name)),
|
||||
)
|
||||
.collect();
|
||||
for protocol in ordered {
|
||||
ui.horizontal(|ui| {
|
||||
let mut on = selected.contains(&protocol.name);
|
||||
if ui.checkbox(&mut on, &protocol.name).changed() {
|
||||
if on {
|
||||
selected.push(protocol.name.clone());
|
||||
} else {
|
||||
selected.retain(|p| p != &protocol.name);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if let Some(index) = selected.iter().position(|p| p == &protocol.name) {
|
||||
if widgets::hint(ui.add_enabled(index > 0, egui::Button::new(icon::ARROW_UP)),
|
||||
"Move transport up in preference order").clicked()
|
||||
{
|
||||
selected.swap(index, index - 1);
|
||||
changed = true;
|
||||
}
|
||||
if widgets::hint(ui.add_enabled(
|
||||
index + 1 < selected.len(),
|
||||
egui::Button::new(icon::ARROW_DOWN),
|
||||
), "Move transport down in preference order").clicked()
|
||||
{
|
||||
selected.swap(index, index + 1);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.indent(("description", &network.network_id, &protocol.name), |ui| {
|
||||
ui.weak(&protocol.summary);
|
||||
});
|
||||
}
|
||||
});
|
||||
if selected.is_empty() {
|
||||
ui.weak("Control only; no IP traffic in this network.");
|
||||
}
|
||||
if changed {
|
||||
agent.send(Command::SetProtocols {
|
||||
network_id: network.network_id.clone(),
|
||||
protocols: selected,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A prominent line about an exit node. One that carries a command copies it
|
||||
/// when clicked.
|
||||
fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
use crate::{
|
||||
client::{Client, Command},
|
||||
widgets,
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
use tsunagi::ipc::{NetworkReport, ProtocolReport};
|
||||
|
||||
fn set_members(selected: &mut Vec<String>, members: &[&ProtocolReport], on: bool) {
|
||||
if on {
|
||||
for p in members {
|
||||
if !selected.contains(&p.name) {
|
||||
selected.push(p.name.clone());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
selected.retain(|name| !members.iter().any(|p| p.name == *name));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn draw_protocols(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
network: &NetworkReport,
|
||||
available: &[ProtocolReport],
|
||||
) {
|
||||
let mut selected = network.protocols.clone();
|
||||
let caption = if selected.is_empty() {
|
||||
"Data transports · control only".into()
|
||||
} else {
|
||||
format!("Data transports {}/{}", selected.len(), available.len())
|
||||
};
|
||||
egui::CollapsingHeader::new(caption)
|
||||
.id_salt(("protocols", &network.network_id))
|
||||
.show(ui, |ui| {
|
||||
let mut groups = Vec::new();
|
||||
for p in available {
|
||||
if !groups.contains(&p.group.as_str()) {
|
||||
groups.push(p.group.as_str());
|
||||
}
|
||||
}
|
||||
for group in groups {
|
||||
let members: Vec<_> = available.iter().filter(|p| p.group == group).collect();
|
||||
let enabled = members
|
||||
.iter()
|
||||
.filter(|p| selected.contains(&p.name))
|
||||
.count();
|
||||
let all = enabled == members.len();
|
||||
let id = ui.make_persistent_id((&network.network_id, "transport group", group));
|
||||
egui::collapsing_header::CollapsingState::load_with_default_open(
|
||||
ui.ctx(),
|
||||
id,
|
||||
false,
|
||||
)
|
||||
.show_header(ui, |ui| {
|
||||
let mut checked = all;
|
||||
let checkbox =
|
||||
egui::Checkbox::new(&mut checked, egui::RichText::new(group).strong())
|
||||
.indeterminate(enabled != 0 && !all);
|
||||
if ui.add_enabled(!agent.busy(), checkbox).changed() {
|
||||
set_members(&mut selected, &members, !all);
|
||||
}
|
||||
ui.weak(format!("{enabled}/{}", members.len()));
|
||||
})
|
||||
.body(|ui| {
|
||||
for p in &members {
|
||||
ui.push_id(&p.name, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.;
|
||||
let position = selected.iter().position(|n| n == &p.name);
|
||||
let mut enabled = position.is_some();
|
||||
if ui
|
||||
.add_enabled(
|
||||
!agent.busy(),
|
||||
egui::Checkbox::new(&mut enabled, &p.label),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
set_members(&mut selected, &[p], enabled);
|
||||
}
|
||||
widgets::info(ui, &p.summary);
|
||||
if let Some(i) = position {
|
||||
widgets::hint(
|
||||
ui.weak(format!("#{}", i + 1)),
|
||||
"Priority across all enabled transports",
|
||||
);
|
||||
for (glyph, next, help) in [
|
||||
(
|
||||
icon::CARET_UP,
|
||||
i.checked_sub(1),
|
||||
"Increase priority across all groups",
|
||||
),
|
||||
(
|
||||
icon::CARET_DOWN,
|
||||
(i + 1 < selected.len()).then_some(i + 1),
|
||||
"Decrease priority across all groups",
|
||||
),
|
||||
] {
|
||||
let r = ui.add_enabled(
|
||||
next.is_some() && !agent.busy(),
|
||||
egui::Button::new(glyph).small().frame(false),
|
||||
);
|
||||
if widgets::hint(r, help).clicked()
|
||||
&& let Some(j) = next
|
||||
{
|
||||
selected.swap(i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
if selected != network.protocols {
|
||||
agent.send(Command::SetProtocols {
|
||||
network_id: network.network_id.clone(),
|
||||
protocols: selected,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn mixed_and_unchecked_groups_enable_every_child_and_keep_global_order() {
|
||||
let wg = ProtocolReport {
|
||||
name: "wg".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let awg = ProtocolReport {
|
||||
name: "awg".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let members = [&wg, &awg];
|
||||
let mut selected = vec!["ss2022".into(), "awg".into(), "tcp-tls".into()];
|
||||
set_members(&mut selected, &members, true);
|
||||
assert_eq!(selected, ["ss2022", "awg", "tcp-tls", "wg"]);
|
||||
set_members(&mut selected, &members, false);
|
||||
assert_eq!(selected, ["ss2022", "tcp-tls"]);
|
||||
set_members(&mut selected, &members, true);
|
||||
assert_eq!(selected, ["ss2022", "tcp-tls", "wg", "awg"]);
|
||||
set_members(&mut selected, &[&wg], false);
|
||||
assert_eq!(selected, ["ss2022", "tcp-tls", "awg"]);
|
||||
}
|
||||
}
|
||||
@@ -644,3 +644,105 @@ fn exit_users_scroll_a_row_inside_the_existing_card_and_disappear_on_deselection
|
||||
assert!((h - baseline).abs() < 1.);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_groups_toggle_in_one_command_and_fit_on_a_phone() {
|
||||
use std::cell::RefCell;
|
||||
use tsunagi::ipc::{ProtocolReport, StatusReport};
|
||||
#[derive(Default)]
|
||||
struct Edits(RefCell<Vec<Vec<String>>>);
|
||||
impl Client for Edits {
|
||||
fn busy(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn send(&self, command: Command) {
|
||||
let Command::SetProtocols {
|
||||
network_id,
|
||||
protocols,
|
||||
} = command
|
||||
else {
|
||||
panic!("unexpected action")
|
||||
};
|
||||
assert_eq!(network_id, "lab");
|
||||
self.0.borrow_mut().push(protocols);
|
||||
}
|
||||
}
|
||||
let edits = Edits::default();
|
||||
let ctx = Context::default();
|
||||
ctx.set_os(egui::os::OperatingSystem::Android);
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
ctx.style_mut(|s| s.animation_time = 0.);
|
||||
let mut state = home::UiState::default();
|
||||
let report = StatusReport {
|
||||
available_protocols: [
|
||||
("Native", "tcp-tls", "TCP + TLS"),
|
||||
("Shoes", "vless-xhttp", "VLESS + XHTTP"),
|
||||
("Shoes", "ss2022", "Shadowsocks 2022"),
|
||||
]
|
||||
.map(|(group, name, label)| ProtocolReport {
|
||||
group: group.into(),
|
||||
name: name.into(),
|
||||
label: label.into(),
|
||||
summary: format!("Details for {label}"),
|
||||
})
|
||||
.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let selected = RefCell::new(vec!["tcp-tls".into(), "ss2022".into()]);
|
||||
let mut draw = |time, events| {
|
||||
frame(&ctx, egui::vec2(320., 700.), time, events, |ctx| {
|
||||
let network = NetworkReport {
|
||||
network_id: "lab".into(),
|
||||
protocols: selected.borrow().clone(),
|
||||
..Default::default()
|
||||
};
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
home::draw_network_details(
|
||||
ui,
|
||||
&edits,
|
||||
&mut state,
|
||||
&Traffic::default(),
|
||||
&network,
|
||||
&report,
|
||||
false,
|
||||
)
|
||||
});
|
||||
})
|
||||
};
|
||||
draw(0., vec![]);
|
||||
let out = draw(0.1, vec![]);
|
||||
let at = label(&out, "Data transports 2/3").unwrap().center();
|
||||
draw(0.2, vec![Event::PointerMoved(at), press(at, true)]);
|
||||
draw(0.3, vec![press(at, false)]);
|
||||
let out = draw(0.4, vec![]);
|
||||
let group = label(&out, "Shoes").unwrap();
|
||||
for (step, expected) in [
|
||||
vec!["tcp-tls", "ss2022", "vless-xhttp"],
|
||||
vec!["tcp-tls"],
|
||||
vec!["tcp-tls", "vless-xhttp", "ss2022"],
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let at = group.center();
|
||||
let t = 1. + step as f64;
|
||||
draw(t, vec![Event::PointerMoved(at), press(at, true)]);
|
||||
draw(t + 0.1, vec![press(at, false)]);
|
||||
let received = std::mem::take(&mut *edits.0.borrow_mut());
|
||||
assert_eq!(received, [expected]);
|
||||
*selected.borrow_mut() = received[0].clone();
|
||||
draw(t + 0.2, vec![]);
|
||||
}
|
||||
// The disclosure arrow is before the checkbox and label. Expanding keeps the selection.
|
||||
let at = egui::pos2(group.left() - 37., group.center().y);
|
||||
draw(5., vec![Event::PointerMoved(at), press(at, true)]);
|
||||
draw(5.1, vec![press(at, false)]);
|
||||
let out = draw(5.2, vec![]);
|
||||
assert!(label(&out, "Shadowsocks 2022").unwrap().right() < 320.);
|
||||
assert!(label(&out, "Details for VLESS + XHTTP").is_none());
|
||||
let info = label(&out, icon::INFO).unwrap().center();
|
||||
draw(5.3, vec![Event::PointerMoved(info), press(info, true)]);
|
||||
draw(5.4, vec![press(info, false)]);
|
||||
assert!(label(&draw(5.5, vec![]), "Details for VLESS + XHTTP").is_some());
|
||||
assert!(edits.0.borrow().is_empty());
|
||||
}
|
||||
@@ -46,6 +46,18 @@ pub fn hint(response: Response, description: &str) -> Response {
|
||||
}
|
||||
}
|
||||
|
||||
/// A compact help button. Tapping reveals the same detail as desktop hover.
|
||||
pub(crate) fn info(ui: &mut Ui, description: &str) {
|
||||
let r = ui.add(egui::Button::new(egui::RichText::new(icon::INFO).weak()).frame(false));
|
||||
r.widget_info(|| WidgetInfo::labeled(WidgetType::Button, true, description));
|
||||
if r.clicked() && ui.ctx().os() == egui::os::OperatingSystem::Android {
|
||||
let until = ui.input(|i| i.time) + 2.5;
|
||||
let key = egui::Id::new(("touch explanation", ui.ctx().viewport_id()));
|
||||
ui.ctx().data_mut(|d| d.insert_temp(key, (r.id, until)));
|
||||
}
|
||||
hint(r, description);
|
||||
}
|
||||
|
||||
/// A glyph-only button with its action exposed to assistive technology.
|
||||
pub fn icon_button(ui: &mut Ui, glyph: &str, description: &str) -> Response {
|
||||
let r = ui.button(glyph);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "tsunagi-vless-xhttp"
|
||||
version = "1.0.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license = "MIT"
|
||||
repository.workspace = true
|
||||
description = "VLESS over XHTTP, HTTP/2 and TLS for peer-to-peer mesh links."
|
||||
|
||||
[dependencies]
|
||||
tsunagi-shoes = { path = "../tsunagi-shoes" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util"] }
|
||||
http = "1"
|
||||
h2 = "0.4"
|
||||
rustls = "0.23"
|
||||
tokio-rustls = "0.26"
|
||||
bytes.workspace = true
|
||||
hex.workspace = true
|
||||
rand = "0.10"
|
||||
subtle = "2.6"
|
||||
zeroize = "1.9"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,20 @@
|
||||
Copyright (c) 2021-2023 Alex Lau <github@alau.ca>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,104 @@
|
||||
//! Adapted from Shoes v0.3.8, src/http2/stream.rs (MIT).
|
||||
use bytes::Bytes;
|
||||
use std::{
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
|
||||
pub(crate) struct H2MultiStream {
|
||||
send: h2::SendStream<Bytes>,
|
||||
recv: h2::RecvStream,
|
||||
recv_buf: Bytes,
|
||||
shutdown_sent: bool,
|
||||
}
|
||||
impl H2MultiStream {
|
||||
pub(crate) fn new(send: h2::SendStream<Bytes>, recv: h2::RecvStream) -> Self {
|
||||
Self {
|
||||
send,
|
||||
recv,
|
||||
recv_buf: Bytes::new(),
|
||||
shutdown_sent: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl AsyncRead for H2MultiStream {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
if buf.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
// Empty DATA is not EOF. Bound work per poll even for a padding-only peer.
|
||||
for _ in 0..32 {
|
||||
if !self.recv_buf.is_empty() {
|
||||
let count = self.recv_buf.len().min(buf.remaining());
|
||||
buf.put_slice(&self.recv_buf.split_to(count));
|
||||
self.recv
|
||||
.flow_control()
|
||||
.release_capacity(count)
|
||||
.map_err(io::Error::other)?;
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
match std::task::ready!(self.recv.poll_data(cx)) {
|
||||
Some(Ok(data)) => self.recv_buf = data,
|
||||
Some(Err(e)) => return Poll::Ready(Err(io::Error::other(e))),
|
||||
None => return Poll::Ready(Ok(())),
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for H2MultiStream {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
if buf.is_empty() {
|
||||
return Poll::Ready(Ok(0));
|
||||
}
|
||||
if self.shutdown_sent {
|
||||
return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into()));
|
||||
}
|
||||
let wanted = buf.len().min(16 * 1024);
|
||||
let send = &mut self.send;
|
||||
send.reserve_capacity(wanted);
|
||||
loop {
|
||||
let capacity = send.capacity();
|
||||
if capacity != 0 {
|
||||
let count = wanted.min(capacity);
|
||||
send.send_data(Bytes::copy_from_slice(&buf[..count]), false)
|
||||
.map_err(io::Error::other)?;
|
||||
return Poll::Ready(Ok(count));
|
||||
}
|
||||
match std::task::ready!(send.poll_capacity(cx)) {
|
||||
Some(Ok(_)) => continue,
|
||||
Some(Err(e)) => return Poll::Ready(Err(io::Error::other(e))),
|
||||
None => return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
// h2 has no per-stream flush; the connection driver handles transmission
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
if !self.shutdown_sent {
|
||||
self.send
|
||||
.send_data(Bytes::new(), true)
|
||||
.map_err(io::Error::other)?;
|
||||
self.shutdown_sent = true;
|
||||
}
|
||||
|
||||
// Don't wait for peer ACK; the connection driver transmits END_STREAM reliably
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Shoes' XHTTP stream-one and VLESS TCP profile over HTTP/2 and pinned TLS 1.3.
|
||||
//! Wire formats adapted from cfal/shoes v0.3.8 (MIT), xhttp/wire.rs and vless/.
|
||||
mod h2_stream;
|
||||
use bytes::Bytes;
|
||||
use h2_stream::H2MultiStream;
|
||||
use iroh::EndpointId;
|
||||
use rustls::pki_types::ServerName;
|
||||
use std::{io, sync::Arc};
|
||||
use subtle::ConstantTimeEq;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpStream,
|
||||
};
|
||||
use tsunagi::{BoxFuture, identity::DeviceIdentity};
|
||||
use tsunagi_shoes::{Profile, Profiles, ShoesWire, Stream, Ticket, driven};
|
||||
use tsunagi_tcp_tls::cert::{generate_self_signed_cert, make_client_config, make_server_config};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// Catalog identifier, independent of Tsunagi's software version.
|
||||
pub const PROTOCOL: &str = "vless-xhttp";
|
||||
/// Initial compatible wire format.
|
||||
pub const WIRE_VERSION: u16 = 1;
|
||||
/// Preferred physical port.
|
||||
pub const PORT: u16 = 9443;
|
||||
|
||||
const TARGET: [u8; 9] = [0, 1, 0, 1, 1, 127, 0, 0, 1]; // no addons, TCP, port 1, IPv4
|
||||
const HEADER_LIMIT: u32 = 8192;
|
||||
|
||||
/// One HTTP/2 endpoint identified by its persistent mesh public key.
|
||||
pub struct VlessXhttp {
|
||||
tls: tokio_rustls::TlsAcceptor,
|
||||
}
|
||||
impl VlessXhttp {
|
||||
/// Construct a server without DNS, public certificates or web ingress.
|
||||
pub fn new(
|
||||
identity: &DeviceIdentity,
|
||||
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let (cert, key) = generate_self_signed_cert(&identity.secret_bytes(), "localhost")?;
|
||||
let mut tls = make_server_config(cert, key)?;
|
||||
Arc::make_mut(&mut tls).alpn_protocols = vec![b"h2".to_vec()];
|
||||
Ok(Self { tls: tls.into() })
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "invalid VLESS/XHTTP handshake")
|
||||
}
|
||||
fn header(p: &Profile) -> Zeroizing<[u8; 26]> {
|
||||
let mut bytes = Zeroizing::new([0; 26]);
|
||||
bytes[1..17].copy_from_slice(&p.secret[..16]);
|
||||
// RFC 9562 UUIDv4 version and variant.
|
||||
bytes[7] = (bytes[7] & 0x0f) | 0x40;
|
||||
bytes[9] = (bytes[9] & 0x3f) | 0x80;
|
||||
bytes[17..].copy_from_slice(&TARGET);
|
||||
bytes
|
||||
}
|
||||
fn request(p: &Profile, authority: std::net::SocketAddr) -> io::Result<http::Request<()>> {
|
||||
let path = format!("/{}/", hex::encode(p.tag));
|
||||
let uri = format!("https://{authority}{path}");
|
||||
let padding = "X".repeat(rand::random_range(100..=1000));
|
||||
http::Request::post(&uri)
|
||||
.header("referer", format!("{uri}?x_padding={padding}"))
|
||||
.header("content-type", "application/grpc")
|
||||
.body(())
|
||||
.map_err(io::Error::other)
|
||||
}
|
||||
fn request_tag<T>(req: &http::Request<T>) -> io::Result<[u8; 32]> {
|
||||
if req.method() != http::Method::POST || req.uri().scheme_str() != Some("https") {
|
||||
return Err(invalid());
|
||||
}
|
||||
let path = req
|
||||
.uri()
|
||||
.path()
|
||||
.strip_prefix('/')
|
||||
.and_then(|p| p.strip_suffix('/'))
|
||||
.ok_or_else(invalid)?;
|
||||
let referer: http::Uri = req
|
||||
.headers()
|
||||
.get("referer")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or_else(invalid)?;
|
||||
let padding = referer
|
||||
.query()
|
||||
.and_then(|q| q.strip_prefix("x_padding="))
|
||||
.ok_or_else(invalid)?;
|
||||
if !(100..=1000).contains(&padding.len()) || path.len() != 64 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut tag = [0; 32];
|
||||
hex::decode_to_slice(path, &mut tag).map_err(|_| invalid())?;
|
||||
Ok(tag)
|
||||
}
|
||||
|
||||
impl ShoesWire for VlessXhttp {
|
||||
fn name(&self) -> &'static str {
|
||||
PROTOCOL
|
||||
}
|
||||
fn version(&self) -> u16 {
|
||||
WIRE_VERSION
|
||||
}
|
||||
fn connect<'a>(
|
||||
&'a self,
|
||||
tcp: TcpStream,
|
||||
peer: EndpointId,
|
||||
profile: &'a Profile,
|
||||
) -> BoxFuture<'a, io::Result<Stream>> {
|
||||
Box::pin(async move {
|
||||
let mut config = make_client_config(peer).map_err(io::Error::other)?;
|
||||
Arc::make_mut(&mut config).alpn_protocols = vec![b"h2".to_vec()];
|
||||
let address = tcp.peer_addr()?;
|
||||
let tls = tokio_rustls::TlsConnector::from(config)
|
||||
.connect(ServerName::IpAddress(address.ip().into()), tcp)
|
||||
.await?;
|
||||
if tls.get_ref().1.alpn_protocol() != Some(b"h2") {
|
||||
return Err(invalid());
|
||||
}
|
||||
let (sender, mut connection) = h2::client::Builder::new()
|
||||
.max_header_list_size(HEADER_LIMIT)
|
||||
.enable_push(false)
|
||||
.handshake::<_, Bytes>(tls)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let open = async {
|
||||
let mut sender = sender.ready().await.map_err(io::Error::other)?;
|
||||
let (response, mut send) = sender
|
||||
.send_request(request(profile, address)?, false)
|
||||
.map_err(io::Error::other)?;
|
||||
send.send_data(Bytes::copy_from_slice(&header(profile)[..]), false)
|
||||
.map_err(io::Error::other)?;
|
||||
let response = response.await.map_err(io::Error::other)?;
|
||||
if response.status() != http::StatusCode::OK {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(H2MultiStream::new(send, response.into_body()))
|
||||
};
|
||||
let stream = tokio::select! { _ = &mut connection => return Err(invalid()), result = open => result? };
|
||||
let mut stream = driven(stream, async move {
|
||||
let _ = connection.await;
|
||||
});
|
||||
let mut response = [0; 2];
|
||||
stream.read_exact(&mut response).await?;
|
||||
if response != [0, 0] {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(stream)
|
||||
})
|
||||
}
|
||||
fn accept<'a>(
|
||||
&'a self,
|
||||
tcp: TcpStream,
|
||||
profiles: &'a Profiles,
|
||||
) -> BoxFuture<'a, io::Result<(Ticket, Stream)>> {
|
||||
Box::pin(async move {
|
||||
let tls = self.tls.accept(tcp).await?;
|
||||
if tls.get_ref().1.alpn_protocol() != Some(b"h2") {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut conn = h2::server::Builder::new()
|
||||
.max_header_list_size(HEADER_LIMIT)
|
||||
.max_concurrent_streams(1)
|
||||
.handshake::<_, Bytes>(tls)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let (req, mut respond) = conn
|
||||
.accept()
|
||||
.await
|
||||
.ok_or_else(invalid)?
|
||||
.map_err(io::Error::other)?;
|
||||
let ticket = profiles.lookup(&request_tag(&req)?)?;
|
||||
let response = http::Response::builder()
|
||||
.header("content-type", "application/grpc")
|
||||
.header("cache-control", "no-store")
|
||||
.body(())
|
||||
.map_err(io::Error::other)?;
|
||||
let send = respond
|
||||
.send_response(response, false)
|
||||
.map_err(io::Error::other)?;
|
||||
let mut stream = driven(H2MultiStream::new(send, req.into_body()), async move {
|
||||
while let Some(Ok((_, mut response))) = conn.accept().await {
|
||||
response.send_reset(h2::Reason::REFUSED_STREAM);
|
||||
}
|
||||
});
|
||||
let mut received = Zeroizing::new([0u8; 26]);
|
||||
stream.read_exact(&mut received[..]).await?;
|
||||
if !bool::from(received[..].ct_eq(&header(&ticket.profile)[..])) {
|
||||
return Err(invalid());
|
||||
}
|
||||
profiles.claim(&ticket)?;
|
||||
stream.write_all(&[0, 0]).await?;
|
||||
Ok((ticket, stream))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stream_one_and_vless_use_the_standard_post_path_uuid_and_tcp_destination() {
|
||||
let p = Profile {
|
||||
tag: [0xda; 32],
|
||||
secret: [0xaa; 32],
|
||||
variant: false,
|
||||
};
|
||||
let req = request(&p, "127.0.0.1:9443".parse().unwrap()).unwrap();
|
||||
assert_eq!(req.headers()["content-type"], "application/grpc");
|
||||
assert_eq!(request_tag(&req).unwrap(), p.tag);
|
||||
assert_eq!(
|
||||
hex::encode(&header(&p)[..]),
|
||||
"00aaaaaaaaaaaa4aaaaaaaaaaaaaaaaaaa00010001017f000001"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn bad_methods_and_paths_are_rejected_before_allocating_a_stream() {
|
||||
let p = Profile {
|
||||
tag: [7; 32],
|
||||
secret: [4; 32],
|
||||
variant: true,
|
||||
};
|
||||
let mut req = request(&p, "127.0.0.1:9443".parse().unwrap()).unwrap();
|
||||
*req.method_mut() = http::Method::GET;
|
||||
assert!(request_tag(&req).is_err());
|
||||
*req.method_mut() = http::Method::POST;
|
||||
*req.uri_mut() = http::Uri::from_static("https://peer.invalid/missing/");
|
||||
assert!(request_tag(&req).is_err());
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,9 @@ rand = "0.10"
|
||||
boringtun = { version = "0.7.1", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
tsunagi-shoes = { path = "../tsunagi-shoes" }
|
||||
tsunagi-vless-xhttp = { path = "../tsunagi-vless-xhttp" }
|
||||
tsunagi-ss2022 = { path = "../tsunagi-ss2022" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls" }
|
||||
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
|
||||
|
||||
@@ -10,25 +10,39 @@ use std::{
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tsunagi::dataplane::transport::ControlSender;
|
||||
use tsunagi::dataplane::transport::{PacketTransport, SharedLink, TransportError};
|
||||
use tsunagi::discovery::SharedMemoryDiscovery;
|
||||
use tsunagi::overlay::{MemoryTun, MemoryTunFactory};
|
||||
use tsunagi::testing::{config_with, network, wait_for_peers, wait_until};
|
||||
use tsunagi::{Agent, BoxFuture, NetworkId};
|
||||
use tsunagi_tcp_tls::{TcpTlsCarrier, TcpTlsTransport};
|
||||
use tsunagi_shoes::{ShoesTransport, ShoesWire};
|
||||
use tsunagi_tcp_tls::{TcpCarrier, TcpTlsCarrier, TcpTlsTransport, candidates::TcpEndpoint};
|
||||
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
|
||||
use tsunagi_wireguard::{UdpCarrier, UdpTransport};
|
||||
|
||||
// Only address selection is constrained to loopback. TLS sockets, identity
|
||||
// verification, framing, membership and both encryption layers remain real.
|
||||
#[derive(Debug)]
|
||||
struct LoopbackTls {
|
||||
inner: Arc<TcpTlsTransport>,
|
||||
struct LoopbackTcp {
|
||||
inner: Arc<dyn TcpEndpoint>,
|
||||
ports: Arc<std::sync::Mutex<Vec<(EndpointId, u16)>>>,
|
||||
}
|
||||
impl PacketTransport for LoopbackTls {
|
||||
impl PacketTransport for LoopbackTcp {
|
||||
fn name(&self) -> &str {
|
||||
"tcp-tls"
|
||||
self.inner.name()
|
||||
}
|
||||
fn attach_control(&self, sender: Arc<dyn ControlSender>) {
|
||||
self.inner.attach_control(sender);
|
||||
}
|
||||
fn on_control(
|
||||
&self,
|
||||
net: NetworkId,
|
||||
peer: EndpointId,
|
||||
protocol: &str,
|
||||
payload: &[u8],
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.on_control(net, peer, protocol, payload)
|
||||
}
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
@@ -47,8 +61,15 @@ impl PacketTransport for LoopbackTls {
|
||||
.find(|(id, _)| *id == peer)
|
||||
.unwrap()
|
||||
.1;
|
||||
self.inner
|
||||
.replace_peer_addrs(peer, vec![SocketAddr::from((Ipv4Addr::LOCALHOST, port))]);
|
||||
self.inner.set_pair_addresses(
|
||||
network,
|
||||
peer,
|
||||
Some(if port == 0 {
|
||||
vec![]
|
||||
} else {
|
||||
vec![SocketAddr::from((Ipv4Addr::LOCALHOST, port))]
|
||||
}),
|
||||
);
|
||||
self.inner.open(network, peer, protocol)
|
||||
}
|
||||
}
|
||||
@@ -95,6 +116,7 @@ impl Node {
|
||||
.with_tunnel(tunnel.clone());
|
||||
let mut wireguard = None;
|
||||
let mut tls = None;
|
||||
let mut shoes = Vec::new();
|
||||
for &protocol in protocols {
|
||||
match protocol {
|
||||
"wg" => {
|
||||
@@ -120,13 +142,35 @@ impl Node {
|
||||
.with_carrier(TcpTlsCarrier::new(transport.clone()))
|
||||
.with_custom_transport(
|
||||
protocol,
|
||||
Arc::new(LoopbackTls {
|
||||
Arc::new(LoopbackTcp {
|
||||
inner: transport.clone(),
|
||||
ports: ports.clone(),
|
||||
}),
|
||||
);
|
||||
tls = Some(transport);
|
||||
}
|
||||
"vless-xhttp" | "ss2022" => {
|
||||
let wire: Arc<dyn ShoesWire> = if protocol == "vless-xhttp" {
|
||||
Arc::new(tsunagi_vless_xhttp::VlessXhttp::new(&identity).unwrap())
|
||||
} else {
|
||||
Arc::new(tsunagi_ss2022::Shadowsocks2022)
|
||||
};
|
||||
let transport = ShoesTransport::bind(wire, Some(0), 0).await.unwrap();
|
||||
ports
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((identity.endpoint_id(), transport.bound_port()));
|
||||
config = config
|
||||
.with_carrier(TcpCarrier::new(transport.clone()))
|
||||
.with_custom_transport(
|
||||
protocol,
|
||||
Arc::new(LoopbackTcp {
|
||||
inner: transport.clone(),
|
||||
ports: ports.clone(),
|
||||
}),
|
||||
);
|
||||
shoes.push(transport);
|
||||
}
|
||||
"wg-quic" => {
|
||||
config = config.with_carrier(Arc::new(
|
||||
tsunagi::dataplane::transport::iroh_link::IrohCarrier,
|
||||
@@ -137,6 +181,9 @@ impl Node {
|
||||
}
|
||||
let agent = Agent::spawn(config).await.unwrap();
|
||||
let mut listeners = tokio::task::JoinSet::new();
|
||||
for transport in shoes {
|
||||
listeners.spawn(transport.listen(agent.clone()));
|
||||
}
|
||||
if let Some(transport) = wireguard.clone() {
|
||||
let incoming = agent.clone();
|
||||
listeners.spawn(async move {
|
||||
@@ -418,9 +465,8 @@ async fn missing_native_transport_cannot_silently_turn_wireguard_into_quic() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wireguard_and_tls_carriers_both_carry_the_same_internal_cipher_and_exact_plaintext_counters()
|
||||
{
|
||||
for protocol in ["wg", "tcp-tls"] {
|
||||
async fn direct_carriers_share_the_internal_cipher_and_count_exact_plaintext() {
|
||||
for protocol in ["wg", "tcp-tls", "vless-xhttp", "ss2022"] {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let ports = Arc::default();
|
||||
let a = Node::new(&discovery, protocol, Arc::clone(&ports)).await;
|
||||
@@ -501,3 +547,42 @@ async fn wireguard_and_tls_carriers_both_carry_the_same_internal_cipher_and_exac
|
||||
b.agent.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn each_tcp_carrier_reverses_when_the_elected_dialler_cannot_reach_the_listener() {
|
||||
for protocol in ["tcp-tls", "vless-xhttp", "ss2022"] {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let ports = Arc::default();
|
||||
let a = Node::new(&discovery, protocol, Arc::clone(&ports)).await;
|
||||
let b = Node::new(&discovery, protocol, Arc::clone(&ports)).await;
|
||||
// Only the smaller identity accepts a connection from its peer.
|
||||
ports
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter_mut()
|
||||
.max_by_key(|(id, _)| *id)
|
||||
.unwrap()
|
||||
.1 = 0;
|
||||
let (name, secret) = network(protocol);
|
||||
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||
b.agent.join_network(&name, &secret).await.unwrap();
|
||||
wait_until(
|
||||
"both endpoints have an established cipher over the reverse socket",
|
||||
|| async {
|
||||
[&a, &b]
|
||||
.iter()
|
||||
.all(|n| {
|
||||
n.tunnel.overview(id).and_then(|o| {
|
||||
o.peers.first()?.tunnel.as_ref().map(|t| t.health.is_up())
|
||||
}) == Some(true)
|
||||
})
|
||||
.then_some(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
deliver(&a, &b, id, 41).await;
|
||||
deliver(&b, &a, id, 42).await;
|
||||
a.agent.shutdown().await;
|
||||
b.agent.shutdown().await;
|
||||
}
|
||||
}
|
||||
+48
-16
@@ -498,7 +498,7 @@ struct UpArgs {
|
||||
long = "protocol",
|
||||
value_name = "LIST",
|
||||
value_delimiter = ',',
|
||||
default_value = "wg,awg,wg-quic,tcp-tls",
|
||||
default_values = PROTOCOLS.iter().map(|p| p.name),
|
||||
help_heading = "Transport"
|
||||
)]
|
||||
protocols: Vec<String>,
|
||||
@@ -1475,7 +1475,11 @@ fn take_tunnel_settings(settings: &mut Vec<Setting>) -> Result<Vec<(String, Stri
|
||||
}
|
||||
|
||||
/// The settings meant for one protocol, refusing any that fit nowhere.
|
||||
fn settings_for(spec: &ProtocolSpec, settings: &[Setting]) -> Vec<(String, String)> {
|
||||
fn settings_for(
|
||||
spec: &ProtocolSpec,
|
||||
settings: &[Setting],
|
||||
selected: &[&ProtocolSpec],
|
||||
) -> Vec<(String, String)> {
|
||||
let mut taken = Vec::new();
|
||||
for setting in settings {
|
||||
let aimed_here = match &setting.protocol {
|
||||
@@ -1485,7 +1489,19 @@ fn settings_for(spec: &ProtocolSpec, settings: &[Setting]) -> Vec<(String, Strin
|
||||
// Unqualified settings go to whichever protocol declares the
|
||||
// key. With one selected that is the obvious reading; with
|
||||
// several, write `protocol:key=value`.
|
||||
None => spec.options.iter().any(|option| option.key == setting.key),
|
||||
None => {
|
||||
// Existing unqualified ports configure the original listeners.
|
||||
// A Shoes listener can inherit one when it is the sole TCP choice.
|
||||
let shoes_port =
|
||||
setting.key == "port" && matches!(spec.name, "vless-xhttp" | "ss2022");
|
||||
let eligible = !shoes_port
|
||||
|| selected
|
||||
.iter()
|
||||
.filter(|p| matches!(p.name, "tcp-tls" | "vless-xhttp" | "ss2022"))
|
||||
.count()
|
||||
== 1;
|
||||
eligible && spec.options.iter().any(|option| option.key == setting.key)
|
||||
}
|
||||
};
|
||||
if aimed_here {
|
||||
taken.push((setting.key.clone(), setting.value.clone()));
|
||||
@@ -1501,6 +1517,7 @@ fn show_protocols() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut out = Report::new();
|
||||
for spec in PROTOCOLS {
|
||||
let mut section = Section::new(format!("{} (wire version {})", spec.name, spec.version));
|
||||
section.push(Row::new(Health::Info, "group", spec.group));
|
||||
section.push(Row::new(Health::Info, "what", spec.summary));
|
||||
if spec.options.is_empty() {
|
||||
section.push(Row::new(Health::Info, "settings", "none"));
|
||||
@@ -2033,7 +2050,7 @@ fn parse_protocol_list(text: &str) -> Result<Vec<String>, String> {
|
||||
};
|
||||
if !PROTOCOLS.iter().any(|spec| spec.name == name) {
|
||||
return Err(format!(
|
||||
"unknown protocol `{name}`; use wg,awg,wg-quic,tcp-tls or `none` alone. Run `tsng protocols` for details"
|
||||
"unknown protocol `{name}`; run `tsng protocols` to list available transports, or use `none` alone"
|
||||
));
|
||||
}
|
||||
if names.iter().any(|n| n == name) {
|
||||
@@ -4729,10 +4746,10 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if !PROTOCOLS
|
||||
.iter()
|
||||
.filter(|spec| setting.protocol.is_some() || wanted.iter().any(|p| p.name == spec.name))
|
||||
.any(|spec| !settings_for(spec, std::slice::from_ref(setting)).is_empty())
|
||||
.any(|spec| !settings_for(spec, std::slice::from_ref(setting), &wanted).is_empty())
|
||||
{
|
||||
return Err(format!(
|
||||
"no configured protocol takes `{}`; qualify disabled protocol settings as protocol:key=value. Run `tsng protocols` for details",
|
||||
"no configured protocol takes `{}`; use protocol:key=value to select a specific listener or configure a disabled transport. Run `tsng protocols` for details",
|
||||
setting.key
|
||||
)
|
||||
.into());
|
||||
@@ -4772,7 +4789,7 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
settings_for(spec, &scoped)
|
||||
settings_for(spec, &scoped, &wanted)
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -4950,13 +4967,7 @@ async fn build_report(
|
||||
|
||||
StatusReport {
|
||||
overlay_config_error: overlay.and_then(|state| state.address_error),
|
||||
available_protocols: PROTOCOLS
|
||||
.iter()
|
||||
.map(|p| tsunagi::ipc::ProtocolReport {
|
||||
name: p.name.into(),
|
||||
summary: p.summary.into(),
|
||||
})
|
||||
.collect(),
|
||||
available_protocols: PROTOCOLS.iter().map(|p| p.report()).collect(),
|
||||
endpoint_id: status.endpoint_id.to_string(),
|
||||
hostname: status.hostname.clone(),
|
||||
bound_sockets: status
|
||||
@@ -5988,10 +5999,31 @@ mod network_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_carriers_include_awg_and_explicit_order_is_preserved() {
|
||||
fn separate_tcp_listeners_preserve_historic_unqualified_ports() {
|
||||
let all: Vec<_> = super::PROTOCOLS.iter().collect();
|
||||
let spec = |name| *all.iter().find(|p| p.name == name).unwrap();
|
||||
let settings = super::parse_settings(&["port=8765".into()]).unwrap();
|
||||
assert_eq!(
|
||||
super::settings_for(spec("tcp-tls"), &settings, &all)[0].1,
|
||||
"8765"
|
||||
);
|
||||
assert!(super::settings_for(spec("vless-xhttp"), &settings, &all).is_empty());
|
||||
for name in ["vless-xhttp", "ss2022"] {
|
||||
let only = [spec(name)];
|
||||
assert_eq!(super::settings_for(only[0], &settings, &only)[0].1, "8765");
|
||||
let qualified = super::parse_settings(&[format!("{name}:port=9876")]).unwrap();
|
||||
assert_eq!(super::settings_for(only[0], &qualified, &all)[0].1, "9876");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_carriers_default_on_and_explicit_order_is_preserved() {
|
||||
use clap::Parser;
|
||||
for (words, expected) in [
|
||||
(vec!["tsng", "up"], vec!["wg", "awg", "wg-quic", "tcp-tls"]),
|
||||
(
|
||||
vec!["tsng", "up"],
|
||||
vec!["wg", "awg", "wg-quic", "tcp-tls", "vless-xhttp", "ss2022"],
|
||||
),
|
||||
(
|
||||
vec![
|
||||
"tsng",
|
||||
|
||||
Reference in new issue
Block a user