Key login failures by username and client address with decay, plus a loose per-username limit that delays every address by a bounded time. Refused attempts write nothing. Unknown usernames share the code path. MFA and session password checks keep a persistent user-bound count that needs a password or a session to reach. Also: local mode refuses a non-loopback bind outside a container; security headers on every response; the Argon2 permit lives as long as the blocking task; a required password change rechecks role, MFA and epoch; auth reset works for any user; mfa_enabled in /api/auth/state; disabling MFA that is off is refused with no side effects; StateCorrupt keeps only line and column. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
506 lines
17 KiB
Rust
506 lines
17 KiB
Rust
use crate::auth_http::{self, blocking, require_auth, ApiError, JsonBody};
|
|
use crate::transport::Transport;
|
|
use acaua_core::auth::AuthService;
|
|
use acaua_core::fusion::Alert;
|
|
use acaua_core::storage::{DatasetSummary, Storage};
|
|
use acaua_core::update::UpdateStatus;
|
|
use acaua_core::zeek::{self, AnalysisReport};
|
|
use acaua_core::{update, AcauaError, Result};
|
|
use axum::body::Body;
|
|
use axum::extract::Request;
|
|
use axum::extract::{DefaultBodyLimit, Query, State};
|
|
use axum::http::{header, HeaderValue, Method, StatusCode, Uri};
|
|
use axum::middleware::{from_fn, from_fn_with_state, Next};
|
|
use axum::response::{IntoResponse, Response};
|
|
use axum::routing::{delete, get, patch, post, MethodRouter};
|
|
use axum::{Json, Router};
|
|
use axum_server::tls_rustls::RustlsConfig;
|
|
use axum_server::Handle;
|
|
use rust_embed::RustEmbed;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::collections::HashMap;
|
|
use std::net::SocketAddr;
|
|
use std::path::PathBuf;
|
|
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
|
use std::time::Duration;
|
|
use tokio::net::TcpListener;
|
|
use tokio::sync::Semaphore;
|
|
use tower_http::compression::CompressionLayer;
|
|
use tower_http::trace::TraceLayer;
|
|
|
|
const LOGO: &[u8] = include_bytes!("../../../logo.png");
|
|
|
|
#[derive(RustEmbed)]
|
|
#[folder = "../../apps/gui/ui/"]
|
|
struct Assets;
|
|
|
|
#[derive(Clone)]
|
|
pub struct AppState {
|
|
storage: Arc<Storage>,
|
|
last_report: Arc<Mutex<Option<AnalysisReport>>>,
|
|
pub auth: Arc<AuthService>,
|
|
pub transport: Arc<Transport>,
|
|
pub argon2: Arc<Semaphore>,
|
|
}
|
|
|
|
impl AppState {
|
|
pub fn new(storage: Arc<Storage>, auth: Arc<AuthService>, transport: Transport) -> Self {
|
|
Self {
|
|
storage,
|
|
last_report: Arc::new(Mutex::new(None)),
|
|
auth,
|
|
transport: Arc::new(transport),
|
|
argon2: Arc::new(Semaphore::new(auth_http::ARGON2_CONCURRENCY)),
|
|
}
|
|
}
|
|
|
|
/// The report is replaced whole, so a poisoned lock still holds a valid one.
|
|
fn report(&self) -> MutexGuard<'_, Option<AnalysisReport>> {
|
|
self.last_report
|
|
.lock()
|
|
.unwrap_or_else(PoisonError::into_inner)
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub enum Verb {
|
|
Get,
|
|
Post,
|
|
Patch,
|
|
Delete,
|
|
}
|
|
|
|
impl Verb {
|
|
/// `HEAD` follows `GET`, as in the router.
|
|
fn matches(self, method: &Method) -> bool {
|
|
match self {
|
|
Verb::Get => *method == Method::GET || *method == Method::HEAD,
|
|
Verb::Post => *method == Method::POST,
|
|
Verb::Patch => *method == Method::PATCH,
|
|
Verb::Delete => *method == Method::DELETE,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// What a non-public route asks of the caller. There is no public level on
|
|
/// purpose: a route is public only by being written into `PUBLIC_ROUTES`.
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub enum Access {
|
|
/// Any session or token; a read token still cannot mutate.
|
|
Authenticated,
|
|
/// A browser session: an API token, whatever its scope, is refused.
|
|
Session,
|
|
/// As `Session`, or the pending token of a first login.
|
|
SessionOrPending,
|
|
/// Administrator role, and Admin scope when through a token.
|
|
Admin,
|
|
/// Administrator in a session that reauthenticated recently, never a
|
|
/// token: otherwise a hijacked session could create an admin outliving it.
|
|
AdminRecentSession,
|
|
}
|
|
|
|
pub struct RouteDef {
|
|
pub verb: Verb,
|
|
pub path: &'static str,
|
|
pub access: Access,
|
|
handler: fn() -> MethodRouter<AppState>,
|
|
}
|
|
|
|
const fn route(
|
|
verb: Verb,
|
|
path: &'static str,
|
|
access: Access,
|
|
handler: fn() -> MethodRouter<AppState>,
|
|
) -> RouteDef {
|
|
RouteDef {
|
|
verb,
|
|
path,
|
|
access,
|
|
handler,
|
|
}
|
|
}
|
|
|
|
/// The one source of routes: `build_app` registers exactly these. Access for
|
|
/// entries also in `PUBLIC_ROUTES` is never consulted.
|
|
pub const ALL_ROUTES: &[RouteDef] = {
|
|
use auth_http as a;
|
|
use Access::{Admin, AdminRecentSession, Authenticated, Session, SessionOrPending};
|
|
use Verb::{Delete, Get, Patch, Post};
|
|
&[
|
|
route(Get, "/api/health", Authenticated, || get(health)),
|
|
route(Get, "/login.html", Authenticated, || get(asset)),
|
|
route(Get, "/login.js", Authenticated, || get(asset)),
|
|
route(Get, "/app.css", Authenticated, || get(asset)),
|
|
route(Get, "/logo.png", Authenticated, || get(logo)),
|
|
route(Get, "/i18n.js", Authenticated, || get(asset)),
|
|
route(Get, "/i18n-en.js", Authenticated, || get(asset)),
|
|
route(Get, "/api/auth/state", Authenticated, || get(a::auth_state)),
|
|
route(Post, "/api/auth/bootstrap", Authenticated, || {
|
|
post(a::bootstrap)
|
|
}),
|
|
route(Post, "/api/auth/login", Authenticated, || post(a::login)),
|
|
route(Post, "/api/auth/mfa", Authenticated, || post(a::mfa)),
|
|
route(
|
|
Post,
|
|
"/api/auth/password-change-required",
|
|
Authenticated,
|
|
|| post(a::password_change_required),
|
|
),
|
|
route(Post, "/api/auth/logout", Session, || post(a::logout)),
|
|
route(Post, "/api/auth/reauth", Session, || post(a::reauth)),
|
|
route(Post, "/api/auth/password", Session, || {
|
|
post(a::change_password)
|
|
}),
|
|
route(Post, "/api/auth/mfa/disable", Session, || {
|
|
post(a::mfa_disable)
|
|
}),
|
|
route(Post, "/api/auth/enroll/start", SessionOrPending, || {
|
|
post(a::enroll_start)
|
|
}),
|
|
route(Post, "/api/auth/enroll/confirm", SessionOrPending, || {
|
|
post(a::enroll_confirm)
|
|
}),
|
|
route(Get, "/api/auth/sessions", Authenticated, || {
|
|
get(a::sessions_list)
|
|
}),
|
|
route(Delete, "/api/auth/sessions", Authenticated, || {
|
|
delete(a::sessions_revoke)
|
|
}),
|
|
route(Get, "/api/auth/tokens", Authenticated, || {
|
|
get(a::tokens_list)
|
|
}),
|
|
route(Post, "/api/auth/tokens", Session, || post(a::tokens_create)),
|
|
route(Delete, "/api/auth/tokens", Authenticated, || {
|
|
delete(a::tokens_revoke)
|
|
}),
|
|
route(Get, "/api/admin/users", Admin, || get(a::users_list)),
|
|
route(Post, "/api/admin/users", AdminRecentSession, || {
|
|
post(a::users_create)
|
|
}),
|
|
route(Patch, "/api/admin/users", AdminRecentSession, || {
|
|
patch(a::users_set_role)
|
|
}),
|
|
route(Delete, "/api/admin/users", AdminRecentSession, || {
|
|
delete(a::users_delete)
|
|
}),
|
|
route(Get, "/api/admin/audit", Admin, || get(a::audit)),
|
|
route(Post, "/api/analyze", Admin, || post(analyze)),
|
|
route(Get, "/api/status", Authenticated, || get(status)),
|
|
route(Get, "/api/alerts", Authenticated, || get(alerts)),
|
|
route(Get, "/api/update", Authenticated, || get(update_check)),
|
|
route(Get, "/relatorio", Authenticated, || get(report_page)),
|
|
]
|
|
};
|
|
|
|
/// Everything reachable without a credential. Exact matches only.
|
|
pub const PUBLIC_ROUTES: &[(Verb, &str)] = &[
|
|
(Verb::Get, "/api/health"),
|
|
(Verb::Get, "/login.html"),
|
|
(Verb::Get, "/login.js"),
|
|
(Verb::Get, "/app.css"),
|
|
(Verb::Get, "/logo.png"),
|
|
(Verb::Get, "/i18n.js"),
|
|
(Verb::Get, "/i18n-en.js"),
|
|
(Verb::Get, "/api/auth/state"),
|
|
(Verb::Post, "/api/auth/bootstrap"),
|
|
(Verb::Post, "/api/auth/login"),
|
|
(Verb::Post, "/api/auth/mfa"),
|
|
(Verb::Post, "/api/auth/password-change-required"),
|
|
];
|
|
|
|
pub fn is_public(method: &Method, path: &str) -> bool {
|
|
PUBLIC_ROUTES
|
|
.iter()
|
|
.any(|(verb, p)| *p == path && verb.matches(method))
|
|
}
|
|
|
|
/// The public files: shared, cacheable, and holding nothing per-user.
|
|
pub fn is_public_asset(method: &Method, path: &str) -> bool {
|
|
!path.starts_with("/api/") && is_public(method, path)
|
|
}
|
|
|
|
/// Paths outside the table (the asset fallback) need a credential too.
|
|
pub fn access_of(method: &Method, path: &str) -> Access {
|
|
ALL_ROUTES
|
|
.iter()
|
|
.find(|r| r.path == path && r.verb.matches(method))
|
|
.map_or(Access::Authenticated, |r| r.access)
|
|
}
|
|
|
|
pub fn build_app(state: AppState) -> Router {
|
|
let mut router = Router::new();
|
|
for r in ALL_ROUTES {
|
|
router = router.route(r.path, (r.handler)());
|
|
}
|
|
router
|
|
.fallback(asset)
|
|
// Bounds every `Json` extractor before anything looks at the input.
|
|
.layer(DefaultBodyLimit::max(auth_http::MAX_BODY_BYTES))
|
|
.layer(from_fn_with_state(state.clone(), require_auth))
|
|
.layer(from_fn_with_state(state.clone(), hsts))
|
|
.layer(from_fn(security_headers))
|
|
.with_state(state)
|
|
.layer(CompressionLayer::new())
|
|
.layer(TraceLayer::new_for_http())
|
|
}
|
|
|
|
/// Adds `Strict-Transport-Security` when the transport is HTTPS. It sits
|
|
/// outside `require_auth`, so refusals carry it too.
|
|
async fn hsts(State(state): State<AppState>, req: Request, next: Next) -> Response {
|
|
let mut response = next.run(req).await;
|
|
if state.transport.hsts() {
|
|
response.headers_mut().insert(
|
|
header::STRICT_TRANSPORT_SECURITY,
|
|
HeaderValue::from_static("max-age=31536000"),
|
|
);
|
|
}
|
|
response
|
|
}
|
|
|
|
/// `style-src 'unsafe-inline'` is the narrowest that works: the report carries
|
|
/// its stylesheet inline and Paged.js adds `<style>` elements while it paginates.
|
|
/// Scripts stay same-origin only. `data:` images are the report's embedded logo
|
|
/// and the MFA QR code.
|
|
pub(crate) const CSP: &str = "default-src 'none'; script-src 'self'; \
|
|
style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; \
|
|
connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'";
|
|
|
|
/// On every response, refusals included.
|
|
async fn security_headers(req: Request, next: Next) -> Response {
|
|
let mut response = next.run(req).await;
|
|
let headers = response.headers_mut();
|
|
headers.insert(
|
|
header::CONTENT_SECURITY_POLICY,
|
|
HeaderValue::from_static(CSP),
|
|
);
|
|
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
|
|
headers.insert(
|
|
header::X_CONTENT_TYPE_OPTIONS,
|
|
HeaderValue::from_static("nosniff"),
|
|
);
|
|
headers.insert(
|
|
header::REFERRER_POLICY,
|
|
HeaderValue::from_static("no-referrer"),
|
|
);
|
|
response
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct Health {
|
|
status: &'static str,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct Status {
|
|
version: &'static str,
|
|
mode: &'static str,
|
|
dataset: DatasetSummary,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct ErrorBody {
|
|
error: String,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct AnalyzeRequest {
|
|
path: String,
|
|
}
|
|
|
|
/// The detail (paths, command output) goes to the log, not to the caller.
|
|
fn failure(status: StatusCode, message: &str, detail: &acaua_core::AcauaError) -> Response {
|
|
tracing::error!(error = %detail, "{message}");
|
|
(
|
|
status,
|
|
Json(ErrorBody {
|
|
error: message.to_string(),
|
|
}),
|
|
)
|
|
.into_response()
|
|
}
|
|
|
|
async fn health() -> Json<Health> {
|
|
Json(Health { status: "ok" })
|
|
}
|
|
|
|
async fn status(State(state): State<AppState>) -> std::result::Result<Json<Status>, ApiError> {
|
|
let storage = state.storage.clone();
|
|
let dataset = blocking(move || {
|
|
Ok(storage
|
|
.summary()
|
|
.unwrap_or_else(|_| DatasetSummary::empty()))
|
|
})
|
|
.await?;
|
|
Ok(Json(Status {
|
|
version: env!("CARGO_PKG_VERSION"),
|
|
mode: "serve",
|
|
dataset,
|
|
}))
|
|
}
|
|
|
|
async fn alerts(State(state): State<AppState>) -> Json<Vec<Alert>> {
|
|
let list = state
|
|
.report()
|
|
.as_ref()
|
|
.map(|r| r.alerts.clone())
|
|
.unwrap_or_default();
|
|
Json(list)
|
|
}
|
|
|
|
async fn analyze(
|
|
State(state): State<AppState>,
|
|
JsonBody(request): JsonBody<AnalyzeRequest>,
|
|
) -> Response {
|
|
let root = state.storage.root().to_path_buf();
|
|
let outcome =
|
|
tokio::task::spawn_blocking(move || zeek::analyze_dir(&request.path, &root)).await;
|
|
match outcome {
|
|
Ok(Ok(report)) => {
|
|
*state.report() = Some(report.clone());
|
|
Json(report).into_response()
|
|
}
|
|
Ok(Err(error)) => failure(StatusCode::BAD_REQUEST, "analysis failed", &error),
|
|
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
|
}
|
|
}
|
|
|
|
/// Executive report of the latest analysis (`?tlp=` picks the TLP label).
|
|
async fn report_page(
|
|
State(state): State<AppState>,
|
|
Query(query): Query<HashMap<String, String>>,
|
|
) -> Response {
|
|
let lock = state.report();
|
|
let Some(report) = lock.as_ref() else {
|
|
return (
|
|
StatusCode::NOT_FOUND,
|
|
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
|
|
"<!doctype html><meta charset=\"utf-8\"><title>Acauã</title><p>Nenhuma análise executada. Rode uma análise no painel e abra o relatório de novo.</p>",
|
|
)
|
|
.into_response();
|
|
};
|
|
let options = acaua_core::report::ReportOptions {
|
|
tlp: query.get("tlp").cloned().unwrap_or_else(|| "AMBER".into()),
|
|
issued_at: None,
|
|
};
|
|
let html = acaua_core::report::render_html_with(report, &options);
|
|
([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response()
|
|
}
|
|
|
|
async fn update_check() -> Response {
|
|
let outcome = tokio::task::spawn_blocking(|| update::check(env!("CARGO_PKG_VERSION"))).await;
|
|
match outcome {
|
|
Ok(Ok(status)) => Json::<UpdateStatus>(status).into_response(),
|
|
Ok(Err(error)) => failure(StatusCode::BAD_GATEWAY, "update check failed", &error),
|
|
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
|
}
|
|
}
|
|
|
|
async fn logo() -> impl IntoResponse {
|
|
([(header::CONTENT_TYPE, "image/png")], Body::from(LOGO))
|
|
}
|
|
|
|
async fn asset(uri: Uri) -> Response {
|
|
let path = uri.path().trim_start_matches('/');
|
|
let path = if path.is_empty() { "index.html" } else { path };
|
|
match Assets::get(path) {
|
|
Some(file) => {
|
|
let mime = mime_guess::from_path(path).first_or_octet_stream();
|
|
Response::builder()
|
|
.header(header::CONTENT_TYPE, mime.as_ref())
|
|
.body(Body::from(file.data.into_owned()))
|
|
.unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
|
|
}
|
|
None => (StatusCode::NOT_FOUND, "not found").into_response(),
|
|
}
|
|
}
|
|
|
|
async fn shutdown_signal() {
|
|
let interrupt = async {
|
|
let _ = tokio::signal::ctrl_c().await;
|
|
};
|
|
#[cfg(unix)]
|
|
let terminate = async {
|
|
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
|
|
Ok(mut stream) => {
|
|
stream.recv().await;
|
|
}
|
|
Err(_) => std::future::pending::<()>().await,
|
|
}
|
|
};
|
|
#[cfg(not(unix))]
|
|
let terminate = std::future::pending::<()>();
|
|
tokio::select! {
|
|
_ = interrupt => {}
|
|
_ = terminate => {}
|
|
}
|
|
}
|
|
|
|
/// Path of an external secret key (a Docker secret), from `ACAUA_SECRET_KEY_FILE`.
|
|
/// An unset or empty variable means the key lives in the data directory.
|
|
pub(crate) fn secret_key_file(get: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
|
|
get("ACAUA_SECRET_KEY_FILE")
|
|
.filter(|value| !value.trim().is_empty())
|
|
.map(PathBuf::from)
|
|
}
|
|
|
|
pub async fn serve(bind: &str, data_dir: PathBuf) -> Result<()> {
|
|
// Decide the exposure before touching the data directory or printing a
|
|
// setup code: a refusal must leave nothing behind.
|
|
let transport = Transport::from_env(&|name| std::env::var(name).ok())?;
|
|
transport.check_bind(bind, &|name| std::env::var(name).ok())?;
|
|
let _ = tracing_subscriber::fmt().try_init();
|
|
std::fs::create_dir_all(&data_dir)?;
|
|
let auth = Arc::new(AuthService::open(
|
|
&data_dir,
|
|
secret_key_file(&|name| std::env::var(name).ok()).as_deref(),
|
|
)?);
|
|
if let Some(code) = auth.ensure_bootstrap(auth_http::unix_now())? {
|
|
eprintln!("Acauã: código de configuração inicial (válido por 1 hora): {code}");
|
|
}
|
|
let tls = match &transport {
|
|
Transport::Tls { cert, key } => Some((cert.clone(), key.clone())),
|
|
_ => None,
|
|
};
|
|
let state = AppState::new(Arc::new(Storage::open(&data_dir)?), auth, transport);
|
|
let service = build_app(state).into_make_service_with_connect_info::<SocketAddr>();
|
|
match tls {
|
|
None => {
|
|
let listener = TcpListener::bind(bind).await?;
|
|
println!("Acauã listening on http://{bind}");
|
|
axum::serve(listener, service)
|
|
.with_graceful_shutdown(shutdown_signal())
|
|
.await?;
|
|
}
|
|
Some((cert, key)) => {
|
|
let addr: SocketAddr = bind.parse().map_err(|_| {
|
|
AcauaError::InvalidInput(format!(
|
|
"--bind `{bind}` must be an IP:port when ACAUA_TRANSPORT=tls"
|
|
))
|
|
})?;
|
|
let config = RustlsConfig::from_pem_file(&cert, &key)
|
|
.await
|
|
.map_err(|e| {
|
|
AcauaError::InvalidInput(format!(
|
|
"cannot load ACAUA_TLS_CERT/ACAUA_TLS_KEY: {e}"
|
|
))
|
|
})?;
|
|
let handle = Handle::new();
|
|
let stopper = handle.clone();
|
|
tokio::spawn(async move {
|
|
shutdown_signal().await;
|
|
stopper.graceful_shutdown(Some(Duration::from_secs(10)));
|
|
});
|
|
println!("Acauã listening on https://{bind}");
|
|
axum_server::bind_rustls(addr, config)
|
|
.handle(handle)
|
|
.serve(service)
|
|
.await?;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
#[path = "web_tests.rs"]
|
|
mod tests;
|