363 lines
12 KiB
Rust
363 lines
12 KiB
Rust
//! Owned local listener + isolated OpenSSH stdio forwards. No remote commands.
|
|
use crate::remote::SshProfile;
|
|
use forward::forward;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::{
|
|
net::SocketAddr,
|
|
sync::{
|
|
Arc,
|
|
atomic::{AtomicU64, Ordering},
|
|
},
|
|
time::Duration,
|
|
};
|
|
use tokio::{
|
|
net::{TcpListener, TcpStream},
|
|
sync::{Semaphore, watch},
|
|
task::JoinSet,
|
|
};
|
|
mod forward;
|
|
|
|
#[derive(Clone, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct Config {
|
|
pub schema_version: u32,
|
|
pub ssh: SshProfile,
|
|
pub listen: SocketAddr,
|
|
pub remote_port: u16,
|
|
pub max_connections: usize,
|
|
}
|
|
/// The `ssh` options of a forward-only tunnel: no multiplexing, no X11, fail when the forward cannot be set up.
|
|
const TUNNEL_OPTIONS: [&str; 15] = [
|
|
"-o",
|
|
"ControlMaster=no",
|
|
"-o",
|
|
"ControlPath=none",
|
|
"-o",
|
|
"ControlPersist=no",
|
|
"-o",
|
|
"ForwardX11=no",
|
|
"-o",
|
|
"ExitOnForwardFailure=yes",
|
|
"-o",
|
|
"ServerAliveInterval=10",
|
|
"-o",
|
|
"ServerAliveCountMax=3",
|
|
"-W",
|
|
];
|
|
|
|
impl Config {
|
|
pub fn arguments(&self) -> Result<Vec<String>, String> {
|
|
if self.schema_version != 1
|
|
|| !self.listen.ip().is_loopback()
|
|
|| self.remote_port == 0
|
|
|| !(1..=16).contains(&self.max_connections)
|
|
{
|
|
return Err("invalid SSH tunnel profile".into());
|
|
}
|
|
let mut args = self.ssh.arguments()?;
|
|
args.truncate(args.len() - 4); // remove -- host sh -s; no remote shell command
|
|
args.extend(TUNNEL_OPTIONS.into_iter().map(str::to_owned));
|
|
args.extend([
|
|
format!("127.0.0.1:{}", self.remote_port),
|
|
"--".into(),
|
|
self.ssh.host.clone(),
|
|
]);
|
|
Ok(args)
|
|
}
|
|
}
|
|
#[derive(Clone, Default)]
|
|
pub struct Counters {
|
|
accepted: Arc<AtomicU64>,
|
|
active: Arc<AtomicU64>,
|
|
completed: Arc<AtomicU64>,
|
|
failed: Arc<AtomicU64>,
|
|
rejected: Arc<AtomicU64>,
|
|
}
|
|
#[derive(Serialize)]
|
|
pub struct Snapshot {
|
|
pub accepted: u64,
|
|
pub active: u64,
|
|
pub completed: u64,
|
|
pub failed: u64,
|
|
pub rejected: u64,
|
|
}
|
|
impl Counters {
|
|
pub fn snapshot(&self) -> Snapshot {
|
|
Snapshot {
|
|
accepted: self.accepted.load(Ordering::Relaxed),
|
|
active: self.active.load(Ordering::Relaxed),
|
|
completed: self.completed.load(Ordering::Relaxed),
|
|
failed: self.failed.load(Ordering::Relaxed),
|
|
rejected: self.rejected.load(Ordering::Relaxed),
|
|
}
|
|
}
|
|
}
|
|
struct Active(Counters);
|
|
impl Drop for Active {
|
|
fn drop(&mut self) {
|
|
self.0.active.fetch_sub(1, Ordering::Relaxed);
|
|
}
|
|
}
|
|
pub struct Tunnel {
|
|
listener: TcpListener,
|
|
args: Vec<String>,
|
|
limit: usize,
|
|
counters: Counters,
|
|
}
|
|
impl Tunnel {
|
|
pub async fn bind(config: &Config) -> Result<Self, String> {
|
|
let args = config.arguments()?;
|
|
let listener = TcpListener::bind(config.listen)
|
|
.await
|
|
.map_err(|_| "SSH tunnel local port unavailable")?;
|
|
Ok(Self {
|
|
listener,
|
|
args,
|
|
limit: config.max_connections,
|
|
counters: Counters::default(),
|
|
})
|
|
}
|
|
pub fn address(&self) -> SocketAddr {
|
|
self.listener.local_addr().expect("bound listener")
|
|
}
|
|
pub fn counters(&self) -> Counters {
|
|
self.counters.clone()
|
|
}
|
|
pub async fn serve(self, shutdown: impl Future<Output = ()> + Send) -> Result<(), String> {
|
|
self.run("ssh", shutdown).await
|
|
}
|
|
async fn run(
|
|
self,
|
|
program: &str,
|
|
shutdown: impl Future<Output = ()> + Send,
|
|
) -> Result<(), String> {
|
|
let mut tasks = JoinSet::new();
|
|
let (cancel_tx, cancel) = watch::channel(false);
|
|
let mut gate = Gate {
|
|
permits: Arc::new(Semaphore::new(self.limit)),
|
|
cancel,
|
|
next_start: tokio::time::Instant::now(),
|
|
};
|
|
tokio::pin!(shutdown);
|
|
loop {
|
|
tokio::select! {
|
|
_ = &mut shutdown => break,
|
|
Some(_) = tasks.join_next(), if !tasks.is_empty() => {},
|
|
accepted = self.listener.accept() => {
|
|
let (stream, _) = accepted.map_err(|_| "tunnel accept failed")?;
|
|
self.admit(&mut gate, program, stream, &mut tasks);
|
|
}
|
|
}
|
|
}
|
|
cancel_tx.send_replace(true);
|
|
while tasks.join_next().await.is_some() {}
|
|
Ok(())
|
|
}
|
|
/// Admits the connection within the limit (otherwise it is closed and counted as rejected) and
|
|
/// starts its forward, at most one every 250 ms.
|
|
fn admit(&self, gate: &mut Gate, program: &str, stream: TcpStream, tasks: &mut JoinSet<()>) {
|
|
let Ok(permit) = gate.permits.clone().try_acquire_owned() else {
|
|
self.counters.rejected.fetch_add(1, Ordering::Relaxed);
|
|
drop(stream);
|
|
return;
|
|
};
|
|
self.counters.accepted.fetch_add(1, Ordering::Relaxed);
|
|
self.counters.active.fetch_add(1, Ordering::Relaxed);
|
|
let start = std::cmp::max(gate.next_start, tokio::time::Instant::now());
|
|
gate.next_start = start + Duration::from_millis(250);
|
|
let connection = Connection {
|
|
program: program.to_string(),
|
|
args: self.args.clone(),
|
|
counters: self.counters.clone(),
|
|
cancel: gate.cancel.clone(),
|
|
start,
|
|
};
|
|
tasks.spawn(connection.serve(stream, permit));
|
|
}
|
|
}
|
|
/// What the accept loop threads between connections.
|
|
struct Gate {
|
|
permits: Arc<Semaphore>,
|
|
cancel: watch::Receiver<bool>,
|
|
next_start: tokio::time::Instant,
|
|
}
|
|
struct Connection {
|
|
program: String,
|
|
args: Vec<String>,
|
|
counters: Counters,
|
|
cancel: watch::Receiver<bool>,
|
|
start: tokio::time::Instant,
|
|
}
|
|
impl Connection {
|
|
async fn serve(self, stream: TcpStream, permit: tokio::sync::OwnedSemaphorePermit) {
|
|
let _permit = permit;
|
|
let _active = Active(self.counters.clone());
|
|
let result = forward(stream, &self.program, &self.args, self.cancel, self.start).await;
|
|
if result.is_ok() {
|
|
self.counters.completed.fetch_add(1, Ordering::Relaxed);
|
|
} else {
|
|
self.counters.failed.fetch_add(1, Ordering::Relaxed);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
fn config() -> Config {
|
|
Config {
|
|
schema_version: 1,
|
|
ssh: SshProfile {
|
|
schema_version: 1,
|
|
id: "test".into(),
|
|
host: "example.test".into(),
|
|
user: None,
|
|
port: None,
|
|
identity_file: None,
|
|
},
|
|
listen: "127.0.0.1:0".parse().unwrap(),
|
|
remote_port: 18766,
|
|
max_connections: 2,
|
|
}
|
|
}
|
|
#[test]
|
|
fn safe_stdio_forward_arguments_and_validation() {
|
|
let c = config();
|
|
let a = c.arguments().unwrap();
|
|
for v in [
|
|
"StrictHostKeyChecking=yes",
|
|
"ClearAllForwardings=yes",
|
|
"ControlMaster=no",
|
|
"ControlPath=none",
|
|
"ControlPersist=no",
|
|
"ForwardAgent=no",
|
|
"PermitLocalCommand=no",
|
|
"-W",
|
|
"127.0.0.1:18766",
|
|
] {
|
|
assert!(a.iter().any(|x| x == v), "{v}");
|
|
}
|
|
assert_eq!(&a[a.len() - 2..], ["--", "example.test"]);
|
|
assert!(!a.iter().any(|x| x == "sh" || x == "-s" || x == "-L"));
|
|
let mut bad = c.clone();
|
|
bad.listen = "0.0.0.0:1234".parse().unwrap();
|
|
assert!(bad.arguments().is_err());
|
|
bad = c.clone();
|
|
bad.remote_port = 0;
|
|
assert!(bad.arguments().is_err());
|
|
bad = c;
|
|
bad.ssh.host = "-oProxyCommand=bad".into();
|
|
assert!(bad.arguments().is_err());
|
|
}
|
|
#[tokio::test]
|
|
async fn occupied_port_is_not_replaced() {
|
|
let held = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let mut c = config();
|
|
c.listen = held.local_addr().unwrap();
|
|
assert!(Tunnel::bind(&c).await.is_err());
|
|
assert!(TcpStream::connect(c.listen).await.is_ok());
|
|
}
|
|
/// A running tunnel whose connections go to `program` instead of SSH.
|
|
#[cfg(unix)]
|
|
struct Running {
|
|
addr: SocketAddr,
|
|
stats: Counters,
|
|
stop: tokio::sync::oneshot::Sender<()>,
|
|
task: tokio::task::JoinHandle<Result<(), String>>,
|
|
}
|
|
#[cfg(unix)]
|
|
async fn start(config: &Config, program: &'static str) -> Running {
|
|
let t = Tunnel::bind(config).await.unwrap();
|
|
let addr = t.address();
|
|
let stats = t.counters();
|
|
let (stop, rx) = tokio::sync::oneshot::channel();
|
|
// cat is a byte transport fixture; remove SSH arguments only inside this test.
|
|
let t = Tunnel { args: vec![], ..t };
|
|
let task = tokio::spawn(t.run(program, async {
|
|
let _ = rx.await;
|
|
}));
|
|
Running {
|
|
addr,
|
|
stats,
|
|
stop,
|
|
task,
|
|
}
|
|
}
|
|
/// Sends 300 kB, half-closes, and expects the same bytes back.
|
|
#[cfg(unix)]
|
|
async fn echo_round_trip(addr: SocketAddr) {
|
|
let mut stream = TcpStream::connect(addr).await.unwrap();
|
|
let data: Vec<u8> = (0..300_000).map(|i| (i % 251) as u8).collect();
|
|
let (mut r, mut w) = stream.split();
|
|
let writer = async {
|
|
w.write_all(&data).await.unwrap();
|
|
w.shutdown().await.unwrap();
|
|
};
|
|
let reader = async {
|
|
let mut out = vec![];
|
|
r.read_to_end(&mut out).await.unwrap();
|
|
out
|
|
};
|
|
let (_, out) = tokio::time::timeout(Duration::from_secs(4), async {
|
|
tokio::join!(writer, reader)
|
|
})
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(out, data);
|
|
}
|
|
// A direct subprocess exercises backpressure, binary data, half-close, lifetime,
|
|
// connection admission and recreation independently of an SSH daemon.
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn bytes_half_close_reconnect_and_owned_shutdown() {
|
|
let t = start(&config(), "/bin/cat").await;
|
|
for _ in 0..2 {
|
|
echo_round_trip(t.addr).await;
|
|
}
|
|
let mut a = TcpStream::connect(t.addr).await.unwrap();
|
|
a.write_all(b"a").await.unwrap();
|
|
let mut b = [0];
|
|
a.read_exact(&mut b).await.unwrap();
|
|
t.stop.send(()).unwrap();
|
|
tokio::time::timeout(Duration::from_secs(2), t.task)
|
|
.await
|
|
.unwrap()
|
|
.unwrap()
|
|
.unwrap();
|
|
assert_eq!(t.stats.snapshot().active, 0);
|
|
assert_eq!(t.stats.snapshot().accepted, 3);
|
|
assert_eq!(a.read(&mut b).await.unwrap(), 0);
|
|
assert!(TcpListener::bind(t.addr).await.is_ok());
|
|
}
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn failure_isolated_and_connection_limit_enforced() {
|
|
let mut c = config();
|
|
c.max_connections = 1;
|
|
let t = start(&c, "/bin/cat").await;
|
|
let mut first = TcpStream::connect(t.addr).await.unwrap();
|
|
first.write_all(b"x").await.unwrap();
|
|
let mut b = [0];
|
|
first.read_exact(&mut b).await.unwrap();
|
|
let mut second = TcpStream::connect(t.addr).await.unwrap();
|
|
assert_eq!(
|
|
tokio::time::timeout(Duration::from_secs(1), second.read(&mut b))
|
|
.await
|
|
.unwrap()
|
|
.unwrap(),
|
|
0
|
|
);
|
|
assert_eq!(t.stats.snapshot().rejected, 1);
|
|
t.stop.send(()).unwrap();
|
|
t.task.await.unwrap().unwrap();
|
|
let t = start(&c, "/usr/bin/false").await;
|
|
let mut client = TcpStream::connect(t.addr).await.unwrap();
|
|
assert_eq!(client.read(&mut b).await.unwrap(), 0);
|
|
tokio::time::sleep(Duration::from_millis(150)).await;
|
|
assert_eq!(t.stats.snapshot().failed, 1);
|
|
t.stop.send(()).unwrap();
|
|
t.task.await.unwrap().unwrap();
|
|
}
|
|
}
|