diff --git a/crates/ide-ssh/src/manager.rs b/crates/ide-ssh/src/manager.rs index ee35ca6ea0..2c05b9b90b 100644 --- a/crates/ide-ssh/src/manager.rs +++ b/crates/ide-ssh/src/manager.rs @@ -152,6 +152,8 @@ impl SshManager { let config = self.config(id)?; let secret = self.secret(&config); let session = Arc::new(self.connect(id, &SshTarget::from(&config), secret.as_deref()).await?); + // The shared session carries the config's port forwards, restarted on every reconnect. + session.start_forwards().await; self.sessions.lock().insert(id.to_owned(), session.clone()); Ok(session) } diff --git a/crates/ide-ssh/src/session.rs b/crates/ide-ssh/src/session.rs index 9ea118da4d..cba0f00ac1 100644 --- a/crates/ide-ssh/src/session.rs +++ b/crates/ide-ssh/src/session.rs @@ -7,7 +7,9 @@ //! (or is recorded silently under `StrictHostKeyChecking accept-new`), and a //! changed key is refused unless host key checking is off. -use crate::target::{Hop, HostKeyPolicy, SshFiles, SshTarget, expand, home, resolve_hops}; +use crate::target::{ + ForwardDirection, Hop, HostKeyPolicy, PortForward, SshFiles, SshTarget, expand, home, resolve_hops, +}; use ide_core::remote_settings::SshAuth; use ide_core::{IdeError, IdeResult, error::ErrorKind}; use parking_lot::Mutex; @@ -113,6 +115,18 @@ pub struct Session { /// Sessions of the `ProxyJump` hosts, kept alive under `handle`. _jumps: Vec>, label: String, + /// The config's `LocalForward` / `RemoteForward`s, started by [`Session::start_forwards`]. + forwards: Vec, + /// `LocalForward` listeners, stopped with the session. + listeners: Mutex>, +} + +impl Drop for Session { + fn drop(&mut self) { + for listener in self.listeners.lock().drain(..) { + listener.abort(); + } + } } impl Session { @@ -158,8 +172,50 @@ impl Session { sessions.push(handle); } let handle = sessions.pop().expect("at least one hop"); - let label = hops.last().expect("at least one hop").label(); - Ok(Session { handle, _jumps: sessions, label }) + let last = hops.last().expect("at least one hop"); + Ok(Session { + handle, + _jumps: sessions, + label: last.label(), + forwards: last.forwards.clone(), + listeners: Mutex::default(), + }) + } + + /// Starts the config's `LocalForward` / `RemoteForward`s, as `ssh` does on connecting: the + /// SSH host listens for each `RemoteForward` (`tcpip-forward`), this machine for each + /// `LocalForward`, until the session closes. A port that cannot be forwarded (in use, refused + /// by the server) is skipped with a warning, as `ssh` goes on without it. + pub async fn start_forwards(self: &Arc) { + for f in &self.forwards { + let what = format!("{}:{} → {}:{}", f.bind, f.port, f.host, f.host_port); + match f.direction { + ForwardDirection::Remote => match self.handle.tcpip_forward(f.bind.clone(), u32::from(f.port)).await { + Ok(_) => tracing::info!("{}: RemoteForward {what}", self.label), + Err(e) => tracing::warn!("{}: RemoteForward {what} failed: {e}", self.label), + }, + ForwardDirection::Local => { + let bind = match f.bind.as_str() { + "localhost" => "127.0.0.1", + "" => "0.0.0.0", + b => b, + }; + match tokio::net::TcpListener::bind((bind, f.port)).await { + Ok(listener) => { + let task = tokio::spawn(local_forward( + listener, + Arc::downgrade(self), + f.host.clone(), + f.host_port, + )); + self.listeners.lock().push(task.abort_handle()); + tracing::info!("{}: LocalForward {what}", self.label); + } + Err(e) => tracing::warn!("{}: LocalForward {what} failed: {e}", self.label), + } + } + } + } } /// `user@host:port` of the target. @@ -404,6 +460,39 @@ fn io(message: impl Into) -> IdeError { IdeError::new(ErrorKind::Io, message) } +/// A `LocalForward` listener: each connection goes through a `direct-tcpip` channel to +/// `host:port` from the SSH host, while the session lives. +async fn local_forward(listener: tokio::net::TcpListener, session: std::sync::Weak, host: String, port: u16) { + while let Ok((mut socket, _)) = listener.accept().await { + let Some(session) = session.upgrade().filter(|s| !s.is_closed()) else { return }; + let host = host.clone(); + tokio::spawn(async move { + match session.direct_tcpip(&host, port).await { + Ok(mut stream) => { + drop(session); + let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await; + } + Err(e) => tracing::warn!("LocalForward: cannot open a channel to {host}:{port}: {e}"), + } + }); + } +} + +/// A `RemoteForward` connection: accepted once `host:port` here answers, then copied both ways. +async fn remote_forward(channel: russh::Channel, reply: client::ChannelOpenHandle, host: String, port: u16) { + match tokio::net::TcpStream::connect((host.as_str(), port)).await { + Ok(mut socket) => { + reply.accept().await; + let mut stream = channel.into_stream(); + let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await; + } + Err(e) => { + tracing::warn!("RemoteForward: cannot connect to {host}:{port}: {e}"); + reply.reject(russh::ChannelOpenFailure::ConnectFailed).await; + } + } +} + // --- connection ---------------------------------------------------------------- #[derive(Debug)] @@ -418,6 +507,8 @@ pub struct Client { known_hosts: PathBuf, host_key_policy: HostKeyPolicy, issue: Arc>>, + /// The `RemoteForward`s whose connections this client accepts. + remote_forwards: Vec, } impl client::Handler for Client { @@ -442,6 +533,26 @@ impl client::Handler for Client { *self.issue.lock() = Some(issue); Ok(false) } + + async fn server_channel_open_forwarded_tcpip( + &mut self, + channel: russh::Channel, + _connected_address: &str, + connected_port: u32, + _originator_address: &str, + _originator_port: u32, + reply: client::ChannelOpenHandle, + _session: &mut client::Session, + ) -> Result<(), Self::Error> { + // Only a port this client asked the server to forward is accepted. + match self.remote_forwards.iter().find(|f| u32::from(f.port) == connected_port) { + Some(f) => { + tokio::spawn(remote_forward(channel, reply, f.host.clone(), f.host_port)); + } + None => reply.reject(russh::ChannelOpenFailure::AdministrativelyProhibited).await, + } + Ok(()) + } } impl Client { @@ -600,6 +711,7 @@ where known_hosts: effective_known_hosts, host_key_policy: hop.host_key_policy, issue: issue.clone(), + remote_forwards: hop.forwards.iter().filter(|f| f.direction == ForwardDirection::Remote).cloned().collect(), }; let result = match stream { None => client::connect(config, (hop.host.as_str(), hop.port), handler).await, diff --git a/crates/ide-ssh/src/target.rs b/crates/ide-ssh/src/target.rs index baa40579e1..0041afbc23 100644 --- a/crates/ide-ssh/src/target.rs +++ b/crates/ide-ssh/src/target.rs @@ -54,6 +54,63 @@ pub(crate) struct Hop { pub host_key_policy: HostKeyPolicy, pub known_hosts: Option, pub agent: Agent, + /// `LocalForward` / `RemoteForward` of the config (the target's; jump hosts forward nothing). + pub forwards: Vec, +} + +/// A `LocalForward` or `RemoteForward` of `~/.ssh/config`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PortForward { + pub direction: ForwardDirection, + /// Address the listening side binds: empty for every address, `localhost` by default. + pub bind: String, + pub port: u16, + /// Where each connection goes, as the other side sees it. + pub host: String, + pub host_port: u16, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ForwardDirection { + /// `LocalForward`: this machine listens, connections go to `host:host_port` from the SSH host. + Local, + /// `RemoteForward`: the SSH host listens, connections go to `host:host_port` from this machine. + Remote, +} + +/// `[bind_address:]port host:hostport` (or the one-argument `-L` / `-R` form with colons); IPv6 +/// addresses in brackets. `None` for what isn't a TCP forward: a Unix socket, or `RemoteForward`'s +/// dynamic (SOCKS) form. +pub(crate) fn parse_forward(direction: ForwardDirection, value: &str) -> Option { + let spec = split_args(value).join(":"); + let mut parts: Vec = Vec::new(); + let mut cur = String::new(); + let mut bracket = false; + for ch in spec.chars() { + match ch { + '[' if cur.is_empty() => bracket = true, + ']' if bracket => bracket = false, + ':' if !bracket => parts.push(std::mem::take(&mut cur)), + '/' => return None, + _ => cur.push(ch), + } + } + parts.push(cur); + let (bind, port, host, host_port) = match parts.as_slice() { + [port, host, host_port] => (None, port, host, host_port), + [bind, port, host, host_port] => (Some(bind.as_str()), port, host, host_port), + _ => return None, + }; + let bind = match bind { + None => "localhost".to_owned(), + Some("*") | Some("") => String::new(), + Some(b) => b.to_owned(), + }; + let (port, host_port) = (port.parse().ok()?, host_port.parse().ok()?); + if host.is_empty() || host_port == 0 { + return None; + } + Some(PortForward { direction, bind, port, host: host.clone(), host_port }) } /// Where the SSH agent of a hop listens (`IdentityAgent`). @@ -158,6 +215,8 @@ struct RawConfig { host_key_policy: Option, user_known_hosts_file: Option, identity_agent: Option, + forwards: Vec, + clear_forwardings: bool, } fn strip_quotes(s: &str) -> &str { @@ -516,6 +575,23 @@ fn parse_config_file( out.user_known_hosts_file = Some(first); } } + "localforward" | "remoteforward" => { + let direction = if key.eq_ignore_ascii_case("localforward") { + ForwardDirection::Local + } else { + ForwardDirection::Remote + }; + match parse_forward(direction, value) { + Some(f) if !out.forwards.contains(&f) => out.forwards.push(f), + Some(_) => {} + None => tracing::debug!("ssh config: {key} {value} is not a TCP port forward; skipped"), + } + } + "clearallforwardings" => { + if matches!(strip_quotes(value).to_ascii_lowercase().as_str(), "yes" | "true") { + out.clear_forwardings = true; + } + } _ => {} } } @@ -559,7 +635,8 @@ fn config_hop( if null_known_hosts { HostKeyPolicy::Off } else { raw.host_key_policy.unwrap_or(HostKeyPolicy::Ask) }; let agent = identity_agent(raw.identity_agent.as_deref(), |p| expand(&expand_tokens(p, alias, &host, port, &user, &local))); - let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent }; + let forwards = if raw.clear_forwardings { Vec::new() } else { raw.forwards }; + let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent, forwards }; (hop, proxy_jump) } @@ -574,7 +651,7 @@ fn jump_hop(config: Option<&Path>, spec: &str) -> Hop { _ => (rest, None), }; let (hop, _) = config_hop(config, host, port, user); - hop + Hop { forwards: Vec::new(), ..hop } } /// The SSH hosts to go through, the target last. @@ -597,6 +674,7 @@ pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResu host_key_policy: HostKeyPolicy::Ask, known_hosts: None, agent: Agent::Default, + forwards: Vec::new(), }, None, ) @@ -636,6 +714,40 @@ pub fn openssh_args(target: &SshTarget) -> Vec { mod tests { use super::*; + #[test] + fn parses_port_forwards_like_openssh() { + let f = |d, v: &str| parse_forward(d, v).map(|f| (f.bind, f.port, f.host, f.host_port)); + let remote = ForwardDirection::Remote; + assert_eq!(f(remote, "9222 127.0.0.1:9222"), Some(("localhost".into(), 9222, "127.0.0.1".into(), 9222))); + assert_eq!(f(remote, "0.0.0.0:8080 web:80"), Some(("0.0.0.0".into(), 8080, "web".into(), 80))); + assert_eq!(f(remote, "*:8080 web:80"), Some((String::new(), 8080, "web".into(), 80))); + assert_eq!(f(remote, "[::1]:8080 [::1]:80"), Some(("::1".into(), 8080, "::1".into(), 80))); + assert_eq!(f(ForwardDirection::Local, "5432:db:5432"), Some(("localhost".into(), 5432, "db".into(), 5432))); + // Dynamic (SOCKS) and Unix socket forwards aren't TCP port forwards. + assert_eq!(f(remote, "1080"), None); + assert_eq!(f(remote, "/tmp/a.sock /tmp/b.sock"), None); + assert_eq!(f(remote, "8080 web:http"), None); + } + + #[test] + fn config_forwards_belong_to_the_target_and_clear_all_forwardings_drops_them() { + let dir = tempfile::tempdir().unwrap(); + let config = dir.path().join("config"); + std::fs::write( + &config, + "Host box\n RemoteForward 9222 127.0.0.1:9222\n LocalForward 5432 db:5432\n ProxyJump gate\n\ + Host gate\n LocalForward 1 a:1\nHost quiet\n RemoteForward 9222 127.0.0.1:9222\n ClearAllForwardings yes\n", + ) + .unwrap(); + let target = |host: &str| SshTarget { host: host.into(), auth: SshAuth::OpenSsh, ..Default::default() }; + let hops = resolve_hops(&target("box"), Some(&config)).unwrap(); + assert_eq!(hops.len(), 2); + assert!(hops[0].forwards.is_empty(), "jump hosts forward nothing"); + let dirs: Vec<_> = hops[1].forwards.iter().map(|f| (f.direction, f.port)).collect(); + assert_eq!(dirs, [(ForwardDirection::Remote, 9222), (ForwardDirection::Local, 5432)]); + assert!(resolve_hops(&target("quiet"), Some(&config)).unwrap()[0].forwards.is_empty()); + } + #[test] fn resolves_aliases_and_proxy_jumps_from_ssh_config() { let tmp = tempfile::tempdir().unwrap(); diff --git a/crates/ide-ssh/tests/session.rs b/crates/ide-ssh/tests/session.rs index 2e9e1a792d..b68e963feb 100644 --- a/crates/ide-ssh/tests/session.rs +++ b/crates/ide-ssh/tests/session.rs @@ -98,6 +98,32 @@ impl server::Handler for Sshd { }); Ok(()) } + + /// `RemoteForward`: listens on 127.0.0.1:`port` and forwards each connection back to the client. + async fn tcpip_forward( + &mut self, + address: &str, + port: &mut u32, + session: &mut ServerSession, + ) -> Result { + let Ok(listener) = TcpListener::bind(("127.0.0.1", *port as u16)).await else { return Ok(false) }; + let (handle, address, port) = (session.handle(), address.to_owned(), *port); + tokio::spawn(async move { + while let Ok((mut socket, peer)) = listener.accept().await { + let Ok(channel) = handle + .channel_open_forwarded_tcpip(address.clone(), port, "127.0.0.1", u32::from(peer.port())) + .await + else { + continue; + }; + tokio::spawn(async move { + let mut stream = channel.into_stream(); + let _ = tokio::io::copy_bidirectional(&mut stream, &mut socket).await; + }); + } + }); + Ok(true) + } } /// Echo server standing in for a remote service. @@ -443,3 +469,50 @@ async fn accept_new_records_an_unknown_key_and_still_refuses_a_changed_one() { let msg = denied(env.connect(&target, None).await); assert!(msg.contains("has changed"), "{msg}"); } + +/// A free local port (bound and released). +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +async fn echoes(port: u16) { + let mut s = TcpStream::connect(("127.0.0.1", port)).await.expect("forwarded port listens"); + s.write_all(b"ping").await.unwrap(); + let mut buf = [0u8; 4]; + s.read_exact(&mut buf).await.unwrap(); + assert_eq!(&buf, b"ping"); +} + +/// `RemoteForward` and `LocalForward` of `~/.ssh/config` are forwarded while the session lives (#6031). +#[tokio::test] +async fn config_port_forwards_follow_the_session() { + let mut env = env().await; + let (remote, local) = (free_port(), free_port()); + let config = env._tmp.path().join("ssh_config"); + std::fs::write( + &config, + format!( + "Host box\n\tHostName 127.0.0.1\n\tStrictHostKeyChecking=no\n\tUserKnownHostsFile=/dev/null\n\ + \tRemoteForward {remote} 127.0.0.1:{echo}\n\tLocalForward 127.0.0.1:{local} localhost:{echo}\n\ + \tRemoteForward /tmp/remote.sock /tmp/local.sock\n", + echo = env.echo_port + ), + ) + .unwrap(); + env.files.config = Some(config); + let target = SshTarget { + host: "box".into(), + port: Some(env.ssh_port), + user: "coder".into(), + auth: SshAuth::OpenSsh, + ..Default::default() + }; + let session = Arc::new(env.connect(&target, None).await.expect("connects")); + session.start_forwards().await; + // The SSH host's port reaches the echo server here; the local port reaches it from the SSH host. + echoes(remote).await; + echoes(local).await; + drop(session); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + assert!(TcpStream::connect(("127.0.0.1", local)).await.is_err(), "a closed session stops its LocalForward"); +}