//! The web terminal: a real pty on the far side, over the same ssh //! target and key the agent's commands use. use std::sync::{Arc, Mutex}; use axum::extract::ws::{Message as WsMessage, WebSocket}; use futures::{SinkExt, StreamExt}; use russh::client::{self, Handle}; use russh::keys::{PrivateKeyWithHashAlg, PublicKeyOrCertificate, decode_secret_key}; 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. pub(crate) struct HostKey { expected: Option, learned: Arc>>, } impl client::Handler for HostKey { type Error = SshError; async fn check_server_key( &mut self, key: &PublicKeyOrCertificate, ) -> Result { let PublicKeyOrCertificate::PublicKey { key, .. } = key else { return Ok(false); }; let Ok(line) = key.to_openssh() else { return Ok(false); }; let fingerprint = sha256_hex(line.as_bytes()); match &self.expected { Some(expected) => Ok(expected == &fingerprint), None => { if let Ok(mut slot) = self.learned.lock() { *slot = Some(fingerprint); } Ok(true) } } } } /// Opens a connection for the preview proxy. pub(crate) async fn connect_handle( target: &TargetRow, private_key: &str, ) -> Result, String> { let (handle, _fingerprint) = connect(target, private_key).await?; Ok(handle) } async fn connect( target: &TargetRow, private_key: &str, ) -> Result<(Handle, Option), String> { let learned = Arc::new(Mutex::new(None)); let handler = HostKey { expected: target.host_fingerprint.clone(), learned: learned.clone(), }; let config = Arc::new(client::Config::default()); let port = u16::try_from(target.port).unwrap_or(22); let mut connection = client::connect(config, (target.host.as_str(), port), handler) .await .map_err(|err| format!("could not reach {}:{}: {err}", target.host, target.port))?; let hash = connection .best_supported_rsa_hash() .await .map_err(|err| format!("ssh negotiation failed: {err}"))? .flatten(); let key = decode_secret_key(private_key, None) .map_err(|err| format!("the stored private key does not decode: {err}"))?; let answer = connection .authenticate_publickey( target.user_name.clone(), PrivateKeyWithHashAlg::new(Arc::new(key), hash), ) .await .map_err(|err| format!("ssh authentication failed: {err}"))?; if !answer.success() { return Err(format!( "{} refused the stored key for {}", target.host, target.user_name )); } let fingerprint = learned.lock().ok().and_then(|slot| slot.clone()); Ok((connection, fingerprint)) } /// Attaches a browser socket to an interactive shell in the room's /// sandbox. pub async fn terminal(socket: WebSocket, state: Shared, workspace: String, target: TargetRow) { 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. 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], ); } let mut channel = match connection.channel_open_session().await { Ok(channel) => channel, Err(err) => { send_error(&mut sink, format!("the far end refused a session: {err}")).await; return; } }; let cwd = format!( "cd {} 2>/dev/null || cd ~; exec bash -l", rhema_sandbox::exec_util::shquote(&workspace) ); if let Err(err) = channel .request_pty(true, "xterm-256color", 100, 30, 0, 0, &[]) .await { send_error(&mut sink, format!("the far end refused a pty: {err}")).await; return; } if let Err(err) = channel.exec(true, cwd).await { send_error(&mut sink, format!("the far end refused the shell: {err}")).await; return; } let _ = sink .send(WsMessage::Text( json!({ "type": "ready" }).to_string().into(), )) .await; loop { tokio::select! { message = channel.wait() => { match message { Some(ChannelMsg::Data { data }) => { if sink.send(WsMessage::Binary(data.to_vec().into())).await.is_err() { break; } } Some(ChannelMsg::ExtendedData { data, .. }) => { if sink.send(WsMessage::Binary(data.to_vec().into())).await.is_err() { break; } } Some(ChannelMsg::ExitStatus { exit_status }) => { let _ = sink .send(WsMessage::Text( json!({ "type": "exit", "code": exit_status }).to_string().into(), )) .await; break; } Some(ChannelMsg::Eof) | Some(ChannelMsg::Close) | None => break, _ => {} } } message = source.next() => { match message { Some(Ok(WsMessage::Binary(data))) => { if channel.data(&data[..]).await.is_err() { break; } } Some(Ok(WsMessage::Text(text))) => { match serde_json::from_str::(&text) { Ok(value) => { if value.get("type").and_then(|kind| kind.as_str()) == Some("resize") { let cols = value.get("cols").and_then(|v| v.as_u64()).unwrap_or(100) as u32; let rows = value.get("rows").and_then(|v| v.as_u64()).unwrap_or(30) as u32; let _ = channel.window_change(cols, rows, 0, 0).await; } else if let Some(data) = value.get("data").and_then(|v| v.as_str()) { let _ = channel.data(data.as_bytes()).await; } } // A plain text frame is keystrokes, for simple // clients that do not speak the control format. Err(_) => { let _ = channel.data(text.as_bytes()).await; } } } Some(Ok(WsMessage::Close(_))) | None => break, Some(Ok(_)) => {} Some(Err(_)) => break, } } } } let _ = channel.close().await; drop(connection); } async fn send_error(sink: &mut S, message: String) where S: futures::Sink + Unpin, { let _ = sink .send(WsMessage::Text( json!({ "type": "error", "message": message }) .to_string() .into(), )) .await; }