feat(api): require an admin token for configuration changes

Group CRUD decides what the scanner sweeps, yet any client that reached the
API could change it. Writes now need XEXEU_ADMIN_TOKEN (or a token generated
at startup and printed as a ?token= link, like sabia ui), compared in
constant time, and a browser Origin must match Host. The dashboard keeps the
token for the tab and asks for it on 401. Reads are unchanged.

Also track .env.example: '.env*' in .gitignore had kept it out of the
repository, although the README tells operators to copy it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-03 10:17:14 -03:00
1 parent 36eadabc7c
commit 90ece32dac
17 files changed
+369 -28

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ path = "src/main.rs"
xexeu-core = { path = "../xexeu-core" }
axum = "0.8"
chrono = { version = "0.4", features = ["clock"] }
clap = { version = "4", features = ["derive"] }
clap = { version = "4", features = ["derive", "env"] }
libc = "0.2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+168
View File
@@ -0,0 +1,168 @@
//! Admin token for the API routes that change state (group CRUD).
//!
//! Reads stay open, as before: the dashboard is meant to sit on loopback or
//! behind a reverse proxy. Writes decide what the scanner sweeps, so they need
//! the admin token in `Authorization: Bearer <token>` or `X-Xexeu-Token`, and a
//! browser `Origin`, when sent, must match `Host` (CSRF).
//!
//! The token comes from `--admin-token`/`XEXEU_ADMIN_TOKEN`; without one, a
//! random token is generated at startup and printed once, the same way
//! `sabia ui` hands out its session token.
use std::fs::File;
use std::io::Read;
use std::sync::Arc;
use axum::extract::{Request, State};
use axum::http::{header, HeaderMap, Method, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
/// Shortest token accepted from configuration; shorter ones are guessable.
pub const MIN_TOKEN_LEN: usize = 16;
#[derive(Clone)]
pub struct AdminToken(Arc<str>);
impl AdminToken {
pub fn new(token: &str) -> Self {
Self(Arc::from(token))
}
/// 32 random bytes from the kernel, hex-encoded.
pub fn generate() -> std::io::Result<Self> {
let mut bytes = [0u8; 32];
File::open("/dev/urandom")?.read_exact(&mut bytes)?;
let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
Ok(Self::new(&hex))
}
pub fn as_str(&self) -> &str {
&self.0
}
/// Constant-time comparison: the time taken does not reveal how many
/// leading characters of a guess were right.
pub fn matches(&self, candidate: &str) -> bool {
let expected = self.0.as_bytes();
let candidate = candidate.as_bytes();
let mut diff = expected.len() ^ candidate.len();
for (index, byte) in expected.iter().enumerate() {
diff |= usize::from(byte ^ candidate.get(index).copied().unwrap_or(0));
}
diff == 0
}
}
/// Token sent by the client, from `Authorization: Bearer` or `X-Xexeu-Token`.
fn presented_token(headers: &HeaderMap) -> Option<&str> {
if let Some(value) = headers.get("x-xexeu-token").and_then(|v| v.to_str().ok()) {
return Some(value.trim());
}
headers
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(str::trim)
}
/// `true` when there is no `Origin` (non-browser client) or its host matches `Host`.
fn same_origin(headers: &HeaderMap) -> bool {
let Some(origin) = headers.get(header::ORIGIN).and_then(|v| v.to_str().ok()) else {
return true;
};
let Some(host) = headers.get(header::HOST).and_then(|v| v.to_str().ok()) else {
return false;
};
let origin_host = origin
.split_once("://")
.map(|(_, rest)| rest)
.unwrap_or(origin)
.trim_end_matches('/');
origin_host.eq_ignore_ascii_case(host)
}
fn is_write(method: &Method) -> bool {
!matches!(*method, Method::GET | Method::HEAD | Method::OPTIONS)
}
pub async fn require_admin(
State(token): State<AdminToken>,
request: Request,
next: Next,
) -> Response {
if is_write(request.method()) {
let headers = request.headers();
if !same_origin(headers) {
return (StatusCode::FORBIDDEN, "origem da requisição não confere").into_response();
}
match presented_token(headers) {
Some(candidate) if token.matches(candidate) => {}
_ => {
return (
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
"token de administração ausente ou inválido",
)
.into_response()
}
}
}
next.run(request).await
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::HeaderValue;
#[test]
fn matches_only_the_exact_token() {
let token = AdminToken::new("abcdef0123456789");
assert!(token.matches("abcdef0123456789"));
assert!(!token.matches("abcdef012345678"));
assert!(!token.matches("abcdef01234567890"));
assert!(!token.matches("Abcdef0123456789"));
assert!(!token.matches(""));
}
#[test]
fn generated_tokens_are_long_and_distinct() {
let a = AdminToken::generate().unwrap();
let b = AdminToken::generate().unwrap();
assert_eq!(a.as_str().len(), 64);
assert_ne!(a.as_str(), b.as_str());
}
#[test]
fn reads_bearer_and_custom_header() {
let mut headers = HeaderMap::new();
headers.insert(
header::AUTHORIZATION,
HeaderValue::from_static("Bearer xyz"),
);
assert_eq!(presented_token(&headers), Some("xyz"));
headers.insert("x-xexeu-token", HeaderValue::from_static("abc"));
assert_eq!(presented_token(&headers), Some("abc"));
headers.clear();
headers.insert(header::AUTHORIZATION, HeaderValue::from_static("Basic xyz"));
assert_eq!(presented_token(&headers), None);
}
#[test]
fn origin_must_match_host() {
let mut headers = HeaderMap::new();
assert!(same_origin(&headers));
headers.insert(header::HOST, HeaderValue::from_static("127.0.0.1:8788"));
headers.insert(
header::ORIGIN,
HeaderValue::from_static("http://127.0.0.1:8788"),
);
assert!(same_origin(&headers));
headers.insert(
header::ORIGIN,
HeaderValue::from_static("https://evil.example"),
);
assert!(!same_origin(&headers));
}
}
+37 -2
View File
@@ -1,3 +1,5 @@
mod auth;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fs;
use std::net::IpAddr;
@@ -56,6 +58,10 @@ enum Command {
sweeps: PathBuf,
#[arg(long, default_value = "data/xexeu")]
data_dir: PathBuf,
/// Token required by the API routes that change state. Without it, a
/// random token is generated at startup and printed once.
#[arg(long, env = "XEXEU_ADMIN_TOKEN", hide_env_values = true)]
admin_token: Option<String>,
},
/// Run the continuous scheduler and scan engine, writing sweep batches.
Scanner {
@@ -175,7 +181,8 @@ async fn main() -> ExitCode {
config,
sweeps,
data_dir,
} => match run_serve(&bind, &config, &sweeps, &data_dir).await {
admin_token,
} => match run_serve(&bind, &config, &sweeps, &data_dir, admin_token.as_deref()).await {
Ok(()) => ExitCode::SUCCESS,
Err(message) => fail(&message),
},
@@ -1460,8 +1467,25 @@ async fn run_serve(
config_path: &Path,
sweeps_dir: &Path,
data_dir: &Path,
admin_token: Option<&str>,
) -> Result<(), String> {
let (config, _report) = validated_config(config_path)?;
// An empty XEXEU_ADMIN_TOKEN (compose's default) means "generate one".
let admin_token = admin_token.map(str::trim).filter(|token| !token.is_empty());
let (admin_token, token_generated) = match admin_token {
Some(token) if token.len() >= auth::MIN_TOKEN_LEN => (auth::AdminToken::new(token), false),
Some(_) => {
return Err(format!(
"XEXEU_ADMIN_TOKEN precisa ter pelo menos {} caracteres",
auth::MIN_TOKEN_LEN
))
}
None => (
auth::AdminToken::generate()
.map_err(|error| format!("falha ao gerar token de administração: {error}"))?,
true,
),
};
fs::create_dir_all(sweeps_dir)
.map_err(|error| format!("falha ao criar {}: {error}", sweeps_dir.display()))?;
fs::create_dir_all(data_dir)
@@ -1595,7 +1619,11 @@ async fn run_serve(
.route("/i18n-en.js", axum::routing::get(i18n_en_js_handler))
.route("/paged.polyfill.js", axum::routing::get(paged_js_handler))
.route("/logo.png", axum::routing::get(logo_handler))
.with_state(state);
.with_state(state)
.layer(axum::middleware::from_fn_with_state(
admin_token.clone(),
auth::require_admin,
));
let listener = tokio::net::TcpListener::bind(bind)
.await
@@ -1606,6 +1634,13 @@ async fn run_serve(
.map_err(|error| format!("falha ao obter endereço local: {error}"))?;
println!("Xexéu listening on http://{local_addr}");
if token_generated {
println!(
"Token de administração gerado nesta execução (defina XEXEU_ADMIN_TOKEN para fixá-lo): \
http://{local_addr}/?token={}",
admin_token.as_str()
);
}
axum::serve(listener, app)
.with_graceful_shutdown(shutdown_signal())
@@ -15,7 +15,21 @@ impl Drop for ChildGuard {
}
}
const ADMIN_TOKEN: &str = "e2e-admin-token-0123456789";
fn http_request(addr: &str, method: &str, path: &str, body: Option<&str>) -> (u16, String, String) {
let auth = format!("Authorization: Bearer {ADMIN_TOKEN}\r\n");
http_request_with(addr, method, path, body, &auth)
}
/// `extra_headers` is a raw block of `Name: value\r\n` lines.
fn http_request_with(
addr: &str,
method: &str,
path: &str,
body: Option<&str>,
extra_headers: &str,
) -> (u16, String, String) {
let mut stream = TcpStream::connect(addr).expect("connect to server");
stream
.set_read_timeout(Some(Duration::from_secs(5)))
@@ -23,7 +37,7 @@ fn http_request(addr: &str, method: &str, path: &str, body: Option<&str>) -> (u1
let payload = body.unwrap_or("");
let request = format!(
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
"{method} {path} HTTP/1.1\r\nHost: {addr}\r\n{extra_headers}Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
payload.len()
);
stream.write_all(request.as_bytes()).expect("write request");
@@ -87,6 +101,7 @@ alvos = ["127.0.0.1/32"]
"--data-dir",
data_dir.to_str().expect("data dir"),
])
.env("XEXEU_ADMIN_TOKEN", ADMIN_TOKEN)
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.spawn()
@@ -118,6 +133,46 @@ alvos = ["127.0.0.1/32"]
assert!(body.contains("\"escopo\""));
assert!(body.contains("\"inicial\""));
// Writes need the admin token; a browser Origin must match Host.
let group = r#"{"nome": "sem-token", "alvos": ["127.0.0.1"]}"#;
let (code, headers, _) =
http_request_with(&addr, "POST", "/api/config/groups", Some(group), "");
assert_eq!(code, 401);
assert!(headers.contains("www-authenticate: Bearer"));
let wrong = "Authorization: Bearer e2e-admin-token-0123456788\r\n";
let (code, _, _) = http_request_with(&addr, "POST", "/api/config/groups", Some(group), wrong);
assert_eq!(code, 401);
let (code, _, _) = http_request_with(&addr, "DELETE", "/api/config/groups/inicial", None, "");
assert_eq!(code, 401);
let cross_site =
format!("Authorization: Bearer {ADMIN_TOKEN}\r\nOrigin: https://evil.example\r\n");
let (code, _, _) = http_request_with(
&addr,
"POST",
"/api/config/groups",
Some(group),
&cross_site,
);
assert_eq!(code, 403);
let same_site = format!("X-Xexeu-Token: {ADMIN_TOKEN}\r\nOrigin: http://{addr}\r\n");
let (code, _, _) = http_request_with(
&addr,
"POST",
"/api/config/groups",
Some(r#"{"nome": "fora", "alvos": ["192.168.1.1"]}"#),
&same_site,
);
assert_eq!(
code, 400,
"same-origin request with the custom header reaches the handler"
);
let (code, _, body) = http_request(&addr, "GET", "/api/config", None);
assert_eq!(code, 200);
assert!(
!body.contains("sem-token"),
"rejected writes must not change the config"
);
// 3. Test POST /api/config/groups - out of scope rejection
let (code, _, body) = http_request(
&addr,