From 930198b8265e2ec264e34cf88cc0935ca1007638 Mon Sep 17 00:00:00 2001 From: Jean Date: Tue, 14 Jul 2026 00:45:52 +0000 Subject: [PATCH] Expand OperServ: SQLINE nick bans, GLOBAL, and KILL Generalise the network-ban store to carry the ircd X-line kind (defaulted to the user@host G-line for existing records) so one event-sourced, lazily-expiring, burst-reasserted list backs every ban type, and drive ADD/DEL/LIST from one implementation per kind: - AKILL stays the user@host G-line; SQLINE is a nick Q-line, its mask validated as a nick glob (an @ is refused so an AKILL-shaped mask can't become an over-broad nick ban). Both are keyed by (kind, mask). - GLOBAL announces to every user via a $* server-glob notice. - KILL [reason] disconnects a user, attributed to the operator. All four are admin-gated, and OperServ itself stays invisible to non-opers. Bans and kills go out as typed actions (AddLine/DelLine/KillUser) the ircd link serialises to ADDLINE/DELLINE/KILL. --- api/src/lib.rs | 20 +++++- inspircd/src/lib.rs | 1 + operserv/src/akill.rs | 140 ------------------------------------ operserv/src/global.rs | 18 +++++ operserv/src/kill.rs | 21 ++++++ operserv/src/lib.rs | 28 +++++--- operserv/src/xline.rs | 157 +++++++++++++++++++++++++++++++++++++++++ src/engine/db.rs | 83 ++++++++++++++-------- src/engine/mod.rs | 72 +++++++++++++++++-- 9 files changed, 351 insertions(+), 189 deletions(-) delete mode 100644 operserv/src/akill.rs create mode 100644 operserv/src/global.rs create mode 100644 operserv/src/kill.rs create mode 100644 operserv/src/xline.rs diff --git a/api/src/lib.rs b/api/src/lib.rs index d4e71c8..844f85b 100644 --- a/api/src/lib.rs +++ b/api/src/lib.rs @@ -92,6 +92,8 @@ pub enum NetAction { AddLine { kind: String, mask: String, setter: String, duration: u64, reason: String }, // Lift a network ban previously set with AddLine. DelLine { kind: String, mask: String }, + // Disconnect a user from the network, sourced from pseudoclient `from`. + KillUser { from: String, uid: String, reason: String }, Raw(String), // Internal only, never serialized to the wire: a registration whose password // still needs its (expensive) key derivation. The link layer runs the @@ -346,6 +348,17 @@ impl ServiceCtx { pub fn del_line(&mut self, kind: &str, mask: &str) { self.actions.push(NetAction::DelLine { kind: kind.to_string(), mask: mask.to_string() }); } + + // Disconnect a user, sourced from pseudoclient `from`. + pub fn kill(&mut self, from: &str, uid: &str, reason: &str) { + self.actions.push(NetAction::KillUser { from: from.to_string(), uid: uid.to_string(), reason: reason.to_string() }); + } + + // Send a notice to every user on the network, sourced from pseudoclient + // `from` (a "$*" server-glob target the ircd fans out to all users). + pub fn global(&mut self, from: &str, text: impl Into) { + self.actions.push(NetAction::Notice { from: from.to_string(), to: "$*".to_string(), text: text.into() }); + } } // --------------------------------------------------------------------------- @@ -408,9 +421,10 @@ pub struct VhostView { pub expires: Option, } -// A network ban (AKILL / G-line) held by OperServ. +// A network ban held by OperServ. `kind` is the ircd X-line type ("G", "Q", …). #[derive(Debug, Clone)] pub struct AkillView { + pub kind: String, pub mask: String, pub setter: String, pub reason: String, @@ -667,8 +681,8 @@ pub trait Store { // Network bans (AKILL / G-lines, oper-only). `akill_add` returns whether the // mask was newly added (false = an existing entry was refreshed); `akills` // lists only entries that haven't lazily expired, oldest first. - fn akill_add(&mut self, mask: &str, setter: &str, reason: &str, expires: Option) -> Result; - fn akill_del(&mut self, mask: &str) -> Result; + fn akill_add(&mut self, kind: &str, mask: &str, setter: &str, reason: &str, expires: Option) -> Result; + fn akill_del(&mut self, kind: &str, mask: &str) -> Result; fn akills(&self) -> Vec; fn register_channel(&mut self, name: &str, founder: &str) -> Result<(), ChanError>; fn drop_channel(&mut self, name: &str) -> Result<(), ChanError>; diff --git a/inspircd/src/lib.rs b/inspircd/src/lib.rs index 85b679e..5a22011 100644 --- a/inspircd/src/lib.rs +++ b/inspircd/src/lib.rs @@ -326,6 +326,7 @@ impl Protocol for InspIrcd { vec![self.sourced(format!("ADDLINE {} {} {} {} {} :{}", kind, mask, setter, now, duration, reason))] } NetAction::DelLine { kind, mask } => vec![self.sourced(format!("DELLINE {} {}", kind, mask))], + NetAction::KillUser { from, uid, reason } => vec![format!(":{} KILL {} :{}", from, uid, reason)], NetAction::Raw(s) => vec![s.clone()], // Internal: the link layer handles these before serialization. NetAction::DeferRegister { .. } | NetAction::DeferPassword { .. } | NetAction::SendEmail { .. } => vec![], diff --git a/operserv/src/akill.rs b/operserv/src/akill.rs deleted file mode 100644 index b4d755e..0000000 --- a/operserv/src/akill.rs +++ /dev/null @@ -1,140 +0,0 @@ -use fedserv_api::{parse_duration, Priv, Sender, ServiceCtx, Store}; -use std::time::{SystemTime, UNIX_EPOCH}; - -// AKILL ADD [+expiry] | DEL | LIST -// [pattern]: manage network bans. Admin-only — a network ban is the heaviest -// hammer services hold. -pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { - if !from.privs.has(Priv::Admin) { - ctx.notice(me, from.uid, "Access denied — AKILL needs the \x02admin\x02 privilege."); - return; - } - match args.get(1).map(|s| s.to_ascii_uppercase()).as_deref() { - Some("ADD") => add(me, from, &args[2..], ctx, db), - Some("DEL") | Some("REMOVE") => del(me, from, args.get(2).copied(), ctx, db), - Some("LIST") | Some("VIEW") => list(me, from, args.get(2).copied(), ctx, db), - _ => ctx.notice(me, from.uid, "Syntax: AKILL ADD [+expiry] | AKILL DEL | AKILL LIST [pattern]"), - } -} - -fn add(me: &str, from: &Sender, rest: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { - // An optional leading +duration, then the mask, then a free-text reason. - let mut rest = rest; - let duration = rest.first().and_then(|t| t.strip_prefix('+')).and_then(parse_duration); - if duration.is_some() { - rest = &rest[1..]; - } - let Some((&raw_mask, reason_words)) = rest.split_first() else { - ctx.notice(me, from.uid, "Syntax: AKILL ADD [+expiry] "); - return; - }; - let Some(mask) = normalize_mask(raw_mask) else { - ctx.notice(me, from.uid, format!("\x02{raw_mask}\x02 isn't a valid \x02user@host\x02 mask.")); - return; - }; - if reason_words.is_empty() { - ctx.notice(me, from.uid, "Please give a reason: AKILL ADD [+expiry] "); - return; - } - let reason = reason_words.join(" "); - // Refuse a mask so broad it would ban most of the network. - if too_wide(&mask) { - ctx.notice(me, from.uid, "That mask is too wide — it would ban almost everyone."); - return; - } - let setter = from.account.unwrap_or(from.nick); - let expires = duration.map(|secs| now() + secs); - match db.akill_add(&mask, setter, &reason, expires) { - Ok(fresh) => { - // The ircd applies the G-line to matching users already online and to - // future connections; duration 0 = permanent. - ctx.add_line("G", &mask, from.nick, duration.unwrap_or(0), &reason); - let word = if fresh { "added" } else { "updated" }; - let expiry = if expires.is_some() { " (temporary)" } else { "" }; - ctx.notice(me, from.uid, format!("AKILL {word} for \x02{mask}\x02{expiry}.")); - } - Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), - } -} - -fn del(me: &str, from: &Sender, arg: Option<&str>, ctx: &mut ServiceCtx, db: &mut dyn Store) { - let Some(arg) = arg else { - ctx.notice(me, from.uid, "Syntax: AKILL DEL "); - return; - }; - // A number targets the entry at that position in AKILL LIST; otherwise it's a - // literal mask. - let mask = match arg.parse::() { - Ok(n) if n >= 1 => match db.akills().get(n - 1) { - Some(a) => a.mask.clone(), - None => { - ctx.notice(me, from.uid, format!("There's no AKILL number \x02{n}\x02.")); - return; - } - }, - _ => normalize_mask(arg).unwrap_or_else(|| arg.to_string()), - }; - match db.akill_del(&mask) { - Ok(true) => { - ctx.del_line("G", &mask); - ctx.notice(me, from.uid, format!("AKILL for \x02{mask}\x02 removed.")); - } - Ok(false) => ctx.notice(me, from.uid, format!("No AKILL matches \x02{mask}\x02.")), - Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), - } -} - -fn list(me: &str, from: &Sender, pattern: Option<&str>, ctx: &mut ServiceCtx, db: &mut dyn Store) { - let pat = pattern.map(|p| p.to_ascii_lowercase()); - let akills = db.akills(); - let mut shown = 0; - for (i, a) in akills.iter().enumerate() { - if let Some(p) = &pat { - if !a.mask.to_ascii_lowercase().contains(p.as_str()) { - continue; - } - } - let expiry = match a.expires { - Some(e) => format!(", expires in {}", human_secs(e.saturating_sub(now()))), - None => String::new(), - }; - ctx.notice(me, from.uid, format!("{}. \x02{}\x02 by {} — {}{}", i + 1, a.mask, a.setter, a.reason, expiry)); - shown += 1; - } - if shown == 0 { - ctx.notice(me, from.uid, "No matching network bans."); - } else { - ctx.notice(me, from.uid, format!("End of AKILL list ({shown} shown).")); - } -} - -// Reduce an input to a `user@host` mask: drop any `nick!` prefix, require a -// single `@` with non-empty sides. Returns None if it isn't shaped like a mask. -fn normalize_mask(input: &str) -> Option { - let body = input.rsplit('!').next().unwrap_or(input); - let (user, host) = body.split_once('@')?; - if user.is_empty() || host.is_empty() || host.contains('@') { - return None; - } - Some(format!("{}@{}", user.to_ascii_lowercase(), host.to_ascii_lowercase())) -} - -// A mask whose user and host are both pure wildcard would catch nearly everyone. -fn too_wide(mask: &str) -> bool { - let Some((user, host)) = mask.split_once('@') else { return true }; - let trivial = |s: &str| s.chars().all(|c| c == '*' || c == '?' || c == '.'); - trivial(user) && trivial(host) -} - -fn human_secs(secs: u64) -> String { - match secs { - 0 => "moments".to_string(), - s if s < 3600 => format!("{}m", s / 60), - s if s < 86_400 => format!("{}h", s / 3600), - s => format!("{}d", s / 86_400), - } -} - -fn now() -> u64 { - SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) -} diff --git a/operserv/src/global.rs b/operserv/src/global.rs new file mode 100644 index 0000000..c7c2402 --- /dev/null +++ b/operserv/src/global.rs @@ -0,0 +1,18 @@ +use fedserv_api::{Priv, Sender, ServiceCtx}; + +// GLOBAL : send an announcement to every user on the network. Admin- +// only — it reaches everyone, so it's the heaviest voice services have. +pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx) { + if !from.privs.has(Priv::Admin) { + ctx.notice(me, from.uid, "Access denied — GLOBAL needs the \x02admin\x02 privilege."); + return; + } + let message = args[1..].join(" "); + if message.trim().is_empty() { + ctx.notice(me, from.uid, "Syntax: GLOBAL "); + return; + } + // A marker so users can tell an official announcement from a normal notice. + ctx.global(me, format!("[\x02Network\x02] {message}")); + ctx.notice(me, from.uid, "Your announcement has been sent to the whole network."); +} diff --git a/operserv/src/kill.rs b/operserv/src/kill.rs new file mode 100644 index 0000000..096e578 --- /dev/null +++ b/operserv/src/kill.rs @@ -0,0 +1,21 @@ +use fedserv_api::{NetView, Priv, Sender, ServiceCtx}; + +// KILL [reason]: disconnect a user from the network. Admin-only. +pub fn handle(me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, net: &dyn NetView) { + if !from.privs.has(Priv::Admin) { + ctx.notice(me, from.uid, "Access denied — KILL needs the \x02admin\x02 privilege."); + return; + } + let Some(&target) = args.get(1) else { + ctx.notice(me, from.uid, "Syntax: KILL [reason]"); + return; + }; + let Some(uid) = net.uid_by_nick(target).map(str::to_string) else { + ctx.notice(me, from.uid, format!("There's no \x02{target}\x02 online.")); + return; + }; + let by = from.account.unwrap_or(from.nick); + let reason = if args.len() > 2 { args[2..].join(" ") } else { "No reason given".to_string() }; + ctx.kill(me, &uid, &format!("({by}) {reason}")); + ctx.notice(me, from.uid, format!("\x02{target}\x02 has been disconnected.")); +} diff --git a/operserv/src/lib.rs b/operserv/src/lib.rs index eede665..f9539df 100644 --- a/operserv/src/lib.rs +++ b/operserv/src/lib.rs @@ -1,13 +1,16 @@ -//! OperServ gives services operators network-wide tools. The first is AKILL: -//! network bans (G-lines) that keep matching users off the whole network, -//! event-sourced so they survive a restart and re-apply at burst, with lazy -//! expiry like the rest of the store. `lib.rs` dispatches; each command is its -//! own file. +//! OperServ gives services operators network-wide tools: AKILL/SQLINE network +//! bans (event-sourced, lazily expiring, re-asserted at burst), a GLOBAL +//! announcement to every user, and KILL to disconnect one. `lib.rs` dispatches; +//! each command family is its own file. use fedserv_api::{NetView, Sender, Service, ServiceCtx, Store}; -#[path = "akill.rs"] -mod akill; +#[path = "xline.rs"] +mod xline; +#[path = "global.rs"] +mod global; +#[path = "kill.rs"] +mod kill; pub struct OperServ { pub uid: String, @@ -24,7 +27,7 @@ impl Service for OperServ { "Operator Service" } - fn on_command(&mut self, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, _net: &dyn NetView, db: &mut dyn Store) { + fn on_command(&mut self, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, net: &dyn NetView, db: &mut dyn Store) { let me = self.uid.as_str(); // Every OperServ command is operator-only: reveal nothing to others. if !from.privs.any() { @@ -32,14 +35,17 @@ impl Service for OperServ { return; } match args.first().copied() { - Some(cmd) if cmd.eq_ignore_ascii_case("AKILL") => akill::handle(me, from, args, ctx, db), + Some(cmd) if cmd.eq_ignore_ascii_case("AKILL") => xline::AKILL.handle(me, from, args, ctx, db), + Some(cmd) if cmd.eq_ignore_ascii_case("SQLINE") => xline::SQLINE.handle(me, from, args, ctx, db), + Some(cmd) if cmd.eq_ignore_ascii_case("GLOBAL") => global::handle(me, from, args, ctx), + Some(cmd) if cmd.eq_ignore_ascii_case("KILL") => kill::handle(me, from, args, ctx, net), Some(cmd) if cmd.eq_ignore_ascii_case("HELP") => help(me, from, ctx), None => help(me, from, ctx), - Some(other) => ctx.notice(me, from.uid, format!("I don't know \x02{other}\x02. Try \x02AKILL\x02 or \x02HELP\x02.")), + Some(other) => ctx.notice(me, from.uid, format!("I don't know \x02{other}\x02. Try \x02HELP\x02.")), } } } fn help(me: &str, from: &Sender, ctx: &mut ServiceCtx) { - ctx.notice(me, from.uid, "OperServ holds network operator tools. \x02AKILL ADD\x02 [+expiry] , \x02AKILL DEL\x02 , \x02AKILL LIST\x02 [pattern] — network bans (Priv::Admin)."); + ctx.notice(me, from.uid, "OperServ holds network operator tools (Priv::Admin): \x02AKILL\x02 ADD|DEL|LIST (user@host bans), \x02SQLINE\x02 ADD|DEL|LIST (nick bans), \x02GLOBAL\x02 (announce to everyone), \x02KILL\x02 [reason] (disconnect a user)."); } diff --git a/operserv/src/xline.rs b/operserv/src/xline.rs new file mode 100644 index 0000000..2a000e9 --- /dev/null +++ b/operserv/src/xline.rs @@ -0,0 +1,157 @@ +use fedserv_api::{parse_duration, Sender, ServiceCtx, Store}; +use std::time::{SystemTime, UNIX_EPOCH}; + +// A network-ban command family (AKILL, SQLINE, …): the ircd X-line `kind`, the +// user-facing command `name`, and the mask shape it accepts. One implementation +// drives ADD / DEL / LIST for every kind so they stay consistent. +pub struct Xline { + pub kind: &'static str, + pub name: &'static str, + pub target: &'static str, // e.g. "user@host" or "nick" — shown in syntax + pub normalize: fn(&str) -> Option, +} + +impl Xline { + pub fn handle(&self, me: &str, from: &Sender, args: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { + match args.get(1).map(|s| s.to_ascii_uppercase()).as_deref() { + Some("ADD") => self.add(me, from, &args[2..], ctx, db), + Some("DEL") | Some("REMOVE") => self.del(me, from, args.get(2).copied(), ctx, db), + Some("LIST") | Some("VIEW") => self.list(me, from, args.get(2).copied(), ctx, db), + _ => ctx.notice(me, from.uid, format!("Syntax: {0} ADD [+expiry] <{1}> | {0} DEL <{1}|number> | {0} LIST [pattern]", self.name, self.target)), + } + } + + fn add(&self, me: &str, from: &Sender, rest: &[&str], ctx: &mut ServiceCtx, db: &mut dyn Store) { + // An optional leading +duration, then the mask, then a free-text reason. + let mut rest = rest; + let duration = rest.first().and_then(|t| t.strip_prefix('+')).and_then(parse_duration); + if duration.is_some() { + rest = &rest[1..]; + } + let Some((&raw, reason_words)) = rest.split_first() else { + ctx.notice(me, from.uid, format!("Syntax: {} ADD [+expiry] <{}> ", self.name, self.target)); + return; + }; + let Some(mask) = (self.normalize)(raw) else { + ctx.notice(me, from.uid, format!("\x02{raw}\x02 isn't a valid \x02{}\x02 mask.", self.target)); + return; + }; + if reason_words.is_empty() { + ctx.notice(me, from.uid, "Please give a reason."); + return; + } + if too_wide(&mask) { + ctx.notice(me, from.uid, "That mask is too wide — it would match almost everyone."); + return; + } + let reason = reason_words.join(" "); + let setter = from.account.unwrap_or(from.nick); + let expires = duration.map(|secs| now() + secs); + match db.akill_add(self.kind, &mask, setter, &reason, expires) { + Ok(fresh) => { + ctx.add_line(self.kind, &mask, from.nick, duration.unwrap_or(0), &reason); + let word = if fresh { "added" } else { "updated" }; + let expiry = if expires.is_some() { " (temporary)" } else { "" }; + ctx.notice(me, from.uid, format!("{} {word} for \x02{mask}\x02{expiry}.", self.name)); + } + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } + } + + fn del(&self, me: &str, from: &Sender, arg: Option<&str>, ctx: &mut ServiceCtx, db: &mut dyn Store) { + let Some(arg) = arg else { + ctx.notice(me, from.uid, format!("Syntax: {} DEL <{}|number>", self.name, self.target)); + return; + }; + // A number targets the nth entry of this kind in the list; else a mask. + let mask = match arg.parse::() { + Ok(n) if n >= 1 => match self.mine(db).get(n - 1) { + Some(mask) => mask.clone(), + None => { + ctx.notice(me, from.uid, format!("There's no {} number \x02{n}\x02.", self.name)); + return; + } + }, + _ => (self.normalize)(arg).unwrap_or_else(|| arg.to_string()), + }; + match db.akill_del(self.kind, &mask) { + Ok(true) => { + ctx.del_line(self.kind, &mask); + ctx.notice(me, from.uid, format!("{} for \x02{mask}\x02 removed.", self.name)); + } + Ok(false) => ctx.notice(me, from.uid, format!("No {} matches \x02{mask}\x02.", self.name)), + Err(_) => ctx.notice(me, from.uid, "Sorry, that didn't work. Please try again in a moment."), + } + } + + fn list(&self, me: &str, from: &Sender, pattern: Option<&str>, ctx: &mut ServiceCtx, db: &mut dyn Store) { + let pat = pattern.map(|p| p.to_ascii_lowercase()); + let mut shown = 0; + for (i, a) in db.akills().iter().filter(|a| a.kind == self.kind).enumerate() { + if let Some(p) = &pat { + if !a.mask.to_ascii_lowercase().contains(p.as_str()) { + continue; + } + } + let expiry = match a.expires { + Some(e) => format!(", expires in {}", human_secs(e.saturating_sub(now()))), + None => String::new(), + }; + ctx.notice(me, from.uid, format!("{}. \x02{}\x02 by {} — {}{}", i + 1, a.mask, a.setter, a.reason, expiry)); + shown += 1; + } + if shown == 0 { + ctx.notice(me, from.uid, format!("No matching {} entries.", self.name)); + } else { + ctx.notice(me, from.uid, format!("End of {} list ({shown} shown).", self.name)); + } + } + + // The live masks of this kind, in list order (for DEL by number). + fn mine(&self, db: &dyn Store) -> Vec { + db.akills().into_iter().filter(|a| a.kind == self.kind).map(|a| a.mask).collect() + } +} + +// AKILL: a user@host G-line. Strips any nick! prefix, lowercases both sides. +pub const AKILL: Xline = Xline { kind: "G", name: "AKILL", target: "user@host", normalize: norm_userhost }; + +// SQLINE: a nick Q-line. The mask is a nick glob (no '@'); wildcards allowed. +pub const SQLINE: Xline = Xline { kind: "Q", name: "SQLINE", target: "nick", normalize: norm_nick }; + +fn norm_userhost(input: &str) -> Option { + let body = input.rsplit('!').next().unwrap_or(input); + let (user, host) = body.split_once('@')?; + if user.is_empty() || host.is_empty() || host.contains('@') { + return None; + } + Some(format!("{}@{}", user.to_ascii_lowercase(), host.to_ascii_lowercase())) +} + +fn norm_nick(input: &str) -> Option { + // A nick mask, not a hostmask: reject an '@' so a user typo can't become an + // over-broad ban, and keep it non-empty. + if input.is_empty() || input.contains('@') || input.contains('!') { + return None; + } + Some(input.to_ascii_lowercase()) +} + +// A mask whose every meaningful character is a wildcard would match nearly all. +fn too_wide(mask: &str) -> bool { + let trivial = |s: &str| s.chars().all(|c| c == '*' || c == '?' || c == '.' || c == '@'); + trivial(mask) +} + +fn human_secs(secs: u64) -> String { + match secs { + 0 => "moments".to_string(), + s if s < 3600 => format!("{}m", s / 60), + s if s < 86_400 => format!("{}h", s / 3600), + s => format!("{}d", s / 86_400), + } +} + +fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} diff --git a/src/engine/db.rs b/src/engine/db.rs index c2b9f53..8761b20 100644 --- a/src/engine/db.rs +++ b/src/engine/db.rs @@ -179,10 +179,23 @@ pub enum Event { // An impending-expiry warning email was sent; cleared by the next Seen/Used. AccountExpiryWarned { account: String }, ChannelExpiryWarned { channel: String }, - // Network bans (OperServ AKILL). Global: a ban covers the whole network, so - // every node holds the list and re-applies it at burst. - AkillAdded { mask: String, setter: String, reason: String, ts: u64, expires: Option }, - AkillRemoved { mask: String }, + // Network bans (OperServ AKILL / SQLINE). Global: a ban covers the whole + // network, so every node holds the list and re-applies it at burst. `kind` + // is the ircd X-line type and defaults to "G" for records predating it. + AkillAdded { + #[serde(default = "gline_kind")] + kind: String, + mask: String, + setter: String, + reason: String, + ts: u64, + expires: Option, + }, + AkillRemoved { + #[serde(default = "gline_kind")] + kind: String, + mask: String, + }, } // Whether an event replicates across the federation. Account identity is Global @@ -282,10 +295,13 @@ pub struct Suspension { pub expires: Option, } -// A network ban (AKILL / G-line): a user@host mask, who set it, why, when, and -// an optional absolute-unix-seconds expiry (None = permanent). +// A network ban: the ircd X-line `kind` (e.g. "G" for a user@host G-line, "Q" +// for a nick Q-line), a mask, who set it, why, when, and an optional +// absolute-unix-seconds expiry (None = permanent). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Akill { + #[serde(default = "gline_kind")] + pub kind: String, pub mask: String, pub setter: String, pub reason: String, @@ -294,6 +310,11 @@ pub struct Akill { pub expires: Option, } +// The default ban kind for records written before bans carried one: a G-line. +fn gline_kind() -> String { + "G".to_string() +} + // A memo left for an account (MemoServ). #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Memo { @@ -1004,7 +1025,7 @@ impl Db { // Compaction is a good moment to forget akills that have already expired. let now = now(); for a in self.akills.iter().filter(|a| a.expires.is_none_or(|e| e > now)) { - snapshot.push(Event::AkillAdded { mask: a.mask.clone(), setter: a.setter.clone(), reason: a.reason.clone(), ts: a.ts, expires: a.expires }); + snapshot.push(Event::AkillAdded { kind: a.kind.clone(), mask: a.mask.clone(), setter: a.setter.clone(), reason: a.reason.clone(), ts: a.ts, expires: a.expires }); } self.log.compact(snapshot)?; tracing::info!(before, after = self.log.len(), "compacted event log"); @@ -1739,25 +1760,27 @@ impl Db { } } - /// Add (or refresh) a network ban. Returns whether the mask was newly added. - pub fn akill_add(&mut self, mask: &str, setter: &str, reason: &str, expires: Option) -> Result { - let fresh = !self.akills.iter().any(|a| a.mask.eq_ignore_ascii_case(mask) && a.expires.is_none_or(|e| e > now())); + /// Add (or refresh) a `kind` network ban. Returns whether it was newly added. + pub fn akill_add(&mut self, kind: &str, mask: &str, setter: &str, reason: &str, expires: Option) -> Result { + let same = |a: &Akill| a.kind == kind && a.mask.eq_ignore_ascii_case(mask); + let fresh = !self.akills.iter().any(|a| same(a) && a.expires.is_none_or(|e| e > now())); self.log - .append(Event::AkillAdded { mask: mask.to_string(), setter: setter.to_string(), reason: reason.to_string(), ts: now(), expires }) + .append(Event::AkillAdded { kind: kind.to_string(), mask: mask.to_string(), setter: setter.to_string(), reason: reason.to_string(), ts: now(), expires }) .map_err(|_| RegError::Internal)?; - self.akills.retain(|a| !a.mask.eq_ignore_ascii_case(mask)); - self.akills.push(Akill { mask: mask.to_string(), setter: setter.to_string(), reason: reason.to_string(), ts: now(), expires }); + self.akills.retain(|a| !same(a)); + self.akills.push(Akill { kind: kind.to_string(), mask: mask.to_string(), setter: setter.to_string(), reason: reason.to_string(), ts: now(), expires }); Ok(fresh) } - /// Lift a network ban. Returns whether a live (non-expired) one was removed. - pub fn akill_del(&mut self, mask: &str) -> Result { - let existed = self.akills.iter().any(|a| a.mask.eq_ignore_ascii_case(mask) && a.expires.is_none_or(|e| e > now())); + /// Lift a `kind` network ban. Returns whether a live one was removed. + pub fn akill_del(&mut self, kind: &str, mask: &str) -> Result { + let same = |a: &Akill| a.kind == kind && a.mask.eq_ignore_ascii_case(mask); + let existed = self.akills.iter().any(|a| same(a) && a.expires.is_none_or(|e| e > now())); if !existed { return Ok(false); } - self.log.append(Event::AkillRemoved { mask: mask.to_string() }).map_err(|_| RegError::Internal)?; - self.akills.retain(|a| !a.mask.eq_ignore_ascii_case(mask)); + self.log.append(Event::AkillRemoved { kind: kind.to_string(), mask: mask.to_string() }).map_err(|_| RegError::Internal)?; + self.akills.retain(|a| !same(a)); Ok(true) } @@ -1767,7 +1790,7 @@ impl Db { self.akills .iter() .filter(|a| a.expires.is_none_or(|e| e > now)) - .map(|a| AkillView { mask: a.mask.clone(), setter: a.setter.clone(), reason: a.reason.clone(), ts: a.ts, expires: a.expires }) + .map(|a| AkillView { kind: a.kind.clone(), mask: a.mask.clone(), setter: a.setter.clone(), reason: a.reason.clone(), ts: a.ts, expires: a.expires }) .collect() } @@ -2669,14 +2692,14 @@ fn apply(accounts: &mut HashMap, channels: &mut HashMap { - // Keyed by mask (case-insensitive): a re-add refreshes in place, so - // replaying over a snapshot stays idempotent. - akills.retain(|a| !a.mask.eq_ignore_ascii_case(&mask)); - akills.push(Akill { mask, setter, reason, ts, expires }); + Event::AkillAdded { kind, mask, setter, reason, ts, expires } => { + // Keyed by (kind, mask), case-insensitive: a re-add refreshes in + // place, so replaying over a snapshot stays idempotent. + akills.retain(|a| !(a.kind == kind && a.mask.eq_ignore_ascii_case(&mask))); + akills.push(Akill { kind, mask, setter, reason, ts, expires }); } - Event::AkillRemoved { mask } => { - akills.retain(|a| !a.mask.eq_ignore_ascii_case(&mask)); + Event::AkillRemoved { kind, mask } => { + akills.retain(|a| !(a.kind == kind && a.mask.eq_ignore_ascii_case(&mask))); } Event::AccountExpiryWarned { account } => { if let Some(a) = accounts.get_mut(&key(&account)) { @@ -2920,11 +2943,11 @@ impl Store for Db { fn set_channel_noexpire(&mut self, channel: &str, on: bool) -> Result { Db::set_channel_noexpire(self, channel, on) } - fn akill_add(&mut self, mask: &str, setter: &str, reason: &str, expires: Option) -> Result { - Db::akill_add(self, mask, setter, reason, expires) + fn akill_add(&mut self, kind: &str, mask: &str, setter: &str, reason: &str, expires: Option) -> Result { + Db::akill_add(self, kind, mask, setter, reason, expires) } - fn akill_del(&mut self, mask: &str) -> Result { - Db::akill_del(self, mask) + fn akill_del(&mut self, kind: &str, mask: &str) -> Result { + Db::akill_del(self, kind, mask) } fn akills(&self) -> Vec { Db::akills(self) diff --git a/src/engine/mod.rs b/src/engine/mod.rs index da73779..c1581e7 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -682,7 +682,7 @@ impl Engine { let now = self.now_secs(); for a in self.db.akills() { let duration = a.expires.map(|e| e.saturating_sub(now)).unwrap_or(0); - out.push(NetAction::AddLine { kind: "G".to_string(), mask: a.mask, setter: a.setter, duration, reason: a.reason }); + out.push(NetAction::AddLine { kind: a.kind, mask: a.mask, setter: a.setter, duration, reason: a.reason }); } out.push(NetAction::Metadata { target: "*".to_string(), @@ -1495,6 +1495,14 @@ impl Engine { } } +// A human label for a network-ban X-line kind, for the audit feed. +fn ban_kind_label(kind: &str) -> &'static str { + match kind { + "Q" => "nick ban", + _ => "network ban", + } +} + // A rough human span for an expiry deadline in an email ("7 days", "12 hours"). fn human_duration(secs: u64) -> String { let plural = |n: u64, unit: &str| format!("{n} {unit}{}", if n == 1 { "" } else { "s" }); @@ -1553,11 +1561,11 @@ fn audit_summary(event: &db::Event) -> Option { Some(t) => format!("set the vhost template to \x02{t}\x02"), None => "cleared the vhost template".to_string(), }, - AkillAdded { mask, reason, expires, .. } => { - let kind = if expires.is_some() { " (temporary)" } else { "" }; - format!("set a network ban on \x02{mask}\x02{kind} ({reason})") + AkillAdded { kind, mask, reason, expires, .. } => { + let temp = if expires.is_some() { " (temporary)" } else { "" }; + format!("set a {} on \x02{mask}\x02{temp} ({reason})", ban_kind_label(kind)) } - AkillRemoved { mask } => format!("lifted the network ban on \x02{mask}\x02"), + AkillRemoved { kind, mask } => format!("lifted the {} on \x02{mask}\x02", ban_kind_label(kind)), AccountNoExpire { account, on } => { let verb = if *on { "pinned" } else { "unpinned" }; format!("{verb} account \x02{account}\x02 against expiry") @@ -3895,6 +3903,60 @@ mod tests { assert_eq!(again, 0, "warning isn't repeated while still idle"); } + // OperServ SQLINE (nick bans), GLOBAL (announce to all), and KILL (disconnect + // a user): the Q-line, the $* broadcast, and the KILL all reach the ircd, and + // each is admin-gated. + #[test] + fn operserv_sqline_global_and_kill() { + use fedserv_operserv::OperServ; + let path = std::env::temp_dir().join("fedserv-osmore.jsonl"); + let _ = std::fs::remove_file(&path); + let mut db = Db::open(&path, "42S"); + db.scram_iterations = 4096; + db.register("staff", "password1", None).unwrap(); + db.register("plain", "password1", None).unwrap(); + let mut e = Engine::new( + vec![ + Box::new(NickServ { uid: "42SAAAAAA".into(), guest_nick: "Guest".into(), guest_seq: 0 }), + Box::new(OperServ { uid: "42SAAAAAH".into() }), + ], + db, + ); + e.set_sid("42S".into()); + let mut opers = std::collections::HashMap::new(); + opers.insert("staff".to_string(), Privs::default().with(fedserv_api::Priv::Admin)); + e.set_opers(opers); + let os = |e: &mut Engine, uid: &str, t: &str| e.handle(NetEvent::Privmsg { from: uid.into(), to: "42SAAAAAH".into(), text: t.into() }); + + e.handle(NetEvent::UserConnect { uid: "000AAAAAS".into(), nick: "staff".into(), host: "h".into() }); + e.handle(NetEvent::Privmsg { from: "000AAAAAS".into(), to: "42SAAAAAA".into(), text: "IDENTIFY password1".into() }); + e.handle(NetEvent::UserConnect { uid: "000AAAAAP".into(), nick: "plain".into(), host: "h".into() }); + e.handle(NetEvent::Privmsg { from: "000AAAAAP".into(), to: "42SAAAAAA".into(), text: "IDENTIFY password1".into() }); + e.handle(NetEvent::UserConnect { uid: "000AAAAAV".into(), nick: "spammer".into(), host: "h".into() }); + + // SQLINE drives a Q-line on the nick mask, tracked separately from AKILLs. + let out = os(&mut e, "000AAAAAS", "SQLINE ADD *bot* botnet"); + assert!(out.iter().any(|a| matches!(a, NetAction::AddLine { kind, mask, .. } if kind == "Q" && mask == "*bot*")), "Q-line added: {out:?}"); + // A rejected @-shaped mask (that belongs to AKILL, not SQLINE). + assert!(os(&mut e, "000AAAAAS", "SQLINE ADD a@b spam").iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("valid"))), "nick mask rejects user@host"); + + // GLOBAL fans out to every user via the $* server glob. + let out = os(&mut e, "000AAAAAS", "GLOBAL rebooting in 5"); + assert!(out.iter().any(|a| matches!(a, NetAction::Notice { to, text, .. } if to == "$*" && text.contains("rebooting in 5"))), "global broadcast: {out:?}"); + + // KILL disconnects the named user, attributed to the oper. + let out = os(&mut e, "000AAAAAS", "KILL spammer flooding"); + assert!(out.iter().any(|a| matches!(a, NetAction::KillUser { uid, reason, .. } if uid == "000AAAAAV" && reason.contains("flooding") && reason.contains("staff"))), "kill issued: {out:?}"); + + // None of it works for a non-admin: refused, and no network action leaks. + for cmd in ["SQLINE ADD *x* y", "GLOBAL hi", "KILL staff go"] { + let out = os(&mut e, "000AAAAAP", cmd); + assert!(out.iter().any(|a| matches!(a, NetAction::Notice { text, .. } if text.contains("Access denied"))), "non-admin refused {cmd}"); + assert!(!out.iter().any(|a| matches!(a, NetAction::AddLine { .. } | NetAction::KillUser { .. })), "no ban/kill from non-admin {cmd}"); + assert!(!out.iter().any(|a| matches!(a, NetAction::Notice { to, .. } if to == "$*")), "no broadcast from non-admin {cmd}"); + } + } + // NOEXPIRE is oper-only. #[test] fn noexpire_command_is_oper_gated() {