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:
1 parent
36eadabc7c
commit
90ece32dac
17 files changed
+361
-20
No files matched your search
@@ -0,0 +1,11 @@
|
|||||||
|
# Xexéu image tag: latest (last release), X.Y.Z / X.Y (pinned), or edge (main).
|
||||||
|
XEXEU_VERSION=latest
|
||||||
|
# Host address and port of the dashboard. Keep it on loopback unless an
|
||||||
|
# authenticating reverse proxy sits in front of it.
|
||||||
|
XEXEU_PUBLISH=127.0.0.1:8788
|
||||||
|
# Admin token for the dashboard actions that change the configuration (group
|
||||||
|
# CRUD). At least 16 characters, e.g. `openssl rand -hex 32`. Empty: a new one
|
||||||
|
# is generated at each start and printed in `docker compose logs xexeu`.
|
||||||
|
XEXEU_ADMIN_TOKEN=
|
||||||
|
# Xexéu container image repository.
|
||||||
|
XEXEU_IMAGE=git.lucasrguerra.dev.br/ciberfauna/xexeu
|
||||||
+3
-1
@@ -2,7 +2,9 @@
|
|||||||
/apps/gui/ui/logo.png
|
/apps/gui/ui/logo.png
|
||||||
*.eml
|
*.eml
|
||||||
__pycache__/
|
__pycache__/
|
||||||
.env*
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
.DS_Store
|
.DS_Store
|
||||||
/data
|
/data
|
||||||
/config
|
/config
|
||||||
+1
-1
@@ -16,7 +16,7 @@ Do not open a public issue with exploit details. Open a minimal issue asking for
|
|||||||
- **Strict authorized scope:** Target expansion enforces the `[escopo]` configuration boundary. Any target or DNS resolution resolving outside authorized CIDR blocks is rejected at validation time, preventing accidental or unauthorized scanning.
|
- **Strict authorized scope:** Target expansion enforces the `[escopo]` configuration boundary. Any target or DNS resolution resolving outside authorized CIDR blocks is rejected at validation time, preventing accidental or unauthorized scanning.
|
||||||
- **Safe vulnerability identification:** Xexéu does not execute exploit payloads, perform credential brute-forcing, or execute denial-of-service tests. Checks are limited to passive banner matching and standard cryptographic handshakes.
|
- **Safe vulnerability identification:** Xexéu does not execute exploit payloads, perform credential brute-forcing, or execute denial-of-service tests. Checks are limited to passive banner matching and standard cryptographic handshakes.
|
||||||
- **Input and batch parsing:** Malformed packets, banner responses, and Parquet batch files must not panic the engine or cause memory exhaustion.
|
- **Input and batch parsing:** Malformed packets, banner responses, and Parquet batch files must not panic the engine or cause memory exhaustion.
|
||||||
- **API exposure:** The API daemon listens on `127.0.0.1:8788` by default. Exposing it on an external network interface requires an authenticating reverse proxy.
|
- **API exposure:** The API daemon listens on `127.0.0.1:8788` by default. Configuration changes require the admin token (`XEXEU_ADMIN_TOKEN`, compared in constant time) and a same-origin request; reads are not authenticated, so exposing it on an external network interface still requires an authenticating reverse proxy.
|
||||||
- **Evidence integrity:** Findings and diff events must be reproducible from the same observations and feeds. Nondeterministic behavior is treated as a correctness and security defect.
|
- **Evidence integrity:** Findings and diff events must be reproducible from the same observations and feeds. Nondeterministic behavior is treated as a correctness and security defect.
|
||||||
- **Privacy & local-first:** There is no telemetry. Vulnerability feeds are cached locally in SQLite/Parquet; air-gapped offline import (`xexeu feeds import`) is fully supported.
|
- **Privacy & local-first:** There is no telemetry. Vulnerability feeds are cached locally in SQLite/Parquet; air-gapped offline import (`xexeu feeds import`) is fully supported.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -16,7 +16,7 @@ Não abra uma issue pública com detalhes de exploração. Abra uma issue mínim
|
|||||||
- **Escopo autorizado estrito:** A expansão de alvos impõe a barreira definida em `[escopo]`. Qualquer alvo ou resolução DNS que caia fora das faixas CIDR autorizadas é rejeitado na validação, prevenindo varreduras acidentais ou não autorizadas.
|
- **Escopo autorizado estrito:** A expansão de alvos impõe a barreira definida em `[escopo]`. Qualquer alvo ou resolução DNS que caia fora das faixas CIDR autorizadas é rejeitado na validação, prevenindo varreduras acidentais ou não autorizadas.
|
||||||
- **Identificação segura de vulnerabilidades:** O Xexéu não executa payloads de exploração, força bruta de credenciais ou testes de negação de serviço. As checagens se limitam a correlação passiva de banners e handshakes criptográficos padronizados.
|
- **Identificação segura de vulnerabilidades:** O Xexéu não executa payloads de exploração, força bruta de credenciais ou testes de negação de serviço. As checagens se limitam a correlação passiva de banners e handshakes criptográficos padronizados.
|
||||||
- **Parsing de entradas e lotes:** Pacotes malformados, respostas anômalas de banner e arquivos de lote Parquet corrompidos não devem causar panic no motor nem exaustão de recursos.
|
- **Parsing de entradas e lotes:** Pacotes malformados, respostas anômalas de banner e arquivos de lote Parquet corrompidos não devem causar panic no motor nem exaustão de recursos.
|
||||||
- **Exposição da API:** O daemon escuta em `127.0.0.1:8788` por padrão. Expô-lo externamente exige um proxy reverso com autenticação.
|
- **Exposição da API:** O daemon escuta em `127.0.0.1:8788` por padrão. Mudanças de configuração exigem o token de administração (`XEXEU_ADMIN_TOKEN`, comparado em tempo constante) e requisição de mesma origem; leituras não são autenticadas, então expô-lo externamente ainda exige um proxy reverso com autenticação.
|
||||||
- **Integridade da evidência:** Achados e eventos de diff devem ser reproduzíveis a partir das mesmas observações e bases de feeds. Nãodeterminismo é tratado como falha de corretude e segurança.
|
- **Integridade da evidência:** Achados e eventos de diff devem ser reproduzíveis a partir das mesmas observações e bases de feeds. Nãodeterminismo é tratado como falha de corretude e segurança.
|
||||||
- **Privacidade e local-first:** Não há telemetria. Os feeds de vulnerabilidades são armazenados localmente em SQLite/Parquet; importação offline para redes isoladas (`xexeu feeds import`) é suportada nativamente.
|
- **Privacidade e local-first:** Não há telemetria. Os feeds de vulnerabilidades são armazenados localmente em SQLite/Parquet; importação offline para redes isoladas (`xexeu feeds import`) é suportada nativamente.
|
||||||
|
|
||||||
|
|||||||
+34
-3
@@ -4,6 +4,36 @@ const SVG_NS = 'http://www.w3.org/2000/svg';
|
|||||||
const $ = (selector) => document.querySelector(selector);
|
const $ = (selector) => document.querySelector(selector);
|
||||||
const $$ = (selector) => document.querySelectorAll(selector);
|
const $$ = (selector) => document.querySelectorAll(selector);
|
||||||
|
|
||||||
|
// Admin token for the routes that change state. `xexeu serve` prints a link
|
||||||
|
// with `?token=`; it is kept for this tab only and dropped from the address bar.
|
||||||
|
const TOKEN_KEY = 'xexeu.adminToken';
|
||||||
|
{
|
||||||
|
const params = new URLSearchParams(location.search);
|
||||||
|
if (params.has('token')) {
|
||||||
|
sessionStorage.setItem(TOKEN_KEY, params.get('token'));
|
||||||
|
params.delete('token');
|
||||||
|
const query = params.toString();
|
||||||
|
history.replaceState(null, '', location.pathname + (query ? `?${query}` : '') + location.hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fetch() for writes: sends the admin token and, on 401, asks for it once and retries.
|
||||||
|
async function adminFetch(url, options = {}) {
|
||||||
|
const send = () => fetch(url, {
|
||||||
|
...options,
|
||||||
|
headers: { ...options.headers, Authorization: `Bearer ${sessionStorage.getItem(TOKEN_KEY) || ''}` },
|
||||||
|
});
|
||||||
|
let res = await send();
|
||||||
|
if (res.status === 401) {
|
||||||
|
const token = window.prompt(t('Token de administração (exibido no log do xexeu serve ou definido em XEXEU_ADMIN_TOKEN):'));
|
||||||
|
if (token && token.trim()) {
|
||||||
|
sessionStorage.setItem(TOKEN_KEY, token.trim());
|
||||||
|
res = await send();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
}
|
||||||
|
|
||||||
// DOM Elements
|
// DOM Elements
|
||||||
const connection = $('#connection');
|
const connection = $('#connection');
|
||||||
const connectionText = $('#connectionText');
|
const connectionText = $('#connectionText');
|
||||||
@@ -253,6 +283,7 @@ async function fetchData() {
|
|||||||
connectionText.textContent = t('Conectado');
|
connectionText.textContent = t('Conectado');
|
||||||
if (state.health && state.health.version) {
|
if (state.health && state.health.version) {
|
||||||
versionEl.textContent = `Xexéu v${state.health.version}`;
|
versionEl.textContent = `Xexéu v${state.health.version}`;
|
||||||
|
$('#versionPill').textContent = `v${state.health.version}`;
|
||||||
}
|
}
|
||||||
if (state.status) {
|
if (state.status) {
|
||||||
feedsStatusEl.textContent = `${formatInt(state.status.feeds_cve_count || 0)} CVEs`;
|
feedsStatusEl.textContent = `${formatInt(state.status.feeds_cve_count || 0)} CVEs`;
|
||||||
@@ -1211,13 +1242,13 @@ async function handleGroupFormSubmit(e) {
|
|||||||
try {
|
try {
|
||||||
let res;
|
let res;
|
||||||
if (editingGroupName) {
|
if (editingGroupName) {
|
||||||
res = await fetch(`/api/config/groups/${encodeURIComponent(editingGroupName)}`, {
|
res = await adminFetch(`/api/config/groups/${encodeURIComponent(editingGroupName)}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
res = await fetch('/api/config/groups', {
|
res = await adminFetch('/api/config/groups', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
@@ -1246,7 +1277,7 @@ async function deleteGroup(name) {
|
|||||||
if (!confirmed) return;
|
if (!confirmed) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/config/groups/${encodeURIComponent(name)}`, {
|
const res = await adminFetch(`/api/config/groups/${encodeURIComponent(name)}`, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
|
|||||||
@@ -49,10 +49,10 @@
|
|||||||
<div class="side-foot">
|
<div class="side-foot">
|
||||||
<div class="status-row">
|
<div class="status-row">
|
||||||
<span id="connection" class="pill"><span class="dot"></span><span id="connectionText">Conectando…</span></span>
|
<span id="connection" class="pill"><span class="dot"></span><span id="connectionText">Conectando…</span></span>
|
||||||
<span class="pill muted">v0.1.0</span>
|
<span id="versionPill" class="pill muted">—</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="status-row">
|
<div class="status-row">
|
||||||
<span id="version" class="mono">Xexéu v0.1.0</span>
|
<span id="version" class="mono">Xexéu</span>
|
||||||
<span class="mono" id="feedsStatus">—</span>
|
<span class="mono" id="feedsStatus">—</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ path = "src/main.rs"
|
|||||||
xexeu-core = { path = "../xexeu-core" }
|
xexeu-core = { path = "../xexeu-core" }
|
||||||
axum = "0.8"
|
axum = "0.8"
|
||||||
chrono = { version = "0.4", features = ["clock"] }
|
chrono = { version = "0.4", features = ["clock"] }
|
||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive", "env"] }
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
mod auth;
|
||||||
|
|
||||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||||
use std::fs;
|
use std::fs;
|
||||||
use std::net::IpAddr;
|
use std::net::IpAddr;
|
||||||
@@ -56,6 +58,10 @@ enum Command {
|
|||||||
sweeps: PathBuf,
|
sweeps: PathBuf,
|
||||||
#[arg(long, default_value = "data/xexeu")]
|
#[arg(long, default_value = "data/xexeu")]
|
||||||
data_dir: PathBuf,
|
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.
|
/// Run the continuous scheduler and scan engine, writing sweep batches.
|
||||||
Scanner {
|
Scanner {
|
||||||
@@ -175,7 +181,8 @@ async fn main() -> ExitCode {
|
|||||||
config,
|
config,
|
||||||
sweeps,
|
sweeps,
|
||||||
data_dir,
|
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,
|
Ok(()) => ExitCode::SUCCESS,
|
||||||
Err(message) => fail(&message),
|
Err(message) => fail(&message),
|
||||||
},
|
},
|
||||||
@@ -1460,8 +1467,25 @@ async fn run_serve(
|
|||||||
config_path: &Path,
|
config_path: &Path,
|
||||||
sweeps_dir: &Path,
|
sweeps_dir: &Path,
|
||||||
data_dir: &Path,
|
data_dir: &Path,
|
||||||
|
admin_token: Option<&str>,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
let (config, _report) = validated_config(config_path)?;
|
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)
|
fs::create_dir_all(sweeps_dir)
|
||||||
.map_err(|error| format!("falha ao criar {}: {error}", sweeps_dir.display()))?;
|
.map_err(|error| format!("falha ao criar {}: {error}", sweeps_dir.display()))?;
|
||||||
fs::create_dir_all(data_dir)
|
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("/i18n-en.js", axum::routing::get(i18n_en_js_handler))
|
||||||
.route("/paged.polyfill.js", axum::routing::get(paged_js_handler))
|
.route("/paged.polyfill.js", axum::routing::get(paged_js_handler))
|
||||||
.route("/logo.png", axum::routing::get(logo_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)
|
let listener = tokio::net::TcpListener::bind(bind)
|
||||||
.await
|
.await
|
||||||
@@ -1606,6 +1634,13 @@ async fn run_serve(
|
|||||||
.map_err(|error| format!("falha ao obter endereço local: {error}"))?;
|
.map_err(|error| format!("falha ao obter endereço local: {error}"))?;
|
||||||
|
|
||||||
println!("Xexéu listening on http://{local_addr}");
|
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)
|
axum::serve(listener, app)
|
||||||
.with_graceful_shutdown(shutdown_signal())
|
.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) {
|
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");
|
let mut stream = TcpStream::connect(addr).expect("connect to server");
|
||||||
stream
|
stream
|
||||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
.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 payload = body.unwrap_or("");
|
||||||
let request = format!(
|
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()
|
payload.len()
|
||||||
);
|
);
|
||||||
stream.write_all(request.as_bytes()).expect("write request");
|
stream.write_all(request.as_bytes()).expect("write request");
|
||||||
@@ -87,6 +101,7 @@ alvos = ["127.0.0.1/32"]
|
|||||||
"--data-dir",
|
"--data-dir",
|
||||||
data_dir.to_str().expect("data dir"),
|
data_dir.to_str().expect("data dir"),
|
||||||
])
|
])
|
||||||
|
.env("XEXEU_ADMIN_TOKEN", ADMIN_TOKEN)
|
||||||
.stdout(Stdio::piped())
|
.stdout(Stdio::piped())
|
||||||
.stderr(Stdio::inherit())
|
.stderr(Stdio::inherit())
|
||||||
.spawn()
|
.spawn()
|
||||||
@@ -118,6 +133,46 @@ alvos = ["127.0.0.1/32"]
|
|||||||
assert!(body.contains("\"escopo\""));
|
assert!(body.contains("\"escopo\""));
|
||||||
assert!(body.contains("\"inicial\""));
|
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
|
// 3. Test POST /api/config/groups - out of scope rejection
|
||||||
let (code, _, body) = http_request(
|
let (code, _, body) = http_request(
|
||||||
&addr,
|
&addr,
|
||||||
|
|||||||
@@ -29,6 +29,9 @@ services:
|
|||||||
build: .
|
build: .
|
||||||
command: ["serve", "--bind", "0.0.0.0:8788", "--config", "/config/xexeu.toml",
|
command: ["serve", "--bind", "0.0.0.0:8788", "--config", "/config/xexeu.toml",
|
||||||
"--sweeps", "/data/sweeps", "--data-dir", "/data/xexeu"]
|
"--sweeps", "/data/sweeps", "--data-dir", "/data/xexeu"]
|
||||||
|
environment:
|
||||||
|
# Empty: a token is generated at each start and printed in `docker compose logs xexeu`.
|
||||||
|
XEXEU_ADMIN_TOKEN: ${XEXEU_ADMIN_TOKEN:-}
|
||||||
ports:
|
ports:
|
||||||
- "${XEXEU_PUBLISH:-127.0.0.1:8788}:8788"
|
- "${XEXEU_PUBLISH:-127.0.0.1:8788}:8788"
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
+13
-3
@@ -19,10 +19,20 @@ Options:
|
|||||||
--config <CONFIG> [default: config/xexeu.toml]
|
--config <CONFIG> [default: config/xexeu.toml]
|
||||||
--sweeps <SWEEPS> [default: data/sweeps]
|
--sweeps <SWEEPS> [default: data/sweeps]
|
||||||
--data-dir <DATA_DIR> [default: data/xexeu]
|
--data-dir <DATA_DIR> [default: data/xexeu]
|
||||||
|
--admin-token <ADMIN_TOKEN> Token required by the API routes that change state.
|
||||||
|
Without it, a random token is generated at startup
|
||||||
|
and printed once [env: XEXEU_ADMIN_TOKEN]
|
||||||
```
|
```
|
||||||
|
|
||||||
This is the `xexeu` Compose service's entrypoint.
|
This is the `xexeu` Compose service's entrypoint.
|
||||||
|
|
||||||
|
Reads (`GET`) are open; the routes that change the configuration
|
||||||
|
(`POST`/`PUT`/`DELETE /api/config/groups…`) need the admin token in
|
||||||
|
`Authorization: Bearer <token>` or `X-Xexeu-Token`, and a browser `Origin`, when
|
||||||
|
present, must match `Host`. Without `XEXEU_ADMIN_TOKEN`, `serve` prints a fresh
|
||||||
|
`http://…/?token=…` link at each start; opening it logs the dashboard in for
|
||||||
|
that tab.
|
||||||
|
|
||||||
## `xexeu scanner`
|
## `xexeu scanner`
|
||||||
|
|
||||||
Runs the continuous scheduler and scan engine, writing sweep batches —
|
Runs the continuous scheduler and scan engine, writing sweep batches —
|
||||||
@@ -75,7 +85,7 @@ Options:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Exits non-zero on an invalid configuration — safe to use in a pre-push hook
|
Exits non-zero on an invalid configuration — safe to use in a pre-push hook
|
||||||
or CI step, which is exactly what `scripts/verificar.sh` does.
|
or CI step, which is exactly what `scripts/check.sh` does.
|
||||||
|
|
||||||
## `xexeu feeds sync` / `xexeu feeds import`
|
## `xexeu feeds sync` / `xexeu feeds import`
|
||||||
|
|
||||||
@@ -142,11 +152,11 @@ Options:
|
|||||||
|
|
||||||
```
|
```
|
||||||
$ xexeu doctor
|
$ xexeu doctor
|
||||||
Xexéu v0.1.0 - Diagnóstico do Ambiente
|
Xexéu v1.0.0 - Diagnóstico do Ambiente
|
||||||
================================================================================
|
================================================================================
|
||||||
Item Status Detalhe
|
Item Status Detalhe
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
versao ok xexeu v0.1.0
|
versao ok xexeu v1.0.0
|
||||||
config ok configuração válida (4 grupo(s))
|
config ok configuração válida (4 grupo(s))
|
||||||
net_raw ok CAP_NET_RAW disponível (motor nativo ativo)
|
net_raw ok CAP_NET_RAW disponível (motor nativo ativo)
|
||||||
sqlite ok banco SQLite acessível em data/xexeu/xexeu.db
|
sqlite ok banco SQLite acessível em data/xexeu/xexeu.db
|
||||||
|
|||||||
+5
-1
@@ -38,7 +38,11 @@ docker compose up -d --build
|
|||||||
```
|
```
|
||||||
|
|
||||||
The dashboard comes up at `http://127.0.0.1:8788` by default (`XEXEU_PUBLISH`
|
The dashboard comes up at `http://127.0.0.1:8788` by default (`XEXEU_PUBLISH`
|
||||||
in `.env` to change the bind address/port).
|
in `.env` to change the bind address/port). To add, edit or remove groups from
|
||||||
|
it, set `XEXEU_ADMIN_TOKEN` in `.env` (`openssl rand -hex 32`) or, leaving it
|
||||||
|
empty, take the one-off link from `docker compose logs xexeu`; inside the
|
||||||
|
container it reads `http://0.0.0.0:8788/?token=…`, so swap the host for the
|
||||||
|
published address.
|
||||||
|
|
||||||
## Why `scanner` runs as `uid 0` restricted to `NET_RAW`
|
## Why `scanner` runs as `uid 0` restricted to `NET_RAW`
|
||||||
|
|
||||||
|
|||||||
@@ -40,6 +40,10 @@ cron, port profile, criticality) without touching `xexeu.toml` by hand —
|
|||||||
see [`configuration.md`](configuration.md#editing-a-group-from-the-dashboard)
|
see [`configuration.md`](configuration.md#editing-a-group-from-the-dashboard)
|
||||||
for how the change reaches the running `scanner`.
|
for how the change reaches the running `scanner`.
|
||||||
|
|
||||||
|
Changing groups needs the admin token: open the `?token=` link printed by
|
||||||
|
`xexeu serve` (or `docker compose logs xexeu`), or type the token when the
|
||||||
|
dashboard asks for it. It is kept for the browser tab only.
|
||||||
|
|
||||||
## Executive report
|
## Executive report
|
||||||
|
|
||||||
<p align="center"><img src="img/relatorio-executivo-pt.png" width="900" alt="Xexéu executive security report cover page: authorized-use and confidentiality badges, title, subtitle, KPI strip and the table of contents"></p>
|
<p align="center"><img src="img/relatorio-executivo-pt.png" width="900" alt="Xexéu executive security report cover page: authorized-use and confidentiality badges, title, subtitle, KPI strip and the table of contents"></p>
|
||||||
|
|||||||
+13
-3
@@ -19,10 +19,20 @@ Options:
|
|||||||
--config <CONFIG> [default: config/xexeu.toml]
|
--config <CONFIG> [default: config/xexeu.toml]
|
||||||
--sweeps <SWEEPS> [default: data/sweeps]
|
--sweeps <SWEEPS> [default: data/sweeps]
|
||||||
--data-dir <DATA_DIR> [default: data/xexeu]
|
--data-dir <DATA_DIR> [default: data/xexeu]
|
||||||
|
--admin-token <ADMIN_TOKEN> Token required by the API routes that change state.
|
||||||
|
Without it, a random token is generated at startup
|
||||||
|
and printed once [env: XEXEU_ADMIN_TOKEN]
|
||||||
```
|
```
|
||||||
|
|
||||||
Esse é o entrypoint do serviço `xexeu` do Compose.
|
Esse é o entrypoint do serviço `xexeu` do Compose.
|
||||||
|
|
||||||
|
Leituras (`GET`) são abertas; as rotas que mudam a configuração
|
||||||
|
(`POST`/`PUT`/`DELETE /api/config/groups…`) exigem o token de administração em
|
||||||
|
`Authorization: Bearer <token>` ou `X-Xexeu-Token`, e um `Origin` de navegador,
|
||||||
|
quando presente, precisa bater com o `Host`. Sem `XEXEU_ADMIN_TOKEN`, o `serve`
|
||||||
|
imprime um link `http://…/?token=…` novo a cada partida; abri-lo autentica o
|
||||||
|
dashboard naquela aba.
|
||||||
|
|
||||||
## `xexeu scanner`
|
## `xexeu scanner`
|
||||||
|
|
||||||
Roda o agendador e o motor de varredura contínuos, gravando lotes — nunca
|
Roda o agendador e o motor de varredura contínuos, gravando lotes — nunca
|
||||||
@@ -78,7 +88,7 @@ Options:
|
|||||||
|
|
||||||
Sai com código não-zero numa configuração inválida — seguro de usar num
|
Sai com código não-zero numa configuração inválida — seguro de usar num
|
||||||
hook de pre-push ou passo de CI, que é exatamente o que
|
hook de pre-push ou passo de CI, que é exatamente o que
|
||||||
`scripts/verificar.sh` faz.
|
`scripts/check.sh` faz.
|
||||||
|
|
||||||
## `xexeu feeds sync` / `xexeu feeds import`
|
## `xexeu feeds sync` / `xexeu feeds import`
|
||||||
|
|
||||||
@@ -147,11 +157,11 @@ Options:
|
|||||||
|
|
||||||
```
|
```
|
||||||
$ xexeu doctor
|
$ xexeu doctor
|
||||||
Xexéu v0.1.0 - Diagnóstico do Ambiente
|
Xexéu v1.0.0 - Diagnóstico do Ambiente
|
||||||
================================================================================
|
================================================================================
|
||||||
Item Status Detalhe
|
Item Status Detalhe
|
||||||
--------------------------------------------------------------------------------
|
--------------------------------------------------------------------------------
|
||||||
versao ok xexeu v0.1.0
|
versao ok xexeu v1.0.0
|
||||||
config ok configuração válida (4 grupo(s))
|
config ok configuração válida (4 grupo(s))
|
||||||
net_raw ok CAP_NET_RAW disponível (motor nativo ativo)
|
net_raw ok CAP_NET_RAW disponível (motor nativo ativo)
|
||||||
sqlite ok banco SQLite acessível em data/xexeu/xexeu.db
|
sqlite ok banco SQLite acessível em data/xexeu/xexeu.db
|
||||||
|
|||||||
@@ -38,7 +38,11 @@ docker compose up -d --build
|
|||||||
```
|
```
|
||||||
|
|
||||||
O dashboard sobe em `http://127.0.0.1:8788` por padrão (`XEXEU_PUBLISH` no
|
O dashboard sobe em `http://127.0.0.1:8788` por padrão (`XEXEU_PUBLISH` no
|
||||||
`.env` pra trocar endereço/porta).
|
`.env` pra trocar endereço/porta). Pra adicionar, editar ou remover grupos
|
||||||
|
por ele, defina `XEXEU_ADMIN_TOKEN` no `.env` (`openssl rand -hex 32`) ou,
|
||||||
|
deixando vazio, pegue o link avulso em `docker compose logs xexeu`; dentro do
|
||||||
|
contêiner ele aparece como `http://0.0.0.0:8788/?token=…`, então troque o host
|
||||||
|
pelo endereço publicado.
|
||||||
|
|
||||||
## Por que o `scanner` roda como `uid 0` restrito a `NET_RAW`
|
## Por que o `scanner` roda como `uid 0` restrito a `NET_RAW`
|
||||||
|
|
||||||
|
|||||||
@@ -43,6 +43,10 @@ exclusões, cron, perfil de portas, criticidade) sem mexer no
|
|||||||
[`configuracao.md`](configuracao.md#editando-um-grupo-pelo-dashboard) pra
|
[`configuracao.md`](configuracao.md#editando-um-grupo-pelo-dashboard) pra
|
||||||
como a mudança chega no `scanner` em execução.
|
como a mudança chega no `scanner` em execução.
|
||||||
|
|
||||||
|
Mexer em grupos exige o token de administração: abra o link `?token=` impresso
|
||||||
|
pelo `xexeu serve` (ou `docker compose logs xexeu`), ou digite o token quando o
|
||||||
|
dashboard pedir. Ele fica guardado só naquela aba do navegador.
|
||||||
|
|
||||||
## Relatório executivo
|
## Relatório executivo
|
||||||
|
|
||||||
<p align="center"><img src="../img/relatorio-executivo-pt.png" width="900" alt="Capa do relatório executivo de segurança da Xexéu: selos de uso autorizado e confidencialidade, título, subtítulo, faixa de KPIs e o sumário"></p>
|
<p align="center"><img src="../img/relatorio-executivo-pt.png" width="900" alt="Capa do relatório executivo de segurança da Xexéu: selos de uso autorizado e confidencialidade, título, subtítulo, faixa de KPIs e o sumário"></p>
|
||||||
|
|||||||
Reference in new issue
Block a user