[edge] Share fixes: per-network password limit and no eviction, revocation epoch never goes down, stray share tokens stripped on every host, admin socket bound in a private directory
This commit is contained in:
@@ -269,9 +269,21 @@ fn bind(path: &Path) -> std::io::Result<tokio::net::UnixListener> {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let l = tokio::net::UnixListener::bind(path)?;
|
// Bind inside a fresh 0700 directory, set the mode, then move the socket into place, so
|
||||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660))?;
|
// there is no moment in which the socket exists with the process umask's permissions.
|
||||||
Ok(l)
|
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]
|
#[async_trait]
|
||||||
|
|||||||
@@ -138,7 +138,9 @@ impl ProxyHttp for EdgeProxy {
|
|||||||
ctx.host = Some(host.clone());
|
ctx.host = Some(host.clone());
|
||||||
|
|
||||||
let mut shared_access = false;
|
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 ip = client_ip(session);
|
||||||
let revs = self.shared.revocations();
|
let revs = self.shared.revocations();
|
||||||
match share::handle(
|
match share::handle(
|
||||||
|
|||||||
+76
-24
@@ -40,47 +40,85 @@ use crate::pages::{self, Page};
|
|||||||
use crate::shared::RevocationState;
|
use crate::shared::RevocationState;
|
||||||
|
|
||||||
const WINDOW: Duration = Duration::from_secs(60);
|
const WINDOW: Duration = Duration::from_secs(60);
|
||||||
|
/// Wrong passwords a minute for one link from one network.
|
||||||
const MAX_FAILURES: u32 = 5;
|
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_ENTRIES: usize = 10_000;
|
||||||
const MAX_FORM: usize = 8 * 1024;
|
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)]
|
#[derive(Default)]
|
||||||
pub struct Throttle {
|
pub struct Throttle {
|
||||||
map: Mutex<HashMap<(ShareId, IpAddr), (Instant, u32)>>,
|
inner: Mutex<Counters>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Counters {
|
||||||
|
links: HashMap<(ShareId, IpAddr), Window>,
|
||||||
|
networks: HashMap<IpAddr, Window>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn live(w: &Window) -> bool {
|
||||||
|
w.0.elapsed() < WINDOW
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count<K: std::hash::Hash + Eq>(m: &mut HashMap<K, Window>, 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 {
|
impl Throttle {
|
||||||
fn key(id: ShareId, ip: Option<IpAddr>) -> (ShareId, IpAddr) {
|
fn net(ip: Option<IpAddr>) -> IpAddr {
|
||||||
let ip = ip.map_or(IpAddr::from([0, 0, 0, 0]), truncate_ip);
|
ip.map_or(IpAddr::from([0, 0, 0, 0]), truncate_ip)
|
||||||
(id, ip)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// True when this visitor may try a password for this link now.
|
/// True when this visitor may try a password for this link now.
|
||||||
pub fn allowed(&self, id: ShareId, ip: Option<IpAddr>) -> bool {
|
pub fn allowed(&self, id: ShareId, ip: Option<IpAddr>) -> bool {
|
||||||
let Ok(m) = self.map.lock() else { return false };
|
let Ok(mut c) = self.inner.lock() else {
|
||||||
match m.get(&Self::key(id, ip)) {
|
return false;
|
||||||
Some((start, n)) => start.elapsed() >= WINDOW || *n < MAX_FAILURES,
|
};
|
||||||
None => true,
|
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<IpAddr>) {
|
pub fn failed(&self, id: ShareId, ip: Option<IpAddr>) {
|
||||||
let Ok(mut m) = self.map.lock() else { return };
|
let Ok(mut c) = self.inner.lock() else { return };
|
||||||
if m.len() >= MAX_ENTRIES {
|
let net = Self::net(ip);
|
||||||
m.retain(|_, (start, _)| start.elapsed() < WINDOW);
|
count(&mut c.links, (id, net));
|
||||||
}
|
count(&mut c.networks, net);
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -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.
|
/// 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<()> {
|
fn strip_token(session: &mut Session, path: &str, rest: &str) -> Result<()> {
|
||||||
let uri = with_query(path, rest)
|
let uri = with_query(path, rest)
|
||||||
|
|||||||
@@ -102,6 +102,8 @@ pub struct Shared {
|
|||||||
pub paths: Paths,
|
pub paths: Paths,
|
||||||
credentials_dir: Option<PathBuf>,
|
credentials_dir: Option<PathBuf>,
|
||||||
revocations: ArcSwap<RevocationState>,
|
revocations: ArcSwap<RevocationState>,
|
||||||
|
/// 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,
|
pub throttle: crate::share::Throttle,
|
||||||
cert_states: Mutex<HashMap<String, CertState>>,
|
cert_states: Mutex<HashMap<String, CertState>>,
|
||||||
pub acme_wake: tokio::sync::Notify,
|
pub acme_wake: tokio::sync::Notify,
|
||||||
@@ -134,6 +136,7 @@ impl Shared {
|
|||||||
paths,
|
paths,
|
||||||
credentials_dir,
|
credentials_dir,
|
||||||
revocations: ArcSwap::from_pointee(RevocationState::default()),
|
revocations: ArcSwap::from_pointee(RevocationState::default()),
|
||||||
|
epoch_seen: std::sync::atomic::AtomicU32::new(0),
|
||||||
throttle: crate::share::Throttle::default(),
|
throttle: crate::share::Throttle::default(),
|
||||||
cert_states: Mutex::new(HashMap::new()),
|
cert_states: Mutex::new(HashMap::new()),
|
||||||
acme_wake: tokio::sync::Notify::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 fail = |message: String| {
|
||||||
let mut old = RevocationState::clone(&self.revocations());
|
let mut old = RevocationState::clone(&self.revocations());
|
||||||
old.error = Some(message.clone());
|
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));
|
self.revocations.store(Arc::new(old));
|
||||||
EdgeError::Config {
|
EdgeError::Config {
|
||||||
path: path.clone(),
|
path: path.clone(),
|
||||||
@@ -335,7 +344,9 @@ impl Shared {
|
|||||||
if meta.len() > 1 << 20 {
|
if meta.len() > 1 << 20 {
|
||||||
return Err(fail("the revocation file is larger than 1 MiB".into()));
|
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 =
|
let file: RevocationFile =
|
||||||
serde_json::from_str(&text).map_err(|e| fail(format!("not a revocation file: {e}")))?;
|
serde_json::from_str(&text).map_err(|e| fail(format!("not a revocation file: {e}")))?;
|
||||||
if file.deny.len() > MAX_DENY {
|
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()))?,
|
.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()));
|
let stamp = Some(runtime::sha256_hex(text.as_bytes()));
|
||||||
self.revocations.store(Arc::new(RevocationState {
|
self.revocations.store(Arc::new(RevocationState {
|
||||||
revocations: Revocations {
|
revocations: Revocations {
|
||||||
|
|||||||
@@ -309,6 +309,25 @@ mod unix {
|
|||||||
let t2 = link("closed.test", 7, "/", now() + 3600, None);
|
let t2 = link("closed.test", 7, "/", now() + 3600, None);
|
||||||
let r = e.get("closed.test", &format!("/?share={t2}"), None).await;
|
let r = e.get("closed.test", &format!("/?share={t2}"), None).await;
|
||||||
assert_eq!(r.status, 302);
|
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")]
|
#[tokio::test(flavor = "multi_thread")]
|
||||||
@@ -460,7 +479,11 @@ mod unix {
|
|||||||
.await;
|
.await;
|
||||||
assert_eq!(r.status, 422, "{}", r.text);
|
assert_eq!(r.status, 422, "{}", r.text);
|
||||||
assert!(r.text.contains("epoch"), "{}", 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);
|
assert_eq!(e.get(HOST, "/", Some(&fresh_cookie)).await.status, 200);
|
||||||
|
|
||||||
// Without the admin call, edge notices a changed file within 5 s.
|
// Without the admin call, edge notices a changed file within 5 s.
|
||||||
|
|||||||
@@ -32,7 +32,10 @@ fn junk_ids_from_the_same_network_cannot_flush_a_link_counter() {
|
|||||||
for n in 0u32..10_000 {
|
for n in 0u32..10_000 {
|
||||||
t.failed(junk(n), Some(ip));
|
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]
|
#[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]);
|
let other = IpAddr::from([10, (n >> 16) as u8, (n >> 8) as u8, n as u8]);
|
||||||
t.failed(junk(n), Some(other));
|
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]);
|
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"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user