diff --git a/crates/openshell-supervisor-process/src/ssh.rs b/crates/openshell-supervisor-process/src/ssh.rs index a11eddbd21..22719382b5 100644 --- a/crates/openshell-supervisor-process/src/ssh.rs +++ b/crates/openshell-supervisor-process/src/ssh.rs @@ -4,6 +4,7 @@ //! Embedded SSH server for sandbox access. mod input; +mod streamlocal; mod upload; #[cfg(test)] @@ -633,6 +634,28 @@ impl russh::server::Handler for SshHandler { Ok(()) } + async fn channel_open_direct_streamlocal( + &mut self, + channel: russh::Channel, + socket_path: &str, + reply: ChannelOpenHandle, + _session: &mut Session, + ) -> Result<(), Self::Error> { + if !streamlocal::is_workspace_socket(socket_path) { + reply + .reject(ChannelOpenFailure::AdministrativelyProhibited) + .await; + return Ok(()); + } + tokio::spawn(streamlocal::forward( + self.boundary_exec.clone(), + socket_path.to_owned(), + channel, + reply, + )); + Ok(()) + } + async fn pty_request( &mut self, channel: ChannelId, @@ -1950,6 +1973,24 @@ mod tests { } } + #[tokio::test] + async fn direct_streamlocal_rejects_outside_workspace_and_failed_exec() { + let client = authenticated_test_client().await; + for (path, failure) in [ + ( + "/run/openshell/control.sock", + ChannelOpenFailure::AdministrativelyProhibited, + ), + ("/sandbox/listener.sock", ChannelOpenFailure::ConnectFailed), + ] { + let error = client + .channel_open_direct_streamlocal(path) + .await + .expect_err("channel opening must fail"); + assert!(matches!(error, russh::Error::ChannelOpenFailure(code) if code == failure)); + } + } + #[tokio::test] async fn direct_tcpip_handler_relays_loopback_bytes() { use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; diff --git a/crates/openshell-supervisor-process/src/ssh/streamlocal.py b/crates/openshell-supervisor-process/src/ssh/streamlocal.py new file mode 100644 index 0000000000..a9508ab67a --- /dev/null +++ b/crates/openshell-supervisor-process/src/ssh/streamlocal.py @@ -0,0 +1,45 @@ +# SPDX-License-Identifier: Apache-2.0 + +import os +import socket +import stat +import sys +import threading +from contextlib import ExitStack + + +def connect(path, sock): + parts = path.split("/")[2:] + with ExitStack() as fds: + directory = os.open("/sandbox", os.O_PATH | os.O_DIRECTORY | os.O_NOFOLLOW) + fds.callback(os.close, directory) + for part in parts[:-1]: + directory = os.open( + part, os.O_PATH | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory + ) + fds.callback(os.close, directory) + endpoint = os.open(parts[-1], os.O_PATH | os.O_NOFOLLOW, dir_fd=directory) + fds.callback(os.close, endpoint) + info = os.fstat(endpoint) + if not stat.S_ISSOCK(info.st_mode) or info.st_uid != os.geteuid(): + raise PermissionError("expected a workload-owned Unix socket") + sock.connect(f"/proc/self/fd/{endpoint}") + + +def send_input(sock): + try: + while data := os.read(0, 64 * 1024): + sock.sendall(data) + sock.shutdown(socket.SHUT_WR) + except OSError: + sock.shutdown(socket.SHUT_RDWR) + + +with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: + connect(sys.argv[1], connection) + sys.stdout.buffer.write(b"\x01") + sys.stdout.buffer.flush() + threading.Thread(target=send_input, args=(connection,), daemon=True).start() + while data := connection.recv(64 * 1024): + sys.stdout.buffer.write(data) + sys.stdout.buffer.flush() diff --git a/crates/openshell-supervisor-process/src/ssh/streamlocal.rs b/crates/openshell-supervisor-process/src/ssh/streamlocal.rs new file mode 100644 index 0000000000..78a177c061 --- /dev/null +++ b/crates/openshell-supervisor-process/src/ssh/streamlocal.rs @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: Apache-2.0 + +use std::{sync::Arc, time::Duration}; + +use openshell_isolation_interface::contract::ExecSpec; +use openshell_sandbox_backend::BoundaryExec; +use russh::{ + Channel, ChannelOpenFailure, + server::{ChannelOpenHandle, Msg}, +}; +use tokio::io::AsyncReadExt; + +pub(super) fn is_workspace_socket(path: &str) -> bool { + path.len() <= 107 + && !path.chars().any(char::is_control) + && path.strip_prefix("/sandbox/").is_some_and(|relative| { + relative + .split('/') + .all(|part| !matches!(part, "" | "." | "..")) + }) +} + +pub(super) async fn forward( + boundary: Arc, + path: String, + channel: Channel, + reply: ChannelOpenHandle, +) { + // The ordinary exec path applies the sandbox identity, Landlock and seccomp + // before the relay opens a socket. The supervisor never resolves the path. + let spec = ExecSpec { + program: "python3".into(), + args: vec![ + "-I".into(), + "-S".into(), + "-c".into(), + include_str!("streamlocal.py").into(), + path, + ], + shell: None, + runtime_helper: None, + env: Vec::new(), + workdir: None, + pty: false, + }; + let Ok(mut exec) = boundary.exec(spec).await else { + reply.reject(ChannelOpenFailure::ConnectFailed).await; + return; + }; + let process = exec.process; + let diagnostics = exec.stderr.take().map(|mut stderr| { + tokio::spawn(async move { tokio::io::copy(&mut stderr, &mut tokio::io::sink()).await }) + }); + let mut marker = [0]; + let connected = + tokio::time::timeout(Duration::from_secs(5), exec.stdout.read_exact(&mut marker)) + .await + .is_ok_and(|result| result.is_ok()) + && marker == [1]; + match exec.stdin.take() { + Some(stdin) if connected => { + reply.accept().await; + let mut workload = tokio::io::join(exec.stdout, stdin); + let mut client = channel.into_stream(); + let _ = tokio::io::copy_bidirectional(&mut client, &mut workload).await; + drop(workload); + } + _ => reply.reject(ChannelOpenFailure::ConnectFailed).await, + } + if let Some(diagnostics) = diagnostics { + diagnostics.abort(); + } + let _ = process.terminate().await; +} + +#[cfg(test)] +mod tests { + use super::is_workspace_socket; + use crate::ssh::tests::test_client; + use openshell_isolation_interface::contract::{ + BackendError, BoundaryExitStatus, BoundarySignal, ExecSpec, + }; + use openshell_sandbox_backend::test_support as rpc_test; + use std::sync::Arc; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + struct RelayProcess; + + #[async_trait::async_trait] + impl rpc_test::BoundaryProcess for RelayProcess { + async fn wait(&self) -> Result { + std::future::pending().await + } + + async fn signal(&self, _: BoundarySignal) -> Result<(), BackendError> { + Ok(()) + } + + async fn terminate(&self) -> Result<(), BackendError> { + Ok(()) + } + } + + struct EchoExec; + + #[async_trait::async_trait] + impl rpc_test::BoundaryExec for EchoExec { + async fn exec(&self, spec: ExecSpec) -> Result { + assert_eq!(spec.program, "python3"); + assert_eq!(spec.args.last().unwrap(), "/sandbox/echo.sock"); + assert!(spec.runtime_helper.is_none()); + let (workload, session) = tokio::io::duplex(64); + let (mut input, mut output) = tokio::io::split(workload); + tokio::spawn(async move { + output.write_all(&[1]).await.unwrap(); + tokio::io::copy(&mut input, &mut output).await.unwrap(); + }); + let (stdout, stdin) = tokio::io::split(session); + Ok(rpc_test::ExecSession { + process: Arc::new(RelayProcess), + stdin: Some(Box::new(stdin)), + stdout: Box::new(stdout), + stderr: None, + terminal: None, + output_status: None, + }) + } + } + + #[tokio::test] + async fn forwards_channel_bytes_after_the_workload_connects() { + let client = test_client( + None, + rpc_test::exec(Arc::new(EchoExec)), + russh::client::Config::default(), + ) + .await; + let mut channel = client + .channel_open_direct_streamlocal("/sandbox/echo.sock") + .await + .unwrap() + .into_stream(); + channel.write_all(b"ping").await.unwrap(); + let mut reply = [0; 4]; + tokio::time::timeout( + std::time::Duration::from_secs(5), + channel.read_exact(&mut reply), + ) + .await + .expect("echo timed out") + .unwrap(); + assert_eq!(&reply, b"ping"); + } + + #[test] + fn streamlocal_paths_must_name_a_socket_under_the_workspace() { + assert!(is_workspace_socket("/sandbox/.rex.example/server.sock")); + for path in [ + "", + "/sandbox", + "/sandbox/", + "/sandbox-other/server.sock", + "/sandbox/../run/docker.sock", + "/sandbox/./server.sock", + "/sandbox//server.sock", + "/sandbox/line\nbreak", + "@abstract", + ] { + assert!(!is_workspace_socket(path), "{path:?}"); + } + assert!(!is_workspace_socket(&format!( + "/sandbox/{}", + "s".repeat(100) + ))); + } +} diff --git a/docs/how-it-works/sandboxes/overview.mdx b/docs/how-it-works/sandboxes/overview.mdx index 123678e9fe..e13c2c0dac 100644 --- a/docs/how-it-works/sandboxes/overview.mdx +++ b/docs/how-it-works/sandboxes/overview.mdx @@ -928,6 +928,8 @@ openshell sandbox ssh-config my-sandbox Append the output to `~/.ssh/config` or use `--editor` on `sandbox create`/`sandbox connect` for automatic setup. If the gateway URL contains credentials, a path, a query, or a fragment, register it under a gateway name and use that name when generating the SSH config. +On Linux images with Python 3, OpenSSH clients can forward Unix stream sockets owned by the workload user below `/sandbox`. The connection runs with the sandbox's workload permissions. The destination path must name the socket directly without symlinks. + SSH config entries that an earlier release generated accept any host key, so connections through them are refused. Using `--editor` on `sandbox create` or `sandbox connect` replaces that sandbox's entry, and every