add server-side command escape w/ public echo for admins
Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
parent
571ab6ac2b
commit
d4775f0763
5 changed files with 134 additions and 55 deletions
|
@ -198,6 +198,11 @@ registration_token = "change this token for something specific to your server"
|
||||||
# defaults to false
|
# defaults to false
|
||||||
# block_non_admin_invites = 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*.
|
# 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
|
# This is checked upon username availability check, registration, and startup as warnings if any local users in your database
|
||||||
# have a forbidden username.
|
# have a forbidden username.
|
||||||
|
|
|
@ -90,9 +90,8 @@ async fn process_event(event: AdminEvent) -> Option<RoomMessageEventContent> {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse and process a message from the admin room
|
// Parse and process a message from the admin room
|
||||||
#[tracing::instrument(name = "process")]
|
async fn process_admin_message(msg: String) -> RoomMessageEventContent {
|
||||||
async fn process_admin_message(room_message: String) -> RoomMessageEventContent {
|
let mut lines = msg.lines().filter(|l| !l.trim().is_empty());
|
||||||
let mut lines = room_message.lines().filter(|l| !l.trim().is_empty());
|
|
||||||
let command_line = lines.next().expect("each string has at least one line");
|
let command_line = lines.next().expect("each string has at least one line");
|
||||||
let body = lines.collect::<Vec<_>>();
|
let body = lines.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
@ -122,8 +121,14 @@ async fn process_admin_message(room_message: String) -> RoomMessageEventContent
|
||||||
fn parse_admin_command(command_line: &str) -> Result<AdminCommand, String> {
|
fn parse_admin_command(command_line: &str) -> Result<AdminCommand, String> {
|
||||||
let mut argv = command_line.split_whitespace().collect::<Vec<_>>();
|
let mut argv = command_line.split_whitespace().collect::<Vec<_>>();
|
||||||
|
|
||||||
|
// 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
|
// 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");
|
argv.insert(0, "admin");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -338,6 +338,8 @@ pub struct Config {
|
||||||
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub block_non_admin_invites: bool,
|
pub block_non_admin_invites: bool,
|
||||||
|
#[serde(default = "true_fn")]
|
||||||
|
pub admin_escape_commands: bool,
|
||||||
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub sentry: bool,
|
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)",
|
"Block non-admin room invites (local and remote, admins can still send and receive invites)",
|
||||||
&self.block_non_admin_invites.to_string(),
|
&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 outgoing federated typing", &self.allow_outgoing_typing.to_string()),
|
||||||
("Allow incoming federated typing", &self.allow_incoming_typing.to_string()),
|
("Allow incoming federated typing", &self.allow_incoming_typing.to_string()),
|
||||||
(
|
(
|
||||||
|
|
|
@ -8,7 +8,10 @@ use conduit::{Error, Result};
|
||||||
pub use create::create_admin_room;
|
pub use create::create_admin_room;
|
||||||
pub use grant::make_user_admin;
|
pub use grant::make_user_admin;
|
||||||
use ruma::{
|
use ruma::{
|
||||||
events::{room::message::RoomMessageEventContent, TimelineEventType},
|
events::{
|
||||||
|
room::message::{Relation, RoomMessageEventContent},
|
||||||
|
TimelineEventType,
|
||||||
|
},
|
||||||
EventId, OwnedRoomId, RoomId, UserId,
|
EventId, OwnedRoomId, RoomId, UserId,
|
||||||
};
|
};
|
||||||
use serde_json::value::to_raw_value;
|
use serde_json::value::to_raw_value;
|
||||||
|
@ -18,7 +21,7 @@ use tokio::{
|
||||||
};
|
};
|
||||||
use tracing::error;
|
use tracing::error;
|
||||||
|
|
||||||
use crate::{pdu::PduBuilder, services};
|
use crate::{pdu::PduBuilder, services, PduEvent};
|
||||||
|
|
||||||
pub type HandlerResult = Pin<Box<dyn Future<Output = Result<AdminEvent, Error>> + Send>>;
|
pub type HandlerResult = Pin<Box<dyn Future<Output = Result<AdminEvent, Error>> + Send>>;
|
||||||
pub type Handler = fn(AdminEvent) -> HandlerResult;
|
pub type Handler = fn(AdminEvent) -> HandlerResult;
|
||||||
|
@ -156,11 +159,11 @@ impl Service {
|
||||||
|
|
||||||
/// Checks whether a given user is an admin of this server
|
/// Checks whether a given user is an admin of this server
|
||||||
pub async fn user_is_admin(&self, user_id: &UserId) -> Result<bool> {
|
pub async fn user_is_admin(&self, user_id: &UserId) -> Result<bool> {
|
||||||
let Ok(Some(admin_room)) = Self::get_admin_room() else {
|
if let Ok(Some(admin_room)) = Self::get_admin_room() {
|
||||||
return Ok(false);
|
services().rooms.state_cache.is_joined(user_id, &admin_room)
|
||||||
};
|
} else {
|
||||||
|
Ok(false)
|
||||||
services().rooms.state_cache.is_joined(user_id, &admin_room)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Gets the room ID of the admin room
|
/// 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
|
/// Errors are propagated from the database, and will have None if there is
|
||||||
/// no admin room
|
/// no admin room
|
||||||
pub fn get_admin_room() -> Result<Option<OwnedRoomId>> {
|
pub fn get_admin_room() -> Result<Option<OwnedRoomId>> {
|
||||||
services()
|
if let Some(room_id) = services()
|
||||||
.rooms
|
.rooms
|
||||||
.alias
|
.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<RoomMessageEventContent>) {
|
async fn handle_response(content: Option<RoomMessageEventContent>) {
|
||||||
if let Some(content) = content {
|
if let Some(content) = content.as_ref() {
|
||||||
if let Err(e) = respond_to_room(content).await {
|
if let Some(Relation::Reply {
|
||||||
error!("{e}");
|
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<()> {
|
async fn respond_to_room(content: &RoomMessageEventContent, room_id: &RoomId, user_id: &UserId) {
|
||||||
let Ok(Some(admin_room)) = Service::get_admin_room() else {
|
assert!(
|
||||||
return Ok(());
|
services()
|
||||||
};
|
.admin
|
||||||
|
.user_is_admin(user_id)
|
||||||
|
.await
|
||||||
|
.expect("checked user is admin"),
|
||||||
|
"sender is not admin"
|
||||||
|
);
|
||||||
|
|
||||||
let mutex_state = Arc::clone(
|
let mutex_state = Arc::clone(
|
||||||
services()
|
services()
|
||||||
|
@ -194,34 +224,33 @@ async fn respond_to_room(output_content: RoomMessageEventContent) -> Result<()>
|
||||||
.roomid_mutex_state
|
.roomid_mutex_state
|
||||||
.write()
|
.write()
|
||||||
.await
|
.await
|
||||||
.entry(admin_room.clone())
|
.entry(room_id.to_owned())
|
||||||
.or_default(),
|
.or_default(),
|
||||||
);
|
);
|
||||||
let state_lock = mutex_state.lock().await;
|
let state_lock = mutex_state.lock().await;
|
||||||
|
|
||||||
let response_pdu = PduBuilder {
|
let response_pdu = PduBuilder {
|
||||||
event_type: TimelineEventType::RoomMessage,
|
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,
|
unsigned: None,
|
||||||
state_key: None,
|
state_key: None,
|
||||||
redacts: None,
|
redacts: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let server_user = &services().globals.server_user;
|
|
||||||
if let Err(e) = services()
|
if let Err(e) = services()
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.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
|
.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(
|
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<()> {
|
) -> Result<()> {
|
||||||
error!("Failed to build and append admin room response PDU: \"{e}\"");
|
error!("Failed to build and append admin room response PDU: \"{e}\"");
|
||||||
let error_room_message = RoomMessageEventContent::text_plain(format!(
|
let error_room_message = RoomMessageEventContent::text_plain(format!(
|
||||||
|
@ -240,8 +269,63 @@ async fn handle_response_error(
|
||||||
services()
|
services()
|
||||||
.rooms
|
.rooms
|
||||||
.timeline
|
.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?;
|
.await?;
|
||||||
|
|
||||||
Ok(())
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -35,10 +35,10 @@ use tracing::{debug, error, info, warn};
|
||||||
|
|
||||||
use super::state_compressor::CompressedStateEvent;
|
use super::state_compressor::CompressedStateEvent;
|
||||||
use crate::{
|
use crate::{
|
||||||
|
admin,
|
||||||
server_is_ours,
|
server_is_ours,
|
||||||
//api::server_server,
|
//api::server_server,
|
||||||
service::{
|
service::{
|
||||||
self,
|
|
||||||
appservice::NamespaceRegex,
|
appservice::NamespaceRegex,
|
||||||
pdu::{EventHash, PduBuilder},
|
pdu::{EventHash, PduBuilder},
|
||||||
rooms::event_handler::parse_incoming_pdu,
|
rooms::event_handler::parse_incoming_pdu,
|
||||||
|
@ -477,30 +477,11 @@ impl Service {
|
||||||
.search
|
.search
|
||||||
.index_pdu(shortroomid, &pdu_id, &body)?;
|
.index_pdu(shortroomid, &pdu_id, &body)?;
|
||||||
|
|
||||||
let server_user = &services().globals.server_user;
|
if admin::is_admin_command(pdu, &body).await {
|
||||||
|
services()
|
||||||
let to_conduit = body.starts_with(&format!("{server_user}: "))
|
.admin
|
||||||
|| body.starts_with(&format!("{server_user} "))
|
.command(body, Some(pdu.event_id.clone()))
|
||||||
|| body.starts_with("!admin")
|
.await;
|
||||||
|| 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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -795,7 +776,7 @@ impl Service {
|
||||||
state_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room state mutex
|
state_lock: &MutexGuard<'_, ()>, // Take mutex guard to make sure users get the room state mutex
|
||||||
) -> Result<Arc<EventId>> {
|
) -> Result<Arc<EventId>> {
|
||||||
let (pdu, pdu_json) = self.create_hash_and_sign_event(pdu_builder, sender, room_id, state_lock)?;
|
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 {
|
if admin_room == room_id {
|
||||||
match pdu.event_type() {
|
match pdu.event_type() {
|
||||||
TimelineEventType::RoomEncryption => {
|
TimelineEventType::RoomEncryption => {
|
||||||
|
@ -1222,6 +1203,7 @@ impl Service {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue