forked from vhaudiquet/rhema-together
Accounts get a profile page with an uploaded picture, shown in the sidebar, the room bar, and every human message. Pictures live in the SQLite database and are served through an authenticated route. Hardening from the security audit: preview hosts expire after 24 hours and carry no-referrer; removing a member or archiving a room ends their event feed, presence socket, and terminal within seconds; previews and the terminal pin the SSH host key; invites are claimed atomically; missing accounts spend the same argon2 time as wrong passwords; registration is closed by default; WebSockets check the origin; and the master key is created with mode 0600. The Dockerfile builds one image with the static client and the server. The Helm chart runs a single replica with a SQLite volume, a wildcard preview ingress, and the proxy settings the event feed and uploads need. It refuses more than one replica because state is in process.
256 lines
9.0 KiB
Rust
256 lines
9.0 KiB
Rust
//! 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<String>,
|
|
learned: Arc<Mutex<Option<String>>>,
|
|
}
|
|
|
|
impl client::Handler for HostKey {
|
|
type Error = SshError;
|
|
|
|
async fn check_server_key(
|
|
&mut self,
|
|
key: &PublicKeyOrCertificate,
|
|
) -> Result<bool, Self::Error> {
|
|
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, returning the host-key
|
|
/// fingerprint when this was the first contact.
|
|
pub(crate) async fn connect_handle(
|
|
target: &TargetRow,
|
|
private_key: &str,
|
|
) -> Result<(Handle<HostKey>, Option<String>), 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<String>) {
|
|
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(
|
|
target: &TargetRow,
|
|
private_key: &str,
|
|
) -> Result<(Handle<HostKey>, Option<String>), 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,
|
|
room: String,
|
|
account: String,
|
|
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.
|
|
remember_host_key(&state, &target, learned);
|
|
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;
|
|
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 }) => {
|
|
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::<serde_json::Value>(&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<S>(sink: &mut S, message: String)
|
|
where
|
|
S: futures::Sink<WsMessage, Error = axum::Error> + Unpin,
|
|
{
|
|
let _ = sink
|
|
.send(WsMessage::Text(
|
|
json!({ "type": "error", "message": message })
|
|
.to_string()
|
|
.into(),
|
|
))
|
|
.await;
|
|
}
|