diff --git a/projects/start-wrt/API_CONTRACT.md b/projects/start-wrt/API_CONTRACT.md index da1e112c42..8bee312a4f 100644 --- a/projects/start-wrt/API_CONTRACT.md +++ b/projects/start-wrt/API_CONTRACT.md @@ -877,6 +877,9 @@ struct Device { /// (`devices.set-dns-injection`; `vpn-server.peer-set-dns-injection` for a /// VPN peer). allow_dns_injection: bool, + /// Whether the router refused this device's DNS records for lack of that + /// permission in the last half hour. + dns_injection_requested: bool, /// Whether the router forwards this device's IPv6 router advertisements /// to the rest of the LAN (`devices.set-router-advertisements`). Always /// false for VPN peers. diff --git a/projects/start-wrt/backend/ctrl/src/auth.rs b/projects/start-wrt/backend/ctrl/src/auth.rs index cb49a9edf0..6b2433dc2a 100644 --- a/projects/start-wrt/backend/ctrl/src/auth.rs +++ b/projects/start-wrt/backend/ctrl/src/auth.rs @@ -13,7 +13,7 @@ use patch_db::{HasModel, ModelExt, PatchDb}; use rpc_toolkit::yajrc::RpcError; use rpc_toolkit::{from_fn_async, CallRemote, Empty, HandlerArgs, HandlerExt, ParentHandler}; use serde::{Deserialize, Serialize}; -use startos::auth::{AuthKeys, LoginContext, Session}; +use startos::auth::{AuthKeys, LoginAttempt, LoginContext, Session}; use startos::middleware::auth::local::LocalAuthContext; use startos::middleware::auth::signature::{ check_enrolled, url_host_str, HasUnenrolledKeys, LoginMetadata, NonceCache, @@ -239,17 +239,47 @@ impl LoginContext for ServerContext { db.as_session_pubkeys_mut() } fn check_password(_: &Model, password: &str) -> Result<(), startos::Error> { - check_password_sync(Path::new(SHADOW_PATH), password).map_err(|e| { - crate::activity::log("auth", "login", false, "Login failed", Some(&e.to_string())); - e.into() - }) + Ok(check_password_sync(Path::new(SHADOW_PATH), password)?) } fn sign_in_expired(session: &Session, now: DateTime) -> bool { sign_in_ended(session.logged_in, now, true) } - async fn post_login_hook(&self, _: &str) -> Result<(), startos::Error> { - crate::activity::log("auth", "login", true, "Logged in", None); - Ok(()) + async fn login_attempt_hook( + &self, + attempt: &LoginAttempt, + result: Result<(), &startos::Error>, + ) { + let mut source = String::new(); + if let Some(peer) = attempt.peer { + source = format!(" from {}", crate::peer::describe(peer).await); + } + let client = describe_client(attempt.user_agent.as_deref()); + match result { + Ok(()) => crate::activity::log( + "auth", + "login", + true, + &format!("Logged in{source} {client}"), + None, + ), + Err(e) => crate::activity::log( + "auth", + "login", + false, + &format!("Login failed{source} {client}"), + Some(&e.to_string()), + ), + } + } +} + +/// Every mainstream browser's user agent starts `Mozilla/`; other clients are +/// named by their first product token. +fn describe_client(user_agent: Option<&str>) -> String { + match user_agent.and_then(|ua| ua.split_whitespace().next()) { + Some(product) if product.starts_with("Mozilla/") => "using a browser".into(), + Some(product) => format!("using {}", product.chars().take(64).collect::()), + None => "with no user agent".into(), } } @@ -701,6 +731,22 @@ mod tests { const LAST_ACTIVE_RESOLUTION: TimeDelta = ::LAST_ACTIVE_RESOLUTION; + #[test] + fn login_clients_are_named_by_user_agent() { + for (user_agent, expected) in [ + ( + Some("Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0"), + "using a browser", + ), + (Some("curl/8.5.0"), "using curl/8.5.0"), + (Some("node"), "using node"), + (Some(" "), "with no user agent"), + (None, "with no user agent"), + ] { + assert_eq!(describe_client(user_agent), expected, "{user_agent:?}"); + } + } + #[test] fn validate_password_length_rejects_short() { assert!(validate_password_length("shortpass12").is_err()); diff --git a/projects/start-wrt/backend/ctrl/src/backup.rs b/projects/start-wrt/backend/ctrl/src/backup.rs index b74ba7c659..8ffd7703c0 100644 --- a/projects/start-wrt/backend/ctrl/src/backup.rs +++ b/projects/start-wrt/backend/ctrl/src/backup.rs @@ -396,12 +396,14 @@ async fn restore( None, ); + crate::boot::record_reboot(crate::boot::RunState::Restoring); tokio::spawn(async { tokio::time::sleep(std::time::Duration::from_secs(1)).await; if let Err(e) = Command::new("reboot") .invoke(ErrorKind::Filesystem.into()) .await { + crate::boot::record_running(); tracing::error!("failed to reboot after restore: {e}"); } }); diff --git a/projects/start-wrt/backend/ctrl/src/bins/daemon.rs b/projects/start-wrt/backend/ctrl/src/bins/daemon.rs index d3aa124341..9064504c92 100644 --- a/projects/start-wrt/backend/ctrl/src/bins/daemon.rs +++ b/projects/start-wrt/backend/ctrl/src/bins/daemon.rs @@ -239,6 +239,7 @@ async fn inner_main() -> Result<(), Error> { } else { // Normal mode: restore WiFi + manage captive portal state + crate::boot::record_start(crate::update::update_pending()); // Record the outcome of a pending OTA update (if any) in the Activity // log now that the new firmware is up. crate::update::check_pending_update_marker(); @@ -387,6 +388,7 @@ async fn inner_main() -> Result<(), Error> { if !setup_mode { tokio::spawn(crate::auth::reap_idle_keys(ctx.clone())); + tokio::spawn(crate::ssh_sessions::run()); } let handler = Server::new(move || ready(Ok(ctx.clone())), main_api()) .middleware(Auth::new().with_local_auth().with_signature_auth()); @@ -508,10 +510,16 @@ async fn inner_main() -> Result<(), Error> { tokio::signal::unix::signal(SignalKind::terminate()).with_kind(ErrorKind::Filesystem)?; let mut sigint = tokio::signal::unix::signal(SignalKind::interrupt()).with_kind(ErrorKind::Filesystem)?; + if !setup_mode { + crate::boot::record_running(); + } tokio::select! { _ = sigterm.recv() => tracing::info!("received SIGTERM, shutting down"), _ = sigint.recv() => tracing::info!("received SIGINT, shutting down"), } + if !setup_mode { + crate::boot::record_stop(); + } server.shutdown().await; Ok(()) diff --git a/projects/start-wrt/backend/ctrl/src/boot.rs b/projects/start-wrt/backend/ctrl/src/boot.rs new file mode 100644 index 0000000000..5d5bdb2ad9 --- /dev/null +++ b/projects/start-wrt/backend/ctrl/src/boot.rs @@ -0,0 +1,260 @@ +//! The `system.boot` activity entry: one per boot, with the firmware version +//! and what ended the run before it, when the router recorded that. + +use std::io::Write; +use std::path::Path; + +/// The daemon's own account of its run, kept across reboots. +const RUN_STATE: &str = "/var/lib/startwrt/run-state"; +/// Exists once this boot has its entry. In RAM. +const BOOT_LOGGED: &str = "/var/run/startwrt-boot-logged"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RunState { + /// Initializing; a run that ends here ended for an unknown reason. + Starting, + Running, + Stopped, + Restarting, + Restoring, +} + +impl RunState { + fn as_str(self) -> &'static str { + match self { + RunState::Starting => "starting", + RunState::Running => "running", + RunState::Stopped => "stopped", + RunState::Restarting => "restarting", + RunState::Restoring => "restoring", + } + } + + fn parse(s: &str) -> Option { + Some(match s.trim() { + "starting" => RunState::Starting, + "running" => RunState::Running, + "stopped" => RunState::Stopped, + "restarting" => RunState::Restarting, + "restoring" => RunState::Restoring, + _ => return None, + }) + } + + /// Why a run that ended in this state led to a boot. + fn reboot_cause(self) -> Option<&'static str> { + match self { + RunState::Starting => None, + RunState::Running => Some("a power loss or crash"), + RunState::Stopped => Some("a clean shutdown"), + RunState::Restarting => Some("a restart from StartWRT"), + RunState::Restoring => Some("restoring a backup"), + } + } +} + +/// Logs `system.boot` on the daemon's first start in a boot, then marks the +/// run as starting. An applied firmware update takes precedence over the +/// recorded state. +pub fn record_start(update_applied: bool) { + if let Some(summary) = start_at(Path::new(RUN_STATE), Path::new(BOOT_LOGGED), update_applied) { + crate::activity::log("system", "boot", true, &summary, None); + } +} + +/// Marks the run as fully started. +pub fn record_running() { + write_state(Path::new(RUN_STATE), RunState::Running); +} + +/// Marks the run as stopped on request, unless a reboot's cause is already +/// recorded. +pub fn record_stop() { + stop_at(Path::new(RUN_STATE)); +} + +/// Records why the router is about to reboot. +pub fn record_reboot(cause: RunState) { + write_state(Path::new(RUN_STATE), cause); +} + +fn start_at(run_state: &Path, boot_logged: &Path, update_applied: bool) -> Option { + let previous = read_state(run_state); + write_state(run_state, RunState::Starting); + if boot_logged.exists() { + return None; + } + if let Err(e) = std::fs::write(boot_logged, "") { + tracing::warn!("failed to mark this boot as logged: {e}"); + } + let cause = if update_applied { + Some("a firmware update") + } else { + previous.and_then(RunState::reboot_cause) + }; + let mut summary = format!( + "Booted v{} ({})", + env!("CARGO_PKG_VERSION"), + short_hash(env!("STARTWRT_GIT_HASH")) + ); + if let Some(cause) = cause { + summary.push_str(" after "); + summary.push_str(cause); + } + Some(summary) +} + +fn stop_at(path: &Path) { + if read_state(path) == Some(RunState::Running) { + write_state(path, RunState::Stopped); + } +} + +fn read_state(path: &Path) -> Option { + RunState::parse(&std::fs::read_to_string(path).ok()?) +} + +/// Durable before it returns: the state must outlive a power loss right after. +fn write_state(path: &Path, state: RunState) { + if let Err(e) = write_durably(path, state.as_str()) { + tracing::warn!("failed to record run state {}: {e}", state.as_str()); + } +} + +fn write_durably(path: &Path, contents: &str) -> std::io::Result<()> { + let dir = path.parent().unwrap_or(Path::new("/")); + std::fs::create_dir_all(dir)?; + let tmp = path.with_extension("tmp"); + let mut file = std::fs::File::create(&tmp)?; + file.write_all(contents.as_bytes())?; + file.sync_all()?; + std::fs::rename(&tmp, path)?; + std::fs::File::open(dir)?.sync_all() +} + +/// A commit hash shortened to 9 digits, keeping any `-modified` mark. +fn short_hash(hash: &str) -> String { + let (commit, mark) = match hash.split_once('-') { + Some((commit, mark)) => (commit, Some(mark)), + None => (hash, None), + }; + if commit.len() <= 9 || !commit.bytes().all(|b| b.is_ascii_hexdigit()) { + return hash.to_string(); + } + match mark { + Some(mark) => format!("{}-{mark}", &commit[..9]), + None => commit[..9].to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn boot(dir: &Path, update_applied: bool) -> Option { + start_at( + &dir.join("run-state"), + &dir.join("boot-logged"), + update_applied, + ) + } + + fn new_boot(dir: &Path) { + std::fs::remove_file(dir.join("boot-logged")).unwrap(); + } + + fn cause(summary: Option) -> Option { + summary + .expect("a boot entry") + .split_once(" after ") + .map(|(_, cause)| cause.to_string()) + } + + #[test] + fn each_boot_names_how_the_previous_run_ended() { + let dir = tempfile::tempdir().unwrap(); + let state = dir.path().join("run-state"); + + assert_eq!(cause(boot(dir.path(), false)), None); + assert_eq!(read_state(&state), Some(RunState::Starting)); + + new_boot(dir.path()); + assert_eq!( + cause(boot(dir.path(), false)), + None, + "never finished starting" + ); + + write_durably(&state, "running").unwrap(); + new_boot(dir.path()); + assert_eq!( + cause(boot(dir.path(), false)).as_deref(), + Some("a power loss or crash") + ); + + write_durably(&state, "running").unwrap(); + stop_at(&state); + new_boot(dir.path()); + assert_eq!( + cause(boot(dir.path(), false)).as_deref(), + Some("a clean shutdown") + ); + + write_durably(&state, "restarting").unwrap(); + stop_at(&state); + new_boot(dir.path()); + assert_eq!( + cause(boot(dir.path(), false)).as_deref(), + Some("a restart from StartWRT") + ); + + write_durably(&state, "restoring").unwrap(); + new_boot(dir.path()); + assert_eq!( + cause(boot(dir.path(), false)).as_deref(), + Some("restoring a backup") + ); + + write_durably(&state, "running").unwrap(); + new_boot(dir.path()); + assert_eq!( + cause(boot(dir.path(), true)).as_deref(), + Some("a firmware update") + ); + } + + #[test] + fn a_daemon_restart_within_a_boot_logs_nothing() { + let dir = tempfile::tempdir().unwrap(); + assert!(boot(dir.path(), false).is_some()); + assert_eq!(boot(dir.path(), false), None); + assert_eq!( + read_state(&dir.path().join("run-state")), + Some(RunState::Starting) + ); + } + + #[test] + fn unreadable_state_names_no_cause() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("run-state"), "garbage").unwrap(); + assert_eq!(cause(boot(dir.path(), false)), None); + } + + #[test] + fn hashes_shorten_to_nine_digits() { + assert_eq!( + short_hash("a64bbe71ed041f2864c40588275425a8b9e500a0"), + "a64bbe71e" + ); + assert_eq!( + short_hash("a64bbe71ed041f2864c40588275425a8b9e500a0-modified"), + "a64bbe71e-modified" + ); + assert_eq!( + short_hash("@wrt/activity-log-gaps"), + "@wrt/activity-log-gaps" + ); + assert_eq!(short_hash("unknown"), "unknown"); + } +} diff --git a/projects/start-wrt/backend/ctrl/src/devices.rs b/projects/start-wrt/backend/ctrl/src/devices.rs index 76d54b7078..59afdaeb25 100644 --- a/projects/start-wrt/backend/ctrl/src/devices.rs +++ b/projects/start-wrt/backend/ctrl/src/devices.rs @@ -1,5 +1,5 @@ use std::collections::HashMap; -use std::net::Ipv4Addr; +use std::net::{IpAddr, Ipv4Addr}; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -86,6 +86,9 @@ pub struct Device { /// (`devices set-dns-injection`; `vpn-server peer-set-dns-injection` for a /// VPN peer). pub allow_dns_injection: bool, + /// Whether the router refused this device's DNS records for lack of that + /// permission in the last half hour. + pub dns_injection_requested: bool, /// Whether the router forwards this device's IPv6 router advertisements /// to the rest of the LAN (`devices set-router-advertisements`). Always /// false for a VPN peer. @@ -1830,6 +1833,10 @@ pub async fn list(_ctx: ServerContext) -> Result, Error> { } } let mdns_by_mac = resolve_mdns_names(mdns_targets).await; + let asking_to_publish = crate::dns_inject::DNS_INJECT + .get() + .map(|di| di.asking_sources()) + .unwrap_or_default(); let mut devices = Vec::new(); for mac in &all_macs { @@ -1984,6 +1991,16 @@ pub async fn list(_ctx: ServerContext) -> Result, Error> { .get(mac) .map(|(rx, tx)| ((rx + tx) as f64 / 1_073_741_824.0 * 10.0).round() / 10.0); + let allow_dns_injection = host.is_some_and(|h| h._allow_dns_inject.as_deref() == Some("1")); + let dns_injection_requested = !allow_dns_injection + && arp_list + .iter() + .map(|e| e.ip.as_str()) + .chain(lease.map(|l| l.ip.as_str())) + .chain(ipv4.as_deref()) + .filter_map(|ip| ip.parse::().ok()) + .any(|ip| asking_to_publish.contains(&ip)); + devices.push(Device { mac: Some(mac.clone()), name, @@ -1999,7 +2016,8 @@ pub async fn list(_ctx: ServerContext) -> Result, Error> { ipv4_reservations, profile_network: profile_address.map(|net| net.to_string()), allow_auto_port_forward: host.is_some_and(|h| h._allow_pcp.as_deref() == Some("1")), - allow_dns_injection: host.is_some_and(|h| h._allow_dns_inject.as_deref() == Some("1")), + allow_dns_injection, + dns_injection_requested, allow_router_advertisements: host.is_some_and(|h| h._allow_ra.as_deref() == Some("1")), security_profile, speed, @@ -2110,6 +2128,12 @@ pub async fn list(_ctx: ServerContext) -> Result, Error> { // No MAC to authorize, so a VPN peer can never be auto-forward capable. allow_auto_port_forward: false, allow_dns_injection: peer_cfg.allow_dns_injection, + dns_injection_requested: !peer_cfg.allow_dns_injection + && peer_cfg + .ip + .as_deref() + .and_then(|ip| ip.parse::().ok()) + .is_some_and(|ip| asking_to_publish.contains(&ip)), allow_router_advertisements: false, security_profile: Some(server.profile_fullname.clone()), speed, @@ -2262,6 +2286,17 @@ fn follow_replaced_reservations( Ok(changed) } +/// What a save did to the assigned name. An absent request leaves it alone. +fn name_change(prior: Option<&str>, requested: Option<&str>) -> Option { + match (prior, requested?) { + (Some(old), "") => Some(format!("cleared name '{old}'")), + (None, "") => None, + (Some(old), new) if old == new => None, + (Some(old), _) => Some(format!("renamed from '{old}'")), + (None, _) => Some("name assigned".into()), + } +} + /// Every field dnsmasq parses, checked before it reaches the config it reads: /// a malformed reservation is one it refuses to start on, taking the LAN's DHCP /// with it. An unchanged reservation is not checked again, so a rename never @@ -2342,7 +2377,8 @@ pub async fn update( .iter() .filter_map(|s| s.get_typed::().ok().flatten()) .find(|h| h.mac.eq_ignore_ascii_case(&mac_upper)) - .and_then(|h| h.name); + .and_then(|h| h.name) + .filter(|name| !name.is_empty()); reservations::write_reservations(&mut cfgs["dhcp"], &mac_upper, &want)?; if let Some(name) = req.name.as_deref() { reservations::write_name(&mut cfgs["dhcp"], &mac_upper, Some(name))?; @@ -2350,7 +2386,7 @@ pub async fn update( let label = match req.name.as_deref() { Some(name) => Some(name.to_string()), - None => prior_name, + None => prior_name.clone(), } .filter(|name| !name.is_empty()); let subject = match label { @@ -2382,7 +2418,10 @@ pub async fn update( return Err(err.into()); } Ok(()) => { - let summary = format!("Updated device {subject}{suffix}"); + let renamed = name_change(prior_name.as_deref(), req.name.as_deref()) + .map(|change| format!(" — {change}")) + .unwrap_or_default(); + let summary = format!("Updated device {subject}{renamed}{suffix}"); crate::activity::log("device", "updated", true, &summary, None); if ctx.effectful() { reload_dnsmasq(); @@ -3796,6 +3835,24 @@ config host 'host_aabbccddeeff_2' } } + #[test] + fn name_changes_describe_the_old_name() { + for (prior, requested, expected) in [ + (Some("old"), Some("new"), Some("renamed from 'old'")), + (Some("old"), Some(""), Some("cleared name 'old'")), + (None, Some("new"), Some("name assigned")), + (Some("same"), Some("same"), None), + (Some("old"), None, None), + (None, Some(""), None), + ] { + assert_eq!( + name_change(prior, requested).as_deref(), + expected, + "{prior:?} → {requested:?}" + ); + } + } + #[test] fn device_vlan_prefers_neighbour_bridge() { let e = arp("192.168.20.5", "br-lan.20", "STALE"); diff --git a/projects/start-wrt/backend/ctrl/src/dns_inject.rs b/projects/start-wrt/backend/ctrl/src/dns_inject.rs index 9774d2a81a..6dadea37c9 100644 --- a/projects/start-wrt/backend/ctrl/src/dns_inject.rs +++ b/projects/start-wrt/backend/ctrl/src/dns_inject.rs @@ -18,7 +18,7 @@ //! recreated. Records, ownership and the directory live in memory; //! clients re-assert within 180 s of a restart. -use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4}; use std::path::PathBuf; use std::sync::{Arc, Mutex, OnceLock}; @@ -65,6 +65,9 @@ const TCP_IDLE_TIMEOUT: Duration = Duration::from_secs(10); const TCP_MAX_CLIENTS: usize = 16; /// Refusal log lines per second, box-wide. const REFUSAL_LOG_RATE: u32 = 20; +/// How long a source refused for lacking the permission counts as asking. +const REQUEST_MEMORY: Duration = Duration::from_secs(30 * 60); +const MAX_REFUSED_SOURCES: usize = 256; const INJECT_FILE_PREFIX: &str = "startwrt-dns-inject.dns_"; /// The domain every profile instance serves its devices under. const LAN_DOMAIN: &str = "lan"; @@ -161,6 +164,7 @@ struct Directory { /// served only to zones that can reach its source. reach: BTreeSet<(String, String)>, hosts: HostNames, + refusals: Refusals, } /// A device's name under `lan.`, placed in the profile whose subnet holds its @@ -262,6 +266,11 @@ impl DnsInject { pub fn invalidate(&self) { self.poke.notify_one(); } + + /// Addresses recently refused for lacking the permission. + pub fn asking_sources(&self) -> HashSet { + self.directory.peek(|d| d.refusals.asking(Instant::now())) + } } /// Run the service for the life of the daemon. @@ -642,31 +651,104 @@ fn policy( auth: UpdateAuth, ) -> ResponseCode { // The client sees only a generic failure. - let refuse = |why: String| { - log_refusal(src, &why); - ResponseCode::Refused - }; directory.mutate(|d| match check(d, src, updates, auth) { Ok(owner) => { claim(d, &owner, updates); + d.refusals.admit(src); ResponseCode::NoError } - Err(why) => refuse(why), + Err(why) => { + if d.refusals.record(src, &why, Instant::now()) { + log_refusal(src, &why); + } + ResponseCode::Refused + } }) } +#[derive(Clone, Debug, PartialEq, Eq)] +enum Refusal { + NotPermitted, + NeedsTcp, + LanZone(LowerName), + NotInjectable(RecordType), + NeedsSignature(RecordType), + OwnedByOther(LowerName), +} + +impl std::fmt::Display for Refusal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Refusal::NotPermitted => f.write_str( + "source holds no known address assignment with the DNS-injection permission", + ), + Refusal::NeedsTcp => f.write_str("an unsigned update must arrive over TCP"), + Refusal::LanZone(name) => write!(f, "{name} is inside the reserved `lan.` zone"), + Refusal::NotInjectable(rtype) => write!(f, "record type {rtype} is not injectable"), + Refusal::NeedsSignature(rtype) => { + write!(f, "record type {rtype} needs a signed update") + } + Refusal::OwnedByOther(name) => write!(f, "{name} is owned by another device"), + } + } +} + +/// The latest refusal of each source since it was last admitted. +#[derive(Default)] +struct Refusals(HashMap); + +impl Refusals { + /// Whether the reason is new for the source. Past the cap, the stalest + /// source is forgotten. + fn record(&mut self, src: IpAddr, why: &Refusal, now: Instant) -> bool { + if let Some((reason, last)) = self.0.get_mut(&src) { + *last = now; + if reason == why { + return false; + } + *reason = why.clone(); + return true; + } + if self.0.len() >= MAX_REFUSED_SOURCES { + if let Some(stalest) = self.0.iter().min_by_key(|(_, (_, last))| *last) { + let stalest = *stalest.0; + self.0.remove(&stalest); + } + } + self.0.insert(src, (why.clone(), now)); + true + } + + fn admit(&mut self, src: IpAddr) { + self.0.remove(&src); + } + + /// Sources refused for lacking the permission within [`REQUEST_MEMORY`]. + fn asking(&self, now: Instant) -> HashSet { + self.0 + .iter() + .filter(|(_, (reason, last))| { + *reason == Refusal::NotPermitted && now.duration_since(*last) < REQUEST_MEMORY + }) + .map(|(src, _)| *src) + .collect() + } +} + /// The update's owner, when the directory admits every record. fn check( d: &Directory, src: IpAddr, updates: &[Record], auth: UpdateAuth, -) -> Result { - let owner = d.by_ip.get(&src).map(|i| i.owner.clone()).ok_or_else(|| { - "source holds no known address assignment with the DNS-injection permission".to_string() - })?; +) -> Result { + let owner = d + .by_ip + .get(&src) + .map(|i| i.owner.clone()) + .ok_or(Refusal::NotPermitted)?; if !auth.tsig && !auth.tcp { - return Err("an unsigned update must arrive over TCP".into()); + return Err(Refusal::NeedsTcp); } let held_by_other = |name: &LowerName, rtype: RecordType| { d.owners @@ -677,7 +759,7 @@ fn check( let name = LowerName::from(&rec.name); // dnsmasq is authoritative for `lan.`. if lan_zone().zone_of(&name) { - return Err(format!("{name} is inside the reserved `lan.` zone")); + return Err(Refusal::LanZone(name)); } let rtype = rec.record_type(); let held = match rec.dns_class { @@ -686,10 +768,10 @@ fn check( rtype, RecordType::A | RecordType::AAAA | RecordType::CNAME | RecordType::TXT ) { - return Err(format!("record type {rtype} is not injectable")); + return Err(Refusal::NotInjectable(rtype)); } if !auth.tsig && !matches!(rtype, RecordType::A | RecordType::AAAA) { - return Err(format!("record type {rtype} needs a signed update")); + return Err(Refusal::NeedsSignature(rtype)); } held_by_other(&name, rtype) } @@ -701,7 +783,7 @@ fn check( _ => false, }; if held { - return Err(format!("{name} is owned by another device")); + return Err(Refusal::OwnedByOther(name)); } } Ok(owner) @@ -733,7 +815,7 @@ fn lan_zone() -> LowerName { LowerName::from(Name::from_ascii("lan.").expect("static valid name")) } -fn log_refusal(src: IpAddr, why: &str) { +fn log_refusal(src: IpAddr, why: &Refusal) { static WINDOW: Mutex> = Mutex::new(None); let mut window = WINDOW.lock().unwrap_or_else(|e| e.into_inner()); let now = Instant::now(); @@ -1383,6 +1465,71 @@ mod tests { SyncMutex::new(d) } + #[tokio::test] + async fn an_unpermitted_source_is_asking_until_admitted() { + let dir = directory(); + let stranger = IpAddr::V4(lan_ip(77)); + let permitted = IpAddr::V4(lan_ip(50)); + let update = |host| [a_record("nas.example.com", lan_ip(host))]; + assert_eq!( + admit(&dir, stranger, &update(77), TCP).await, + ResponseCode::Refused + ); + assert_eq!( + admit(&dir, permitted, &update(50), UpdateAuth::default()).await, + ResponseCode::Refused, + "refused for another reason" + ); + let asking = dir.peek(|d| d.refusals.asking(Instant::now())); + assert_eq!(asking, HashSet::from([stranger])); + + dir.mutate(|d| { + d.by_ip.insert( + stranger, + Injector { + owner: Owner::Mac("AA:00:00:00:00:77".into()), + profile: "lan".into(), + }, + ) + }); + assert_eq!( + admit(&dir, stranger, &update(77), TCP).await, + ResponseCode::NoError + ); + assert!(dir.peek(|d| d.refusals.asking(Instant::now()).is_empty())); + } + + #[test] + fn a_refusal_is_new_only_when_its_reason_changes() { + let mut refusals = Refusals::default(); + let src = IpAddr::V4(lan_ip(77)); + let now = Instant::now(); + assert!(refusals.record(src, &Refusal::NotPermitted, now)); + assert!(!refusals.record(src, &Refusal::NotPermitted, now)); + assert!(refusals.record(src, &Refusal::NeedsTcp, now)); + assert!(refusals.record(src, &Refusal::NotPermitted, now)); + refusals.admit(src); + assert!(refusals.record(src, &Refusal::NotPermitted, now)); + + let later = now + REQUEST_MEMORY; + assert!(refusals.asking(later).is_empty(), "forgotten after a while"); + } + + #[test] + fn refusals_forget_the_stalest_source_past_the_cap() { + let mut refusals = Refusals::default(); + let start = Instant::now(); + for n in 0..=MAX_REFUSED_SOURCES { + let src = IpAddr::V6(std::net::Ipv6Addr::from(n as u128 + 1)); + let at = start + Duration::from_millis(n as u64); + refusals.record(src, &Refusal::NotPermitted, at); + } + assert_eq!(refusals.0.len(), MAX_REFUSED_SOURCES); + assert!(!refusals + .0 + .contains_key(&IpAddr::V6(std::net::Ipv6Addr::from(1)))); + } + async fn publish_public_name_offline(signed: bool) { use hickory_server::proto::op::update_message::append; use hickory_server::proto::op::Message; diff --git a/projects/start-wrt/backend/ctrl/src/lib.rs b/projects/start-wrt/backend/ctrl/src/lib.rs index d88ef74201..9393ba3c98 100644 --- a/projects/start-wrt/backend/ctrl/src/lib.rs +++ b/projects/start-wrt/backend/ctrl/src/lib.rs @@ -6,6 +6,7 @@ pub mod activity; pub mod auth; pub mod backup; pub mod bins; +pub mod boot; pub mod boot0; pub mod captive; pub mod continuations; @@ -29,6 +30,7 @@ pub mod lan_guard; pub mod logs; pub mod luci_proxy; pub mod migrate; +pub mod peer; pub mod port_control; pub mod profiles; pub mod progress; @@ -38,6 +40,7 @@ pub mod reservations; pub mod setup; pub use startos::sign; pub mod ssh_keys; +pub mod ssh_sessions; pub mod ssl; pub mod system; pub mod tls; diff --git a/projects/start-wrt/backend/ctrl/src/migrate.rs b/projects/start-wrt/backend/ctrl/src/migrate.rs index 0fb52178fc..c6c66d58ce 100644 --- a/projects/start-wrt/backend/ctrl/src/migrate.rs +++ b/projects/start-wrt/backend/ctrl/src/migrate.rs @@ -89,6 +89,34 @@ impl Migration { Migration::ReissueRootCa => reissue_root_ca(root).await, } } + + /// Completes "Updated settings to …". + fn purpose(self) -> &'static str { + match self { + Migration::RemoveEtcNftablesRules => { + "remove firewall rule files left by earlier versions" + } + Migration::StripUnreferencedWanZoneVpns => { + "take unused VPN connections out of the WAN firewall zone" + } + Migration::PppoeWanIpv6 => "stop PPPoE connections from running a second IPv6 client", + Migration::StoreLanAccessMode => "store each profile's LAN Access setting", + Migration::ExpandLogRetention => "keep more system log history", + Migration::StoreLogsUnderVar => "move the system and activity logs into /var", + Migration::RemoveSessionsJson => "remove sign-in sessions saved by earlier versions", + Migration::ForceDhcpPools => { + "hand out addresses without first checking for another DHCP server" + } + Migration::RemoveServerCert => { + "remove the single HTTPS certificate earlier versions used" + } + Migration::EnableFlowOffloading => "speed up forwarding of established connections", + Migration::ScopeReservedNames => { + "serve each reserved device's name only within its own profile" + } + Migration::ReissueRootCa => "reissue the Root CA in a form iOS can install", + } + } } /// Applies every migration the configuration under the filesystem root has @@ -96,26 +124,87 @@ impl Migration { /// /// Without a record, a configuration that StartWRT has already run on starts /// from the first migration and a fresh one is recorded as current. A failed -/// migration stops the run and stays pending for the next boot. +/// migration stops the run and stays pending for the next boot. A run that +/// applies or fails a migration records it in the activity log. pub async fn run(root: &Path) -> Result<(), Error> { + let mut progress = Progress::default(); + let result = apply_pending(root, &mut progress).await; + if let Some(summary) = progress.summary(result.is_ok()) { + let error = result.as_ref().err().map(|e| e.to_string()); + crate::activity::log( + "system", + "migrate", + result.is_ok(), + &summary, + error.as_deref(), + ); + } + result.map_err(|e| match progress.failed { + Some(migration) => Error::new( + eyre!("migration {migration:?} failed: {e}"), + ErrorKind::Filesystem, + ), + None => e, + }) +} + +#[derive(Default)] +struct Progress { + applied: Vec, + failed: Option, +} + +impl Progress { + fn summary(&self, succeeded: bool) -> Option { + let version = env!("CARGO_PKG_VERSION"); + let updated = purposes(&self.applied); + match (succeeded, self.applied.is_empty(), self.failed) { + (true, true, _) => None, + (true, false, _) => Some(format!("Updated settings for v{version} to {updated}")), + (false, true, Some(failed)) => Some(format!( + "Couldn't update settings for v{version} to {}", + failed.purpose() + )), + (false, true, None) => Some(format!("Couldn't update settings for v{version}")), + (false, false, Some(failed)) => Some(format!( + "Updated settings for v{version} to {updated}, but couldn't {}", + failed.purpose() + )), + (false, false, None) => Some(format!( + "Updated settings for v{version} to {updated}, but couldn't finish" + )), + } + } +} + +fn purposes(migrations: &[Migration]) -> String { + let purposes: Vec<_> = migrations.iter().map(|m| m.purpose()).collect(); + match purposes.as_slice() { + [] => String::new(), + [one] => one.to_string(), + [first, second] => format!("{first} and {second}"), + [rest @ .., last] => format!("{}, and {last}", rest.join(", ")), + } +} + +async fn apply_pending(root: &Path, progress: &mut Progress) -> Result<(), Error> { let record = root.join(RECORD); - let mut applied = match read_record(&record).await? { - Some(applied) => applied, + let mut done = match read_record(&record).await? { + Some(done) => done, None if has_run_startwrt(root).await => 0, None => { write_record(&record, MIGRATIONS.len()).await?; return Ok(()); } }; - while let Some(migration) = MIGRATIONS.get(applied) { - migration.apply(root).await.map_err(|e| { - Error::new( - eyre!("migration {migration:?} failed: {e}"), - ErrorKind::Filesystem, - ) - })?; - applied += 1; - write_record(&record, applied).await?; + while let Some(&migration) = MIGRATIONS.get(done) { + if let Err(e) = migration.apply(root).await { + progress.failed = Some(migration); + return Err(e); + } + done += 1; + write_record(&record, done).await?; + progress.applied.push(migration); } Ok(()) } @@ -454,6 +543,53 @@ async fn move_file(from: &Path, to: &Path, collision: Collision) -> Result<(), E mod tests { use super::*; + #[test] + fn migration_outcomes_say_what_changed() { + let v = env!("CARGO_PKG_VERSION"); + let progress = |applied: &[Migration], failed| Progress { + applied: applied.to_vec(), + failed, + }; + let dhcp = Migration::ForceDhcpPools; + let cert = Migration::RemoveServerCert; + let offload = Migration::EnableFlowOffloading; + assert_eq!(progress(&[], None).summary(true), None); + assert_eq!( + progress(&[cert], None).summary(true), + Some(format!( + "Updated settings for v{v} to remove the single HTTPS certificate earlier versions used" + )) + ); + assert_eq!( + progress(&[dhcp, cert, offload], None).summary(true), + Some(format!( + "Updated settings for v{v} to hand out addresses without first checking for another DHCP server, remove the single HTTPS certificate earlier versions used, and speed up forwarding of established connections" + )) + ); + assert_eq!( + progress(&[], Some(cert)).summary(false), + Some(format!( + "Couldn't update settings for v{v} to remove the single HTTPS certificate earlier versions used" + )) + ); + assert_eq!( + progress(&[], None).summary(false), + Some(format!("Couldn't update settings for v{v}")) + ); + assert_eq!( + progress(&[cert, offload], Some(Migration::ScopeReservedNames)).summary(false), + Some(format!( + "Updated settings for v{v} to remove the single HTTPS certificate earlier versions used and speed up forwarding of established connections, but couldn't serve each reserved device's name only within its own profile" + )) + ); + assert_eq!( + progress(&[cert], None).summary(false), + Some(format!( + "Updated settings for v{v} to remove the single HTTPS certificate earlier versions used, but couldn't finish" + )) + ); + } + const SHIPPED_SYSTEM: &str = "\ config system \toption hostname 'router' diff --git a/projects/start-wrt/backend/ctrl/src/peer.rs b/projects/start-wrt/backend/ctrl/src/peer.rs new file mode 100644 index 0000000000..d4a5bd2597 --- /dev/null +++ b/projects/start-wrt/backend/ctrl/src/peer.rs @@ -0,0 +1,176 @@ +//! Names the network a client reaches the router from, for the activity log. + +use std::net::IpAddr; + +use serde::Deserialize; +use uciedit::openwrt::NetworkInterface; +use uciedit::{Arena, Configs}; + +use crate::vpn_server::UciVpnServer; +use crate::wan::WAN_INTERFACE; +use crate::ServerContext; + +/// `192.168.0.23 (Admin profile)`, or the bare address when its network is +/// unknown. +pub async fn describe(ip: IpAddr) -> String { + let ip = ip.to_canonical(); + match network_of(ip).await { + Some(network) => format!("{ip} ({network})"), + None => ip.to_string(), + } +} + +async fn network_of(ip: IpAddr) -> Option { + let device = route_device(ip).await?; + let bytes = uciedit::read_all("/etc/config", &["network", "startwrt"]) + .await + .ok()?; + let arena = Arena::new(); + network_label(&bytes.parse(&arena).ok()?, &device) +} + +/// The interface the router answers the address through. +async fn route_device(ip: IpAddr) -> Option { + let output = tokio::process::Command::new("ip") + .args(["-j", "route", "get", &ip.to_string()]) + .output() + .await + .ok()?; + if !output.status.success() { + return None; + } + parse_route_device(&output.stdout) +} + +fn parse_route_device(json: &[u8]) -> Option { + #[derive(Deserialize)] + struct Route { + dev: String, + } + serde_json::from_slice::>(json) + .ok()? + .into_iter() + .next() + .map(|route| route.dev) +} + +fn network_label(cfgs: &Configs, device: &str) -> Option { + if device == "lo" { + return Some("this router".into()); + } + let interface_device = |section: &str| { + cfgs["network"] + .sections + .iter() + .find(|s| s.name().as_deref() == Some(section))? + .get::() + .ok() + .map(|iface| iface.device) + }; + let profiles = crate::profiles::list_config(ServerContext::default(), cfgs).ok()?; + let profile_name = |interface: &str| { + profiles + .iter() + .find(|p| p.interface == interface) + .map(|p| p.fullname.clone()) + }; + if let Some(profile) = profiles + .iter() + .find(|p| interface_device(&p.interface).as_deref() == Some(device)) + { + return Some(format!("{} profile", profile.fullname)); + } + // netifd names a WireGuard device after its interface section. + if let Some(name) = cfgs["startwrt"] + .sections + .iter() + .filter_map(|s| s.get::().ok()) + .find(|server| server.interface == device) + .and_then(|server| profile_name(&server.profile_interface)) + { + return Some(format!("{name} profile, VPN")); + } + if device == format!("pppoe-{WAN_INTERFACE}") + || interface_device(WAN_INTERFACE).as_deref() == Some(device) + { + return Some("WAN".into()); + } + None +} + +#[cfg(test)] +mod tests { + use uciedit::parse_all; + + use super::*; + + const NETWORK: &str = "\ +config interface 'lan' +\toption device 'br-lan' +\toption proto 'static' +\toption ipaddr '192.168.0.1' +\toption netmask '255.255.255.0' + +config interface 'iot' +\toption device 'br-lan.20' +\toption proto 'static' +\toption ipaddr '192.168.20.1' +\toption netmask '255.255.255.0' + +config interface 'wg_lan' +\toption proto 'wireguard' + +config interface 'wan' +\toption device 'eth0' +\toption proto 'dhcp' +"; + + const STARTWRT: &str = "\ +config profile +\toption fullname 'Admin' +\toption interface 'lan' +\toption vlan_tag '1' + +config profile +\toption fullname 'IoT' +\toption interface 'iot' +\toption vlan_tag '20' + +config vpn_server +\toption interface 'wg_lan' +\toption profile_interface 'lan' +\toption label 'Home' +\toption listen_port '51820' +\toption endpoint 'vpn.example.com' +"; + + #[tokio::test] + async fn names_the_network_behind_each_device() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("network"), NETWORK).unwrap(); + std::fs::write(dir.path().join("startwrt"), STARTWRT).unwrap(); + let arena = Arena::new(); + let cfgs = parse_all(dir.path(), &arena, &["network", "startwrt"]) + .await + .unwrap(); + for (device, label) in [ + ("br-lan", Some("Admin profile")), + ("br-lan.20", Some("IoT profile")), + ("wg_lan", Some("Admin profile, VPN")), + ("eth0", Some("WAN")), + ("pppoe-wan", Some("WAN")), + ("lo", Some("this router")), + ("wg_out", None), + ] { + assert_eq!(network_label(&cfgs, device).as_deref(), label, "{device}"); + } + } + + #[test] + fn reads_the_device_from_a_route_lookup() { + let json = br#"[{"dst":"192.168.20.7","dev":"br-lan.20","prefsrc":"192.168.20.1","flags":[],"uid":0,"cache":[]}]"#; + assert_eq!(parse_route_device(json).as_deref(), Some("br-lan.20")); + assert_eq!(parse_route_device(b"[]"), None); + assert_eq!(parse_route_device(b"not json"), None); + } +} diff --git a/projects/start-wrt/backend/ctrl/src/published_ports.rs b/projects/start-wrt/backend/ctrl/src/published_ports.rs index 027b93ebbb..ea1acfe1d8 100644 --- a/projects/start-wrt/backend/ctrl/src/published_ports.rs +++ b/projects/start-wrt/backend/ctrl/src/published_ports.rs @@ -2708,6 +2708,7 @@ config rule 'pp_a_v6' profile_network: None, allow_auto_port_forward: false, allow_dns_injection: false, + dns_injection_requested: false, allow_router_advertisements: false, security_profile: None, speed: None, diff --git a/projects/start-wrt/backend/ctrl/src/ssh_sessions.rs b/projects/start-wrt/backend/ctrl/src/ssh_sessions.rs new file mode 100644 index 0000000000..3a9112b1c7 --- /dev/null +++ b/projects/start-wrt/backend/ctrl/src/ssh_sessions.rs @@ -0,0 +1,378 @@ +//! Brackets SSH sessions in the activity log: an `auth.ssh` entry when a +//! dropbear session authenticates and another when it ends. + +use std::collections::HashMap; +use std::net::IpAddr; +use std::process::Stdio; +use std::time::{Duration, Instant}; + +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::process::Command; + +const AUTHORIZED_KEYS: &str = "/etc/dropbear/authorized_keys"; +/// Open sessions tracked at once; the oldest is forgotten first. +const MAX_SESSIONS: usize = 64; +const RESTART_DELAY: Duration = Duration::from_secs(5); + +#[derive(Debug, PartialEq, Eq)] +enum Event { + Opened { + pid: u32, + user: String, + method: Method, + peer: IpAddr, + }, + Closed { + pid: u32, + user: String, + peer: IpAddr, + }, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Method { + Key { + algorithm: String, + /// `SHA256:` and unpadded base64, as dropbear prints it. + fingerprint: String, + }, + Password, +} + +/// Follows the system log for the daemon's lifetime. +pub async fn run() { + let mut sessions = Sessions::default(); + loop { + if let Err(e) = follow(&mut sessions).await { + tracing::warn!("SSH session tracking stopped: {e}"); + } + tokio::time::sleep(RESTART_DELAY).await; + } +} + +async fn follow(sessions: &mut Sessions) -> std::io::Result<()> { + let mut child = Command::new("logread") + .arg("-f") + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(true) + .spawn()?; + let stdout = child + .stdout + .take() + .ok_or_else(|| std::io::Error::other("logread has no stdout"))?; + let mut lines = BufReader::new(stdout).lines(); + while let Some(line) = lines.next_line().await? { + let Some(event) = + crate::logs::parse_logread_line(&line).and_then(|entry| parse_event(&entry.message)) + else { + continue; + }; + let summary = describe(sessions.observe(event, Instant::now())).await; + crate::activity::log("auth", "ssh", true, &summary, None); + } + Ok(()) +} + +/// What an entry reports. +#[derive(Debug, PartialEq, Eq)] +enum Report { + Opened { + user: String, + method: Method, + peer: IpAddr, + }, + Closed { + user: String, + peer: IpAddr, + /// Unknown for a session opened before the daemon started. + lasted: Option, + }, +} + +/// Open sessions by dropbear process. +#[derive(Default)] +struct Sessions(HashMap); + +impl Sessions { + fn observe(&mut self, event: Event, now: Instant) -> Report { + match event { + Event::Opened { + pid, + user, + method, + peer, + } => { + if self.0.len() >= MAX_SESSIONS && !self.0.contains_key(&pid) { + if let Some(oldest) = self.0.iter().min_by_key(|(_, opened)| **opened) { + let oldest = *oldest.0; + self.0.remove(&oldest); + } + } + self.0.insert(pid, now); + Report::Opened { user, method, peer } + } + Event::Closed { pid, user, peer } => Report::Closed { + user, + peer, + lasted: self.0.remove(&pid).map(|opened| now - opened), + }, + } + } +} + +async fn describe(report: Report) -> String { + match report { + Report::Opened { user, method, peer } => { + let credential = match method { + Method::Password => "a password".to_string(), + Method::Key { + algorithm, + fingerprint, + } => { + let keys = tokio::fs::read_to_string(AUTHORIZED_KEYS) + .await + .unwrap_or_default(); + match key_name(&keys, &fingerprint) { + Some(name) => format!("key '{name}'"), + None => format!("{algorithm} key {fingerprint}"), + } + } + }; + format!( + "SSH session opened for {user} from {} with {credential}", + crate::peer::describe(peer).await + ) + } + Report::Closed { user, peer, lasted } => { + let mut summary = format!( + "SSH session closed for {user} from {}", + crate::peer::describe(peer).await + ); + if let Some(lasted) = lasted { + summary.push_str(" after "); + summary.push_str(&format_duration(lasted)); + } + summary + } + } +} + +/// The comment on the authorized key with this fingerprint. +fn key_name(authorized_keys: &str, fingerprint: &str) -> Option { + authorized_keys + .lines() + .filter_map(|line| line.trim().parse::().ok()) + .find(|key| format!("SHA256:{}", key.fingerprint()) == fingerprint) + .and_then(|key| key.comment) + .filter(|comment| !comment.is_empty()) +} + +fn format_duration(d: Duration) -> String { + let secs = d.as_secs(); + let (h, m, s) = (secs / 3600, secs / 60 % 60, secs % 60); + match (h, m) { + (0, 0) => format!("{s}s"), + (0, _) => format!("{m}m {s}s"), + _ => format!("{h}h {m}m"), + } +} + +/// Reads a dropbear session's authentication or exit from a log message. +fn parse_event(message: &str) -> Option { + let (_, rest) = message.split_once("dropbear[")?; + let (pid, text) = rest.split_once("]: ")?; + let pid = pid.parse().ok()?; + + if let Some(rest) = text.strip_prefix("Pubkey auth succeeded for '") { + if text.ends_with(", extra auth required") { + return None; + } + let (user, rest) = rest.split_once("' with ")?; + let (algorithm, rest) = rest.split_once(" key ")?; + let (fingerprint, addr) = rest.split_once(" from ")?; + return Some(Event::Opened { + pid, + user: user.to_string(), + method: Method::Key { + algorithm: algorithm.to_string(), + fingerprint: fingerprint.to_string(), + }, + peer: parse_peer(addr)?, + }); + } + if let Some(rest) = text.strip_prefix("Password auth succeeded for '") { + if text.ends_with(", extra auth required") { + return None; + } + let (user, addr) = rest.split_once("' from ")?; + return Some(Event::Opened { + pid, + user: user.to_string(), + method: Method::Password, + peer: parse_peer(addr)?, + }); + } + if let Some(rest) = text.strip_prefix("Exit (") { + let (user, rest) = rest.split_once(") from <")?; + let (addr, _) = rest.split_once(">")?; + return Some(Event::Closed { + pid, + user: user.to_string(), + peer: parse_peer(addr)?, + }); + } + None +} + +/// `host:port`, the host unbracketed even when IPv6. +fn parse_peer(addr: &str) -> Option { + let (host, _port) = addr.trim().rsplit_once(':')?; + host.parse::().ok().map(|ip| ip.to_canonical()) +} + +#[cfg(test)] +mod tests { + use super::*; + + const KEY: &str = + "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl laptop"; + + fn key_fingerprint() -> String { + format!( + "SHA256:{}", + KEY.parse::() + .unwrap() + .fingerprint() + ) + } + + #[test] + fn reads_dropbear_session_lines() { + let fp = key_fingerprint(); + assert_eq!( + parse_event(&format!( + "authpriv.notice dropbear[4242]: Pubkey auth succeeded for 'root' with ssh-ed25519 key {fp} from 192.168.0.23:51234" + )), + Some(Event::Opened { + pid: 4242, + user: "root".into(), + method: Method::Key { + algorithm: "ssh-ed25519".into(), + fingerprint: fp.clone(), + }, + peer: "192.168.0.23".parse().unwrap(), + }) + ); + assert_eq!( + parse_event( + "authpriv.notice dropbear[7]: Password auth succeeded for 'root' from fd00::5:40000" + ), + Some(Event::Opened { + pid: 7, + user: "root".into(), + method: Method::Password, + peer: "fd00::5".parse().unwrap(), + }) + ); + assert_eq!( + parse_event( + "authpriv.info dropbear[4242]: Exit (root) from <::ffff:192.168.0.23:51234>: Disconnect received" + ), + Some(Event::Closed { + pid: 4242, + user: "root".into(), + peer: "192.168.0.23".parse().unwrap(), + }) + ); + for ignored in [ + "authpriv.info dropbear[9]: Child connection from 192.168.0.23:51234", + "authpriv.info dropbear[9]: Exit before auth from <192.168.0.23:51234>: Exited normally", + "authpriv.warn dropbear[9]: Bad password attempt for 'root' from 192.168.0.23:51234", + "authpriv.notice dropbear[9]: Password auth succeeded for 'root' from 192.168.0.23:51234, extra auth required", + "daemon.info startwrt-ctrld[1]: startwrt-activity [auth.ssh] OK SSH session opened for root", + ] { + assert_eq!(parse_event(ignored), None, "{ignored}"); + } + } + + #[test] + fn a_session_closes_with_how_long_it_lasted() { + let mut sessions = Sessions::default(); + let peer: IpAddr = "192.168.0.23".parse().unwrap(); + let start = Instant::now(); + let opened = sessions.observe( + Event::Opened { + pid: 1, + user: "root".into(), + method: Method::Password, + peer, + }, + start, + ); + assert!(matches!(opened, Report::Opened { .. })); + let closed = |sessions: &mut Sessions, pid| { + sessions.observe( + Event::Closed { + pid, + user: "root".into(), + peer, + }, + start + Duration::from_secs(725), + ) + }; + assert_eq!( + closed(&mut sessions, 1), + Report::Closed { + user: "root".into(), + peer, + lasted: Some(Duration::from_secs(725)), + } + ); + assert_eq!( + closed(&mut sessions, 1), + Report::Closed { + user: "root".into(), + peer, + lasted: None, + }, + "opened before the daemon started" + ); + } + + #[test] + fn tracking_stays_bounded() { + let mut sessions = Sessions::default(); + let start = Instant::now(); + for pid in 0..=MAX_SESSIONS as u32 { + sessions.observe( + Event::Opened { + pid, + user: "root".into(), + method: Method::Password, + peer: "192.168.0.23".parse().unwrap(), + }, + start + Duration::from_secs(pid.into()), + ); + } + assert_eq!(sessions.0.len(), MAX_SESSIONS); + assert!(!sessions.0.contains_key(&0)); + } + + #[test] + fn keys_are_named_by_their_comment() { + let fp = key_fingerprint(); + let keys = format!("# managed\n\nnot a key\n{KEY}\n"); + assert_eq!(key_name(&keys, &fp).as_deref(), Some("laptop")); + assert_eq!(key_name(&keys, "SHA256:other"), None); + let uncommented = KEY.rsplit_once(' ').unwrap().0; + assert_eq!(key_name(uncommented, &fp), None); + } + + #[test] + fn durations_read_at_a_glance() { + assert_eq!(format_duration(Duration::from_secs(45)), "45s"); + assert_eq!(format_duration(Duration::from_secs(725)), "12m 5s"); + assert_eq!(format_duration(Duration::from_secs(7500)), "2h 5m"); + } +} diff --git a/projects/start-wrt/backend/ctrl/src/system.rs b/projects/start-wrt/backend/ctrl/src/system.rs index dd3a595da0..624b85a1a6 100644 --- a/projects/start-wrt/backend/ctrl/src/system.rs +++ b/projects/start-wrt/backend/ctrl/src/system.rs @@ -782,12 +782,14 @@ async fn factory_reset(_ctx: ServerContext) -> Result<(), Error> { async fn restart(_ctx: ServerContext) -> Result<(), Error> { crate::activity::log("system", "restart", true, "System restart initiated", None); + crate::boot::record_reboot(crate::boot::RunState::Restarting); tokio::spawn(async { tokio::time::sleep(std::time::Duration::from_secs(1)).await; if let Err(e) = tokio::process::Command::new("reboot") .invoke(ErrorKind::Filesystem.into()) .await { + crate::boot::record_running(); tracing::error!("failed to reboot: {e}"); } }); diff --git a/projects/start-wrt/backend/ctrl/src/update.rs b/projects/start-wrt/backend/ctrl/src/update.rs index ff6571e0e4..1471cbc2cf 100644 --- a/projects/start-wrt/backend/ctrl/src/update.rs +++ b/projects/start-wrt/backend/ctrl/src/update.rs @@ -215,6 +215,12 @@ fn clear_pending_marker() { let _ = std::fs::remove_file(PENDING_UPDATE_MARKER); } +/// Whether this boot follows an update [`check_pending_update_marker`] has +/// yet to confirm. +pub fn update_pending() -> bool { + Path::new(PENDING_UPDATE_MARKER).exists() +} + /// Logs a pending update's boot outcome in Activity during daemon startup. pub fn check_pending_update_marker() { let target = match std::fs::read_to_string(PENDING_UPDATE_MARKER) { diff --git a/projects/start-wrt/changelog/minor-added-activity-log-detail.md b/projects/start-wrt/changelog/minor-added-activity-log-detail.md new file mode 100644 index 0000000000..6d07ef514d --- /dev/null +++ b/projects/start-wrt/changelog/minor-added-activity-log-detail.md @@ -0,0 +1,7 @@ +--- +release-notes: false +--- + +- The Activity log records each time the router starts, with its version and, when known, why it restarted; the settings changes an update made; and every SSH session, with its source address, key, and duration. +- Sign-ins in the Activity log show the address and profile they came from and whether they came from a browser or another client, and a renamed device's entry names its old name. +- A device's page notes when the device is trying to publish DNS records without permission, and the system log reports each refused source once instead of on every retry. diff --git a/projects/start-wrt/docs/src/devices.md b/projects/start-wrt/docs/src/devices.md index b8ba2db64c..9f66fa876a 100644 --- a/projects/start-wrt/docs/src/devices.md +++ b/projects/start-wrt/docs/src/devices.md @@ -29,7 +29,7 @@ Click a device name to open its detail page: - **Allow automatic port forwarding** — Under **Permissions**. Off by default. Toggle on to let this device open and renew its own port forwards using the standard UPnP and PCP protocols. Used by StartOS servers (which configure themselves automatically), game consoles, and similar devices. See [Automatic port forwarding](published-ports.md#automatic-port-forwarding). -- **Allow DNS record publishing** — Off by default. Toggle on to let this device publish DNS names into the router — any name outside `.lan`, pointing at any address — so every device on your network can resolve them. Any device that speaks RFC 2136 over TCP (`nsupdate -v`, for example) can publish; a StartOS server does it automatically for its **private domains**. A name is served only to networks whose Security Profile can reach that device. Enabling asks for confirmation; grant it only to a device you trust. Published names appear in a read-only table below the toggle. The device renews or withdraws its own records, a record lapses when the device loses the address it published from, and turning the toggle off removes them immediately. For an [Inbound VPN](inbound-vpn.md#allowing-dns-record-publishing) client, grant the same permission from its VPN's client list. +- **Allow DNS record publishing** — Off by default. Toggle on to let this device publish DNS names into the router — any name outside `.lan`, pointing at any address — so every device on your network can resolve them. Any device that speaks RFC 2136 over TCP (`nsupdate -v`, for example) can publish; a StartOS server does it automatically for its **private domains**. A name is served only to networks whose Security Profile can reach that device. Enabling asks for confirmation; grant it only to a device you trust. While this is off, a note beside the toggle shows when the device has recently tried to publish. Published names appear in a read-only table below the toggle. The device renews or withdraws its own records, a record lapses when the device loses the address it published from, and turning the toggle off removes them immediately. For an [Inbound VPN](inbound-vpn.md#allowing-dns-record-publishing) client, grant the same permission from its VPN's client list. Names ending in `.lan` cannot be published; that zone is the router's own. Enable this toggle **before** adding the private domain on the server: while publishing is refused, other devices may cache a "no such domain" answer for a while. See [Private Domains](/start-os/private-domains.html) in the StartOS book for choosing a domain and clearing a cached miss. diff --git a/projects/start-wrt/docs/src/settings.md b/projects/start-wrt/docs/src/settings.md index a5f2423095..7d8dd7cf49 100644 --- a/projects/start-wrt/docs/src/settings.md +++ b/projects/start-wrt/docs/src/settings.md @@ -67,7 +67,7 @@ Manage the public keys authorized to access your router's command line over SSH. ## Activity -View a log of administrative actions taken through the web interface. Each entry shows: +View a log of administrative actions taken through the web interface, along with sign-ins, SSH sessions, and each time the router starts. Each entry shows: - **Status icon** — Green check for successful actions, red X for failures. - **Timestamp** — When the action occurred. diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts index 3077aa080d..aa6721bf51 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/de.ts @@ -579,4 +579,5 @@ export default { 615: 'Mit diesem Profil gelöschte veröffentlichte Ports: {list}.', 616: 'Außerhalb des Subnetzes des Profils dieses Geräts', 617: 'Keine nutzbare Host-Adresse', + 618: 'Dieses Gerät versucht, DNS-Einträge zu veröffentlichen. Erlauben Sie das Veröffentlichen von DNS-Einträgen, damit sie in Ihrem Netzwerk aufgelöst werden.', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts index 4dc59a41be..990b1732b4 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/en.ts @@ -584,4 +584,5 @@ export const ENGLISH: Record = { 'Published ports deleted with this profile: {list}.': 615, "Outside the subnet of this device's profile": 616, 'Not a usable host address': 617, + 'This device is trying to publish DNS records. Allow DNS record publishing for them to resolve on your network.': 618, } diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts index eda45ed778..1ed404e3b2 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/es.ts @@ -579,4 +579,5 @@ export default { 615: 'Puertos publicados que se eliminan con este perfil: {list}.', 616: 'Fuera de la subred del perfil de este dispositivo', 617: 'No es una dirección de host utilizable', + 618: 'Este dispositivo intenta publicar registros DNS. Permita la publicación de registros DNS para que se resuelvan en su red.', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts index b5aa2882f9..f8d6023442 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/fr.ts @@ -579,4 +579,5 @@ export default { 615: 'Ports publiés supprimés avec ce profil : {list}.', 616: 'En dehors du sous-réseau du profil de cet appareil', 617: "Pas une adresse d'hôte utilisable", + 618: 'Cet appareil tente de publier des enregistrements DNS. Autorisez la publication d’enregistrements DNS pour qu’ils soient résolus sur votre réseau.', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts b/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts index 444b5af153..28d5a99328 100644 --- a/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts +++ b/projects/start-wrt/web/src/app/i18n/dictionaries/pl.ts @@ -579,4 +579,5 @@ export default { 615: 'Opublikowane porty usuwane wraz z tym profilem: {list}.', 616: 'Poza podsiecią profilu tego urządzenia', 617: 'To nie jest użyteczny adres hosta', + 618: 'To urządzenie próbuje opublikować rekordy DNS. Zezwól na publikowanie rekordów DNS, aby były rozpoznawane w Twojej sieci.', } satisfies i18n diff --git a/projects/start-wrt/web/src/app/routes/devices/routes/device/index.ts b/projects/start-wrt/web/src/app/routes/devices/routes/device/index.ts index 1b98561b27..1aaab35a00 100644 --- a/projects/start-wrt/web/src/app/routes/devices/routes/device/index.ts +++ b/projects/start-wrt/web/src/app/routes/devices/routes/device/index.ts @@ -14,6 +14,7 @@ import { TuiHintDirective, TuiInput, TuiLink, + TuiNotification, TuiTitle, } from '@taiga-ui/core' import { provideTranslatedValidationErrors } from 'src/app/i18n/validation-errors' @@ -167,6 +168,14 @@ import { i18nKey } from 'src/app/i18n/i18n.providers' /> {{ 'Allow DNS record publishing' | i18n }} + @if (data()?.dnsInjectionRequested) { +
+ {{ + 'This device is trying to publish DNS records. Allow DNS record publishing for them to resolve on your network.' + | i18n + }} +
+ }