[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)?;
|
||||
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]
|
||||
|
||||
@@ -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(
|
||||
|
||||
+76
-24
@@ -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<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 {
|
||||
fn key(id: ShareId, ip: Option<IpAddr>) -> (ShareId, IpAddr) {
|
||||
let ip = ip.map_or(IpAddr::from([0, 0, 0, 0]), truncate_ip);
|
||||
(id, ip)
|
||||
fn net(ip: Option<IpAddr>) -> 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<IpAddr>) -> 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<IpAddr>) {
|
||||
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)
|
||||
|
||||
@@ -102,6 +102,8 @@ pub struct Shared {
|
||||
pub paths: Paths,
|
||||
credentials_dir: Option<PathBuf>,
|
||||
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,
|
||||
cert_states: Mutex<HashMap<String, CertState>>,
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user