diff --git a/crates/edge/src/admin.rs b/crates/edge/src/admin.rs index 09fa478..9ffd085 100644 --- a/crates/edge/src/admin.rs +++ b/crates/edge/src/admin.rs @@ -269,9 +269,21 @@ fn bind(path: &Path) -> std::io::Result { )); } } - let l = tokio::net::UnixListener::bind(path)?; - std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660))?; - Ok(l) + // Bind inside a fresh 0700 directory, set the mode, then move the socket into place, so + // there is no moment in which the socket exists with the process umask's permissions. + use std::os::unix::fs::DirBuilderExt; + let parent = path.parent().unwrap_or(Path::new(".")); + let private = parent.join(format!(".ianitor-admin-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&private); + std::fs::DirBuilder::new().mode(0o700).create(&private)?; + let staged = private.join("admin.sock"); + let bound = tokio::net::UnixListener::bind(&staged).and_then(|l| { + std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o660))?; + std::fs::rename(&staged, path)?; + Ok(l) + }); + let _ = std::fs::remove_dir_all(&private); + bound } #[async_trait] diff --git a/crates/edge/src/proxy.rs b/crates/edge/src/proxy.rs index f8c365f..6b07927 100644 --- a/crates/edge/src/proxy.rs +++ b/crates/edge/src/proxy.rs @@ -138,7 +138,9 @@ impl ProxyHttp for EdgeProxy { ctx.host = Some(host.clone()); let mut shared_access = false; - if host.cfg.share_links { + if !host.cfg.share_links { + share::strip_any_token(session)?; + } else { let ip = client_ip(session); let revs = self.shared.revocations(); match share::handle( diff --git a/crates/edge/src/share.rs b/crates/edge/src/share.rs index 1785c54..60e984a 100644 --- a/crates/edge/src/share.rs +++ b/crates/edge/src/share.rs @@ -40,47 +40,85 @@ use crate::pages::{self, Page}; use crate::shared::RevocationState; const WINDOW: Duration = Duration::from_secs(60); +/// Wrong passwords a minute for one link from one network. const MAX_FAILURES: u32 = 5; +/// Wrong passwords a minute from one network, whatever the link: the link id a guess names +/// is unproven, so per-link counting alone could be dodged with made-up ids. +const MAX_NETWORK_FAILURES: u32 = 20; const MAX_ENTRIES: usize = 10_000; const MAX_FORM: usize = 8 * 1024; -/// Wrong-password counters per (link, visitor network). +type Window = (Instant, u32); + +/// Wrong-password counters per (link, visitor network) and per visitor network. Entries live +/// one minute. A full table refuses newcomers rather than forgetting anyone, so flooding it +/// can lock visitors out for a minute but never reset a counter. #[derive(Default)] pub struct Throttle { - map: Mutex>, + inner: Mutex, +} + +#[derive(Default)] +struct Counters { + links: HashMap<(ShareId, IpAddr), Window>, + networks: HashMap, +} + +fn live(w: &Window) -> bool { + w.0.elapsed() < WINDOW +} + +fn count(m: &mut HashMap, k: K) { + if m.len() >= MAX_ENTRIES && !m.contains_key(&k) { + m.retain(|_, w| live(w)); + if m.len() >= MAX_ENTRIES { + return; + } + } + let e = m.entry(k).or_insert((Instant::now(), 0)); + if !live(e) { + *e = (Instant::now(), 0); + } + e.1 = e.1.saturating_add(1); } impl Throttle { - fn key(id: ShareId, ip: Option) -> (ShareId, IpAddr) { - let ip = ip.map_or(IpAddr::from([0, 0, 0, 0]), truncate_ip); - (id, ip) + fn net(ip: Option) -> IpAddr { + ip.map_or(IpAddr::from([0, 0, 0, 0]), truncate_ip) } /// True when this visitor may try a password for this link now. pub fn allowed(&self, id: ShareId, ip: Option) -> bool { - let Ok(m) = self.map.lock() else { return false }; - match m.get(&Self::key(id, ip)) { - Some((start, n)) => start.elapsed() >= WINDOW || *n < MAX_FAILURES, - None => true, + let Ok(mut c) = self.inner.lock() else { + return false; + }; + let net = Self::net(ip); + let under = |w: Option<&Window>, max: u32| w.is_none_or(|w| !live(w) || w.1 < max); + if !under(c.networks.get(&net), MAX_NETWORK_FAILURES) + || !under(c.links.get(&(id, net)), MAX_FAILURES) + { + return false; } + // A full table that has no room for this visitor: refuse. + for full in [ + c.links.len() >= MAX_ENTRIES, + c.networks.len() >= MAX_ENTRIES, + ] { + if full { + c.links.retain(|_, w| live(w)); + c.networks.retain(|_, w| live(w)); + } + } + let room_links = c.links.len() < MAX_ENTRIES || c.links.contains_key(&(id, net)); + let room_nets = c.networks.len() < MAX_ENTRIES || c.networks.contains_key(&net); + room_links && room_nets } pub fn failed(&self, id: ShareId, ip: Option) { - let Ok(mut m) = self.map.lock() else { return }; - if m.len() >= MAX_ENTRIES { - m.retain(|_, (start, _)| start.elapsed() < WINDOW); - } - if m.len() >= MAX_ENTRIES { - // Full of live entries: forget the oldest rather than grow without bound. - if let Some(oldest) = m.iter().min_by_key(|(_, (s, _))| *s).map(|(k, _)| *k) { - m.remove(&oldest); - } - } - let e = m.entry(Self::key(id, ip)).or_insert((Instant::now(), 0)); - if e.0.elapsed() >= WINDOW { - *e = (Instant::now(), 0); - } - e.1 += 1; + let Ok(mut c) = self.inner.lock() else { return }; + let net = Self::net(ip); + count(&mut c.links, (id, net)); + count(&mut c.networks, net); } } @@ -169,6 +207,20 @@ fn with_query(path: &str, query: &str) -> String { } } +/// On a host without share links: drop any `share=ish1.…` token from the request target, so +/// neither the auth server (X-Forwarded-Uri) nor the upstream ever sees one. +pub fn strip_any_token(session: &mut Session) -> Result<()> { + let Some(query) = session.req_header().uri.query().map(str::to_owned) else { + return Ok(()); + }; + let (token, rest) = split_query(&query); + if token.is_some() { + let path = session.req_header().uri.path().to_owned(); + strip_token(session, &path, &rest)?; + } + Ok(()) +} + /// Drop the `share=` token from the request target, so the upstream never sees it. fn strip_token(session: &mut Session, path: &str, rest: &str) -> Result<()> { let uri = with_query(path, rest) diff --git a/crates/edge/src/shared.rs b/crates/edge/src/shared.rs index 50f8a21..b0d1db7 100644 --- a/crates/edge/src/shared.rs +++ b/crates/edge/src/shared.rs @@ -102,6 +102,8 @@ pub struct Shared { pub paths: Paths, credentials_dir: Option, revocations: ArcSwap, + /// The highest revocation epoch seen since start; a file with a lower one is refused. + epoch_seen: std::sync::atomic::AtomicU32, pub throttle: crate::share::Throttle, cert_states: Mutex>, pub acme_wake: tokio::sync::Notify, @@ -134,6 +136,7 @@ impl Shared { paths, credentials_dir, revocations: ArcSwap::from_pointee(RevocationState::default()), + epoch_seen: std::sync::atomic::AtomicU32::new(0), throttle: crate::share::Throttle::default(), cert_states: Mutex::new(HashMap::new()), acme_wake: tokio::sync::Notify::new(), @@ -323,9 +326,15 @@ impl Shared { }); } }; + let text = std::fs::read(path).ok(); + let sha = text.as_deref().map(runtime::sha256_hex); let fail = |message: String| { let mut old = RevocationState::clone(&self.revocations()); old.error = Some(message.clone()); + // Remember this content, so the poller reports it once, not every 5 s. + if old.loaded { + old.stamp = sha.clone(); + } self.revocations.store(Arc::new(old)); EdgeError::Config { path: path.clone(), @@ -335,7 +344,9 @@ impl Shared { if meta.len() > 1 << 20 { return Err(fail("the revocation file is larger than 1 MiB".into())); } - let text = std::fs::read_to_string(path).map_err(|e| fail(e.to_string()))?; + let text = text + .and_then(|b| String::from_utf8(b).ok()) + .ok_or_else(|| fail("cannot read the revocation file as text".into()))?; let file: RevocationFile = serde_json::from_str(&text).map_err(|e| fail(format!("not a revocation file: {e}")))?; if file.deny.len() > MAX_DENY { @@ -348,6 +359,15 @@ impl Shared { .ok_or_else(|| fail("a link id is not 32 hex digits".into()))?, ); } + // The epoch only goes up: a lower one would bring stopped links back. + let seen = self.epoch_seen.load(Ordering::SeqCst); + if file.epoch < seen { + return Err(fail(format!( + "the revocation epoch went down from {seen} to {}; keeping the old state", + file.epoch + ))); + } + self.epoch_seen.store(file.epoch, Ordering::SeqCst); let stamp = Some(runtime::sha256_hex(text.as_bytes())); self.revocations.store(Arc::new(RevocationState { revocations: Revocations { diff --git a/crates/edge/tests/share_links.rs b/crates/edge/tests/share_links.rs index e3f86d7..c0f5e2f 100644 --- a/crates/edge/tests/share_links.rs +++ b/crates/edge/tests/share_links.rs @@ -309,6 +309,25 @@ mod unix { let t2 = link("closed.test", 7, "/", now() + 3600, None); let r = e.get("closed.test", &format!("/?share={t2}"), None).await; assert_eq!(r.status, 302); + // ...and is not passed on to the auth server or the upstream either. + let r = e + .get( + "closed.test", + &format!("/x?b=2&share={t2}"), + Some("authelia_session=good"), + ) + .await; + assert_eq!(r.status, 200); + let body: serde_json::Value = serde_json::from_slice(&r.body).unwrap(); + assert_eq!(body["query"], "b=2"); + for req in e.auth.requests() { + for (_, v) in &req.headers { + assert!( + !String::from_utf8_lossy(v).contains("ish1."), + "token sent to the auth server" + ); + } + } } #[tokio::test(flavor = "multi_thread")] @@ -460,7 +479,11 @@ mod unix { .await; assert_eq!(r.status, 422, "{}", r.text); assert!(r.text.contains("epoch"), "{}", r.text); - assert_eq!(e.get(HOST, "/", Some(&keep_cookie)).await.status, 302, "still stopped"); + assert_eq!( + e.get(HOST, "/", Some(&keep_cookie)).await.status, + 302, + "still stopped" + ); assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200); // Without the admin call, edge notices a changed file within 5 s. diff --git a/crates/edge/tests/share_throttle.rs b/crates/edge/tests/share_throttle.rs index f078e86..0ca17da 100644 --- a/crates/edge/tests/share_throttle.rs +++ b/crates/edge/tests/share_throttle.rs @@ -32,7 +32,10 @@ fn junk_ids_from_the_same_network_cannot_flush_a_link_counter() { for n in 0u32..10_000 { t.failed(junk(n), Some(ip)); } - assert!(!t.allowed(victim, Some(ip)), "10,000 junk failures reset the victim's counter"); + assert!( + !t.allowed(victim, Some(ip)), + "10,000 junk failures reset the victim's counter" + ); } #[test] @@ -66,7 +69,13 @@ fn a_full_table_refuses_new_visitors_instead_of_forgetting_old_ones() { let other = IpAddr::from([10, (n >> 16) as u8, (n >> 8) as u8, n as u8]); t.failed(junk(n), Some(other)); } - assert!(!t.allowed(victim, Some(ip)), "the victim's counter survived"); + assert!( + !t.allowed(victim, Some(ip)), + "the victim's counter survived" + ); let newcomer = IpAddr::from([203, 0, 113, 5]); - assert!(!t.allowed(ShareId([3; 16]), Some(newcomer)), "full table: refuse, don't forget"); + assert!( + !t.allowed(ShareId([3; 16]), Some(newcomer)), + "full table: refuse, don't forget" + ); }