feat(ssh): support OpenSSH ProxyCommand for tunnel hosts

This commit is contained in:
zipg authored and GitHub committed 2026-10-04 09:51:35 +08:00
1 parent 53cd0c516e
commit a3a5f4f9bd
29 files changed
+413 -10

No files matched your search

+1
View File
@@ -40,6 +40,7 @@ pub mod sqlite_worker;
pub use dbx_driver_sqlserver as sqlserver;
pub use dbx_driver_support::ssh_host_key;
pub use dbx_platform::ssh_prompt;
pub mod ssh_proxy_command;
pub mod ssh_tunnel;
pub use dbx_driver_mysql::starrocks;
pub use dbx_driver_mysql::tidb;
@@ -568,6 +568,7 @@ async fn open_final_hop_session(
&final_ssh.auth_method,
ssh_tunnel::effective_hop_timeout(final_ssh),
tunnels.known_hosts_path(),
&final_ssh.proxy_command,
)
.await;
}
@@ -603,6 +604,7 @@ async fn open_final_hop_session(
&final_ssh.auth_method,
ssh_tunnel::effective_hop_timeout(final_ssh),
tunnels.known_hosts_path(),
&final_ssh.proxy_command,
)
.await
{
@@ -0,0 +1,225 @@
//! Executing an OpenSSH-style `ProxyCommand` for an SSH tunnel.
//!
//! Only a small allowlist of transport helpers may be spawned: the SSH config
//! (and a shared tunnel profile) is data that can come from a cloned repo or a
//! synced profile, so running an arbitrary shell command from it would be a
//! code-execution footgun. The command is split into arguments ourselves (no
//! shell), which also means shell metacharacters cannot be used to chain extra
//! commands onto an allowlisted binary.
//!
//! Tokens `%h` (host), `%p` (port), `%r` (remote user) and `%%` are expanded
//! from the effective SSH endpoint before the program starts. `%n` (the
//! original host alias) is not available once the host has been resolved, so
//! it expands to the same value as `%h` — prefer `%h` in new configs.
use std::process::Stdio;
use tokio::io::{AsyncReadExt, Join};
use tokio::process::{ChildStdin, ChildStdout, Command};
/// Transport helpers that a `ProxyCommand` may invoke. Compared against the
/// basename of the first argv token, case-insensitively, with a trailing
/// `.exe` ignored.
pub const ALLOWED_PROXY_COMMAND_BINARIES: &[&str] =
&["nc", "ncat", "netcat", "cloudflared", "socat", "connect", "corkscrew", "ssh"];
/// Expands `%h`/`%p`/`%r`/`%n`/`%%` in a `ProxyCommand` template.
pub fn expand_proxy_command_tokens(command: &str, host: &str, port: u16, user: &str) -> String {
let mut expanded = String::with_capacity(command.len());
let mut chars = command.chars();
while let Some(ch) = chars.next() {
if ch != '%' {
expanded.push(ch);
continue;
}
match chars.next() {
Some('h') | Some('n') => expanded.push_str(host),
Some('p') => expanded.push_str(&port.to_string()),
Some('r') => expanded.push_str(user),
Some('%') => expanded.push('%'),
Some(other) => {
expanded.push('%');
expanded.push(other);
}
None => expanded.push('%'),
}
}
expanded
}
/// Splits a `ProxyCommand` into argv with POSIX-like quote handling: single
/// quotes are literal, double quotes allow `\` escapes, and a backslash
/// outside quotes escapes the next character.
pub fn parse_proxy_command_argv(command: &str) -> Result<Vec<String>, String> {
let mut argv: Vec<String> = Vec::new();
let mut current = String::new();
let mut has_token = false;
let mut quote: Option<char> = None;
let mut chars = command.chars();
while let Some(ch) = chars.next() {
match quote {
Some(open) => {
if ch == open {
quote = None;
has_token = true;
} else if open == '"' && ch == '\\' {
if let Some(escaped) = chars.next() {
current.push(escaped);
}
has_token = true;
} else {
current.push(ch);
has_token = true;
}
}
None if ch == '\'' || ch == '"' => {
quote = Some(ch);
has_token = true;
}
None if ch == '\\' => {
if let Some(escaped) = chars.next() {
current.push(escaped);
has_token = true;
}
}
None if ch.is_whitespace() => {
if has_token {
argv.push(std::mem::take(&mut current));
has_token = false;
}
}
None => {
current.push(ch);
has_token = true;
}
}
}
if quote.is_some() {
return Err("ProxyCommand has an unterminated quote".to_string());
}
if has_token {
argv.push(current);
}
if argv.is_empty() {
return Err("ProxyCommand is empty".to_string());
}
Ok(argv)
}
/// Returns `Ok(())` when the program is on the allowlist, otherwise a message
/// naming the allowed binaries.
pub fn validate_proxy_command_program(program: &str) -> Result<(), String> {
let basename = program.rsplit(['/', '\\']).next().unwrap_or(program);
let basename = basename.strip_suffix(".exe").unwrap_or(basename);
if ALLOWED_PROXY_COMMAND_BINARIES.iter().any(|allowed| allowed.eq_ignore_ascii_case(basename)) {
return Ok(());
}
Err(format!(
"ProxyCommand program '{program}' is not allowed; supported helpers: {}",
ALLOWED_PROXY_COMMAND_BINARIES.join(", ")
))
}
/// Starts the `ProxyCommand` process and returns its stdin/stdout joined into
/// one duplex stream for the SSH handshake. The child is reaped in the
/// background; dropping the stream closes its stdin, which makes the usual
/// helpers (`nc`, `cloudflared`) exit.
pub fn spawn_proxy_command_stream(
command: &str,
host: &str,
port: u16,
user: &str,
) -> Result<Join<ChildStdout, ChildStdin>, String> {
let expanded = expand_proxy_command_tokens(command, host, port, user);
let argv = parse_proxy_command_argv(&expanded)?;
let (program, args) = argv.split_first().expect("parse_proxy_command_argv never returns empty");
validate_proxy_command_program(program)?;
let mut child = Command::new(program)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|error| format!("Failed to start ProxyCommand '{program}': {error}"))?;
let Some(stdout) = child.stdout.take() else {
return Err("ProxyCommand stdout pipe is unavailable".to_string());
};
let Some(stdin) = child.stdin.take() else {
return Err("ProxyCommand stdin pipe is unavailable".to_string());
};
let mut stderr = child.stderr.take();
tokio::spawn(async move {
if let Some(stderr) = stderr.as_mut() {
let mut buffer = [0u8; 4096];
loop {
match stderr.read(&mut buffer).await {
Ok(0) | Err(_) => break,
Ok(read) => {
log::debug!("ProxyCommand stderr: {}", String::from_utf8_lossy(&buffer[..read]).trim_end())
}
}
}
}
let _ = child.wait().await;
});
Ok(tokio::io::join(stdout, stdin))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expands_host_port_and_user_tokens() {
assert_eq!(expand_proxy_command_tokens("nc %h %p", "db.internal", 2222, "deploy"), "nc db.internal 2222");
assert_eq!(expand_proxy_command_tokens("ssh -W %h:%p jump", "10.0.0.5", 22, "root"), "ssh -W 10.0.0.5:22 jump");
assert_eq!(expand_proxy_command_tokens("run %% literal", "h", 1, "u"), "run % literal");
assert_eq!(expand_proxy_command_tokens("user %r", "h", 1, "deploy"), "user deploy");
}
#[test]
fn keeps_unknown_tokens_verbatim() {
assert_eq!(expand_proxy_command_tokens("tool %z %h", "h", 1, "u"), "tool %z h");
}
#[test]
fn parses_quoted_arguments() {
assert_eq!(
parse_proxy_command_argv("cloudflared access ssh --hostname db.internal").unwrap(),
vec!["cloudflared", "access", "ssh", "--hostname", "db.internal"]
);
assert_eq!(parse_proxy_command_argv("tool 'a b' \"c d\"").unwrap(), vec!["tool", "a b", "c d"]);
assert_eq!(parse_proxy_command_argv("tool a\\ b").unwrap(), vec!["tool", "a b"]);
}
#[test]
fn rejects_unterminated_quotes() {
assert!(parse_proxy_command_argv("tool 'oops").is_err());
}
#[test]
fn allowlist_accepts_known_helpers_and_rejects_others() {
assert!(validate_proxy_command_program("nc").is_ok());
assert!(validate_proxy_command_program("/usr/bin/nc").is_ok());
assert!(validate_proxy_command_program("cloudflared.exe").is_ok());
assert!(validate_proxy_command_program("ssh").is_ok());
let error = validate_proxy_command_program("/bin/sh").unwrap_err();
assert!(error.contains("not allowed"), "{error}");
assert!(error.contains("nc"), "{error}");
}
#[test]
fn shell_metacharacters_are_not_executed() {
// `;` is a plain argument character because we never involve a shell;
// the allowlist still rejects non-helper programs.
let argv = parse_proxy_command_argv("nc %h %p; rm -rf /").unwrap();
assert_eq!(argv, vec!["nc", "%h", "%p;", "rm", "-rf", "/"]);
assert!(validate_proxy_command_program(&argv[0]).is_ok());
}
}
+58 -10
View File
@@ -411,6 +411,7 @@ pub async fn connect_and_authenticate(
auth_method: &str,
connect_timeout_secs: u64,
known_hosts_path: &Path,
proxy_command: &str,
) -> Result<Handle<SshClient>, String> {
let config = Arc::new(ssh_client_config());
let connect_timeout = Duration::from_secs(connect_timeout_secs);
@@ -422,16 +423,33 @@ pub async fn connect_and_authenticate(
let host_key_verifier = Arc::new(HostKeyVerifier::new(known_hosts_path.to_path_buf()));
let (started_tx, mut started_rx) = mpsc::channel::<Instant>(1);
let connect_fut = client::connect(
config,
(connect_host, connect_port),
SshClient {
host_key_verifier: host_key_verifier.clone(),
host: host_key_host.to_string(),
port: host_key_port,
prompt_started_tx: Some(started_tx),
},
);
let handler = SshClient {
host_key_verifier: host_key_verifier.clone(),
host: host_key_host.to_string(),
port: host_key_port,
prompt_started_tx: Some(started_tx),
};
// A ProxyCommand swaps the direct TCP connection for a helper process
// (`nc`, `cloudflared`, ...) whose stdio carries the SSH handshake. Tokens
// expand from the logical host/port so a forwarded jump hop still names
// the host it is reaching rather than the previous hop's local endpoint.
let proxy_stream = if proxy_command.trim().is_empty() {
None
} else {
Some(crate::db::ssh_proxy_command::spawn_proxy_command_stream(
proxy_command,
host_key_host,
host_key_port,
ssh_user,
)?)
};
let direct_host = connect_host.to_string();
let connect_fut = async move {
match proxy_stream {
Some(stream) => client::connect_stream(config, stream, handler).await,
None => client::connect(config, (direct_host.as_str(), connect_port), handler).await,
}
};
tokio::pin!(connect_fut);
// `connect_timeout` is meant to bound the *network* portion of the
@@ -1251,6 +1269,7 @@ async fn tunnel_reconnect_loop(
target: TunnelTarget,
allow_exec_channel_proxy: bool,
status: Arc<TunnelStatus>,
proxy_command: String,
) {
loop {
// Reaching the top of the loop means a live session: either the initial
@@ -1291,6 +1310,7 @@ async fn tunnel_reconnect_loop(
&auth_method,
connect_timeout_secs,
&known_hosts_path,
&proxy_command,
)
.await
{
@@ -1473,6 +1493,7 @@ impl TunnelManager {
remote_port: u16,
expose_to_lan: bool,
allow_exec_channel_proxy: bool,
proxy_command: &str,
) -> Result<u16, String> {
self.start_tunnel_on_local_port(
connection_id,
@@ -1493,6 +1514,7 @@ impl TunnelManager {
expose_to_lan,
allow_exec_channel_proxy,
None,
proxy_command,
)
.await
}
@@ -1518,6 +1540,7 @@ impl TunnelManager {
expose_to_lan: bool,
allow_exec_channel_proxy: bool,
requested_local_port: Option<u16>,
proxy_command: &str,
) -> Result<u16, String> {
{
let mut tunnels = self.tunnels.lock().await;
@@ -1564,6 +1587,7 @@ impl TunnelManager {
expose_to_lan,
allow_exec_channel_proxy,
requested_local_port,
proxy_command,
)
.await?;
@@ -1591,6 +1615,7 @@ impl TunnelManager {
auth_method: &str,
connect_timeout_secs: u64,
allow_exec_channel_proxy: bool,
proxy_command: &str,
) -> Result<u16, String> {
{
let mut tunnels = self.tunnels.lock().await;
@@ -1628,6 +1653,7 @@ impl TunnelManager {
connect_timeout_secs,
&self.known_hosts_path,
allow_exec_channel_proxy,
proxy_command,
)
.await?;
@@ -1741,6 +1767,7 @@ impl TunnelManager {
is_last && hop.expose_lan,
hop.allow_exec_channel_proxy,
None,
&hop.proxy_command,
)
.await
.map_err(|err| format!("SSH hop {} failed: {err}", index + 1))?;
@@ -1839,6 +1866,7 @@ async fn spawn_tunnel(
expose_to_lan: bool,
allow_exec_channel_proxy: bool,
requested_local_port: Option<u16>,
proxy_command: &str,
) -> Result<(JoinHandle<()>, u16, Arc<TunnelStatus>), String> {
spawn_tunnel_target(
connect_host,
@@ -1858,6 +1886,7 @@ async fn spawn_tunnel(
expose_to_lan,
allow_exec_channel_proxy,
requested_local_port,
proxy_command,
)
.await
}
@@ -1878,6 +1907,7 @@ async fn spawn_socks5_proxy(
connect_timeout_secs: u64,
known_hosts_path: &Path,
allow_exec_channel_proxy: bool,
proxy_command: &str,
) -> Result<(JoinHandle<()>, u16, Arc<TunnelStatus>), String> {
spawn_tunnel_target(
connect_host,
@@ -1897,6 +1927,7 @@ async fn spawn_socks5_proxy(
false,
allow_exec_channel_proxy,
None,
proxy_command,
)
.await
}
@@ -1920,6 +1951,7 @@ async fn spawn_tunnel_target(
expose_to_lan: bool,
allow_exec_channel_proxy: bool,
requested_local_port: Option<u16>,
proxy_command: &str,
) -> Result<(JoinHandle<()>, u16, Arc<TunnelStatus>), String> {
let (listener, local_port) = bind_tunnel_listener(expose_to_lan, requested_local_port).await?;
@@ -1938,6 +1970,7 @@ async fn spawn_tunnel_target(
auth_method,
connect_timeout_secs,
known_hosts_path,
proxy_command,
)
.await?;
@@ -1961,6 +1994,7 @@ async fn spawn_tunnel_target(
target,
allow_exec_channel_proxy,
status.clone(),
proxy_command.to_string(),
));
Ok((handle, local_port, status))
@@ -2208,6 +2242,7 @@ mod tests {
ssh_agent_sock_path: String::new(),
auth_method: "password".to_string(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
}
}
@@ -2969,6 +3004,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"password",
5,
&known_hosts_path,
"",
)
.await
.expect("password + TOTP authentication should succeed");
@@ -3015,6 +3051,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"key",
5,
&known_hosts_path,
"",
)
.await
.expect("public key + TOTP authentication should succeed");
@@ -3137,6 +3174,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"none",
5,
false,
"",
)
.await
.unwrap();
@@ -3156,6 +3194,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"none",
5,
false,
"",
)
.await
.unwrap();
@@ -3291,6 +3330,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
5432,
false,
true,
"",
)
.await
.expect("start fallback tunnel");
@@ -3346,6 +3386,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
5432,
false,
false,
"",
)
.await
.expect("start tunnel");
@@ -3389,6 +3430,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"none",
5,
&known_hosts_path,
"",
)
.await
.expect("forwarded SSH connection should authenticate");
@@ -3438,6 +3480,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"none",
1,
&known_hosts_path,
"",
)
.await
.expect("accepting the host key after the network timeout window should still succeed");
@@ -3487,6 +3530,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
5432,
false,
false,
"",
);
let second = manager.start_tunnel(
"shared-layer",
@@ -3506,6 +3550,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
5432,
false,
false,
"",
);
let (first_port, second_port) = tokio::join!(first, second);
@@ -3716,6 +3761,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
3306,
false,
false,
"",
)
.await
.expect("initial tunnel start should succeed");
@@ -3760,6 +3806,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
3306,
false,
false,
"",
)
.await;
@@ -3806,6 +3853,7 @@ uveF/dLmnVN1IriEyEvHAAAACGRieC10ZXN0AQIDBAU=
"key",
5,
&known_hosts_path,
"",
)
.await
{
@@ -200,6 +200,7 @@ async fn start_transport_layers_internal(
&resolved.auth_method,
effective_ssh_connect_timeout_secs(resolved.connect_timeout_secs),
resolved.allow_exec_channel_proxy,
&resolved.proxy_command,
)
.await
.map_err(|err| format!("SSH layer {} failed: {err}", index + 1))?
@@ -226,6 +227,7 @@ async fn start_transport_layers_internal(
is_last && resolved.expose_lan,
resolved.allow_exec_channel_proxy,
if is_last { final_ssh_local_port } else { None },
&resolved.proxy_command,
)
.await
.map_err(|err| format!("SSH layer {} failed: {err}", index + 1))?
@@ -411,6 +413,7 @@ mod tests {
ssh_agent_sock_path: String::new(),
auth_method: "password".to_string(),
allow_exec_channel_proxy: false,
proxy_command: String::new(),
})
}