feat: run sandbox transports in disposable workers

The control plane opened ssh connections itself, so a malicious ssh
server attacked the process that held the database, the master key, and
every room's keys. It now starts one worker per target and workspace.
The worker gets one target key on stdin, binds loopback behind a random
token, and serves exec, files, the pty, and the preview proxy. It has no
database and no master key, and a closed stdin ends it.

The preview HTTP client moved into the worker too. The app sees a typed
response, and the worker caps bodies, output tails, handshakes, and
transport waits.

Direct targets now reject loopback, private, link-local, multicast,
unspecified, carrier-grade NAT, and documentation addresses when a
target is created and again when its worker starts.
TOGETHER_ALLOW_PRIVATE_TARGETS=1 lifts the check for a server that runs
on one private network.
This commit is contained in:
vhaudiquet committed 2026-11-29 18:22:44 +01:00
1 parent a8f7e74ba0
commit fc684115b5
16 files changed
+1355 -208

No files matched your search

+111 -6
View File
@@ -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<Shared>,
@@ -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<WsMessage> {
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<TMessage> {
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(),
}
}))),
}
}
+6
View File
@@ -366,10 +366,16 @@ pub async fn archive(
Path(id): Path<String>,
) -> AppResult<Json<Value>> {
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 })))
}
+23 -11
View File
@@ -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<Shared>,
@@ -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<String>>(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(),