From d4775f076309aa91fb1972706bc6244de14ff03e Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Thu, 13 Jun 2024 22:22:21 +0000 Subject: [PATCH] add server-side command escape w/ public echo for admins Signed-off-by: Jason Volk --- conduwuit-example.toml | 5 ++ src/admin/handler.rs | 13 ++- src/core/config/mod.rs | 3 + src/service/admin/mod.rs | 134 ++++++++++++++++++++++++------ src/service/rooms/timeline/mod.rs | 34 ++------ 5 files changed, 134 insertions(+), 55 deletions(-) diff --git a/conduwuit-example.toml b/conduwuit-example.toml index 04bf26cd..97652eee 100644 --- a/conduwuit-example.toml +++ b/conduwuit-example.toml @@ -198,6 +198,11 @@ registration_token = "change this token for something specific to your server" # defaults to false # block_non_admin_invites = false +# Allows admins to enter commands in rooms other than #admins by prefixing with \!admin. The reply +# will be publicly visible to the room, originating from the sender. +# defaults to true +#admin_escape_commands = true + # List of forbidden username patterns/strings. Values in this list are matched as *contains*. # This is checked upon username availability check, registration, and startup as warnings if any local users in your database # have a forbidden username. diff --git a/src/admin/handler.rs b/src/admin/handler.rs index b44f08f4..e283def5 100644 --- a/src/admin/handler.rs +++ b/src/admin/handler.rs @@ -90,9 +90,8 @@ async fn process_event(event: AdminEvent) -> Option { } // Parse and process a message from the admin room -#[tracing::instrument(name = "process")] -async fn process_admin_message(room_message: String) -> RoomMessageEventContent { - let mut lines = room_message.lines().filter(|l| !l.trim().is_empty()); +async fn process_admin_message(msg: String) -> RoomMessageEventContent { + let mut lines = msg.lines().filter(|l| !l.trim().is_empty()); let command_line = lines.next().expect("each string has at least one line"); let body = lines.collect::>(); @@ -122,8 +121,14 @@ async fn process_admin_message(room_message: String) -> RoomMessageEventContent fn parse_admin_command(command_line: &str) -> Result { let mut argv = command_line.split_whitespace().collect::>(); + // Remove any escapes that came with a server-side escape command + if !argv.is_empty() && argv[0].ends_with("admin") { + argv[0] = argv[0].trim_start_matches('\\'); + } + // First indice has to be "admin" but for console convenience we add it here - if !argv.is_empty() && !argv[0].ends_with("admin") { + let server_user = services().globals.server_user.as_str(); + if !argv.is_empty() && !argv[0].ends_with("admin") && !argv[0].starts_with(server_user) { argv.insert(0, "admin"); } diff --git a/src/core/config/mod.rs b/src/core/config/mod.rs index dadb000b..58696f88 100644 --- a/src/core/config/mod.rs +++ b/src/core/config/mod.rs @@ -338,6 +338,8 @@ pub struct Config { #[serde(default)] pub block_non_admin_invites: bool, + #[serde(default = "true_fn")] + pub admin_escape_commands: bool, #[serde(default)] pub sentry: bool, @@ -610,6 +612,7 @@ impl fmt::Display for Config { "Block non-admin room invites (local and remote, admins can still send and receive invites)", &self.block_non_admin_invites.to_string(), ), + ("Enable admin escape commands", &self.admin_escape_commands.to_string()), ("Allow outgoing federated typing", &self.allow_outgoing_typing.to_string()), ("Allow incoming federated typing", &self.allow_incoming_typing.to_string()), ( diff --git a/src/service/admin/mod.rs b/src/service/admin/mod.rs index d93b5a03..aa4c2c21 100644 --- a/src/service/admin/mod.rs +++ b/src/service/admin/mod.rs @@ -8,7 +8,10 @@ use conduit::{Error, Result}; pub use create::create_admin_room; pub use grant::make_user_admin; use ruma::{ - events::{room::message::RoomMessageEventContent, TimelineEventType}, + events::{ + room::message::{Relation, RoomMessageEventContent}, + TimelineEventType, + }, EventId, OwnedRoomId, RoomId, UserId, }; use serde_json::value::to_raw_value; @@ -18,7 +21,7 @@ use tokio::{ }; use tracing::error; -use crate::{pdu::PduBuilder, services}; +use crate::{pdu::PduBuilder, services, PduEvent}; pub type HandlerResult = Pin> + Send>>; pub type Handler = fn(AdminEvent) -> HandlerResult; @@ -156,11 +159,11 @@ impl Service { /// Checks whether a given user is an admin of this server pub async fn user_is_admin(&self, user_id: &UserId) -> Result { - let Ok(Some(admin_room)) = Self::get_admin_room() else { - return Ok(false); - }; - - services().rooms.state_cache.is_joined(user_id, &admin_room) + if let Ok(Some(admin_room)) = Self::get_admin_room() { + services().rooms.state_cache.is_joined(user_id, &admin_room) + } else { + Ok(false) + } } /// Gets the room ID of the admin room @@ -168,25 +171,52 @@ impl Service { /// Errors are propagated from the database, and will have None if there is /// no admin room pub fn get_admin_room() -> Result> { - services() + if let Some(room_id) = services() .rooms .alias - .resolve_local_alias(&services().globals.admin_alias) + .resolve_local_alias(&services().globals.admin_alias)? + { + if services() + .rooms + .state_cache + .is_joined(&services().globals.server_user, &room_id)? + { + return Ok(Some(room_id)); + } + } + + Ok(None) } } async fn handle_response(content: Option) { - if let Some(content) = content { - if let Err(e) = respond_to_room(content).await { - error!("{e}"); + if let Some(content) = content.as_ref() { + if let Some(Relation::Reply { + in_reply_to, + }) = content.relates_to.as_ref() + { + if let Ok(Some(pdu)) = services().rooms.timeline.get_pdu(&in_reply_to.event_id) { + let response_sender = if is_admin_room(&pdu.room_id) { + &services().globals.server_user + } else { + &pdu.sender + }; + + respond_to_room(content, &pdu.room_id, response_sender).await; + } } } } -async fn respond_to_room(output_content: RoomMessageEventContent) -> Result<()> { - let Ok(Some(admin_room)) = Service::get_admin_room() else { - return Ok(()); - }; +async fn respond_to_room(content: &RoomMessageEventContent, room_id: &RoomId, user_id: &UserId) { + assert!( + services() + .admin + .user_is_admin(user_id) + .await + .expect("checked user is admin"), + "sender is not admin" + ); let mutex_state = Arc::clone( services() @@ -194,34 +224,33 @@ async fn respond_to_room(output_content: RoomMessageEventContent) -> Result<()> .roomid_mutex_state .write() .await - .entry(admin_room.clone()) + .entry(room_id.to_owned()) .or_default(), ); let state_lock = mutex_state.lock().await; let response_pdu = PduBuilder { event_type: TimelineEventType::RoomMessage, - content: to_raw_value(&output_content).expect("event is valid, we just created it"), + content: to_raw_value(content).expect("event is valid, we just created it"), unsigned: None, state_key: None, redacts: None, }; - let server_user = &services().globals.server_user; if let Err(e) = services() .rooms .timeline - .build_and_append_pdu(response_pdu, server_user, &admin_room, &state_lock) + .build_and_append_pdu(response_pdu, user_id, room_id, &state_lock) .await { - handle_response_error(&e, &admin_room, server_user, &state_lock).await?; + if let Err(e) = handle_response_error(&e, room_id, user_id, &state_lock).await { + error!("{e}"); + } } - - Ok(()) } async fn handle_response_error( - e: &Error, admin_room: &RoomId, server_user: &UserId, state_lock: &MutexGuard<'_, ()>, + e: &Error, room_id: &RoomId, user_id: &UserId, state_lock: &MutexGuard<'_, ()>, ) -> Result<()> { error!("Failed to build and append admin room response PDU: \"{e}\""); let error_room_message = RoomMessageEventContent::text_plain(format!( @@ -240,8 +269,63 @@ async fn handle_response_error( services() .rooms .timeline - .build_and_append_pdu(response_pdu, server_user, admin_room, state_lock) + .build_and_append_pdu(response_pdu, user_id, room_id, state_lock) .await?; Ok(()) } + +pub async fn is_admin_command(pdu: &PduEvent, body: &str) -> bool { + // Server-side command-escape with public echo + let is_escape = body.starts_with('\\'); + let is_public_escape = is_escape && body.trim_start_matches('\\').starts_with("!admin"); + + // Admin command with public echo (in admin room) + let server_user = &services().globals.server_user; + let is_public_prefix = body.starts_with("!admin") || body.starts_with(server_user.as_str()); + + // Expected backward branch + if !is_public_escape && !is_public_prefix { + return false; + } + + // Check if server-side command-escape is disabled by configuration + if is_public_escape && !services().globals.config.admin_escape_commands { + return false; + } + + // Prevent unescaped !admin from being used outside of the admin room + if is_public_prefix && !is_admin_room(&pdu.room_id) { + return false; + } + + // Only senders who are admin can proceed + if !services() + .admin + .user_is_admin(&pdu.sender) + .await + .unwrap_or(false) + { + return false; + } + + // This will evaluate to false if the emergency password is set up so that + // the administrator can execute commands as conduit + let emergency_password_set = services().globals.emergency_password().is_some(); + let from_server = pdu.sender == *server_user && !emergency_password_set; + if from_server && is_admin_room(&pdu.room_id) { + return false; + } + + // Authentic admin command + true +} + +#[must_use] +pub fn is_admin_room(room_id: &RoomId) -> bool { + if let Ok(Some(admin_room_id)) = Service::get_admin_room() { + admin_room_id == room_id + } else { + false + } +} diff --git a/src/service/rooms/timeline/mod.rs b/src/service/rooms/timeline/mod.rs index 31a687a0..7deba4de 100644 --- a/src/service/rooms/timeline/mod.rs +++ b/src/service/rooms/timeline/mod.rs @@ -35,10 +35,10 @@ use tracing::{debug, error, info, warn}; use super::state_compressor::CompressedStateEvent; use crate::{ + admin, server_is_ours, //api::server_server, service::{ - self, appservice::NamespaceRegex, pdu::{EventHash, PduBuilder}, rooms::event_handler::parse_incoming_pdu, @@ -477,30 +477,11 @@ impl Service { .search .index_pdu(shortroomid, &pdu_id, &body)?; - let server_user = &services().globals.server_user; - - let to_conduit = body.starts_with(&format!("{server_user}: ")) - || body.starts_with(&format!("{server_user} ")) - || body.starts_with("!admin") - || body == format!("{server_user}:") - || body == *server_user; - - // This will evaluate to false if the emergency password is set up so that - // the administrator can execute commands as conduit - let from_conduit = pdu.sender == *server_user && services().globals.emergency_password().is_none(); - if let Some(admin_room) = service::admin::Service::get_admin_room()? { - if to_conduit - && !from_conduit && admin_room == pdu.room_id - && services() - .rooms - .state_cache - .is_joined(server_user, &admin_room)? - { - services() - .admin - .command(body, Some(pdu.event_id.clone())) - .await; - } + if admin::is_admin_command(pdu, &body).await { + services() + .admin + .command(body, Some(pdu.event_id.clone())) + .await; } } }, @@ -795,7 +776,7 @@ impl Service { state_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room state mutex ) -> Result> { let (pdu, pdu_json) = self.create_hash_and_sign_event(pdu_builder, sender, room_id, state_lock)?; - if let Some(admin_room) = service::admin::Service::get_admin_room()? { + if let Some(admin_room) = admin::Service::get_admin_room()? { if admin_room == room_id { match pdu.event_type() { TimelineEventType::RoomEncryption => { @@ -1222,6 +1203,7 @@ impl Service { Ok(()) } } + #[cfg(test)] mod tests { use super::*;