fix(core): close auth bypass, hangs and memory leaks found by review

Security:
- An empty API_PASSWORD passed validation (only the literal "changeme" was
  rejected) and verify_password("", "") returned true, so a login with an
  empty password minted an admin token. Require >= 16 characters and >= 32
  non-whitespace bytes for JWT_SECRET; verify rejects an empty stored secret.
- syn_challenge_enabled required a real challenge_secret_hex: the public
  placeholder from config.h is now rejected in every spelling.
- docker-compose: Redis/ClickHouse/Grafana are loopback-only and every
  password uses ${VAR:?} instead of a default. An exposed Redis was a way to
  lift bans and publish unbans to the whole fleet with one redis-cli.
- Empty CORS_ORIGIN no longer means "allow any origin".
- ban_cidr / userspace blacklist validate and mask prefixes; CIDR bans are
  stored as ranges, so a /24 or /64 ban actually covers the subnet (before,
  only the network address was blocked).

Availability:
- ClickHouse client has connect/request timeouts and no mutex held across
  await: a hung analytics backend can no longer freeze the ban path. Events
  go through a bounded buffer with a drop counter.
- Redis uses a ConnectionManager with per-command timeouts; pubsub and
  reconcile reset the backoff after success; publish cannot block shutdown.
- Ban durations from pubsub are clamped and use checked_add; the sync task
  survives panics instead of silently dying.
- Blacklist TOCTOU (remove_if) and replace_redis no longer empties the table
  during a Redis reconnect.
- RateLimiter and reputation have hard caps with incremental eviction instead
  of an unbounded DashMap and a stop-the-world retain.
- The attack detector scores before updating its baseline and needs several
  quiet windows to leave UnderAttack, so a sustained flood keeps banning new
  offenders instead of ending after one tick.
- accept() backs off on EMFILE/ENFILE, shutdown Err is treated as shutdown,
  a global semaphore bounds in-flight connections, rate limiting runs before
  PoW, whitelisted IPs are never banned, and connect/handshake/relay have
  timeouts with an idle budget.
- PoW uses the configured difficulty as a floor, the clamp is enforced, and
  nonce framing survives split segments and coalesced handshake bytes.
- Subnet tracker memory is capped (prefixes and per-prefix sources) and the
  monitor bans with the configured TTL.

CI and docs:
- CI runs the test suite with --no-default-features --features protocol-http;
  make ebpf fails on errors; the secrets gate catches weak compose defaults.
- doctor skips protected endpoints without a token and exits non-zero on
  failure; a drain timeout returns exit code 1.
- TODO §2b records the review findings, what is fixed and what is deferred;
  configuration/testing docs describe the new XDP and secret semantics.
This commit is contained in:
Loki 2026-11-16 12:06:23 +01:00
parent 14dcaccdbf
commit c1a076a4a3
Signed by: boba
GPG key ID: 6CDE87BC9A778D97
57 changed files with 4193 additions and 1171 deletions

135
src/manager/security.rs Normal file
View file

@ -0,0 +1,135 @@
//! Startup security policy of the management plane.
//!
//! Weak credentials turn the control plane API into an authentication bypass:
//! an empty `API_PASSWORD` matches an empty login, and a guessable
//! `JWT_SECRET` lets anyone mint admin tokens. The manager validates both
//! before it binds a socket, and derives its CORS policy from an explicit
//! `CORS_ORIGIN` value instead of silently allowing every origin.
use anyhow::{Result, bail};
use subtle::ConstantTimeEq;
use tower_http::cors::{AllowOrigin, Any, CorsLayer};
/// Minimum length of `API_PASSWORD` in characters.
const MIN_API_PASSWORD_CHARS: usize = 16;
/// Minimum number of non-whitespace bytes in `JWT_SECRET`.
const MIN_JWT_SECRET_BYTES: usize = 32;
/// Placeholder password shipped in documentation and examples.
const DEFAULT_API_PASSWORD: &str = "changeme";
/// Validates `API_PASSWORD` before the manager starts serving.
///
/// # Errors
/// Rejects an empty or whitespace-only password, a password shorter than
/// `MIN_API_PASSWORD_CHARS` characters, and the `changeme` placeholder.
pub fn validate_api_password(password: &str) -> Result<()> {
let trimmed = password.trim();
if trimmed.is_empty() {
bail!("API_PASSWORD must not be empty: an empty password would accept an empty login");
}
if trimmed.chars().count() < MIN_API_PASSWORD_CHARS {
bail!("API_PASSWORD must be at least {MIN_API_PASSWORD_CHARS} characters long");
}
if trimmed.eq_ignore_ascii_case(DEFAULT_API_PASSWORD) {
bail!("API_PASSWORD must not be the default placeholder '{DEFAULT_API_PASSWORD}'");
}
Ok(())
}
/// Validates `JWT_SECRET` before the manager starts serving.
///
/// # Errors
/// Rejects a secret with fewer than `MIN_JWT_SECRET_BYTES` non-whitespace
/// bytes, which includes empty and all-whitespace secrets.
pub fn validate_jwt_secret(secret: &str) -> Result<()> {
let significant = secret.bytes().filter(|byte| !byte.is_ascii_whitespace()).count();
if significant < MIN_JWT_SECRET_BYTES {
bail!("JWT_SECRET must contain at least {MIN_JWT_SECRET_BYTES} non-whitespace bytes, got {significant}");
}
Ok(())
}
/// Compares a login password with the configured one in constant time.
///
/// An empty stored password never verifies: that is the authentication bypass
/// the startup policy ([`validate_api_password`]) rules out, and the handler
/// keeps the same guarantee for any state built by other code paths.
#[must_use]
pub fn verify_password(provided: &str, expected: &str) -> bool {
if expected.is_empty() {
return false;
}
let provided = provided.as_bytes();
let expected = expected.as_bytes();
let len_match = (provided.len() as u64).ct_eq(&(expected.len() as u64));
let min_len = provided.len().min(expected.len());
let bytes_match = provided[..min_len].ct_eq(&expected[..min_len]);
bool::from(len_match & bytes_match)
}
/// Cross-origin resource sharing policy derived from `CORS_ORIGIN`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CorsPolicy {
/// No cross-origin layer at all: browsers on other origins are denied.
Deny,
/// Every origin is allowed; requires an explicit `CORS_ORIGIN=*`.
Any,
/// Only the listed origins are allowed.
AllowList(Vec<String>),
}
impl CorsPolicy {
/// Parses the raw `CORS_ORIGIN` value.
///
/// An unset or empty variable denies cross-origin access, `*` must be set
/// explicitly to allow any origin, and anything else is a comma-separated
/// list of origins.
///
/// # Errors
/// Fails on an empty entry, on a wildcard mixed with concrete origins, and
/// on an entry that is not a valid HTTP header value.
pub fn parse(raw: Option<&str>) -> Result<Self> {
let Some(raw) = raw else {
return Ok(Self::Deny);
};
let raw = raw.trim();
if raw.is_empty() {
return Ok(Self::Deny);
}
if raw == "*" {
return Ok(Self::Any);
}
let mut origins = Vec::new();
for entry in raw.split(',') {
let origin = entry.trim();
if origin.is_empty() {
bail!("CORS_ORIGIN contains an empty origin entry");
}
if origin == "*" {
bail!("CORS_ORIGIN wildcard '*' must be used alone, not inside an origin list");
}
axum::http::HeaderValue::from_str(origin)
.map_err(|_| anyhow::anyhow!("CORS_ORIGIN entry '{origin}' is not a valid HTTP header value"))?;
origins.push(origin.to_owned());
}
Ok(Self::AllowList(origins))
}
/// Builds the axum CORS layer for this policy.
///
/// Returns `None` for [`CorsPolicy::Deny`] so the router is served without
/// any cross-origin layer.
#[must_use]
pub fn cors_layer(&self) -> Option<CorsLayer> {
match self {
Self::Deny => None,
Self::Any => Some(CorsLayer::new().allow_origin(Any)),
Self::AllowList(origins) => {
let allowed = origins
.iter()
.filter_map(|origin| axum::http::HeaderValue::from_str(origin).ok());
Some(CorsLayer::new().allow_origin(AllowOrigin::list(allowed)))
},
}
}
}