Revert "feat: add reverse ssh sandbox targets"
This reverts commit d85f68a176.
This commit is contained in:
1 parent
d85f68a176
commit
4d9530cc34
20 files changed
+38
-893
No files matched your search
@@ -59,10 +59,6 @@ pub fn router(state: Shared) -> Router {
|
||||
)
|
||||
.route("/sandbox-targets/{id}", delete(settings::delete_target))
|
||||
.route("/sandbox-targets/{id}/test", post(settings::test_target))
|
||||
.route(
|
||||
"/sandbox-targets/{id}/tunnel-key",
|
||||
post(settings::rotate_tunnel_key),
|
||||
)
|
||||
.route("/rooms", get(rooms::list).post(rooms::create))
|
||||
.route(
|
||||
"/rooms/{id}",
|
||||
|
||||
+14
-94
@@ -336,7 +336,7 @@ pub async fn delete_provider(
|
||||
pub async fn list_targets(user: AuthUser, State(state): State<Shared>) -> AppResult<Json<Value>> {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, name, host, port, user_name, workspace_root, public_key, host_fingerprint, kind
|
||||
"SELECT id, name, host, port, user_name, workspace_root, public_key, host_fingerprint
|
||||
FROM sandbox_targets WHERE account_id = ?1 ORDER BY created_at ASC",
|
||||
)?;
|
||||
let rows = stmt.query_map(rusqlite::params![user.user.id], |row| {
|
||||
@@ -349,15 +349,6 @@ pub async fn list_targets(user: AuthUser, State(state): State<Shared>) -> AppRes
|
||||
workspace_root: row.get(5)?,
|
||||
public_key: row.get(6)?,
|
||||
host_fingerprint: row.get(7)?,
|
||||
kind: row.get(8)?,
|
||||
tunnel_command: if row.get::<_, String>(8)? == "tunnel" {
|
||||
Some(state.config.tunnel_command(
|
||||
u16::try_from(row.get::<_, i64>(3)?).unwrap_or(0),
|
||||
&row.get::<_, String>(0)?,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
},
|
||||
})
|
||||
})?;
|
||||
let targets = rows.collect::<Result<Vec<_>, _>>()?;
|
||||
@@ -367,11 +358,7 @@ pub async fn list_targets(user: AuthUser, State(state): State<Shared>) -> AppRes
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateTarget {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub host: String,
|
||||
/// `direct` (the default) or `tunnel` for a machine behind NAT.
|
||||
#[serde(default)]
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub port: Option<u16>,
|
||||
#[serde(default)]
|
||||
@@ -395,28 +382,16 @@ pub async fn create_target(
|
||||
if name.is_empty() || name.chars().count() > 60 {
|
||||
return Err(AppError::bad_request("name must be 1 to 60 characters"));
|
||||
}
|
||||
let kind = body.kind.trim();
|
||||
let kind = if kind.is_empty() { "direct" } else { kind };
|
||||
if kind != "direct" && kind != "tunnel" {
|
||||
return Err(AppError::bad_request("kind must be direct or tunnel"));
|
||||
let host = body.host.trim();
|
||||
if host.is_empty() || host.contains(char::is_whitespace) {
|
||||
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 (host, port, tunnel_public_key, tunnel_private_key) = if kind == "tunnel" {
|
||||
let port = crate::tunnel::next_port(&state)?;
|
||||
let (private, public) = crate::tunnel::new_key()?;
|
||||
("127.0.0.1".to_owned(), port, Some(public), Some(private))
|
||||
} else {
|
||||
let host = body.host.trim();
|
||||
if host.is_empty() || host.contains(char::is_whitespace) {
|
||||
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)?;
|
||||
}
|
||||
(host.to_owned(), port, None, None)
|
||||
};
|
||||
let user_name = body
|
||||
.user_name
|
||||
.map(|value| value.trim().to_owned())
|
||||
@@ -451,9 +426,8 @@ pub async fn create_target(
|
||||
let id = random_id(12);
|
||||
state.db.conn().execute(
|
||||
"INSERT INTO sandbox_targets (id, account_id, name, host, port, user_name,
|
||||
workspace_root, private_key_ciphertext, public_key,
|
||||
kind, tunnel_public_key, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
|
||||
workspace_root, private_key_ciphertext, public_key, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
|
||||
rusqlite::params![
|
||||
id,
|
||||
user.user.id,
|
||||
@@ -464,26 +438,10 @@ pub async fn create_target(
|
||||
workspace_root.trim_end_matches('/'),
|
||||
sealed,
|
||||
public_key,
|
||||
kind,
|
||||
tunnel_public_key,
|
||||
crate::util::now_ms()
|
||||
],
|
||||
)?;
|
||||
if kind == "tunnel"
|
||||
&& let Err(err) = crate::tunnel::refresh(&state)
|
||||
{
|
||||
let _ = state.db.conn().execute(
|
||||
"DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
let mut response = json!({ "id": id, "public_key": public_key, "kind": kind });
|
||||
if kind == "tunnel" {
|
||||
response["tunnel_private_key"] = json!(tunnel_private_key);
|
||||
response["tunnel_command"] = json!(state.config.tunnel_command(port, &id));
|
||||
}
|
||||
Ok(Json(response))
|
||||
Ok(Json(json!({ "id": id, "public_key": public_key })))
|
||||
}
|
||||
|
||||
fn generate_key() -> AppResult<(String, String)> {
|
||||
@@ -500,41 +458,6 @@ fn generate_key() -> AppResult<(String, String)> {
|
||||
Ok((private, public))
|
||||
}
|
||||
|
||||
/// Replaces a reverse ssh target's tunnel key. The old key stops
|
||||
/// working when the authorized_keys file is rewritten.
|
||||
pub async fn rotate_tunnel_key(
|
||||
user: AuthUser,
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let (kind, port): (String, i64) = state
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT kind, port FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||
)
|
||||
.map_err(|_| AppError::not_found("sandbox target not found"))?;
|
||||
if kind != "tunnel" {
|
||||
return Err(AppError::bad_request(
|
||||
"this sandbox is not a reverse ssh target",
|
||||
));
|
||||
}
|
||||
let (private, public) = crate::tunnel::new_key()?;
|
||||
state.db.conn().execute(
|
||||
"UPDATE sandbox_targets SET tunnel_public_key = ?1 WHERE id = ?2 AND account_id = ?3",
|
||||
rusqlite::params![public, id, user.user.id],
|
||||
)?;
|
||||
crate::tunnel::refresh(&state)?;
|
||||
let port = u16::try_from(port)
|
||||
.map_err(|_| AppError::internal("the tunnel port is outside the valid range"))?;
|
||||
Ok(Json(json!({
|
||||
"tunnel_private_key": private,
|
||||
"tunnel_command": state.config.tunnel_command(port, &id),
|
||||
})))
|
||||
}
|
||||
|
||||
/// Deletes a target.
|
||||
pub async fn delete_target(
|
||||
user: AuthUser,
|
||||
@@ -545,7 +468,6 @@ pub async fn delete_target(
|
||||
"DELETE FROM sandbox_targets WHERE id = ?1 AND account_id = ?2",
|
||||
rusqlite::params![id, user.user.id],
|
||||
)?;
|
||||
crate::tunnel::refresh(&state)?;
|
||||
state.workers.remove_target(&id).await;
|
||||
Ok(Json(json!({ "ok": true })))
|
||||
}
|
||||
@@ -563,7 +485,7 @@ pub async fn test_target(
|
||||
.db
|
||||
.conn()
|
||||
.query_row(
|
||||
"SELECT host, port, user_name, private_key_ciphertext, host_fingerprint, kind
|
||||
"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| {
|
||||
@@ -573,7 +495,6 @@ pub async fn test_target(
|
||||
row.get::<_, String>(2)?,
|
||||
row.get::<_, String>(3)?,
|
||||
row.get::<_, Option<String>>(4)?,
|
||||
row.get::<_, String>(5)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
@@ -585,7 +506,6 @@ pub async fn test_target(
|
||||
user_name: row.2.clone(),
|
||||
private_key_ciphertext: row.3,
|
||||
host_fingerprint: row.4,
|
||||
kind: row.5,
|
||||
};
|
||||
let sandbox = crate::worker::WorkerSandbox::new(state.clone(), "/", &target);
|
||||
let cancelled = AtomicBool::new(false);
|
||||
|
||||
@@ -38,51 +38,12 @@ pub struct Config {
|
||||
/// cannot turn the server into a probe of its own network.
|
||||
#[serde(default)]
|
||||
pub allow_private_targets: bool,
|
||||
/// The host sandboxes dial for a reverse ssh tunnel. Empty uses the
|
||||
/// host from `public_url`.
|
||||
#[serde(default)]
|
||||
pub tunnel_ssh_host: String,
|
||||
/// The port the tunnel sshd listens on.
|
||||
#[serde(default = "default_tunnel_ssh_port")]
|
||||
pub tunnel_ssh_port: u16,
|
||||
/// The account the tunnel sshd accepts.
|
||||
#[serde(default = "default_tunnel_user")]
|
||||
pub tunnel_user: String,
|
||||
/// The loopback port range the server hands to tunnel targets.
|
||||
#[serde(default = "default_tunnel_port_start")]
|
||||
pub tunnel_port_start: u16,
|
||||
#[serde(default = "default_tunnel_port_end")]
|
||||
pub tunnel_port_end: u16,
|
||||
/// The authorized_keys file the tunnel sshd reads. The server writes
|
||||
/// one restricted key per tunnel target.
|
||||
#[serde(default = "default_tunnel_authorized_keys")]
|
||||
pub tunnel_authorized_keys: PathBuf,
|
||||
}
|
||||
|
||||
fn default_steps() -> u32 {
|
||||
48
|
||||
}
|
||||
|
||||
fn default_tunnel_ssh_port() -> u16 {
|
||||
2222
|
||||
}
|
||||
|
||||
fn default_tunnel_user() -> String {
|
||||
"tunnel".into()
|
||||
}
|
||||
|
||||
fn default_tunnel_port_start() -> u16 {
|
||||
22000
|
||||
}
|
||||
|
||||
fn default_tunnel_port_end() -> u16 {
|
||||
22999
|
||||
}
|
||||
|
||||
fn default_tunnel_authorized_keys() -> PathBuf {
|
||||
PathBuf::from("data/tunnel/authorized_keys")
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -96,12 +57,6 @@ impl Default for Config {
|
||||
allowed_frame_ancestors: Vec::new(),
|
||||
allow_registration: false,
|
||||
allow_private_targets: false,
|
||||
tunnel_ssh_host: String::new(),
|
||||
tunnel_ssh_port: default_tunnel_ssh_port(),
|
||||
tunnel_user: default_tunnel_user(),
|
||||
tunnel_port_start: default_tunnel_port_start(),
|
||||
tunnel_port_end: default_tunnel_port_end(),
|
||||
tunnel_authorized_keys: default_tunnel_authorized_keys(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,65 +98,11 @@ impl Config {
|
||||
if let Ok(value) = std::env::var("TOGETHER_ALLOW_PRIVATE_TARGETS") {
|
||||
config.allow_private_targets = matches!(value.as_str(), "1" | "true" | "yes");
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_SSH_HOST") {
|
||||
config.tunnel_ssh_host = value;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_SSH_PORT") {
|
||||
config.tunnel_ssh_port = value.parse()?;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_USER") {
|
||||
config.tunnel_user = value;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_PORT_START") {
|
||||
config.tunnel_port_start = value.parse()?;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_PORT_END") {
|
||||
config.tunnel_port_end = value.parse()?;
|
||||
}
|
||||
if let Ok(value) = std::env::var("TOGETHER_TUNNEL_AUTHORIZED_KEYS") {
|
||||
config.tunnel_authorized_keys = value.into();
|
||||
}
|
||||
if config.tunnel_port_start == 0 || config.tunnel_port_start > config.tunnel_port_end {
|
||||
anyhow::bail!("the tunnel port range is invalid");
|
||||
}
|
||||
if config.tunnel_ssh_port == 0 {
|
||||
anyhow::bail!("the tunnel ssh port is invalid");
|
||||
}
|
||||
config.tunnel_ssh_host = config.tunnel_ssh_host.trim().to_owned();
|
||||
config.tunnel_user = config.tunnel_user.trim().to_owned();
|
||||
if config.tunnel_user.is_empty() || config.tunnel_user.contains(char::is_whitespace) {
|
||||
anyhow::bail!("the tunnel user is invalid");
|
||||
}
|
||||
config.public_url = config.public_url.trim_end_matches('/').to_owned();
|
||||
config.preview_origin = config.preview_origin.trim_end_matches('/').to_owned();
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// The host a sandbox passes to `autossh -R`.
|
||||
pub fn tunnel_host(&self) -> String {
|
||||
if !self.tunnel_ssh_host.is_empty() {
|
||||
return self.tunnel_ssh_host.clone();
|
||||
}
|
||||
let rest = self
|
||||
.public_url
|
||||
.split("://")
|
||||
.nth(1)
|
||||
.unwrap_or(&self.public_url);
|
||||
let host = rest.split('/').next().unwrap_or(rest);
|
||||
host.split(':').next().unwrap_or(host).to_owned()
|
||||
}
|
||||
|
||||
/// The command that turns a sandbox's local sshd into a loopback
|
||||
/// port on the server.
|
||||
pub fn tunnel_command(&self, port: u16, target_id: &str) -> String {
|
||||
format!(
|
||||
"autossh -M 0 -N -R 127.0.0.1:{port}:localhost:22 -p {} {}@{} -i ./rhema-tunnel-{target_id} -o ExitOnForwardFailure=yes -o ServerAliveInterval=30",
|
||||
self.tunnel_ssh_port,
|
||||
self.tunnel_user,
|
||||
self.tunnel_host(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether cookies should carry `Secure`.
|
||||
pub fn secure_cookies(&self) -> bool {
|
||||
self.public_url.starts_with("https://")
|
||||
|
||||
@@ -26,7 +26,6 @@ impl Db {
|
||||
conn.pragma_update(None, "foreign_keys", "ON")?;
|
||||
conn.busy_timeout(std::time::Duration::from_secs(5))?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
migrate(&conn)?;
|
||||
Ok(Self {
|
||||
conn: Arc::new(Mutex::new(conn)),
|
||||
})
|
||||
@@ -48,43 +47,6 @@ impl Db {
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds columns that arrived after the first release. `CREATE TABLE IF
|
||||
/// NOT EXISTS` leaves an existing table alone, so each column is checked
|
||||
/// before the ALTER.
|
||||
fn migrate(conn: &Connection) -> rusqlite::Result<()> {
|
||||
if !has_column(conn, "sandbox_targets", "kind")? {
|
||||
conn.execute(
|
||||
"ALTER TABLE sandbox_targets ADD COLUMN kind TEXT NOT NULL DEFAULT 'direct'",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
if !has_column(conn, "sandbox_targets", "tunnel_public_key")? {
|
||||
conn.execute(
|
||||
"ALTER TABLE sandbox_targets ADD COLUMN tunnel_public_key TEXT",
|
||||
[],
|
||||
)?;
|
||||
}
|
||||
// A tunnel target owns one loopback port. Direct targets may share a
|
||||
// port, so the index is partial.
|
||||
conn.execute_batch(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS sandbox_tunnel_port
|
||||
ON sandbox_targets(port) WHERE kind = 'tunnel';",
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_column(conn: &Connection, table: &str, column: &str) -> rusqlite::Result<bool> {
|
||||
let mut stmt = conn.prepare(&format!("PRAGMA table_info({table})"))?;
|
||||
let mut rows = stmt.query([])?;
|
||||
while let Some(row) = rows.next()? {
|
||||
let name: String = row.get(1)?;
|
||||
if name == column {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
const SCHEMA: &str = r#"
|
||||
CREATE TABLE IF NOT EXISTS meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
@@ -138,8 +100,6 @@ CREATE TABLE IF NOT EXISTS sandbox_targets (
|
||||
private_key_ciphertext TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
host_fingerprint TEXT,
|
||||
kind TEXT NOT NULL DEFAULT 'direct',
|
||||
tunnel_public_key TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
) STRICT;
|
||||
|
||||
@@ -205,50 +165,3 @@ CREATE INDEX IF NOT EXISTS members_room ON members(room_id);
|
||||
CREATE INDEX IF NOT EXISTS events_room_seq ON events(room_id, seq);
|
||||
CREATE INDEX IF NOT EXISTS auth_sessions_account ON auth_sessions(account_id);
|
||||
"#;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_old_target_table_gains_the_tunnel_columns() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("rhema-db-migrate-{}", crate::util::random_token(6)));
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let path = dir.join("old.db");
|
||||
{
|
||||
let conn = Connection::open(&path).expect("old db");
|
||||
conn.execute_batch(
|
||||
"CREATE TABLE sandbox_targets (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
host TEXT NOT NULL,
|
||||
port INTEGER NOT NULL DEFAULT 22,
|
||||
user_name TEXT NOT NULL,
|
||||
workspace_root TEXT NOT NULL,
|
||||
private_key_ciphertext TEXT NOT NULL,
|
||||
public_key TEXT NOT NULL,
|
||||
host_fingerprint TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
) STRICT;",
|
||||
)
|
||||
.expect("old schema");
|
||||
}
|
||||
let db = Db::open(&path).expect("open");
|
||||
let conn = db.conn();
|
||||
let mut stmt = conn
|
||||
.prepare("PRAGMA table_info(sandbox_targets)")
|
||||
.expect("pragma");
|
||||
let columns: Vec<String> = stmt
|
||||
.query_map([], |row| row.get(1))
|
||||
.expect("rows")
|
||||
.collect::<Result<_, _>>()
|
||||
.expect("columns");
|
||||
assert!(columns.iter().any(|column| column == "kind"));
|
||||
assert!(columns.iter().any(|column| column == "tunnel_public_key"));
|
||||
drop(stmt);
|
||||
drop(conn);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,6 @@ mod preview;
|
||||
mod room;
|
||||
mod ssh;
|
||||
mod state;
|
||||
mod tunnel;
|
||||
mod util;
|
||||
mod worker;
|
||||
|
||||
@@ -55,9 +54,6 @@ async fn main() -> anyhow::Result<()> {
|
||||
presence: Default::default(),
|
||||
logins: Default::default(),
|
||||
});
|
||||
if let Err(err) = tunnel::refresh(&state) {
|
||||
tracing::warn!(error = %err.message, "could not write the tunnel authorized_keys file");
|
||||
}
|
||||
let app = api::router(state).layer(TraceLayer::new_for_http());
|
||||
let listener = tokio::net::TcpListener::bind(&config.listen).await?;
|
||||
tracing::info!(listen = %config.listen, "rhema-together");
|
||||
|
||||
@@ -116,8 +116,6 @@ pub struct SandboxTarget {
|
||||
pub workspace_root: String,
|
||||
pub public_key: String,
|
||||
pub host_fingerprint: Option<String>,
|
||||
pub kind: String,
|
||||
pub tunnel_command: Option<String>,
|
||||
}
|
||||
|
||||
/// A directory entry in the read-only file pane.
|
||||
|
||||
+2
-5
@@ -51,7 +51,6 @@ pub struct TargetRow {
|
||||
pub user_name: String,
|
||||
pub private_key_ciphertext: String,
|
||||
pub host_fingerprint: Option<String>,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
/// Reads everything a turn needs.
|
||||
@@ -106,7 +105,7 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
|
||||
},
|
||||
)?;
|
||||
let target = conn.query_row(
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint, kind
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint
|
||||
FROM sandbox_targets WHERE id = ?1",
|
||||
rusqlite::params![target_id],
|
||||
|row| {
|
||||
@@ -117,7 +116,6 @@ pub fn load_turn_config(state: &Shared, room_id: &str) -> AppResult<TurnConfig>
|
||||
user_name: row.get(3)?,
|
||||
private_key_ciphertext: row.get(4)?,
|
||||
host_fingerprint: row.get(5)?,
|
||||
kind: row.get(6)?,
|
||||
})
|
||||
},
|
||||
)?;
|
||||
@@ -194,7 +192,7 @@ pub fn load_room_target(state: &Shared, room: &str) -> AppResult<(String, Target
|
||||
let target_id =
|
||||
target_id.ok_or_else(|| AppError::bad_request("room has no sandbox configured"))?;
|
||||
let target = conn.query_row(
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint, kind
|
||||
"SELECT id, host, port, user_name, private_key_ciphertext, host_fingerprint
|
||||
FROM sandbox_targets WHERE id = ?1",
|
||||
rusqlite::params![target_id],
|
||||
|row| {
|
||||
@@ -205,7 +203,6 @@ pub fn load_room_target(state: &Shared, room: &str) -> AppResult<(String, Target
|
||||
user_name: row.get(3)?,
|
||||
private_key_ciphertext: row.get(4)?,
|
||||
host_fingerprint: row.get(5)?,
|
||||
kind: row.get(6)?,
|
||||
})
|
||||
},
|
||||
)?;
|
||||
|
||||
-192
@@ -1,192 +0,0 @@
|
||||
//! Reverse ssh targets: the sandbox dials out to the tunnel sshd, and
|
||||
//! the worker reaches its sshd through a loopback port on the server.
|
||||
//!
|
||||
//! The server writes the tunnel sshd's authorized_keys file. Each key
|
||||
//! carries `permitlisten` for the one port the target owns, so a tunnel
|
||||
//! key cannot bind another target's port.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::io::Write;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
use ssh_key::{Algorithm, LineEnding, PrivateKey};
|
||||
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::state::Shared;
|
||||
|
||||
/// Generates the key the sandbox uses to authenticate to the tunnel
|
||||
/// sshd. The private half is shown once and never stored.
|
||||
pub(crate) fn new_key() -> AppResult<(String, String)> {
|
||||
let key = PrivateKey::random(&mut rand::rngs::OsRng, Algorithm::Ed25519)
|
||||
.map_err(|err| AppError::internal(format!("could not generate a tunnel key: {err}")))?;
|
||||
let private = key
|
||||
.to_openssh(LineEnding::LF)
|
||||
.map_err(|err| AppError::internal(format!("could not encode a tunnel key: {err}")))?
|
||||
.to_string();
|
||||
let public = key
|
||||
.public_key()
|
||||
.to_openssh()
|
||||
.map_err(|err| AppError::internal(format!("could not encode a tunnel key: {err}")))?;
|
||||
Ok((private, public))
|
||||
}
|
||||
|
||||
/// Picks the first free loopback port in the configured range.
|
||||
pub(crate) fn next_port(state: &Shared) -> AppResult<u16> {
|
||||
let used: HashSet<i64> = {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare("SELECT port FROM sandbox_targets WHERE kind = 'tunnel'")?;
|
||||
let rows = stmt.query_map([], |row| row.get::<_, i64>(0))?;
|
||||
rows.collect::<Result<_, _>>()?
|
||||
};
|
||||
(state.config.tunnel_port_start..=state.config.tunnel_port_end)
|
||||
.find(|port| !used.contains(&(*port as i64)))
|
||||
.ok_or_else(|| AppError::bad_request("no tunnel ports are free"))
|
||||
}
|
||||
|
||||
/// Rewrites the authorized_keys file the tunnel sshd reads. One key per
|
||||
/// tunnel target, restricted to that target's loopback port.
|
||||
pub(crate) fn refresh(state: &Shared) -> AppResult<()> {
|
||||
let rows = {
|
||||
let conn = state.db.conn();
|
||||
let mut stmt = conn.prepare(
|
||||
"SELECT id, tunnel_public_key, port FROM sandbox_targets
|
||||
WHERE kind = 'tunnel' AND tunnel_public_key IS NOT NULL
|
||||
ORDER BY port",
|
||||
)?;
|
||||
let rows = stmt.query_map([], |row| {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, String>(1)?,
|
||||
row.get::<_, i64>(2)?,
|
||||
))
|
||||
})?;
|
||||
rows.collect::<Result<Vec<_>, _>>()?
|
||||
};
|
||||
let mut text = String::new();
|
||||
for (id, public_key, port) in rows {
|
||||
let key = public_key.trim();
|
||||
if key.is_empty() || key.contains('\n') {
|
||||
continue;
|
||||
}
|
||||
let port = u16::try_from(port).unwrap_or(0);
|
||||
if port == 0 {
|
||||
continue;
|
||||
}
|
||||
text.push_str(&format!(
|
||||
"restrict,port-forwarding,permitlisten=\"127.0.0.1:{port}\" {key} {id}\n"
|
||||
));
|
||||
}
|
||||
write_atomic(&state.config.tunnel_authorized_keys, text.as_bytes())
|
||||
}
|
||||
|
||||
fn write_atomic(path: &std::path::Path, body: &[u8]) -> AppResult<()> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|err| {
|
||||
AppError::internal(format!(
|
||||
"could not create the tunnel key directory {}: {err}",
|
||||
parent.display()
|
||||
))
|
||||
})?;
|
||||
}
|
||||
let tmp = path.with_extension("tmp");
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(&tmp)
|
||||
.map_err(|err| {
|
||||
AppError::internal(format!(
|
||||
"could not write the tunnel key file {}: {err}",
|
||||
tmp.display()
|
||||
))
|
||||
})?;
|
||||
file.write_all(body)
|
||||
.map_err(|err| AppError::internal(format!("could not write the tunnel key file: {err}")))?;
|
||||
file.sync_all()
|
||||
.map_err(|err| AppError::internal(format!("could not sync the tunnel key file: {err}")))?;
|
||||
let mut perms = file
|
||||
.metadata()
|
||||
.map_err(|err| AppError::internal(format!("could not stat the tunnel key file: {err}")))?
|
||||
.permissions();
|
||||
perms.set_mode(0o640);
|
||||
std::fs::set_permissions(&tmp, perms)
|
||||
.map_err(|err| AppError::internal(format!("could not chmod the tunnel key file: {err}")))?;
|
||||
drop(file);
|
||||
std::fs::rename(&tmp, path).map_err(|err| {
|
||||
AppError::internal(format!(
|
||||
"could not install the tunnel key file {}: {err}",
|
||||
path.display()
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
use crate::config::Config;
|
||||
use crate::crypto::Secrets;
|
||||
use crate::db::Db;
|
||||
use crate::state::AppState;
|
||||
|
||||
fn test_state() -> (Shared, std::path::PathBuf) {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"rhema-tunnel-test-{}",
|
||||
crate::util::random_token(6)
|
||||
));
|
||||
std::fs::create_dir_all(&dir).expect("temp dir");
|
||||
let config = Config {
|
||||
database: dir.join("test.db"),
|
||||
secret_key_file: dir.join("test.key"),
|
||||
tunnel_authorized_keys: dir.join("tunnel/authorized_keys"),
|
||||
..Config::default()
|
||||
};
|
||||
let db = Db::open(&config.database).expect("db");
|
||||
let secrets = Secrets::load_or_create(&config.secret_key_file).expect("secrets");
|
||||
db.conn()
|
||||
.execute(
|
||||
"INSERT INTO accounts (id, handle, display_name, kind, created_at)
|
||||
VALUES ('a1', 'a', 'A', 'user', 0)",
|
||||
[],
|
||||
)
|
||||
.expect("account");
|
||||
db.conn()
|
||||
.execute(
|
||||
"INSERT INTO sandbox_targets
|
||||
(id, account_id, name, host, port, user_name, workspace_root,
|
||||
private_key_ciphertext, public_key, kind, tunnel_public_key, created_at)
|
||||
VALUES ('t1', 'a1', 'sandbox', '127.0.0.1', 22000, 'root', '/root',
|
||||
'sealed', 'ssh-ed25519 AAAA target', 'tunnel',
|
||||
'ssh-ed25519 AAAA tunnel', 0)",
|
||||
[],
|
||||
)
|
||||
.expect("target");
|
||||
let state = Arc::new(AppState {
|
||||
config,
|
||||
db,
|
||||
secrets,
|
||||
hub: Default::default(),
|
||||
rooms: Default::default(),
|
||||
workers: Default::default(),
|
||||
presence: Default::default(),
|
||||
logins: Default::default(),
|
||||
});
|
||||
(state, dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tunnel_keys_are_restricted_to_their_port() {
|
||||
let (state, dir) = test_state();
|
||||
assert_eq!(next_port(&state).expect("port"), 22001);
|
||||
refresh(&state).expect("refresh");
|
||||
let text = std::fs::read_to_string(&state.config.tunnel_authorized_keys).expect("file");
|
||||
assert!(
|
||||
text.contains(
|
||||
"restrict,port-forwarding,permitlisten=\"127.0.0.1:22000\" ssh-ed25519 AAAA tunnel t1"
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
std::fs::remove_dir_all(dir).ok();
|
||||
}
|
||||
}
|
||||
+1
-5
@@ -318,7 +318,7 @@ impl WorkerSandbox {
|
||||
private_key: key,
|
||||
host_fingerprint: target.host_fingerprint.clone(),
|
||||
},
|
||||
allow_private: state.config.allow_private_targets || target.kind == "tunnel",
|
||||
allow_private: state.config.allow_private_targets,
|
||||
})
|
||||
};
|
||||
self.state
|
||||
@@ -515,9 +515,6 @@ impl WorkerState {
|
||||
user_name: self.target.user_name.clone(),
|
||||
private_key_ciphertext: String::new(),
|
||||
host_fingerprint: self.target.host_fingerprint.clone(),
|
||||
// The worker does not use the kind; it is already past the
|
||||
// target check. A valid value keeps the row honest.
|
||||
kind: "direct".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -880,7 +877,6 @@ mod smoke {
|
||||
user_name: "vhaudiquet".into(),
|
||||
private_key_ciphertext: secrets.seal_str(&key).expect("seal"),
|
||||
host_fingerprint: None,
|
||||
kind: "direct".into(),
|
||||
};
|
||||
let state = Arc::new(AppState {
|
||||
config,
|
||||
|
||||
Reference in new issue
Block a user