diff --git a/AGENTS.md b/AGENTS.md index fb5fca4..acd172e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,11 @@ Rules: loop), and the spec says where. - The sandbox is the security boundary. Approval is always `AllowAll`; never add an approval prompt in the room. +- The control plane never opens an ssh connection and never parses ssh, + HTTP, or terminal bytes from a sandbox. `src/worker.rs` owns the data + plane: one disposable process per target, one room's key on stdin, a + loopback route behind a random token, no database, no master key. + Keep new sandbox parsing there, not in `src/api` or `src/room`. - Every path into the sandbox goes through `rhema_sandbox::Sandbox` or `ShellSandbox` (agent tools, files, terminal, preview). Do not spawn a command on the host for room work. @@ -52,8 +57,9 @@ src/room/agent.rs per-turn config, ssh sandbox, HostAgent assembly src/room/runner.rs one task per room; mention -> turn; steering src/room/message_tool.rs the agent's voice in the room src/room/preview_tool.rs the agent's preview target -src/ssh.rs russh client, PTY terminal, direct-tcpip -src/preview.rs signed preview hosts, ssh proxy, static reads +src/worker.rs disposable data plane: loopback HTTP, PTY, forward, worker spawn +src/ssh.rs russh client and PTY pump, used only by the worker +src/preview.rs signed preview hosts, worker forward, static reads web/app/ Nuxt 4 SPA (no SSR) ``` diff --git a/Cargo.lock b/Cargo.lock index ae43d4a..97e59f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3618,6 +3618,18 @@ dependencies = [ "tokio", ] +[[package]] +name = "rhema-sandbox-http" +version = "0.5.1" +dependencies = [ + "async-trait", + "base64 0.23.1", + "reqwest", + "rhema-sandbox", + "serde", + "serde_json", +] + [[package]] name = "rhema-sandbox-ssh" version = "0.5.1" @@ -3686,11 +3698,14 @@ dependencies = [ "futures", "hex", "hmac 0.12.1", + "http-body-util", "hyper", "hyper-util", "mime_guess", + "nix", "percent-encoding", "rand 0.8.8", + "reqwest", "rhema-bash", "rhema-core", "rhema-host-agent", @@ -3700,6 +3715,7 @@ dependencies = [ "rhema-provider-mistral", "rhema-provider-registry", "rhema-sandbox", + "rhema-sandbox-http", "rhema-sandbox-ssh", "rhema-transcript", "rusqlite", @@ -3714,6 +3730,7 @@ dependencies = [ "time", "tokio", "tokio-stream", + "tokio-tungstenite", "tower-http", "tracing", "tracing-subscriber", diff --git a/Cargo.toml b/Cargo.toml index fa10316..c689f5d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,9 +21,12 @@ hex = "0.4" hmac = "0.12" hyper = { version = "1", features = ["client", "http1"] } hyper-util = { version = "0.1", features = ["tokio"] } +http-body-util = "0.1" mime_guess = "2" +nix = { version = "0.31", features = ["process"] } percent-encoding = "2" rand = "0.8" +reqwest = { version = "0.13", default-features = false, features = ["json", "rustls", "stream"] } rhema-bash = { path = "../rhema/crates/rhema-bash" } rhema-core = { path = "../rhema/crates/rhema-core" } rhema-host-agent = { path = "../rhema/crates/rhema-host-agent" } @@ -33,6 +36,7 @@ rhema-provider-copilot = { path = "../rhema/crates/rhema-provider-copilot" } rhema-provider-mistral = { path = "../rhema/crates/rhema-provider-mistral" } rhema-provider-registry = { path = "../rhema/crates/rhema-provider-registry" } rhema-sandbox = { path = "../rhema/crates/rhema-sandbox" } +rhema-sandbox-http = { path = "../rhema/crates/rhema-sandbox-http" } rhema-sandbox-ssh = { path = "../rhema/crates/rhema-sandbox-ssh" } rhema-transcript = { path = "../rhema/crates/rhema-transcript" } russh = { version = "0.65", default-features = false, features = ["ring", "rsa"] } @@ -46,6 +50,7 @@ tar = "0.4" thiserror = "2" time = "0.3" tokio = { version = "1", features = ["full"] } +tokio-tungstenite = "0.29" tokio-stream = { version = "0.1", features = ["sync"] } tower-http = { version = "0.6", features = ["fs", "trace", "compression-gzip"] } tracing = "0.1" diff --git a/README.md b/README.md index 6273e5e..f48779a 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,7 @@ Every field can be set in the YAML file (`TOGETHER_CONFIG`, default | `TOGETHER_WEB_DIR` | `web/.output/public` | built client | | `TOGETHER_MAX_TURN_STEPS` | `48` | step cap per turn | | `TOGETHER_ALLOW_REGISTRATION` | `false` | whether `/register` works | +| `TOGETHER_ALLOW_PRIVATE_TARGETS` | `false` | whether a sandbox target may use a loopback or private address | ## Security model diff --git a/specs/rhema-together.md b/specs/rhema-together.md index c6a2506..4869da3 100644 --- a/specs/rhema-together.md +++ b/specs/rhema-together.md @@ -233,6 +233,40 @@ an idle period or when the owner changes the target. A room whose target is unreachable keeps its chat: messages post, a turn fails with a room message, and the panes show the error instead of a spinner. +### A hostile sandbox + +The far side is treated as hostile input, not as a trusted peer. The +control plane never opens an ssh connection and never parses an ssh, +HTTP, or terminal byte from a sandbox. Each room gets a disposable +worker process (`rhema-together worker`) that: + +- holds only that room's target key, never the master key or the + database; +- listens on loopback behind a random token; +- serves the `rhema-sandbox` HTTP protocol, a pty websocket, and a raw + preview forward socket; +- is started with a cleared environment, `PR_SET_DUMPABLE=0`, and + `PR_SET_NO_NEW_PRIVS`; +- exits when its parent closes stdin, so a crashed server leaves no + orphan holding a key. + +If a hostile sandbox exploits russh, the protocol parser, or a worker +route, it lands in a process with no database, no master key, and no +provider credential. The parent kills it and starts another. A +deployment should run workers under a different UID or in a separate +container with no mount for the database and secret key; the +child-process boundary is the portable default, not the strongest tier. + +Caps are part of the boundary: a 32 MiB file route cap, 50 KiB output +tails, a 16 MiB static preview cap, a 4 KiB forward handshake line, and +the upstream request timeouts. No path from a sandbox reaches a host +shell: the worker only sends commands over the transport. + +The worker does not make the network safe by itself. A direct ssh target +is still a user-supplied address. Link targets are the default because +the server never dials a user's network. Direct target address checks +belong to the API and the config, not to the worker. + ### Why ssh first The ssh backend already runs commands on a remote box with no daemon on @@ -517,10 +551,16 @@ login. The room log is the audit trail, and abort is the control. ### Outbound connections -The server dials addresses that users supply. Block loopback, link-local, -and multicast destinations by default, so a sandbox target cannot turn -the harness into a probe of its own network. An operator can allow a -private range in the config when every user is on the same network. +The default is a connector link: the sandbox dials out to the server, so +the server never dials a user-supplied address and a hostile sandbox +cannot use it as a probe of the server's network. Direct ssh remains an +opt-in compatibility mode. Its address is checked when the target is +created and again when the worker starts: loopback, private, link-local, +multicast, unspecified, carrier-grade NAT, and documentation addresses +are rejected. An operator on one private network can set +`TOGETHER_ALLOW_PRIVATE_TARGETS=1`. The worker dials the address, never +the control plane. A DNS name that resolves to a public address when the +worker starts and to a private one later is outside this check. ### Secrets @@ -660,8 +700,9 @@ explanation. Settled: -1. Sandbox: SSH only in v1. ecrou waits for a live mode, with the - shell-on-top runner as a possible degraded mode. +1. Sandbox: the per-room disposable worker owns every transport. A + connector link is the default; direct SSH is opt-in. ecrou waits for a + live mode, with the shell-on-top runner as a possible degraded mode. 2. Provider and model: the room owner picks both, and only the owner changes them. Every turn spends from that config. 3. Interrupts: any member. v1 has no rate limit. diff --git a/src/api/files.rs b/src/api/files.rs index 0fde998..9a4d8ae 100644 --- a/src/api/files.rs +++ b/src/api/files.rs @@ -4,14 +4,17 @@ use std::sync::atomic::AtomicBool; use std::time::Duration; use axum::Json; -use axum::extract::ws::WebSocketUpgrade; +use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade}; use axum::extract::{Path, Query, State}; -use axum::http::HeaderMap; +use axum::http::{HeaderMap, HeaderValue}; use axum::response::Response; +use futures::{SinkExt, StreamExt}; use rhema_sandbox::Sandbox; use rhema_sandbox::exec_util::shquote; use serde::Deserialize; use serde_json::{Value, json}; +use tokio_tungstenite::tungstenite::Message as TMessage; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; use crate::auth::AuthUser; use crate::error::{AppError, AppResult}; @@ -215,8 +218,8 @@ pub async fn git( }))) } -/// The web terminal upgrade. The ssh connection is opened only after -/// the socket is accepted, with the same target and key as the agent. +/// The web terminal upgrade. The control plane only proxies bytes: the +/// room's worker owns the ssh connection and the pty. pub async fn terminal( user: AuthUser, State(state): State, @@ -229,8 +232,110 @@ pub async fn terminal( } member_of(&state, &room, &user.user.id)?; let (workspace, target) = room_workspace(&state, &room)?; + let worker = crate::worker::client_for(&state, &workspace, &target) + .await + .map_err(|err| AppError::new(axum::http::StatusCode::BAD_GATEWAY, err))?; let account = user.user.id.clone(); - Ok(ws.on_upgrade(move |socket| { - crate::ssh::terminal(socket, state, room, account, workspace, target) + Ok(ws.on_upgrade(move |socket| async move { + proxy_terminal(socket, worker, state, room, account).await; })) } + +async fn proxy_terminal( + socket: WebSocket, + worker: crate::worker::WorkerClient, + state: Shared, + room: String, + account: String, +) { + let url = format!("ws://127.0.0.1:{}/pty?cols=100&rows=30", worker.http_port); + let Ok(mut request) = url.into_client_request() else { + return; + }; + let Ok(token) = HeaderValue::from_str(&worker.token) else { + return; + }; + request.headers_mut().insert("x-rhema-token", token); + let (worker_socket, _) = match tokio_tungstenite::connect_async(request).await { + Ok(pair) => pair, + Err(err) => { + let (mut sink, _) = socket.split(); + let _ = sink + .send(WsMessage::Text( + json!({ "type": "error", "message": format!("the sandbox worker did not answer: {err}") }) + .to_string() + .into(), + )) + .await; + return; + } + }; + let (mut browser_sink, mut browser_source) = socket.split(); + let (mut worker_sink, mut worker_source) = worker_socket.split(); + let mut access = tokio::time::interval(std::time::Duration::from_secs(2)); + loop { + tokio::select! { + _ = access.tick() => { + if member_of(&state, &room, &account).is_err() { + break; + } + } + message = worker_source.next() => { + match message { + Some(Ok(message)) => { + if let Some(message) = from_worker(message) + && browser_sink.send(message).await.is_err() + { + break; + } + } + _ => break, + } + } + message = browser_source.next() => { + match message { + Some(Ok(message)) => { + if let Some(message) = to_worker(message) + && worker_sink.send(message).await.is_err() + { + break; + } + } + _ => break, + } + } + } + } + let _ = worker_sink.close().await; +} + +fn from_worker(message: TMessage) -> Option { + match message { + TMessage::Text(text) => Some(WsMessage::Text(text.as_str().into())), + TMessage::Binary(data) => Some(WsMessage::Binary(data)), + TMessage::Ping(data) => Some(WsMessage::Ping(data)), + TMessage::Pong(data) => Some(WsMessage::Pong(data)), + TMessage::Close(frame) => Some(WsMessage::Close(frame.map(|frame| { + axum::extract::ws::CloseFrame { + code: frame.code.into(), + reason: frame.reason.as_str().into(), + } + }))), + TMessage::Frame(_) => None, + } +} + +fn to_worker(message: WsMessage) -> Option { + match message { + WsMessage::Text(text) => Some(TMessage::Text(text.as_str().into())), + WsMessage::Binary(data) => Some(TMessage::Binary(data)), + WsMessage::Ping(data) => Some(TMessage::Ping(data)), + WsMessage::Pong(data) => Some(TMessage::Pong(data)), + WsMessage::Close(frame) => Some(TMessage::Close(frame.map(|frame| { + tokio_tungstenite::tungstenite::protocol::CloseFrame { + code: frame.code.into(), + reason: frame.reason.as_str().into(), + } + }))), + } +} diff --git a/src/api/rooms.rs b/src/api/rooms.rs index a914000..2b5bca9 100644 --- a/src/api/rooms.rs +++ b/src/api/rooms.rs @@ -366,10 +366,16 @@ pub async fn archive( Path(id): Path, ) -> AppResult> { owner_of(&state, &id, &user.user.id)?; + let workspace: String = state.db.conn().query_row( + "SELECT workspace FROM rooms WHERE id = ?1", + rusqlite::params![id], + |row| row.get(0), + )?; state.db.conn().execute( "UPDATE rooms SET archived_at = ?1 WHERE id = ?2", rusqlite::params![now_ms(), id], )?; + state.workers.remove_workspace(&workspace).await; Ok(Json(json!({ "ok": true }))) } diff --git a/src/api/settings.rs b/src/api/settings.rs index 6143f36..6980979 100644 --- a/src/api/settings.rs +++ b/src/api/settings.rs @@ -1,6 +1,5 @@ //! Provider configurations and ssh sandbox targets. -use std::sync::Arc; use std::sync::atomic::AtomicBool; use std::time::Duration; @@ -388,6 +387,11 @@ pub async fn create_target( return Err(AppError::bad_request("host must be a hostname or address")); } let port = body.port.unwrap_or(22); + if !state.config.allow_private_targets { + crate::util::check_target_address(host, port) + .await + .map_err(AppError::bad_request)?; + } let user_name = body .user_name .map(|value| value.trim().to_owned()) @@ -464,12 +468,14 @@ pub async fn delete_target( "DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2", rusqlite::params![id, user.user.id], )?; - state.previews.forget(&id); + state.workers.remove_target(&id).await; Ok(Json(json!({ "ok": true }))) } -/// Opens an ssh connection and runs `printf ok` at `/`. This proves the -/// key, the host key, and the login, without touching the room's files. +/// Runs `printf ok` at `/` through the room-worker path. This proves +/// the key, the host key, and the login without touching room files. +/// The probe still goes through a disposable worker, so the control +/// plane never opens an ssh connection itself. pub async fn test_target( user: AuthUser, State(state): State, @@ -479,8 +485,8 @@ pub async fn test_target( .db .conn() .query_row( - "SELECT host, port, user_name, private_key_ciphertext FROM sandbox_targets - WHERE id = ?1 AND account_id = ?2", + "SELECT host, port, user_name, private_key_ciphertext, host_fingerprint + FROM sandbox_targets WHERE id = ?1 AND account_id = ?2", rusqlite::params![id, user.user.id], |row| { Ok(( @@ -488,15 +494,21 @@ pub async fn test_target( row.get::<_, i64>(1)?, row.get::<_, String>(2)?, row.get::<_, String>(3)?, + row.get::<_, Option>(4)?, )) }, ) .map_err(|_| AppError::not_found("sandbox target not found"))?; - let key = state.secrets.open_str(&row.3)?; - let sandbox = rhema_sandbox_ssh::SshSandbox::new(format!("{}@{}:{}", row.2, row.0, row.1)) - .with_workspace("/") - .with_private_key(key); - let cancelled = Arc::new(AtomicBool::new(false)); + let target = crate::room::agent::TargetRow { + id: id.clone(), + host: row.0.clone(), + port: row.1, + user_name: row.2.clone(), + private_key_ciphertext: row.3, + host_fingerprint: row.4, + }; + let sandbox = crate::worker::WorkerSandbox::new(state.clone(), "/", &target); + let cancelled = AtomicBool::new(false); let mut progress = rhema_sandbox::OutputOnly(|_| {}); let request = rhema_sandbox::RunRequest { command: "printf ok".into(), diff --git a/src/config.rs b/src/config.rs index ae550d1..844f666 100644 --- a/src/config.rs +++ b/src/config.rs @@ -33,6 +33,11 @@ pub struct Config { /// invites as the only doors. #[serde(default)] pub allow_registration: bool, + /// Whether a sandbox target may point at a loopback, private, + /// link-local, or multicast address. Off by default, so a target + /// cannot turn the server into a probe of its own network. + #[serde(default)] + pub allow_private_targets: bool, } fn default_steps() -> u32 { @@ -51,6 +56,7 @@ impl Default for Config { max_turn_steps: default_steps(), allowed_frame_ancestors: Vec::new(), allow_registration: false, + allow_private_targets: false, } } } @@ -89,6 +95,9 @@ impl Config { if let Ok(value) = std::env::var("TOGETHER_ALLOW_REGISTRATION") { config.allow_registration = matches!(value.as_str(), "1" | "true" | "yes"); } + if let Ok(value) = std::env::var("TOGETHER_ALLOW_PRIVATE_TARGETS") { + config.allow_private_targets = matches!(value.as_str(), "1" | "true" | "yes"); + } config.public_url = config.public_url.trim_end_matches('/').to_owned(); config.preview_origin = config.preview_origin.trim_end_matches('/').to_owned(); Ok(config) diff --git a/src/main.rs b/src/main.rs index 4af5981..309e030 100644 --- a/src/main.rs +++ b/src/main.rs @@ -12,6 +12,7 @@ mod room; mod ssh; mod state; mod util; +mod worker; use std::sync::Arc; @@ -25,13 +26,18 @@ use crate::state::{AppState, Hub}; #[tokio::main] async fn main() -> anyhow::Result<()> { tracing_subscriber::fmt() + .with_writer(std::io::stderr) .with_env_filter( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| "rhema_together=info,tower_http=warn".into()), ) .init(); - let config_path = std::env::args() - .nth(1) + let mut args = std::env::args().skip(1); + let first = args.next(); + if first.as_deref() == Some("worker") { + return worker::run_worker().await; + } + let config_path = first .map(std::path::PathBuf::from) .unwrap_or_else(|| std::path::PathBuf::from("together.yaml")); let config = Config::load(&config_path)?; @@ -44,7 +50,7 @@ async fn main() -> anyhow::Result<()> { secrets, hub: Hub::default(), rooms: Default::default(), - previews: Default::default(), + workers: Default::default(), presence: Default::default(), logins: Default::default(), }); diff --git a/src/preview.rs b/src/preview.rs index 97cf2ce..21295fd 100644 --- a/src/preview.rs +++ b/src/preview.rs @@ -7,15 +7,14 @@ //! serves a file or folder with `index.html` read over ssh. Paths and the //! origin stay stable, so absolute asset URLs keep working. -use std::collections::HashMap; use std::sync::atomic::AtomicBool; -use std::sync::{Arc, Mutex}; use std::time::Duration; use axum::body::Body; use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode, Uri, header}; use axum::response::{IntoResponse, Response}; -use hyper_util::rt::TokioIo; +use base64::Engine; +use futures::TryStreamExt; use percent_encoding::percent_decode_str; use rhema_sandbox::Sandbox; use rhema_sandbox::exec_util::shquote; @@ -29,37 +28,6 @@ use crate::room::agent::{self, TargetRow}; use crate::state::Shared; use crate::util::safe_rel_path; -/// One ssh connection per sandbox, opened lazily by the first preview -/// request and reused by the channels after it. -#[derive(Default)] -pub struct PreviewTunnels { - handles: Mutex>>>, -} - -impl PreviewTunnels { - fn get(&self, target: &str) -> Option>> { - self.handles - .lock() - .unwrap_or_else(|err| err.into_inner()) - .get(target) - .cloned() - } - - fn put(&self, target: &str, handle: Arc>) { - self.handles - .lock() - .unwrap_or_else(|err| err.into_inner()) - .insert(target.to_owned(), handle); - } - - pub(crate) fn forget(&self, target: &str) { - self.handles - .lock() - .unwrap_or_else(|err| err.into_inner()) - .remove(target); - } -} - /// The preview scheme and host for this configuration, if previews /// are on. fn domain(config: &Config) -> Option<(&str, &str)> { @@ -443,73 +411,58 @@ async fn try_proxy( port: u16, request: Request, ) -> Result { + const PROXY_BODY_CAP: usize = 16 * 1024 * 1024; let (workspace, target) = agent::load_room_target(state, room).map_err(|err| err.message)?; - let _ = workspace; - let key = state - .secrets - .open_str(&target.private_key_ciphertext) - .map_err(|err| err.message)?; - let handle = match state.previews.get(&target.id) { - Some(handle) => handle, - None => { - let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?; - crate::ssh::remember_host_key(state, &target, learned); - let handle = Arc::new(handle); - state.previews.put(&target.id, handle.clone()); - handle - } - }; - let channel = match handle - .channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0) + let worker = crate::worker::client_for(state, &workspace, &target).await?; + let (parts, body) = request.into_parts(); + let bytes = axum::body::to_bytes(body, PROXY_BODY_CAP) .await - { - Ok(channel) => channel, - Err(_) => { - state.previews.forget(&target.id); - let (handle, learned) = crate::ssh::connect_handle(&target, &key).await?; - crate::ssh::remember_host_key(state, &target, learned); - let handle = Arc::new(handle); - state.previews.put(&target.id, handle.clone()); - handle - .channel_open_direct_tcpip("127.0.0.1", port as u32, "127.0.0.1", 0) - .await - .map_err(|err| format!("the sandbox refused port {port}: {err}"))? + .map_err(|err| format!("the preview request body is too large: {err}"))?; + let mut headers = std::collections::BTreeMap::new(); + for (name, value) in parts.headers.iter() { + if matches!( + name, + &header::HOST | &header::CONTENT_LENGTH | &header::TRANSFER_ENCODING + ) { + continue; } - }; - let stream = channel.into_stream(); - let io = TokioIo::new(stream); - let (mut sender, connection) = hyper::client::conn::http1::handshake(io) - .await - .map_err(|err| format!("http handshake failed: {err}"))?; - tokio::spawn(async move { - let _ = connection.await; - }); - let path = request - .uri() + if let Ok(value) = value.to_str() { + headers.insert(name.to_string(), value.to_owned()); + } + } + headers.insert("host".into(), format!("127.0.0.1:{port}")); + let path = parts + .uri .path_and_query() .map(|value| value.as_str()) - .unwrap_or("/"); - let uri: Uri = path.parse().map_err(|err| format!("bad path: {err}"))?; - let (parts, body) = request.into_parts(); - let mut outbound = Request::builder() - .method(parts.method) - .uri(uri) - .body(body) - .map_err(|err| format!("could not build the request: {err}"))?; - *outbound.headers_mut() = parts.headers; - strip_hop_by_hop(outbound.headers_mut()); - outbound.headers_mut().insert( - header::HOST, - HeaderValue::from_str(&format!("127.0.0.1:{port}")).unwrap(), - ); - let response = sender - .send_request(outbound) + .unwrap_or("/") + .to_owned(); + let proxy = crate::worker::ProxyRequest { + port, + method: parts.method.to_string(), + path, + headers, + body_base64: base64::engine::general_purpose::STANDARD.encode(bytes), + }; + let response = reqwest::Client::builder() + .timeout(Duration::from_secs(30)) + .build() + .map_err(|err| format!("could not build the preview client: {err}"))? + .post(format!("{}/room/proxy", worker.base_url())) + .header(rhema_sandbox::protocol::TOKEN_HEADER, &worker.token) + .json(&proxy) + .send() .await - .map_err(|err| format!("the preview did not answer: {err}"))?; - let (parts, body) = response.into_parts(); - let mut out = Response::new(Body::new(body)); - *out.status_mut() = parts.status; - *out.headers_mut() = parts.headers; + .map_err(|err| format!("the sandbox worker did not answer: {err}"))?; + let status = response.status(); + let headers = response.headers().clone(); + let mut out = Response::new(Body::from_stream( + response + .bytes_stream() + .map_err(|err| std::io::Error::other(err.to_string())), + )); + *out.status_mut() = status; + *out.headers_mut() = headers; strip_hop_by_hop(out.headers_mut()); Ok(no_referrer(out)) } diff --git a/src/room/agent.rs b/src/room/agent.rs index dd4a6e9..6848a3b 100644 --- a/src/room/agent.rs +++ b/src/room/agent.rs @@ -12,7 +12,6 @@ use rhema_core::{Overlay, Session, ToolResolver}; use rhema_host_agent::{HostAgent, HostAgentConfig}; use rhema_sandbox::WorkspaceSeed; use rhema_sandbox::{Sandbox, ShellSandbox}; -use rhema_sandbox_ssh::SshSandbox; use crate::error::{AppError, AppResult}; use crate::state::Shared; @@ -44,6 +43,7 @@ pub struct ProviderRow { } /// The sandbox row, ciphertext included. +#[derive(Clone)] pub struct TargetRow { pub id: String, pub host: String, @@ -155,22 +155,27 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult }) } -/// The ssh destination in the form the backend resolves. -fn destination(target: &TargetRow) -> String { - format!("{}@{}:{}", target.user_name, target.host, target.port) -} - -/// A sandbox handle for this room. -pub fn build_sandbox(state: &Shared, config: &TurnConfig) -> AppResult { +/// A sandbox handle for this room. The control plane never opens the +/// ssh connection itself: the handle belongs to the room's disposable +/// worker, and every call crosses a loopback HTTP route. +pub fn build_sandbox( + state: &Shared, + config: &TurnConfig, +) -> AppResult { sandbox_for(state, &config.workspace, &config.target) } /// A sandbox handle from a workspace and a target row. -pub fn sandbox_for(state: &Shared, workspace: &str, target: &TargetRow) -> AppResult { - let key = state.secrets.open_str(&target.private_key_ciphertext)?; - Ok(SshSandbox::new(destination(target)) - .with_workspace(workspace.to_owned()) - .with_private_key(key)) +pub fn sandbox_for( + state: &Shared, + workspace: &str, + target: &TargetRow, +) -> AppResult { + Ok(crate::worker::WorkerSandbox::new( + state.clone(), + workspace, + target, + )) } /// The room's workspace and target, for routes that do not need the diff --git a/src/ssh.rs b/src/ssh.rs index f803daf..f7c13c3 100644 --- a/src/ssh.rs +++ b/src/ssh.rs @@ -1,7 +1,13 @@ //! The web terminal: a real pty on the far side, over the same ssh //! target and key the agent's commands use. +//! +//! This module is the worker side. The control plane never parses ssh: +//! it proxies the terminal websocket to the room's worker and the +//! worker owns the client here. The host-key policy learns the key on +//! first contact and refuses a change after that. use std::sync::{Arc, Mutex}; +use std::time::Duration; use axum::extract::ws::{Message as WsMessage, WebSocket}; use futures::{SinkExt, StreamExt}; @@ -11,7 +17,6 @@ use russh::{ChannelMsg, Error as SshError}; use serde_json::json; use crate::room::agent::TargetRow; -use crate::state::Shared; use crate::util::sha256_hex; /// The host-key policy: learn the key on first contact, refuse a change. @@ -46,29 +51,8 @@ impl client::Handler for HostKey { } } -/// Opens a connection for the preview proxy, returning the host-key -/// fingerprint when this was the first contact. -pub(crate) async fn connect_handle( - target: &TargetRow, - private_key: &str, -) -> Result<(Handle, Option), String> { - connect(target, private_key).await -} - -/// Pins a learned host key after a successful login. A later connection -/// then refuses a different key. -pub(crate) fn remember_host_key(state: &Shared, target: &TargetRow, learned: Option) { - if target.host_fingerprint.is_none() - && let Some(fingerprint) = learned - { - let _ = state.db.conn().execute( - "UPDATE sandbox_targets SET host_fingerprint = ?1 WHERE id = ?2", - rusqlite::params![fingerprint, target.id], - ); - } -} - -async fn connect( +/// Opens an ssh connection to `target` with the given key text. +pub(crate) async fn connect_with_key( target: &TargetRow, private_key: &str, ) -> Result<(Handle, Option), String> { @@ -106,46 +90,31 @@ async fn connect( Ok((connection, fingerprint)) } -/// Attaches a browser socket to an interactive shell in the room's -/// sandbox. -pub async fn terminal( +/// Opens an interactive shell and pumps the browser socket from it. +/// +/// The caller has already authenticated the browser and checked room +/// membership; this half knows only the target, the key and the cwd. +pub(crate) async fn terminal_with_key( socket: WebSocket, - state: Shared, - room: String, - account: String, - workspace: String, - target: TargetRow, + target: &TargetRow, + key: &str, + workspace: &str, + cols: u32, + rows: u32, ) { let (mut sink, mut source) = socket.split(); - let key = match state.secrets.open_str(&target.private_key_ciphertext) { - Ok(key) => key, - Err(err) => { - let _ = sink - .send(WsMessage::Text( - json!({ "type": "error", "message": err.message }) - .to_string() - .into(), - )) - .await; - return; - } - }; - let (connection, learned) = match connect(&target, &key).await { - Ok(connection) => connection, - Err(message) => { - let _ = sink - .send(WsMessage::Text( - json!({ "type": "error", "message": message }) - .to_string() - .into(), - )) - .await; - return; - } - }; - // Learn the host key once the login succeeded, not before: a - // server that refuses us should not become known. - remember_host_key(&state, &target, learned); + let (connection, _learned) = + match tokio::time::timeout(Duration::from_secs(20), connect_with_key(target, key)).await { + Ok(Ok(connection)) => connection, + Ok(Err(message)) => { + send_error(&mut sink, message).await; + return; + } + Err(_) => { + send_error(&mut sink, "the sandbox did not answer in time".into()).await; + return; + } + }; let mut channel = match connection.channel_open_session().await { Ok(channel) => channel, Err(err) => { @@ -155,10 +124,10 @@ pub async fn terminal( }; let cwd = format!( "cd {} 2>/dev/null || cd ~; exec bash -l", - rhema_sandbox::exec_util::shquote(&workspace) + rhema_sandbox::exec_util::shquote(workspace) ); if let Err(err) = channel - .request_pty(true, "xterm-256color", 100, 30, 0, 0, &[]) + .request_pty(true, "xterm-256color", cols, rows, 0, 0, &[]) .await { send_error(&mut sink, format!("the far end refused a pty: {err}")).await; @@ -173,14 +142,8 @@ pub async fn terminal( json!({ "type": "ready" }).to_string().into(), )) .await; - let mut access = tokio::time::interval(std::time::Duration::from_secs(2)); loop { tokio::select! { - _ = access.tick() => { - if crate::api::rooms::member_of(&state, &room, &account).is_err() { - break; - } - } message = channel.wait() => { match message { Some(ChannelMsg::Data { data }) => { @@ -241,7 +204,7 @@ pub async fn terminal( drop(connection); } -async fn send_error(sink: &mut S, message: String) +pub(crate) async fn send_error(sink: &mut S, message: String) where S: futures::Sink + Unpin, { diff --git a/src/state.rs b/src/state.rs index 0a21c20..40f18f4 100644 --- a/src/state.rs +++ b/src/state.rs @@ -12,7 +12,6 @@ use crate::crypto::Secrets; use crate::db::Db; use crate::error::AppResult; use crate::models::Envelope; -use crate::preview::PreviewTunnels; use crate::room::RoomRunner; /// One room's live feed and sequence allocator. @@ -125,7 +124,7 @@ pub struct AppState { pub secrets: Secrets, pub hub: Hub, pub rooms: RoomRunner, - pub previews: PreviewTunnels, + pub workers: crate::worker::Workers, pub presence: crate::presence::Presence, pub logins: crate::login::Logins, } diff --git a/src/util.rs b/src/util.rs index 54a1f66..7e96bf1 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,5 +1,7 @@ //! Small helpers shared by the API and the turn runner. +use std::net::{IpAddr, Ipv4Addr}; + use rand::RngCore; /// Milliseconds since the Unix epoch. @@ -10,6 +12,82 @@ pub fn now_ms() -> i64 { .unwrap_or(0) } +/// Parses an IP literal, including a bracketed IPv6 address. +pub fn literal_ip(host: &str) -> Option { + let host = host.trim().trim_start_matches('[').trim_end_matches(']'); + host.parse().ok() +} + +/// True when a target address is local. The list is the one a server +/// must not dial on behalf of a user: loopback, private, link-local, +/// multicast, unspecified, carrier-grade NAT, and the documentation +/// ranges. IPv4-mapped IPv6 follows its IPv4 part. +pub fn forbidden_target_ip(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => forbidden_v4(v4), + IpAddr::V6(v6) => { + if let Some(v4) = v6.to_ipv4_mapped() { + return forbidden_v4(v4); + } + let s = v6.segments(); + v6.is_loopback() + || v6.is_unspecified() + || v6.is_multicast() + || (s[0] & 0xffc0) == 0xfe80 + || (s[0] & 0xfe00) == 0xfc00 + || (s[0] & 0xffc0) == 0xfec0 + || (s[0] == 0x2001 && s[1] == 0x0db8) + } + } +} + +fn forbidden_v4(v4: Ipv4Addr) -> bool { + let o = v4.octets(); + v4.is_loopback() + || v4.is_private() + || v4.is_link_local() + || v4.is_broadcast() + || v4.is_unspecified() + || v4.is_multicast() + || v4.is_documentation() + || (o[0] == 100 && (o[1] & 0xc0) == 64) +} + +/// Resolves a target and rejects it when any address is local. A +/// hostname that does not resolve is an error too: a target the server +/// cannot reach is not a target. +pub async fn check_target_address(host: &str, port: u16) -> Result<(), String> { + if let Some(ip) = literal_ip(host) { + return if forbidden_target_ip(ip) { + Err(format!( + "{host} is a local or private address; an operator can allow those with TOGETHER_ALLOW_PRIVATE_TARGETS=1" + )) + } else { + Ok(()) + }; + } + let addrs = tokio::time::timeout( + std::time::Duration::from_secs(5), + tokio::net::lookup_host((host, port)), + ) + .await + .map_err(|_| format!("could not resolve {host} in time"))? + .map_err(|err| format!("could not resolve {host}: {err}"))? + .collect::>(); + if addrs.is_empty() { + return Err(format!("{host} did not resolve to an address")); + } + for addr in addrs { + if forbidden_target_ip(addr.ip()) { + return Err(format!( + "{host} resolves to the local address {}; an operator can allow private targets with TOGETHER_ALLOW_PRIVATE_TARGETS=1", + addr.ip() + )); + } + } + Ok(()) +} + /// A URL-safe random token of `bytes` entropy, no padding. pub fn random_token(bytes: usize) -> String { use base64::Engine; @@ -102,6 +180,38 @@ mod tests { ); } + #[test] + fn local_target_addresses_are_forbidden() { + for text in [ + "127.0.0.1", + "10.0.0.1", + "172.16.0.1", + "192.168.1.1", + "169.254.169.254", + "100.64.0.1", + "0.0.0.0", + "224.0.0.1", + "::1", + "fe80::1", + "fc00::1", + "::ffff:127.0.0.1", + ] { + let ip = literal_ip(text).unwrap(); + assert!(forbidden_target_ip(ip), "{text} should be forbidden"); + } + for text in ["1.1.1.1", "2606:4700:4700::1111", "::ffff:1.1.1.1"] { + let ip = literal_ip(text).unwrap(); + assert!(!forbidden_target_ip(ip), "{text} should be allowed"); + } + } + + #[tokio::test] + async fn a_literal_loopback_target_is_rejected() { + assert!(check_target_address("127.0.0.1", 22).await.is_err()); + assert!(check_target_address("[::1]", 22).await.is_err()); + assert!(check_target_address("1.1.1.1", 22).await.is_ok()); + } + #[test] fn mentions_need_a_word_boundary() { assert!(mentions_agent("@rhema fix this")); diff --git a/src/worker.rs b/src/worker.rs new file mode 100644 index 0000000..23f90d9 --- /dev/null +++ b/src/worker.rs @@ -0,0 +1,909 @@ +//! The sandbox data plane. +//! +//! The control plane never speaks ssh, and never parses a byte a +//! sandbox sends. Every room gets a disposable worker process: it holds +//! only that room's target key, listens on loopback behind a random +//! token, and serves the `rhema-sandbox` wire protocol, a pty websocket, +//! and a raw forward socket. The app reaches it with the ordinary +//! `HttpSandbox` client and proxies browser bytes. +//! +//! If a hostile sandbox exploits the ssh client or the worker's parser, +//! it lands in a process with no database, no master key, and no long +//! lived credentials beyond the one room's key. The parent kills it when +//! the room goes away, and the parent holds its stdin open so a crashed +//! app takes the worker with it. + +use std::collections::HashMap; +use std::sync::Arc; +use std::time::Duration; + +use axum::body::Body; +use axum::extract::ws::WebSocketUpgrade; +use axum::extract::{Query, State}; +use axum::http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{get as get_route, post}; +use axum::{Json, Router}; +use base64::Engine; +use futures::TryStreamExt; +use http_body_util::{BodyExt, Full}; +use hyper::body::Bytes; +use rhema_sandbox::protocol::{ + Ack, ExecCall, ExecReply, FileReply, PutFile, SeedRequest, TOKEN_HEADER, +}; +use rhema_sandbox::{Sandbox, SandboxError, WorkspaceSeed}; +use rhema_sandbox_ssh::SshSandbox; +use serde::{Deserialize, Serialize}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; +use tokio::sync::Mutex; + +use crate::room::agent::TargetRow; +use crate::state::Shared; + +/// The largest body a file route accepts, and the largest file the +/// worker returns. The protocol's own clients cap lower per route; this +/// is the outer wall. +const FILE_CAP: usize = 32 * 1024 * 1024; +/// The output tail the wire carries. The ssh backend already tails its +/// capture; this keeps a different backend honest too. +const OUTPUT_CAP: usize = 50 * 1024; +/// A hostile sandbox can accept a connection and stop talking. The +/// worker gives every transport step a bounded wait so a room cannot +/// pin a worker forever. +const SSH_STEP_TIMEOUT: Duration = Duration::from_secs(20); + +/// Everything a worker needs, and nothing else. It carries one target's +/// decrypted key; the worker never sees the master key, the database, +/// or another room. +#[derive(Clone, Serialize, Deserialize)] +pub struct WorkerConfig { + /// The room's workspace root on the far side. + pub workspace: String, + /// One sandbox target, key text included. + pub target: WorkerTarget, + /// Whether this target may be a local or private address. + #[serde(default)] + pub allow_private: bool, +} + +/// One ssh destination and its credential. +#[derive(Clone, Serialize, Deserialize)] +pub struct WorkerTarget { + pub id: String, + pub host: String, + pub port: u16, + pub user_name: String, + pub private_key: String, + pub host_fingerprint: Option, +} + +/// One preview request, as the app hands it to the worker. The worker +/// is the only side that parses the sandbox's HTTP reply. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct ProxyRequest { + pub port: u16, + pub method: String, + pub path: String, + #[serde(default)] + pub headers: std::collections::BTreeMap, + #[serde(default)] + pub body_base64: String, +} + +/// The line the worker writes on stdout once its listeners are bound. +/// The parent reads it before the worker serves anything. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct Handshake { + pub port: u16, + pub token: String, +} + +/// The app-side handle to one worker. +#[derive(Clone, Debug)] +pub struct WorkerClient { + pub http_port: u16, + pub token: String, +} + +impl WorkerClient { + /// The worker's loopback base URL, no trailing slash. + pub fn base_url(&self) -> String { + format!("http://127.0.0.1:{}", self.http_port) + } + + /// The ordinary sandbox client, pointed at this worker. + pub fn sandbox(&self) -> rhema_sandbox_http::HttpSandbox { + rhema_sandbox_http::HttpSandbox::new(self.base_url(), "room", &self.token) + } +} + +/// The worker process for a room, keyed by target and workspace. +#[derive(Default)] +pub struct Workers { + inner: Mutex>, +} + +struct WorkerHandle { + client: WorkerClient, + /// Kept open: the worker exits when this pipe closes, so a parent + /// crash cannot leave an orphan holding the target key. + _stdin: tokio::process::ChildStdin, + _child: tokio::process::Child, +} + +impl Workers { + /// The client for `key`, spawning `build`'s worker when there is no + /// live one. The closure runs only on a miss, so a cached worker + /// does not decrypt the target again. + pub async fn client_with(&self, key: &str, build: F) -> Result + where + F: FnOnce() -> Result, + { + let mut workers = self.inner.lock().await; + if let Some(handle) = workers.get_mut(key) + && handle + ._child + .try_wait() + .map(|status| status.is_none()) + .unwrap_or(false) + { + return Ok(handle.client.clone()); + } + workers.remove(key); + let config = build()?; + let (client, stdin, child) = spawn_worker(config).await?; + workers.insert( + key.to_owned(), + WorkerHandle { + client: client.clone(), + _stdin: stdin, + _child: child, + }, + ); + Ok(client) + } + + /// Drops one worker, killing its process. + pub async fn remove(&self, key: &str) { + self.inner.lock().await.remove(key); + } + + /// Drops every worker whose key ends in `workspace`. The archive + /// route uses this so a room that stops running does not leave a + /// process holding its key. + pub async fn remove_workspace(&self, workspace: &str) { + let suffix = format!(":{workspace}"); + let mut workers = self.inner.lock().await; + let keys: Vec = workers + .keys() + .filter(|key| key.ends_with(&suffix)) + .cloned() + .collect(); + for key in keys { + workers.remove(&key); + } + } + + /// Drops every worker that names `target`. + pub async fn remove_target(&self, target: &str) { + let prefix = format!("target:{target}:"); + let mut workers = self.inner.lock().await; + let keys: Vec = workers + .keys() + .filter(|key| key.starts_with(&prefix)) + .cloned() + .collect(); + for key in keys { + workers.remove(&key); + } + } +} + +/// Starts one worker and waits for its handshake. The config rides the +/// child's stdin, never argv or the environment, so the key does not +/// show up in `ps`. +async fn spawn_worker( + config: WorkerConfig, +) -> Result< + ( + WorkerClient, + tokio::process::ChildStdin, + tokio::process::Child, + ), + String, +> { + let exe = match std::env::var_os("RHEMA_WORKER_BIN") { + Some(path) => std::path::PathBuf::from(path), + None => std::env::current_exe() + .map_err(|err| format!("could not find the server binary: {err}"))?, + }; + let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into()); + let mut child = tokio::process::Command::new(exe) + .arg("worker") + // The worker needs no server environment. Clearing it keeps + // provider keys, the secret path, and every other TOGETHER_* + // out of a process that reads hostile bytes for a living. + .env_clear() + .env("HOME", home) + .env("PATH", "/usr/local/bin:/usr/bin:/bin") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::inherit()) + .kill_on_drop(true) + .spawn() + .map_err(|err| format!("could not start a sandbox worker: {err}"))?; + let mut stdin = child + .stdin + .take() + .ok_or_else(|| "the worker has no stdin".to_owned())?; + let line = serde_json::to_string(&config) + .map_err(|err| format!("the worker config does not serialize: {err}"))?; + stdin + .write_all(line.as_bytes()) + .await + .map_err(|err| format!("could not hand the worker its config: {err}"))?; + stdin + .write_all(b"\n") + .await + .map_err(|err| format!("could not hand the worker its config: {err}"))?; + stdin + .flush() + .await + .map_err(|err| format!("could not hand the worker its config: {err}"))?; + let stdout = child + .stdout + .take() + .ok_or_else(|| "the worker has no stdout".to_owned())?; + let mut reader = tokio::io::BufReader::new(stdout); + let mut answer = String::new(); + let read = tokio::time::timeout( + Duration::from_secs(10), + tokio::io::AsyncBufReadExt::read_line(&mut reader, &mut answer), + ) + .await + .map_err(|_| "the sandbox worker did not start in time".to_owned())? + .map_err(|err| format!("could not read the worker handshake: {err}"))?; + if read == 0 { + return Err("the sandbox worker exited before its handshake".into()); + } + let handshake: Handshake = serde_json::from_str(answer.trim()) + .map_err(|err| format!("the worker handshake is malformed: {err}"))?; + Ok(( + WorkerClient { + http_port: handshake.port, + token: handshake.token, + }, + stdin, + child, + )) +} + +/// The app-side `Sandbox`: every call goes through the room's worker. +pub struct WorkerSandbox { + state: Shared, + key: String, + workspace: String, + target: TargetRow, +} + +impl WorkerSandbox { + pub fn new(state: Shared, workspace: &str, target: &TargetRow) -> Self { + Self { + state, + key: format!("target:{}:{}", target.id, workspace), + workspace: workspace.to_owned(), + target: target.clone(), + } + } + + /// The live worker client, spawning or replacing the worker as + /// needed. + pub async fn client(&self) -> Result { + let state = self.state.clone(); + let workspace = self.workspace.clone(); + let target = self.target.clone(); + let build = move || -> Result { + let key = state + .secrets + .open_str(&target.private_key_ciphertext) + .map_err(|err| err.message)?; + Ok(WorkerConfig { + workspace: workspace.clone(), + target: WorkerTarget { + id: target.id.clone(), + host: target.host.clone(), + port: u16::try_from(target.port).unwrap_or(22), + user_name: target.user_name.clone(), + private_key: key, + host_fingerprint: target.host_fingerprint.clone(), + }, + allow_private: state.config.allow_private_targets, + }) + }; + self.state + .workers + .client_with(&self.key, build) + .await + .map_err(SandboxError::Unavailable) + } + + /// Drops the worker after a transport failure, so the next call + /// starts a fresh one. + async fn forget(&self) { + self.state.workers.remove(&self.key).await; + } +} + +#[async_trait::async_trait] +impl Sandbox for WorkerSandbox { + async fn run( + &self, + request: rhema_sandbox::RunRequest, + cancelled: &std::sync::atomic::AtomicBool, + progress: &mut dyn rhema_sandbox::ToolProgress, + ) -> Result { + for attempt in 0..2 { + let client = self.client().await?; + match client + .sandbox() + .run(request.clone(), cancelled, progress) + .await + { + Ok(outcome) => return Ok(outcome), + Err(SandboxError::Unavailable(err)) if attempt == 0 => { + tracing::warn!(worker = %self.key, error = %err, "sandbox worker unavailable, restarting"); + self.forget().await; + } + Err(err) => return Err(err), + } + } + unreachable!("two attempts either return or forget") + } + + async fn seed(&self, seed: &WorkspaceSeed) -> Result<(), SandboxError> { + for attempt in 0..2 { + let client = self.client().await?; + match client.sandbox().seed(seed).await { + Ok(()) => return Ok(()), + Err(SandboxError::Unavailable(err)) if attempt == 0 => { + tracing::warn!(worker = %self.key, error = %err, "sandbox worker unavailable, restarting"); + self.forget().await; + } + Err(err) => return Err(err), + } + } + unreachable!("two attempts either return or forget") + } + + async fn read_file(&self, path: &str) -> Result, SandboxError> { + for attempt in 0..2 { + let client = self.client().await?; + match client.sandbox().read_file(path).await { + Ok(bytes) => return Ok(bytes), + Err(SandboxError::Unavailable(err)) if attempt == 0 => { + tracing::warn!(worker = %self.key, error = %err, "sandbox worker unavailable, restarting"); + self.forget().await; + } + Err(err) => return Err(err), + } + } + unreachable!("two attempts either return or forget") + } + + async fn write_file(&self, path: &str, contents: &[u8]) -> Result<(), SandboxError> { + for attempt in 0..2 { + let client = self.client().await?; + match client.sandbox().write_file(path, contents).await { + Ok(()) => return Ok(()), + Err(SandboxError::Unavailable(err)) if attempt == 0 => { + tracing::warn!(worker = %self.key, error = %err, "sandbox worker unavailable, restarting"); + self.forget().await; + } + Err(err) => return Err(err), + } + } + unreachable!("two attempts either return or forget") + } +} + +/// The app-side client for a room's worker, for the terminal and preview +/// proxies that speak a socket rather than the `Sandbox` trait. +pub async fn client_for( + state: &Shared, + workspace: &str, + target: &TargetRow, +) -> Result { + WorkerSandbox::new(state.clone(), workspace, target) + .client() + .await + .map_err(|err| err.to_string()) +} + +// --------------------------------------------------------------------- +// The worker process itself. +// --------------------------------------------------------------------- + +/// Runs the worker role. The config arrives on stdin; the handshake and +/// the sandbox routes go over loopback. +pub async fn run_worker() -> anyhow::Result<()> { + // A worker holds a target key; keep it out of core dumps and make + // sure no new privilege can be gained here. Both calls are Linux + // only; other Unix targets keep the process boundary alone. + #[cfg(target_os = "linux")] + { + let _ = nix::sys::prctl::set_dumpable(false); + let _ = nix::sys::prctl::set_no_new_privs(); + } + let mut line = String::new(); + std::io::stdin().read_line(&mut line)?; + let config: WorkerConfig = serde_json::from_str(line.trim())?; + if !config.allow_private { + crate::util::check_target_address(&config.target.host, config.target.port) + .await + .map_err(|err| anyhow::anyhow!(err))?; + } + let token = crate::util::random_token(32); + let http = TcpListener::bind(("127.0.0.1", 0)).await?; + let handshake = Handshake { + port: http.local_addr()?.port(), + token: token.clone(), + }; + { + use std::io::Write; + let mut out = std::io::stdout(); + writeln!(out, "{}", serde_json::to_string(&handshake)?)?; + out.flush()?; + } + // The parent holds the write end of stdin for the worker's life. A + // closed pipe means the server is gone, and a worker without a + // server must not linger with a target key. + tokio::spawn(async move { + let mut stdin = tokio::io::stdin(); + let mut sink = [0u8; 1024]; + loop { + match stdin.read(&mut sink).await { + Ok(0) | Err(_) => std::process::exit(0), + Ok(_) => {} + } + } + }); + let destination = format!( + "{}@{}:{}", + config.target.user_name, config.target.host, config.target.port + ); + let sandbox = SshSandbox::new(destination) + .with_workspace(config.workspace.clone()) + .with_private_key(config.target.private_key.clone()); + let state = Arc::new(WorkerState { + sandbox, + target: config.target, + workspace: config.workspace, + token: token.clone(), + preview: Mutex::new(None), + }); + let app = Router::new() + .route("/{session}/exec", post(exec)) + .route("/{session}/put", post(put)) + .route("/{session}/get", post(read_file_route)) + .route("/{session}/seed", post(seed)) + .route("/{session}/proxy", post(proxy)) + .route("/pty", get_route(pty)) + .layer(axum::middleware::from_fn_with_state(state.clone(), auth)) + .layer(axum::extract::DefaultBodyLimit::max(FILE_CAP + 1024 * 1024)) + .with_state(state); + axum::serve(http, app).await?; + Ok(()) +} + +struct WorkerState { + sandbox: SshSandbox, + target: WorkerTarget, + workspace: String, + token: String, + /// The preview proxy's ssh connection, opened on first use and + /// reused by every forwarded channel. A dead handle is replaced. + preview: Mutex>>>, +} + +impl WorkerState { + fn target_row(&self) -> TargetRow { + TargetRow { + id: self.target.id.clone(), + host: self.target.host.clone(), + port: i64::from(self.target.port), + user_name: self.target.user_name.clone(), + private_key_ciphertext: String::new(), + host_fingerprint: self.target.host_fingerprint.clone(), + } + } +} + +async fn auth( + State(state): State>, + headers: HeaderMap, + request: axum::extract::Request, + next: axum::middleware::Next, +) -> Response { + let presented = headers + .get(TOKEN_HEADER) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + if presented != state.token { + return (StatusCode::UNAUTHORIZED, "bad sandbox token").into_response(); + } + next.run(request).await +} + +async fn exec( + State(state): State>, + Json(call): Json, +) -> Result, (StatusCode, String)> { + let cwd = call.cwd.unwrap_or_else(|| state.workspace.clone()); + if !inside(&state.workspace, &cwd) { + return Err(( + StatusCode::FORBIDDEN, + "the command cwd is outside the room workspace".into(), + )); + } + let request = rhema_sandbox::RunRequest { + command: call.command, + cwd: cwd.into(), + timeout: Duration::from_secs(call.timeout_secs.max(1)), + env: call.env, + }; + let cancelled = std::sync::atomic::AtomicBool::new(false); + let mut progress = rhema_sandbox::OutputOnly(|_| {}); + match state.sandbox.run(request, &cancelled, &mut progress).await { + Ok(outcome) => Ok(Json(ExecReply { + exit_code: outcome.code, + stdout: tail(&outcome.stdout), + stderr: tail(&outcome.stderr), + timed_out: false, + })), + Err(SandboxError::Timeout(_)) => Ok(Json(ExecReply { + exit_code: Some(124), + stdout: String::new(), + stderr: String::new(), + timed_out: true, + })), + Err(err) => Err((StatusCode::BAD_GATEWAY, err.to_string())), + } +} + +#[derive(Deserialize)] +struct PathBody { + path: String, +} + +async fn read_file_route( + State(state): State>, + Json(body): Json, +) -> Json { + if !inside(&state.workspace, &body.path) || body.path.split('/').any(|part| part == "..") { + return Json(FileReply { + content_base64: None, + error: Some("the path is outside the room workspace".into()), + }); + } + match state.sandbox.read_file(&body.path).await { + Ok(bytes) if bytes.len() <= FILE_CAP => Json(FileReply { + content_base64: Some(base64::engine::general_purpose::STANDARD.encode(bytes)), + error: None, + }), + Ok(_) => Json(FileReply { + content_base64: None, + error: Some("the file is larger than the sandbox route allows".into()), + }), + Err(err) => Json(FileReply { + content_base64: None, + error: Some(err.to_string()), + }), + } +} + +async fn put(State(state): State>, Json(body): Json) -> Json { + if !inside(&state.workspace, &body.path) || body.path.split('/').any(|part| part == "..") { + return Json(Ack { + error: Some("the path is outside the room workspace".into()), + }); + } + let bytes = match base64::engine::general_purpose::STANDARD.decode(&body.content_base64) { + Ok(bytes) => bytes, + Err(err) => { + return Json(Ack { + error: Some(format!("the file body is not base64: {err}")), + }); + } + }; + if bytes.len() > FILE_CAP { + return Json(Ack { + error: Some("the file is larger than the sandbox route allows".into()), + }); + } + match state.sandbox.write_file(&body.path, &bytes).await { + Ok(()) => Json(Ack { error: None }), + Err(err) => Json(Ack { + error: Some(err.to_string()), + }), + } +} + +async fn seed(State(state): State>, Json(body): Json) -> Json { + let seed = match body { + SeedRequest::Git { git } => WorkspaceSeed::GitClone(git), + SeedRequest::Tarball { + tarball_base64, + tarball_name, + } => WorkspaceSeed::Tarball { + name: tarball_name.unwrap_or_else(|| "room-seed".into()), + tar_gz_base64: tarball_base64, + }, + }; + match state.sandbox.seed(&seed).await { + Ok(()) => Json(Ack { error: None }), + Err(err) => Json(Ack { + error: Some(err.to_string()), + }), + } +} + +async fn proxy( + State(state): State>, + Json(request): Json, +) -> Result { + const PROXY_BODY_CAP: usize = 16 * 1024 * 1024; + let body = base64::engine::general_purpose::STANDARD + .decode(&request.body_base64) + .map_err(|err| { + ( + StatusCode::BAD_REQUEST, + format!("the proxy body is not base64: {err}"), + ) + })?; + if body.len() > PROXY_BODY_CAP { + return Err(( + StatusCode::PAYLOAD_TOO_LARGE, + "the proxy body is larger than the route allows".into(), + )); + } + let method = request + .method + .parse::() + .map_err(|err| (StatusCode::BAD_REQUEST, format!("bad proxy method: {err}")))?; + let path = if request.path.starts_with('/') { + request.path.clone() + } else { + format!("/{}", request.path) + }; + let remote = tokio::time::timeout(SSH_STEP_TIMEOUT, preview_channel(&state, request.port)) + .await + .map_err(|_| { + ( + StatusCode::GATEWAY_TIMEOUT, + "the preview did not answer in time".into(), + ) + })? + .map_err(|err| (StatusCode::BAD_GATEWAY, err))?; + let io = hyper_util::rt::TokioIo::new(remote); + let (mut sender, connection) = + hyper::client::conn::http1::handshake(io) + .await + .map_err(|err| { + ( + StatusCode::BAD_GATEWAY, + format!("http handshake failed: {err}"), + ) + })?; + tokio::spawn(async move { + let _ = connection.await; + }); + let mut builder = hyper::Request::builder().method(method).uri(path); + for (name, value) in &request.headers { + if let (Ok(name), Ok(value)) = ( + HeaderName::from_bytes(name.as_bytes()), + HeaderValue::from_str(value), + ) { + builder = builder.header(name, value); + } + } + // Hyper sets the length from the body; a stale browser header would + // make it disagree with the bytes. + let outbound = builder + .body(Full::new(Bytes::from(body))) + .map_err(|err| (StatusCode::BAD_REQUEST, format!("bad proxy request: {err}")))?; + let reply = sender.send_request(outbound).await.map_err(|err| { + ( + StatusCode::BAD_GATEWAY, + format!("the preview did not answer: {err}"), + ) + })?; + let (parts, body) = reply.into_parts(); + let stream = body.into_data_stream(); + let body = Body::from_stream(stream.map_err(|err| std::io::Error::other(err.to_string()))); + let mut out = Response::new(body); + *out.status_mut() = parts.status; + *out.headers_mut() = parts.headers; + strip_hop_by_hop(out.headers_mut()); + Ok(out) +} + +async fn pty( + State(state): State>, + Query(query): Query>, + ws: WebSocketUpgrade, +) -> Response { + let cols = query + .get("cols") + .and_then(|value| value.parse().ok()) + .unwrap_or(100); + let rows = query + .get("rows") + .and_then(|value| value.parse().ok()) + .unwrap_or(30); + let target = state.target_row(); + let key = state.target.private_key.clone(); + let workspace = state.workspace.clone(); + ws.on_upgrade(move |socket| async move { + crate::ssh::terminal_with_key(socket, &target, &key, &workspace, cols, rows).await; + }) +} + +async fn preview_channel( + state: &WorkerState, + port: u16, +) -> Result, String> { + let mut slot = state.preview.lock().await; + if let Some(handle) = slot.as_ref() { + match tokio::time::timeout( + SSH_STEP_TIMEOUT, + handle.channel_open_direct_tcpip("127.0.0.1", u32::from(port), "127.0.0.1", 0), + ) + .await + { + Ok(Ok(channel)) => return Ok(channel.into_stream()), + _ => { + *slot = None; + } + } + } + let target = state.target_row(); + let (handle, _learned) = tokio::time::timeout( + SSH_STEP_TIMEOUT, + crate::ssh::connect_with_key(&target, &state.target.private_key), + ) + .await + .map_err(|_| "the sandbox did not answer in time".to_owned())??; + let handle = Arc::new(handle); + let channel = tokio::time::timeout( + SSH_STEP_TIMEOUT, + handle.channel_open_direct_tcpip("127.0.0.1", u32::from(port), "127.0.0.1", 0), + ) + .await + .map_err(|_| "the sandbox refused port in time".to_owned())? + .map_err(|err| format!("the sandbox refused port {port}: {err}"))?; + *slot = Some(handle); + Ok(channel.into_stream()) +} + +fn strip_hop_by_hop(headers: &mut HeaderMap) { + for name in [ + axum::http::header::CONNECTION, + HeaderName::from_static("keep-alive"), + HeaderName::from_static("proxy-authenticate"), + HeaderName::from_static("proxy-authorization"), + axum::http::header::TE, + axum::http::header::TRAILER, + axum::http::header::TRANSFER_ENCODING, + axum::http::header::UPGRADE, + ] { + headers.remove(name); + } +} + +fn inside(workspace: &str, path: &str) -> bool { + let root = workspace.trim_end_matches('/'); + if root.is_empty() { + return path.starts_with('/'); + } + path == root || path.starts_with(&format!("{root}/")) +} + +fn tail(bytes: &[u8]) -> String { + let start = bytes.len().saturating_sub(OUTPUT_CAP); + String::from_utf8_lossy(&bytes[start..]).into_owned() +} + +#[cfg(test)] +mod tests { + use super::{inside, tail}; + + #[test] + fn workspace_paths_stay_inside() { + assert!(inside("/srv/room", "/srv/room")); + assert!(inside("/srv/room", "/srv/room/project")); + assert!(inside("/srv/room/", "/srv/room/project")); + assert!(!inside("/srv/room", "/srv/room-2")); + assert!(!inside("/srv/room", "/srv")); + assert!(!inside("/srv/room", "/etc/passwd")); + } + + #[test] + fn a_root_workspace_accepts_absolute_paths() { + assert!(inside("/", "/")); + assert!(inside("/", "/tmp/project")); + } + + #[test] + fn the_output_tail_is_capped() { + let text = "x".repeat(70_000); + assert_eq!(tail(text.as_bytes()).len(), 50 * 1024); + } +} + +#[cfg(test)] +mod smoke { + //! A manual end-to-end check of the `WorkerSandbox` path. It needs a + //! local sshd and a key; run with + //! `cargo test worker_sandbox_round_trip -- --ignored --nocapture`. + use std::path::PathBuf; + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + use std::time::Duration; + + use super::WorkerSandbox; + use crate::config::Config; + use crate::crypto::Secrets; + use crate::db::Db; + use crate::room::agent::TargetRow; + use crate::state::{AppState, Hub}; + use rhema_sandbox::Sandbox; + + #[tokio::test] + #[ignore] + async fn worker_sandbox_round_trip() { + let dir = PathBuf::from("/tmp/rhema-worker-test"); + let key = std::fs::read_to_string(dir.join("client_ed25519")).expect("client key"); + let config = Config { + allow_private_targets: true, + ..Config::default() + }; + let db = Db::open(&dir.join("smoke.db")).expect("db"); + let secrets = Secrets::load_or_create(&dir.join("smoke.key")).expect("secrets"); + let target = TargetRow { + id: "smoke".into(), + host: "127.0.0.1".into(), + port: 2223, + user_name: "vhaudiquet".into(), + private_key_ciphertext: secrets.seal_str(&key).expect("seal"), + host_fingerprint: None, + }; + let state = Arc::new(AppState { + config, + db, + secrets, + hub: Hub::default(), + rooms: Default::default(), + workers: Default::default(), + presence: Default::default(), + logins: Default::default(), + }); + let sandbox = WorkerSandbox::new(state, &dir.join("ws").to_string_lossy(), &target); + let cancelled = AtomicBool::new(false); + let mut progress = rhema_sandbox::OutputOnly(|_| {}); + let outcome = sandbox + .run( + rhema_sandbox::RunRequest { + command: "printf worker-ok".into(), + cwd: dir.join("ws"), + timeout: Duration::from_secs(20), + env: Default::default(), + }, + &cancelled, + &mut progress, + ) + .await + .expect("run"); + assert_eq!(String::from_utf8_lossy(&outcome.stdout).trim(), "worker-ok"); + } +}