feat(report): executive report at /relatorio with a Relatório button
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and clippy (push) Successful in 13s
CI / Tests (Linux) (push) Successful in 34s
CI / Dependency audit (push) Successful in 10s
Release / ci (push) Successful in 57s
Release / Build image (arm64) (push) Failing after 28s
Release / Build image (amd64) (push) Successful in 7m14s
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and clippy (push) Successful in 13s
CI / Tests (Linux) (push) Successful in 34s
CI / Dependency audit (push) Successful in 10s
Release / ci (push) Successful in 57s
Release / Build image (arm64) (push) Failing after 28s
Release / Build image (amd64) (push) Successful in 7m14s
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6a14c29b97
commit
a218111996
13 files changed
+1034
-1
No files matched your search
@@ -6,6 +6,9 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Executive report: a **Relatório** button in the analysis view opens `GET /relatorio`, an A4 report of the latest analysis paginated by the vendored Paged.js, with a full-bleed cover (logo, TLP badge, beacon-lane motif drawn from the top hosts), table of contents, KPIs, host ranking, one section per pillar, every alert with its evidence, methodology and glossary. Defaults to `TLP:AMBER` (`?tlp=` changes it) and HTML-escapes every string read from the logs.
|
||||
|
||||
### Changed
|
||||
- Documentation reviewed; the Xexéu references in this changelog now read Harpia.
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Adicionado
|
||||
- Relatório executivo: o botão **Relatório** na tela de análise abre `GET /relatorio`, um relatório A4 da última análise paginado pelo Paged.js empacotado, com capa sangrada (logo, selo TLP, motivo de faixas de beacon desenhado a partir dos hosts do topo), sumário, indicadores, ranking de hosts, uma seção por pilar, todos os alertas com a evidência, metodologia e glossário. Padrão `TLP:AMBER` (`?tlp=` troca) e escapa em HTML todo texto lido dos logs.
|
||||
|
||||
### Alterado
|
||||
- Documentação revisada; as referências ao Xexéu neste changelog agora citam o Harpia.
|
||||
|
||||
|
||||
@@ -1128,6 +1128,7 @@ function renderReportSummary() {
|
||||
output.textContent = t('Nenhuma análise executada.');
|
||||
$('#gotoAlerts').hidden = true;
|
||||
$('#gotoHosts').hidden = true;
|
||||
$('#openReport').hidden = true;
|
||||
return;
|
||||
}
|
||||
reportSummary.hidden = false;
|
||||
@@ -1146,6 +1147,7 @@ function renderReportSummary() {
|
||||
reportStatus.textContent = report.status || '—';
|
||||
$('#gotoAlerts').hidden = false;
|
||||
$('#gotoHosts').hidden = false;
|
||||
$('#openReport').hidden = false;
|
||||
|
||||
const lines = [
|
||||
message(
|
||||
@@ -1337,6 +1339,7 @@ async function analyzeDataset() {
|
||||
output.textContent = message('Falha na análise: {n}', error.message);
|
||||
$('#gotoAlerts').hidden = true;
|
||||
$('#gotoHosts').hidden = true;
|
||||
$('#openReport').hidden = true;
|
||||
} finally {
|
||||
analyzeBtn.disabled = false;
|
||||
}
|
||||
@@ -1561,6 +1564,7 @@ function init() {
|
||||
$('#seeAllAlerts').addEventListener('click', () => showView('alerts'));
|
||||
$('#gotoAlerts').addEventListener('click', () => showView('alerts'));
|
||||
$('#gotoHosts').addEventListener('click', () => showView('hosts'));
|
||||
$('#openReport').addEventListener('click', () => window.open('/relatorio', '_blank', 'noopener'));
|
||||
|
||||
langSel.addEventListener('change', () => {
|
||||
localStorage.setItem('acaua-lang', langSel.value);
|
||||
|
||||
@@ -103,6 +103,8 @@ export const EN = {
|
||||
'A API de fusão lista apenas hosts com pelo menos um alerta. Hosts sem alerta não aparecem nesta tabela.': 'The fusion API only lists hosts with at least one alert. Hosts without alerts do not appear in this table.',
|
||||
'Ver alertas': 'View alerts',
|
||||
'Ver hosts': 'View hosts',
|
||||
'Relatório': 'Report',
|
||||
'Abre o relatório executivo da última análise em uma nova aba': 'Opens the executive report of the latest analysis in a new tab',
|
||||
'Estado do serviço': 'Service status',
|
||||
'Versão, dataset e armazenamento informados pela API local.': 'Version, dataset and storage reported by the local API.',
|
||||
'{n} pilares ativos': '{n} active pillars',
|
||||
|
||||
@@ -279,6 +279,7 @@
|
||||
<div class="report-actions">
|
||||
<button id="gotoAlerts" type="button" class="btn" hidden>Ver alertas</button>
|
||||
<button id="gotoHosts" type="button" class="btn" hidden>Ver hosts</button>
|
||||
<button id="openReport" type="button" class="btn primary" hidden title="Abre o relatório executivo da última análise em uma nova aba">Relatório</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
Vendored
+4
@@ -6,3 +6,7 @@ the interface: the UI stays vanilla HTML, CSS and JavaScript, like Guará and
|
||||
Sabiá.
|
||||
|
||||
Document every vendored file with its project URL, version and license.
|
||||
|
||||
| File | Project | Version | License |
|
||||
| --- | --- | --- | --- |
|
||||
| `paged.polyfill.min.js` | Paged.js, https://gitlab.coko.foundation/pagedjs/pagedjs (paginates the executive report at `/relatorio`) | 0.4.3 | MIT |
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* @license Paged.js v0.4.3 | MIT | https://gitlab.coko.foundation/pagedjs/pagedjs
|
||||
*/
|
||||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PagedPolyfill=t()}(this,(function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t,n,r={exports:{}},a={exports:{}};var i,o,s,l,d=function(){},p=d(),c=function(e){return e!==p&&null!==e};function u(){return l||(l=1,s=(n?t:(n=1,t=function(){try{return Object.keys("primitive"),!0}catch(e){return!1}}))()?Object.keys:function(){if(o)return i;o=1;var e=c,t=Object.keys;return i=function(n){return t(e(n)?Object(n):n)}}()),s}var m,h,g=c,f=function(e){if(!g(e))throw new TypeError("Cannot use null or undefined");return e};var y,b,S=function(){var e,t=Object.assign;return"function"==typeof t&&(t(e={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),e.foo+e.bar+e.trzy==="razdwatrzy")}()?Object.assign:function(){if(h)return m;h=1;var e=u(),t=f,n=Math.max;return m=function(r,a){var i,o,s,l=n(arguments.length,2);for(r=Object(t(r)),s=function(e){try{r[e]=a[e]}catch(e){i||(i=e)}},o=1;o<l;++o)e(a=arguments[o]).forEach(s);if(void 0!==i)throw i;return r},m}(),v=c,x=Array.prototype.forEach,k=Object.create,w="razdwatrzy";var C,T="function"==typeof w.contains&&!0===w.contains("dwa")&&!1===w.contains("foo")?String.prototype.contains:function(){if(b)return y;b=1;var e=String.prototype.indexOf;return y=function(t){return e.call(this,t,arguments[1])>-1},y}(),_=S,z=function(e){var t=k(null);return x.call(arguments,(function(e){v(e)&&function(e,t){var n;for(n in e)t[n]=e[n]}(Object(e),t)})),t},O=function(e){return"function"==typeof e},A=T;C=a.exports=function(e,t){var n,r,a,i,o;return arguments.length<2||"string"!=typeof e?(i=t,t=e,e=null):i=arguments[2],null==e?(n=a=!0,r=!1):(n=A.call(e,"c"),r=A.call(e,"e"),a=A.call(e,"w")),o={value:t,configurable:n,enumerable:r,writable:a},i?_(z(i),o):o},C.gs=function(e,t,n){var r,a,i,o;return"string"!=typeof e?(i=n,n=t,t=e,e=null):i=arguments[3],null==t?t=void 0:O(t)?null==n?n=void 0:O(n)||(i=n,n=void 0):(i=t,t=n=void 0),null==e?(r=!0,a=!1):(r=A.call(e,"c"),a=A.call(e,"e")),o={get:t,set:n,configurable:r,enumerable:a},i?_(z(i),o):o};var E=a.exports,j=function(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return e};!function(e,t){var n,r,a,i,o,s,l,d=E,p=j,c=Function.prototype.apply,u=Function.prototype.call,m=Object.create,h=Object.defineProperty,g=Object.defineProperties,f=Object.prototype.hasOwnProperty,y={configurable:!0,enumerable:!1,writable:!0};n=function(e,t){var n;return p(t),f.call(this,"__ee__")?n=this.__ee__:(n=y.value=m(null),h(this,"__ee__",y),y.value=null),n[e]?"object"==typeof n[e]?n[e].push(t):n[e]=[n[e],t]:n[e]=t,this},r=function(e,t){var r,i;return p(t),i=this,n.call(this,e,r=function(){a.call(i,e,r),c.call(t,this,arguments)}),r.__eeOnceListener__=t,this},a=function(e,t){var n,r,a,i;if(p(t),!f.call(this,"__ee__"))return this;if(!(n=this.__ee__)[e])return this;if("object"==typeof(r=n[e]))for(i=0;a=r[i];++i)a!==t&&a.__eeOnceListener__!==t||(2===r.length?n[e]=r[i?0:1]:r.splice(i,1));else r!==t&&r.__eeOnceListener__!==t||delete n[e];return this},i=function(e){var t,n,r,a,i;if(f.call(this,"__ee__")&&(a=this.__ee__[e]))if("object"==typeof a){for(n=arguments.length,i=new Array(n-1),t=1;t<n;++t)i[t-1]=arguments[t];for(a=a.slice(),t=0;r=a[t];++t)c.call(r,this,i)}else switch(arguments.length){case 1:u.call(a,this);break;case 2:u.call(a,this,arguments[1]);break;case 3:u.call(a,this,arguments[1],arguments[2]);break;default:for(n=arguments.length,i=new Array(n-1),t=1;t<n;++t)i[t-1]=arguments[t];c.call(a,this,i)}},o={on:n,once:r,off:a,emit:i},s={on:d(n),once:d(r),off:d(a),emit:d(i)},l=g({},s),e.exports=t=function(e){return null==e?m(l):g(Object(e),s)},t.methods=o}(r,r.exports);var W=r.exports,L=e(W);class B{constructor(e){this.context=e||this,this.hooks=[]}register(){for(var e=0;e<arguments.length;++e)if("function"==typeof arguments[e])this.hooks.push(arguments[e]);else for(var t=0;t<arguments[e].length;++t)this.hooks.push(arguments[e][t])}trigger(){var e=arguments,t=this.context,n=[];return this.hooks.forEach((function(r){var a=r.apply(t,e);a&&"function"==typeof a.then?n.push(a):n.push(new Promise(((e,t)=>{e(a)})))})),Promise.all(n)}triggerSync(){var e=arguments,t=this.context,n=[];return this.hooks.forEach((function(r){var a=r.apply(t,e);n.push(a)})),n}list(){return this.hooks}clear(){return this.hooks=[]}}function P(e){if(!e)return;let t;if(void 0!==e.getBoundingClientRect)t=e.getBoundingClientRect();else{let n=document.createRange();n.selectNode(e),t=n.getBoundingClientRect()}return t}function q(e){if(!e)return;let t;if(void 0!==e.getClientRects)t=e.getClientRects();else{let n=document.createRange();n.selectNode(e),t=n.getClientRects()}return t}function M(){var e=(new Date).getTime();return"undefined"!=typeof performance&&"function"==typeof performance.now&&(e+=performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replaceLine truncated
|
||||
@@ -4,13 +4,14 @@ use acaua_core::update::UpdateStatus;
|
||||
use acaua_core::zeek::{self, AnalysisReport};
|
||||
use acaua_core::{update, Result};
|
||||
use axum::body::Body;
|
||||
use axum::extract::State;
|
||||
use axum::extract::{Query, State};
|
||||
use axum::http::{header, StatusCode, Uri};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use rust_embed::RustEmbed;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpListener;
|
||||
@@ -101,6 +102,28 @@ async fn analyze(
|
||||
})
|
||||
}
|
||||
|
||||
/// 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.last_report.lock().unwrap();
|
||||
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() -> std::result::Result<Json<UpdateStatus>, (StatusCode, Json<ErrorBody>)> {
|
||||
update::check(env!("CARGO_PKG_VERSION"))
|
||||
.map(Json)
|
||||
@@ -167,6 +190,7 @@ pub async fn serve(bind: &str, data_dir: PathBuf) -> Result<()> {
|
||||
.route("/api/alerts", get(alerts))
|
||||
.route("/api/analyze", post(analyze))
|
||||
.route("/api/update", get(update_check))
|
||||
.route("/relatorio", get(report_page))
|
||||
.route("/logo.png", get(logo))
|
||||
.fallback(asset)
|
||||
.with_state(state)
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
@@ -6,6 +6,7 @@ pub mod pillar1;
|
||||
pub mod pillar2;
|
||||
pub mod pillar3;
|
||||
pub mod pillar4;
|
||||
pub mod report;
|
||||
pub mod storage;
|
||||
pub mod update;
|
||||
pub mod zeek;
|
||||
|
||||
@@ -0,0 +1,957 @@
|
||||
//! Executive report: renders an [`AnalysisReport`] as a self-contained HTML
|
||||
//! document paginated by Paged.js (A4, cover, table of contents, margin boxes).
|
||||
//!
|
||||
//! Every string that comes from Zeek logs (hosts, domains, summaries, evidence)
|
||||
//! is attacker-controlled and goes through [`html_escape`] before it reaches
|
||||
//! the markup. The logo is embedded as a base64 data URI so the file renders
|
||||
//! offline and keeps its branding when saved.
|
||||
|
||||
use crate::fusion::Alert;
|
||||
use crate::pillar4::HostScore;
|
||||
use crate::zeek::AnalysisReport;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
const LOGO: &[u8] = include_bytes!("../../../logo.png");
|
||||
const LOGO_MARK: &[u8] = include_bytes!("../assets/logo-mark.png");
|
||||
|
||||
/// Path the web server exposes the vendored Paged.js polyfill under.
|
||||
pub const PAGED_JS_PATH: &str = "/vendor/paged.polyfill.min.js";
|
||||
|
||||
/// Traffic Light Protocol labels accepted by the report.
|
||||
pub const TLP_LEVELS: [&str; 5] = ["CLEAR", "GREEN", "AMBER", "AMBER+STRICT", "RED"];
|
||||
|
||||
/// Options that change how the report is rendered.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ReportOptions {
|
||||
/// TLP label without the `TLP:` prefix. Unknown values fall back to AMBER.
|
||||
pub tlp: String,
|
||||
/// Issue timestamp shown on the cover; `None` uses the current UTC time.
|
||||
pub issued_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for ReportOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
tlp: "AMBER".to_string(),
|
||||
issued_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalizes a user supplied TLP label; anything unknown becomes AMBER.
|
||||
pub fn normalize_tlp(raw: &str) -> &'static str {
|
||||
let upper = raw.trim().to_ascii_uppercase();
|
||||
let upper = upper.trim_start_matches("TLP:");
|
||||
TLP_LEVELS
|
||||
.iter()
|
||||
.find(|level| **level == upper)
|
||||
.copied()
|
||||
.unwrap_or("AMBER")
|
||||
}
|
||||
|
||||
/// Escapes text for HTML element content and quoted attribute values.
|
||||
pub fn html_escape(raw: &str) -> String {
|
||||
let mut out = String::with_capacity(raw.len());
|
||||
for c in raw.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn base64(bytes: &[u8]) -> String {
|
||||
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
|
||||
for chunk in bytes.chunks(3) {
|
||||
let b = [
|
||||
chunk[0],
|
||||
*chunk.get(1).unwrap_or(&0),
|
||||
*chunk.get(2).unwrap_or(&0),
|
||||
];
|
||||
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
|
||||
out.push(TABLE[(n >> 18) as usize & 63] as char);
|
||||
out.push(TABLE[(n >> 12) as usize & 63] as char);
|
||||
out.push(if chunk.len() > 1 {
|
||||
TABLE[(n >> 6) as usize & 63] as char
|
||||
} else {
|
||||
'='
|
||||
});
|
||||
out.push(if chunk.len() > 2 {
|
||||
TABLE[n as usize & 63] as char
|
||||
} else {
|
||||
'='
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `data:image/png;base64,...` URI of the full logo.
|
||||
pub fn logo_data_uri() -> String {
|
||||
format!("data:image/png;base64,{}", base64(LOGO))
|
||||
}
|
||||
|
||||
/// Small logo wrapped in an SVG data URI, usable as a CSS background in the
|
||||
/// Paged.js margin boxes.
|
||||
fn logo_mark_css_uri() -> String {
|
||||
let svg = format!(
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"128\" height=\"128\" viewBox=\"0 0 128 128\"><image width=\"128\" height=\"128\" xlink:href=\"data:image/png;base64,{}\"/></svg>",
|
||||
base64(LOGO_MARK)
|
||||
);
|
||||
format!("data:image/svg+xml;base64,{}", base64(svg.as_bytes()))
|
||||
}
|
||||
|
||||
fn num(value: f64, decimals: usize) -> String {
|
||||
if !value.is_finite() {
|
||||
return "—".to_string();
|
||||
}
|
||||
format!("{value:.decimals$}").replace('.', ",")
|
||||
}
|
||||
|
||||
fn int(value: u64) -> String {
|
||||
let digits = value.to_string();
|
||||
let mut out = String::new();
|
||||
for (i, c) in digits.chars().enumerate() {
|
||||
if i > 0 && (digits.len() - i).is_multiple_of(3) {
|
||||
out.push('.');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn ev_f64(evidence: &Value, key: &str) -> Option<f64> {
|
||||
evidence.get(key).and_then(Value::as_f64)
|
||||
}
|
||||
|
||||
fn ev_str<'a>(evidence: &'a Value, key: &str) -> Option<&'a str> {
|
||||
evidence.get(key).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
fn pillar_name(pillar: u8) -> &'static str {
|
||||
match pillar {
|
||||
1 => "Beaconing",
|
||||
2 => "Sessão persistente",
|
||||
3 => "Túnel DNS / anomalia de protocolo",
|
||||
4 => "Fusão de evidências",
|
||||
_ => "Desconhecido",
|
||||
}
|
||||
}
|
||||
|
||||
fn severity(score: f64) -> (&'static str, &'static str) {
|
||||
if score >= 0.85 {
|
||||
("crit", "Crítico")
|
||||
} else if score >= 0.65 {
|
||||
("high", "Alto")
|
||||
} else if score >= 0.40 {
|
||||
("med", "Médio")
|
||||
} else {
|
||||
("low", "Baixo")
|
||||
}
|
||||
}
|
||||
|
||||
fn score_chip(score: f64) -> String {
|
||||
let (class, label) = severity(score);
|
||||
format!(
|
||||
"<span class=\"sev sev-{class}\">{} · {label}</span>",
|
||||
num(score, 3)
|
||||
)
|
||||
}
|
||||
|
||||
/// Origin and destination of a conn based alert. The summary is built by
|
||||
/// `zeek::analyze_dir` as `"...: ORIG[:any] -> DEST:PORT (...)"`.
|
||||
fn endpoints(alert: &Alert, owner: Option<&str>) -> (String, String) {
|
||||
if let (Some(orig), Some(domain)) = (
|
||||
ev_str(&alert.evidence, "orig_h"),
|
||||
ev_str(&alert.evidence, "base_domain"),
|
||||
) {
|
||||
return (orig.to_string(), domain.to_string());
|
||||
}
|
||||
let summary = alert.summary.as_str();
|
||||
let after_colon = summary.split_once(": ").map(|(_, rest)| rest).unwrap_or("");
|
||||
let (left, right) = after_colon.split_once(" -> ").unwrap_or(("", ""));
|
||||
let orig = left.trim_end_matches(":any").to_string();
|
||||
let dest = right
|
||||
.split_once(" (")
|
||||
.map(|(d, _)| d)
|
||||
.unwrap_or(right)
|
||||
.to_string();
|
||||
let orig = if orig.is_empty() {
|
||||
owner.unwrap_or("—").to_string()
|
||||
} else {
|
||||
orig
|
||||
};
|
||||
let dest = if dest.is_empty() {
|
||||
"—".to_string()
|
||||
} else {
|
||||
dest
|
||||
};
|
||||
(orig, dest)
|
||||
}
|
||||
|
||||
fn flatten_evidence(value: &Value, prefix: &str, out: &mut Vec<(String, String)>) {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
for (k, v) in map {
|
||||
let key = if prefix.is_empty() {
|
||||
k.clone()
|
||||
} else {
|
||||
format!("{prefix}.{k}")
|
||||
};
|
||||
flatten_evidence(v, &key, out);
|
||||
}
|
||||
}
|
||||
Value::Array(items) => {
|
||||
let joined = items
|
||||
.iter()
|
||||
.take(8)
|
||||
.map(|v| match v {
|
||||
Value::String(s) => s.clone(),
|
||||
other => other.to_string(),
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let more = if items.len() > 8 { ", …" } else { "" };
|
||||
out.push((prefix.to_string(), format!("[{joined}{more}]")));
|
||||
}
|
||||
Value::Number(n) => {
|
||||
let text = match n.as_f64() {
|
||||
Some(f) if n.is_f64() => num(f, 4),
|
||||
_ => n.to_string(),
|
||||
};
|
||||
out.push((prefix.to_string(), text));
|
||||
}
|
||||
Value::String(s) => out.push((prefix.to_string(), s.clone())),
|
||||
Value::Bool(b) => out.push((prefix.to_string(), if *b { "sim" } else { "não" }.into())),
|
||||
Value::Null => out.push((prefix.to_string(), "—".into())),
|
||||
}
|
||||
}
|
||||
|
||||
struct Ctx<'a> {
|
||||
report: &'a AnalysisReport,
|
||||
owner: HashMap<&'a str, &'a str>,
|
||||
by_id: HashMap<&'a str, &'a Alert>,
|
||||
}
|
||||
|
||||
impl<'a> Ctx<'a> {
|
||||
fn new(report: &'a AnalysisReport) -> Self {
|
||||
let mut owner = HashMap::new();
|
||||
for host in &report.hosts {
|
||||
for term in &host.terms {
|
||||
if let Some(id) = &term.alert_id {
|
||||
owner.insert(id.as_str(), host.orig_h.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
let by_id = report.alerts.iter().map(|a| (a.id.as_str(), a)).collect();
|
||||
Self {
|
||||
report,
|
||||
owner,
|
||||
by_id,
|
||||
}
|
||||
}
|
||||
|
||||
fn alerts_of(&self, pillar: u8) -> Vec<&'a Alert> {
|
||||
let mut list: Vec<&Alert> = self
|
||||
.report
|
||||
.alerts
|
||||
.iter()
|
||||
.filter(|a| a.pillar == pillar)
|
||||
.collect();
|
||||
list.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.id.cmp(&b.id)));
|
||||
list
|
||||
}
|
||||
|
||||
fn host_alert(&self, host: &HostScore, pillar: u8) -> Option<&'a Alert> {
|
||||
host.terms
|
||||
.iter()
|
||||
.find(|t| t.pillar == pillar)
|
||||
.and_then(|t| t.alert_id.as_deref())
|
||||
.and_then(|id| self.by_id.get(id).copied())
|
||||
}
|
||||
|
||||
fn endpoints(&self, alert: &Alert) -> (String, String) {
|
||||
endpoints(alert, self.owner.get(alert.id.as_str()).copied())
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted_hosts(report: &AnalysisReport) -> Vec<&HostScore> {
|
||||
let mut hosts: Vec<&HostScore> = report.hosts.iter().collect();
|
||||
hosts.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.orig_h.cmp(&b.orig_h)));
|
||||
hosts
|
||||
}
|
||||
|
||||
/// Cover motif: one beacon lane per top host. Lanes with a Pilar 1 alert get
|
||||
/// ticks spaced by the detected period, Pilar 2 shows as a bar sized by
|
||||
/// session hours, Pilar 3 as a dense burst. Opacity follows the fused score.
|
||||
fn cover_motif(ctx: &Ctx) -> String {
|
||||
let hosts = sorted_hosts(ctx.report);
|
||||
let lanes = hosts.len().clamp(1, 9);
|
||||
let mut svg = String::from(
|
||||
"<svg class=\"motif\" viewBox=\"0 0 210 120\" preserveAspectRatio=\"none\" aria-hidden=\"true\">",
|
||||
);
|
||||
let gap = 120.0 / (lanes as f64 + 1.0);
|
||||
for i in 0..lanes {
|
||||
let y = gap * (i as f64 + 1.0);
|
||||
let _ = write!(
|
||||
svg,
|
||||
"<line x1=\"0\" y1=\"{y:.2}\" x2=\"210\" y2=\"{y:.2}\" stroke=\"#45d6b0\" stroke-opacity=\"0.14\" stroke-width=\"0.25\"/>"
|
||||
);
|
||||
let Some(host) = hosts.get(i) else { continue };
|
||||
let opacity = 0.30 + 0.70 * host.score.clamp(0.0, 1.0);
|
||||
let color = if host.score >= 0.70 {
|
||||
"#f0b35b"
|
||||
} else {
|
||||
"#45d6b0"
|
||||
};
|
||||
if let Some(alert) = ctx.host_alert(host, 1) {
|
||||
let period = ev_f64(&alert.evidence, "period_detected_seconds").unwrap_or(3600.0);
|
||||
let spacing = (2.5 + period.max(1.0).log10() * 2.2).clamp(3.0, 16.0);
|
||||
let mut x = 78.0 + (i as f64 * 1.7) % spacing;
|
||||
while x < 206.0 {
|
||||
let _ = write!(
|
||||
svg,
|
||||
"<line x1=\"{x:.2}\" y1=\"{:.2}\" x2=\"{x:.2}\" y2=\"{:.2}\" stroke=\"{color}\" stroke-opacity=\"{opacity:.2}\" stroke-width=\"0.7\" stroke-linecap=\"round\"/>",
|
||||
y - 2.6,
|
||||
y + 2.6
|
||||
);
|
||||
x += spacing;
|
||||
}
|
||||
}
|
||||
if let Some(alert) = ctx.host_alert(host, 2) {
|
||||
let hours = ev_f64(&alert.evidence, "longest_session_seconds").unwrap_or(0.0) / 3600.0;
|
||||
let len = (20.0 + hours * 6.0).clamp(20.0, 150.0);
|
||||
let _ = write!(
|
||||
svg,
|
||||
"<rect x=\"84\" y=\"{:.2}\" width=\"{len:.2}\" height=\"1.6\" rx=\"0.8\" fill=\"{color}\" fill-opacity=\"{:.2}\"/>",
|
||||
y - 0.8,
|
||||
opacity * 0.8
|
||||
);
|
||||
}
|
||||
if let Some(alert) = ctx.host_alert(host, 3) {
|
||||
let unique = ev_f64(&alert.evidence, "unique_subdomains").unwrap_or(40.0);
|
||||
let count = (unique / 4.0).clamp(10.0, 60.0) as usize;
|
||||
for k in 0..count {
|
||||
let jitter = ((k * 37 + i * 11) % 17) as f64 / 17.0;
|
||||
let x = 120.0 + k as f64 * 1.4 + jitter;
|
||||
let h = 1.0 + jitter * 2.0;
|
||||
let _ = write!(
|
||||
svg,
|
||||
"<line x1=\"{x:.2}\" y1=\"{:.2}\" x2=\"{x:.2}\" y2=\"{:.2}\" stroke=\"#fb923c\" stroke-opacity=\"{:.2}\" stroke-width=\"0.45\"/>",
|
||||
y - h,
|
||||
y + h,
|
||||
opacity * 0.9
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
svg.push_str("</svg>");
|
||||
svg
|
||||
}
|
||||
|
||||
const CSS: &str = r#"
|
||||
:root{
|
||||
--ink:#0d1f1a;--muted:#55665f;--line:#d7e2dd;--paper:#ffffff;--tint:#f2f8f5;
|
||||
--accent:#087f68;--accent-2:#45d6b0;--gold:#f0b35b;--orange:#f97316;--orange-2:#fb923c;
|
||||
--crit:#b42318;--high:#c2410c;--med:#a16207;--low:#4b6b61;
|
||||
--sans:system-ui,"Inter","Segoe UI",Roboto,sans-serif;
|
||||
--mono:ui-monospace,"JetBrains Mono","IBM Plex Mono",monospace;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
html,body{margin:0;background:var(--paper);color:var(--ink);font-family:var(--sans);font-size:10pt;line-height:1.5}
|
||||
@page{size:A4;margin:22mm 16mm 20mm 16mm;
|
||||
@top-left{content:"";background-image:var(--logo-mark);background-size:contain;background-repeat:no-repeat;background-position:left center;width:9mm;height:9mm;margin-top:8mm}
|
||||
@top-center{content:"ACAUÃ · RELATÓRIO EXECUTIVO";font-family:var(--mono);font-size:7pt;letter-spacing:.14em;color:#55665f;margin-top:8mm}
|
||||
@top-right{content:var(--tlp-label);font-family:var(--mono);font-size:7pt;font-weight:700;letter-spacing:.08em;color:#a15c00;margin-top:8mm}
|
||||
@bottom-left{content:"Ciberfauna · Acauã · uso autorizado";font-family:var(--mono);font-size:7pt;color:#55665f}
|
||||
@bottom-right{content:counter(page) " / " counter(pages);font-family:var(--mono);font-size:7pt;color:#55665f}
|
||||
}
|
||||
@page cover{margin:0;@top-left{content:none}@top-center{content:none}@top-right{content:none}@bottom-left{content:none}@bottom-right{content:none}}
|
||||
.cover{page:cover;break-after:page;position:relative;width:210mm;height:297mm;overflow:hidden;color:#e8f5f0;
|
||||
background:radial-gradient(120% 80% at 80% 55%,#0d3a2f 0%,#06201a 45%,#030d0a 100%)}
|
||||
.cover .glow{position:absolute;left:70mm;top:92mm;width:160mm;height:160mm;border-radius:50%;
|
||||
background:radial-gradient(circle,rgba(249,115,22,.42) 0%,rgba(251,146,60,.16) 38%,rgba(249,115,22,0) 68%)}
|
||||
.cover .motif{position:absolute;left:0;top:112mm;width:210mm;height:120mm;opacity:.9}
|
||||
.cover .logo{position:absolute;left:86mm;top:100mm;width:136mm;height:136mm;object-fit:contain;filter:drop-shadow(0 6mm 10mm rgba(0,0,0,.55))}
|
||||
.cover .topbar{position:absolute;left:18mm;right:18mm;top:14mm;display:flex;justify-content:space-between;align-items:center}
|
||||
.wordmark{font-weight:800;letter-spacing:.42em;font-size:11pt;color:#fff}
|
||||
.tlp-wrap{display:flex;gap:3mm;align-items:center;font-family:var(--mono);font-size:7.5pt;letter-spacing:.12em}
|
||||
.tlp{display:inline-block;border:1.2px solid var(--tlp-color);color:var(--tlp-color);border-radius:999px;padding:1mm 3.2mm;font-family:var(--mono);font-weight:700;font-size:7.5pt;letter-spacing:.08em;background:rgba(0,0,0,.25)}
|
||||
.auth{color:#9fc7ba}
|
||||
.cover .head{position:absolute;left:18mm;right:18mm;top:34mm}
|
||||
.eyebrow{font-family:var(--mono);font-size:8pt;letter-spacing:.2em;color:var(--orange-2);text-transform:uppercase}
|
||||
.cover h1{font-size:50px;line-height:1.02;font-weight:800;letter-spacing:-.03em;margin:4mm 0 4mm;color:#fff;max-width:165mm}
|
||||
.cover .sub{font-size:11.5pt;color:#b9d8cd;max-width:150mm;margin:0}
|
||||
.cover .numbers{position:absolute;left:18mm;top:128mm;width:66mm;display:flex;flex-direction:column;gap:6mm}
|
||||
.cover .numbers div{border-left:2px solid var(--accent-2);padding-left:4mm}
|
||||
.cover .numbers b{display:block;font-size:26pt;font-weight:800;line-height:1;color:#fff;letter-spacing:-.02em}
|
||||
.cover .numbers span{font-family:var(--mono);font-size:7pt;letter-spacing:.14em;text-transform:uppercase;color:#9fc7ba}
|
||||
.cover .meta{position:absolute;left:18mm;right:18mm;bottom:14mm;border-top:1px solid rgba(232,245,240,.25);padding-top:4mm;display:grid;grid-template-columns:1fr 1.6fr 1fr 1fr;gap:5mm}
|
||||
.cover .meta span{display:block;font-family:var(--mono);font-size:6.5pt;letter-spacing:.16em;text-transform:uppercase;color:#86b3a5}
|
||||
.cover .meta b{display:block;font-size:9pt;font-weight:600;color:#fff;word-break:break-all}
|
||||
section{break-before:page}
|
||||
section.flow{break-before:auto;margin-top:8mm}
|
||||
h2{font-size:18pt;font-weight:800;letter-spacing:-.02em;margin:0 0 3mm;padding-top:4mm;position:relative;break-after:avoid}
|
||||
h2::before{content:"";position:absolute;top:0;left:0;width:14mm;height:3px;background:var(--accent);border-radius:2px}
|
||||
h3{font-size:11.5pt;margin:6mm 0 2mm;break-after:avoid}
|
||||
p{margin:0 0 3mm}
|
||||
.lead{font-size:11pt;color:#22352f}
|
||||
.muted{color:var(--muted)}
|
||||
.mono{font-family:var(--mono)}
|
||||
.toc ol{list-style:none;padding:0;margin:6mm 0 0}
|
||||
.toc li{border-bottom:1px solid var(--line);padding:2.6mm 0}
|
||||
.toc a{display:flex;color:var(--ink);text-decoration:none;font-size:11pt}
|
||||
.toc a span.n{font-family:var(--mono);color:var(--accent);width:10mm}
|
||||
.toc a span.t{flex:1}
|
||||
.toc a::after{content:target-counter(attr(href),page);font-family:var(--mono);color:var(--muted)}
|
||||
.kpis{display:grid;grid-template-columns:repeat(3,1fr);gap:4mm;margin:5mm 0}
|
||||
.kpi{border-top:3px solid var(--accent);background:var(--tint);padding:3mm 4mm;break-inside:avoid}
|
||||
.kpi.warn{border-top-color:var(--orange)}
|
||||
.kpi b{display:block;font-size:20pt;font-weight:800;letter-spacing:-.02em;line-height:1.1}
|
||||
.kpi span{font-family:var(--mono);font-size:7pt;letter-spacing:.12em;text-transform:uppercase;color:var(--muted)}
|
||||
.callout{border-left:3px solid var(--accent);background:var(--tint);padding:3mm 4mm;margin:4mm 0;break-inside:avoid}
|
||||
.callout.act{border-left-color:var(--orange)}
|
||||
.callout strong{font-family:var(--mono);font-size:7.5pt;letter-spacing:.14em;text-transform:uppercase;display:block;margin-bottom:1mm;color:var(--accent)}
|
||||
.callout.act strong{color:var(--high)}
|
||||
table{width:100%;border-collapse:collapse;margin:3mm 0 5mm;font-size:8.5pt}
|
||||
thead{display:table-header-group}
|
||||
th{text-align:left;font-family:var(--mono);font-size:7pt;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);border-bottom:1.5px solid var(--ink);padding:1.6mm 2mm}
|
||||
td{padding:1.6mm 2mm;border-bottom:1px solid var(--line);vertical-align:top;word-break:break-word}
|
||||
tbody tr:nth-child(even) td{background:var(--tint)}
|
||||
tr{break-inside:avoid}
|
||||
td.num,th.num{text-align:right;font-variant-numeric:tabular-nums}
|
||||
.sev{display:inline-block;font-family:var(--mono);font-size:7pt;font-weight:700;padding:.3mm 1.6mm;border-radius:3px;white-space:nowrap}
|
||||
.sev-crit{background:#fde8e6;color:var(--crit)}.sev-high{background:#fff0e5;color:var(--high)}
|
||||
.sev-med{background:#fdf5df;color:var(--med)}.sev-low{background:#eaf2ef;color:var(--low)}
|
||||
.card{border:1px solid var(--line);border-radius:2mm;padding:3mm 4mm;margin:0 0 4mm;break-inside:avoid}
|
||||
.card header{display:flex;justify-content:space-between;gap:3mm;align-items:baseline;margin-bottom:1.5mm}
|
||||
.card header .id{font-family:var(--mono);font-size:8pt;color:var(--muted)}
|
||||
.card .sum{font-family:var(--mono);font-size:8pt;margin:0 0 2mm;word-break:break-all}
|
||||
.ev{display:grid;grid-template-columns:repeat(2,1fr);gap:.6mm 5mm;font-size:7.5pt;margin:0}
|
||||
.ev div{display:flex;justify-content:space-between;gap:2mm;border-bottom:1px dotted var(--line)}
|
||||
.ev dt{font-family:var(--mono);color:var(--muted)}
|
||||
.ev dd{margin:0;font-family:var(--mono);text-align:right;word-break:break-all}
|
||||
.empty{color:var(--muted);font-style:italic}
|
||||
.gloss dt{font-weight:700;margin-top:3mm}
|
||||
.gloss dd{margin:0 0 0 0;color:#22352f}
|
||||
.pill{font-family:var(--mono);font-size:7pt;color:var(--accent);letter-spacing:.1em;text-transform:uppercase}
|
||||
"#;
|
||||
|
||||
/// Renders the executive report with the default options (TLP:AMBER, now).
|
||||
pub fn render_html(report: &AnalysisReport) -> String {
|
||||
render_html_with(report, &ReportOptions::default())
|
||||
}
|
||||
|
||||
/// Renders the executive report as a standalone HTML document.
|
||||
pub fn render_html_with(report: &AnalysisReport, options: &ReportOptions) -> String {
|
||||
let ctx = Ctx::new(report);
|
||||
let tlp = normalize_tlp(&options.tlp);
|
||||
let tlp_color = match tlp {
|
||||
"CLEAR" => "#e5e7eb",
|
||||
"GREEN" => "#4ade80",
|
||||
"RED" => "#f87171",
|
||||
_ => "#f0b35b",
|
||||
};
|
||||
let issued = options.issued_at.clone().unwrap_or_else(|| {
|
||||
let format = time::macros::format_description!("[day]/[month]/[year] [hour]:[minute] UTC");
|
||||
OffsetDateTime::now_utc()
|
||||
.format(&format)
|
||||
.unwrap_or_else(|_| "—".to_string())
|
||||
});
|
||||
let hosts = sorted_hosts(report);
|
||||
let p1 = ctx.alerts_of(1);
|
||||
let p2 = ctx.alerts_of(2);
|
||||
let p3 = ctx.alerts_of(3);
|
||||
let top_score = hosts.first().map(|h| h.score).unwrap_or(0.0);
|
||||
let critical = hosts.iter().filter(|h| h.score >= 0.85).count();
|
||||
let multi = hosts
|
||||
.iter()
|
||||
.filter(|h| h.terms.iter().filter(|t| t.m > 0.0).count() >= 2)
|
||||
.count();
|
||||
|
||||
let mut h = String::with_capacity(2 * 1024 * 1024);
|
||||
h.push_str("<!doctype html>\n<html lang=\"pt-BR\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Acauã · Relatório executivo</title>\n<style>");
|
||||
let _ = write!(
|
||||
h,
|
||||
":root{{--logo-mark:url(\"{}\");--tlp-label:\"TLP:{tlp}\";--tlp-color:{tlp_color}}}",
|
||||
logo_mark_css_uri()
|
||||
);
|
||||
h.push_str(CSS);
|
||||
h.push_str("</style>\n</head>\n<body>\n");
|
||||
|
||||
// ------------------------------------------------------------ cover
|
||||
let tlp_html = html_escape(tlp);
|
||||
h.push_str("<div class=\"cover\">\n<div class=\"glow\"></div>\n");
|
||||
h.push_str(&cover_motif(&ctx));
|
||||
let _ = write!(
|
||||
h,
|
||||
"\n<img class=\"logo\" src=\"{}\" alt=\"Logo do Acauã\">\n",
|
||||
logo_data_uri()
|
||||
);
|
||||
let _ = write!(
|
||||
h,
|
||||
"<div class=\"topbar\"><span class=\"wordmark\">ACAUÃ</span><span class=\"tlp-wrap\"><span class=\"auth\">USO AUTORIZADO</span><span class=\"tlp\">TLP:{tlp_html}</span></span></div>"
|
||||
);
|
||||
h.push_str("<div class=\"head\"><div class=\"eyebrow\">Ciberfauna · Detecção de ameaças em tráfego de rede</div><h1>Relatório executivo de caça a ameaças</h1><p class=\"sub\">Análise determinística de logs Zeek: beaconing, sessões persistentes, túneis DNS e fusão de evidências por host.</p></div>\n");
|
||||
let _ = write!(
|
||||
h,
|
||||
"<div class=\"numbers\"><div><b>{}</b><span>alertas</span></div><div><b>{}</b><span>hosts priorizados</span></div><div><b>{}</b><span>maior score de host</span></div><div><b>{}</b><span>registros lidos</span></div></div>",
|
||||
report.alerts.len(),
|
||||
report.hosts.len(),
|
||||
num(top_score, 2),
|
||||
int(report.records)
|
||||
);
|
||||
let _ = write!(
|
||||
h,
|
||||
"<div class=\"meta\"><div><span>Emissão</span><b>{}</b></div><div><span>Escopo</span><b>{}</b></div><div><span>Achados</span><b>{} alertas · {} hosts</b></div><div><span>Classificação</span><b>TLP:{tlp_html}</b></div></div>\n</div>",
|
||||
html_escape(&issued),
|
||||
// the cover only names the folder; the full path is in "Escopo da análise"
|
||||
html_escape(
|
||||
report
|
||||
.directory
|
||||
.trim_end_matches(['/', '\\'])
|
||||
.rsplit(['/', '\\'])
|
||||
.next()
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or(&report.directory)
|
||||
),
|
||||
report.alerts.len(),
|
||||
report.hosts.len()
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------ TOC
|
||||
let sections = [
|
||||
("resumo", "Sumário executivo"),
|
||||
("hosts", "Hosts priorizados"),
|
||||
("pilar1", "Pilar 1 · Beaconing"),
|
||||
("pilar2", "Pilar 2 · Sessões persistentes"),
|
||||
("pilar3", "Pilar 3 · Túneis DNS e anomalias de protocolo"),
|
||||
("pilar4", "Pilar 4 · Fusão de evidências"),
|
||||
("alertas", "Alertas e evidências"),
|
||||
("metodologia", "Metodologia e glossário"),
|
||||
("escopo", "Escopo da análise"),
|
||||
];
|
||||
h.push_str("<section class=\"toc\"><h2>Sumário</h2><ol>");
|
||||
for (i, (id, title)) in sections.iter().enumerate() {
|
||||
let _ = write!(
|
||||
h,
|
||||
"<li><a href=\"#{id}\"><span class=\"n\">{:02}</span><span class=\"t\">{title}</span></a></li>",
|
||||
i + 1
|
||||
);
|
||||
}
|
||||
h.push_str("</ol></section>\n");
|
||||
|
||||
// ------------------------------------------------------------ summary
|
||||
h.push_str("<section id=\"resumo\"><h2>Sumário executivo</h2>");
|
||||
let _ = write!(
|
||||
h,
|
||||
"<p class=\"lead\">O Acauã leu {} arquivo(s) de log Zeek ({} de DNS), com {} registros, e produziu {} alerta(s) em {} host(s) de origem. Os scores são determinísticos e reproduzíveis: cada número vem acompanhado da evidência em JSON que o gerou.</p>",
|
||||
report.logs_seen,
|
||||
report.dns_logs_seen,
|
||||
int(report.records),
|
||||
report.alerts.len(),
|
||||
report.hosts.len()
|
||||
);
|
||||
let _ = write!(
|
||||
h,
|
||||
"<div class=\"kpis\"><div class=\"kpi\"><b>{}</b><span>Beaconing (P1)</span></div><div class=\"kpi\"><b>{}</b><span>Sessões persistentes (P2)</span></div><div class=\"kpi\"><b>{}</b><span>Túneis DNS (P3)</span></div><div class=\"kpi warn\"><b>{}</b><span>Hosts com score ≥ 0,85</span></div><div class=\"kpi\"><b>{}</b><span>Hosts com 2+ pilares</span></div><div class=\"kpi\"><b>{}</b><span>Maior score fundido</span></div></div>",
|
||||
p1.len(),
|
||||
p2.len(),
|
||||
p3.len(),
|
||||
critical,
|
||||
multi,
|
||||
num(top_score, 3)
|
||||
);
|
||||
if let Some(top) = hosts.first() {
|
||||
let pillars: Vec<String> = top
|
||||
.terms
|
||||
.iter()
|
||||
.filter(|t| t.m > 0.0)
|
||||
.map(|t| format!("P{}", t.pillar))
|
||||
.collect();
|
||||
let _ = write!(
|
||||
h,
|
||||
"<div class=\"callout\"><strong>Leitura</strong>O host de maior prioridade é <span class=\"mono\">{}</span>, com score fundido {} a partir de {}. Hosts que aparecem em mais de um pilar acumulam evidências independentes e merecem atenção primeiro.</div>",
|
||||
html_escape(&top.orig_h),
|
||||
num(top.score, 3),
|
||||
if pillars.is_empty() {
|
||||
"nenhum pilar".to_string()
|
||||
} else {
|
||||
pillars.join(", ")
|
||||
}
|
||||
);
|
||||
h.push_str("<div class=\"callout act\"><strong>Ação</strong>Valide os hosts do topo do ranking com o responsável pela máquina, confira os destinos e domínios listados contra inteligência de ameaças e, se confirmado, isole o host e bloqueie o destino no perímetro.</div>");
|
||||
} else {
|
||||
h.push_str("<div class=\"callout\"><strong>Leitura</strong>Nenhum alerta atingiu os limiares dos pilares neste recorte. Isso não prova ausência de ameaça: confira se o período e os logs analisados cobrem o tráfego de interesse.</div>");
|
||||
}
|
||||
h.push_str("</section>\n");
|
||||
|
||||
// ------------------------------------------------------------ hosts
|
||||
h.push_str("<section id=\"hosts\" class=\"flow\"><h2>Hosts priorizados</h2><p>Ranking por score fundido (Pilar 4). As colunas m1, m2 e m3 são as massas de evidência de cada pilar que entram na combinação.</p>");
|
||||
if hosts.is_empty() {
|
||||
h.push_str("<p class=\"empty\">Nenhum host com alerta.</p>");
|
||||
} else {
|
||||
h.push_str("<table><thead><tr><th>#</th><th>Host de origem</th><th class=\"num\">m1</th><th class=\"num\">m2</th><th class=\"num\">m3</th><th>Score fundido</th></tr></thead><tbody>");
|
||||
for (i, host) in hosts.iter().enumerate() {
|
||||
let m = |p: u8| {
|
||||
host.terms
|
||||
.iter()
|
||||
.find(|t| t.pillar == p)
|
||||
.map(|t| num(t.m, 3))
|
||||
.unwrap_or_else(|| "—".into())
|
||||
};
|
||||
let _ = write!(
|
||||
h,
|
||||
"<tr><td class=\"num\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td>{}</td></tr>",
|
||||
i + 1,
|
||||
html_escape(&host.orig_h),
|
||||
m(1),
|
||||
m(2),
|
||||
m(3),
|
||||
score_chip(host.score)
|
||||
);
|
||||
}
|
||||
h.push_str("</tbody></table>");
|
||||
}
|
||||
h.push_str("</section>\n");
|
||||
|
||||
// ------------------------------------------------------------ pillar 1
|
||||
h.push_str("<section id=\"pilar1\" class=\"flow\"><h2>Pilar 1 · Beaconing</h2><p>Implantes de comando e controle costumam chamar o servidor em intervalos regulares, mesmo espaçados por horas. O pilar procura periodicidade nos horários de início das conexões de cada tupla (origem, destino, porta) com um periodograma de Rayleigh/Schuster e exige significância e regularidade. Alerta a partir de score 0,40.</p>");
|
||||
if p1.is_empty() {
|
||||
h.push_str("<p class=\"empty\">Nenhum alerta de beaconing neste recorte.</p>");
|
||||
} else {
|
||||
h.push_str("<table><thead><tr><th>Origem</th><th>Destino</th><th class=\"num\">Período</th><th class=\"num\">Obs.</th><th class=\"num\">p-valor</th><th>Score</th></tr></thead><tbody>");
|
||||
for a in &p1 {
|
||||
let (o, d) = ctx.endpoints(a);
|
||||
let period = ev_f64(&a.evidence, "period_detected_seconds").unwrap_or(f64::NAN);
|
||||
let _ = write!(
|
||||
h,
|
||||
"<tr><td class=\"mono\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{} s</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td>{}</td></tr>",
|
||||
html_escape(&o),
|
||||
html_escape(&d),
|
||||
num(period, 0),
|
||||
ev_f64(&a.evidence, "observations").map(|v| int(v as u64)).unwrap_or_else(|| "—".into()),
|
||||
ev_f64(&a.evidence, "p_value").map(|v| format!("{v:.2e}")).unwrap_or_else(|| "—".into()),
|
||||
score_chip(a.score)
|
||||
);
|
||||
}
|
||||
h.push_str("</tbody></table>");
|
||||
}
|
||||
let _ = write!(
|
||||
h,
|
||||
"<p class=\"muted\">Tuplas excluídas antes do cálculo: {} fora de TCP/UDP, {} multicast ou broadcast, {} em portas de infraestrutura (DNS, NTP, DHCP, NetBIOS, SSDP, mDNS, LLMNR).</p></section>",
|
||||
report.p1_excluded.non_tcp_udp,
|
||||
report.p1_excluded.multicast_broadcast,
|
||||
report.p1_excluded.infra_port
|
||||
);
|
||||
|
||||
// ------------------------------------------------------------ pillar 2
|
||||
h.push_str("<section id=\"pilar2\" class=\"flow\"><h2>Pilar 2 · Sessões persistentes</h2><p>Conexões TCP que ficam abertas por horas são típicas de shells reversos e túneis. O Zeek divide sessões longas por timeout de inatividade; o pilar reencadeia as partes (intervalo de até 3600 s sem novo SYN) e pontua a duração em escala logarítmica, registrando PCR e tentativas falhas. Alerta a partir de score 0,2181.</p>");
|
||||
if p2.is_empty() {
|
||||
h.push_str("<p class=\"empty\">Nenhuma sessão persistente acima do limiar.</p>");
|
||||
} else {
|
||||
h.push_str("<table><thead><tr><th>Origem</th><th>Destino</th><th class=\"num\">Duração</th><th class=\"num\">Partes</th><th class=\"num\">PCR</th><th class=\"num\">Bytes/h</th><th>Score</th></tr></thead><tbody>");
|
||||
for a in &p2 {
|
||||
let (o, d) = ctx.endpoints(a);
|
||||
let _ = write!(
|
||||
h,
|
||||
"<tr><td class=\"mono\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{} h</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td>{}</td></tr>",
|
||||
html_escape(&o),
|
||||
html_escape(&d),
|
||||
num(ev_f64(&a.evidence, "longest_session_seconds").unwrap_or(f64::NAN) / 3600.0, 1),
|
||||
ev_f64(&a.evidence, "parts").map(|v| int(v as u64)).unwrap_or_else(|| "—".into()),
|
||||
num(ev_f64(&a.evidence, "pcr").unwrap_or(f64::NAN), 2),
|
||||
ev_f64(&a.evidence, "bytes_per_hour").map(|v| int(v.max(0.0) as u64)).unwrap_or_else(|| "—".into()),
|
||||
score_chip(a.score)
|
||||
);
|
||||
}
|
||||
h.push_str("</tbody></table>");
|
||||
}
|
||||
h.push_str("</section>\n");
|
||||
|
||||
// ------------------------------------------------------------ pillar 3
|
||||
h.push_str("<section id=\"pilar3\" class=\"flow\"><h2>Pilar 3 · Túneis DNS e anomalias de protocolo</h2><p>Túneis DNS escondem dados nos subdomínios das consultas. O pilar mede, por host e domínio base, a capacidade de informação por hora UTC: entropia de Shannon multiplicada pelos caracteres de subdomínios únicos. A divergência JSD aparece só como contexto (peso 0) e nunca altera o score. Alerta a partir de score 0,40.</p>");
|
||||
if p3.is_empty() {
|
||||
h.push_str("<p class=\"empty\">Nenhuma anomalia DNS acima do limiar.</p>");
|
||||
} else {
|
||||
h.push_str("<table><thead><tr><th>Origem</th><th>Domínio base</th><th class=\"num\">Subd. únicos</th><th class=\"num\">Bits</th><th class=\"num\">Entropia</th><th class=\"num\">NXDOMAIN</th><th>Score</th></tr></thead><tbody>");
|
||||
for a in &p3 {
|
||||
let (o, d) = ctx.endpoints(a);
|
||||
let _ = write!(
|
||||
h,
|
||||
"<tr><td class=\"mono\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}%</td><td>{}</td></tr>",
|
||||
html_escape(&o),
|
||||
html_escape(&d),
|
||||
ev_f64(&a.evidence, "unique_subdomains").map(|v| int(v as u64)).unwrap_or_else(|| "—".into()),
|
||||
ev_f64(&a.evidence, "information_bits").map(|v| int(v.max(0.0) as u64)).unwrap_or_else(|| "—".into()),
|
||||
num(ev_f64(&a.evidence, "entropy_bits_per_char").unwrap_or(f64::NAN), 2),
|
||||
num(ev_f64(&a.evidence, "nxdomain_ratio").unwrap_or(f64::NAN) * 100.0, 1),
|
||||
score_chip(a.score)
|
||||
);
|
||||
}
|
||||
h.push_str("</tbody></table>");
|
||||
}
|
||||
h.push_str("</section>\n");
|
||||
|
||||
// ------------------------------------------------------------ pillar 4
|
||||
h.push_str("<section id=\"pilar4\" class=\"flow\"><h2>Pilar 4 · Fusão de evidências</h2><p>Cada host recebe um score único pela combinação noisy-OR ponderada das evidências dos três pilares: S = 1 − ∏(1 − wᵢ·mᵢ), com w₁ = w₂ = w₃ = 0,75. Evidências independentes reforçam umas às outras, mas nenhum pilar sozinho chega a 1.</p>");
|
||||
if hosts.is_empty() {
|
||||
h.push_str("<p class=\"empty\">Sem hosts para fundir.</p>");
|
||||
} else {
|
||||
if let Some(top) = hosts.first() {
|
||||
let _ = write!(
|
||||
h,
|
||||
"<p class=\"muted\">Método {} · fórmula {}.</p>",
|
||||
html_escape(top.method),
|
||||
html_escape(top.formula_version)
|
||||
);
|
||||
}
|
||||
h.push_str("<table><thead><tr><th>Host</th><th>Termos (pilar: w·m)</th><th class=\"num\">∏(1 − w·m)</th><th>Score</th></tr></thead><tbody>");
|
||||
for host in &hosts {
|
||||
let terms = host
|
||||
.terms
|
||||
.iter()
|
||||
.map(|t| format!("P{}: {}", t.pillar, num(t.weighted, 3)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" · ");
|
||||
let _ = write!(
|
||||
h,
|
||||
"<tr><td class=\"mono\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{}</td><td>{}</td></tr>",
|
||||
html_escape(&host.orig_h),
|
||||
html_escape(&terms),
|
||||
num(host.product, 4),
|
||||
score_chip(host.score)
|
||||
);
|
||||
}
|
||||
h.push_str("</tbody></table>");
|
||||
}
|
||||
h.push_str("</section>\n");
|
||||
|
||||
// ------------------------------------------------------------ alerts
|
||||
h.push_str("<section id=\"alertas\"><h2>Alertas e evidências</h2><p>Cada alerta traz o resumo gerado pelo motor e a evidência JSON achatada em pares chave e valor, na ordem em que o motor a registrou.</p>");
|
||||
if report.alerts.is_empty() {
|
||||
h.push_str("<p class=\"empty\">Nenhum alerta.</p>");
|
||||
}
|
||||
let mut ordered: Vec<&Alert> = report.alerts.iter().collect();
|
||||
ordered.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.id.cmp(&b.id)));
|
||||
for a in ordered {
|
||||
let mut pairs = Vec::new();
|
||||
flatten_evidence(&a.evidence, "", &mut pairs);
|
||||
let _ = write!(
|
||||
h,
|
||||
"<article class=\"card\"><header><span><span class=\"pill\">Pilar {} · {}</span></span><span>{} <span class=\"id\">{}</span></span></header><p class=\"sum\">{}</p><dl class=\"ev\">",
|
||||
a.pillar,
|
||||
pillar_name(a.pillar),
|
||||
score_chip(a.score),
|
||||
html_escape(&a.id),
|
||||
html_escape(&a.summary)
|
||||
);
|
||||
for (k, v) in &pairs {
|
||||
let _ = write!(
|
||||
h,
|
||||
"<div><dt>{}</dt><dd>{}</dd></div>",
|
||||
html_escape(k),
|
||||
html_escape(v)
|
||||
);
|
||||
}
|
||||
h.push_str("</dl></article>");
|
||||
}
|
||||
h.push_str("</section>\n");
|
||||
|
||||
// ------------------------------------------------------------ methodology
|
||||
h.push_str(concat!(
|
||||
"<section id=\"metodologia\"><h2>Metodologia e glossário</h2>",
|
||||
"<p>O Acauã é determinístico: mesma entrada, mesmos scores. Não há modelo opaco; cada pilar é uma fórmula versionada, validada com fixtures sintéticas e capturas públicas, e todo alerta carrega a evidência que o justifica.</p>",
|
||||
"<dl class=\"gloss\">",
|
||||
"<dt>Pilar 1 · Beaconing (v1.2)</dt><dd>Periodicidade sobre os horários de início das conexões com periodograma de Rayleigh/Schuster limitado ao intervalo observado, portão de significância por regularidade (MADM e assimetria de Bowley) e exclusão de portas de infraestrutura. Exige ao menos 20 observações.</dd>",
|
||||
"<dt>Pilar 2 · Sessões persistentes (v1.0)</dt><dd>Conexões TCP longas reencadeadas através dos timeouts de inatividade do Zeek, score logarítmico de persistência, PCR e contagem de tentativas falhas.</dd>",
|
||||
"<dt>Pilar 3 · Anomalias de protocolo (v1.0)</dt><dd>Capacidade de informação em subdomínios DNS únicos por hora UTC (entropia × caracteres), com taxa de NXDOMAIN e distribuição de tipos de consulta como contexto.</dd>",
|
||||
"<dt>Pilar 4 · Fusão de evidências (v1.0)</dt><dd>Noisy-OR ponderado por host, com pesos iguais de 0,75 e evidência determinística em JSON para auditoria do ranking.</dd>",
|
||||
"<dt>Beaconing</dt><dd>Chamadas periódicas de um implante ao servidor de comando e controle.</dd>",
|
||||
"<dt>PCR</dt><dd>Producer/consumer ratio: (bytes enviados − recebidos) / total. Perto de +1 indica envio de dados; perto de −1, download.</dd>",
|
||||
"<dt>NXDOMAIN</dt><dd>Resposta DNS de domínio inexistente; taxas altas acompanham geração algorítmica de nomes.</dd>",
|
||||
"<dt>JSD</dt><dd>Divergência de Jensen-Shannon entre a distribuição de caracteres do grupo e a referência; informativa, peso 0.</dd>",
|
||||
"<dt>Noisy-OR</dt><dd>Combinação probabilística em que cada evidência independente reduz a chance de o host ser benigno.</dd>",
|
||||
"<dt>TLP</dt><dd>Traffic Light Protocol: indica com quem o relatório pode ser compartilhado. TLP:AMBER limita o uso à organização e a quem precisa saber.</dd>",
|
||||
"<dt>Faixas de score</dt><dd>Crítico ≥ 0,85 · Alto ≥ 0,65 · Médio ≥ 0,40 · Baixo abaixo disso.</dd>",
|
||||
"</dl></section>\n"
|
||||
));
|
||||
|
||||
// ------------------------------------------------------------ scope
|
||||
h.push_str("<section id=\"escopo\" class=\"flow\"><h2>Escopo da análise</h2><table><tbody>");
|
||||
let rows = [
|
||||
("Diretório analisado", html_escape(&report.directory)),
|
||||
("Arquivos de log lidos", report.logs_seen.to_string()),
|
||||
("Arquivos dns.log", report.dns_logs_seen.to_string()),
|
||||
("Registros ingeridos", int(report.records)),
|
||||
("Alertas", report.alerts.len().to_string()),
|
||||
("Hosts com score", report.hosts.len().to_string()),
|
||||
(
|
||||
"Versão do esquema de evidência",
|
||||
report.evidence_schema_version.to_string(),
|
||||
),
|
||||
("Estado do motor", html_escape(report.status)),
|
||||
("Emissão", html_escape(&issued)),
|
||||
("Classificação", format!("TLP:{tlp_html}")),
|
||||
];
|
||||
for (k, v) in rows {
|
||||
let _ = write!(h, "<tr><th>{k}</th><td class=\"mono\">{v}</td></tr>");
|
||||
}
|
||||
h.push_str("</tbody></table><div class=\"callout\"><strong>Limites</strong>O resultado reflete apenas os logs entregues ao Acauã e a janela de sete dias usada pelos pilares 1 e 2. Movimentação lateral e sessões UDP ainda não são avaliadas. Use este relatório como priorização para investigação humana, não como veredito.</div></section>\n");
|
||||
|
||||
let _ = write!(
|
||||
h,
|
||||
"<script src=\"{PAGED_JS_PATH}\"></script>\n</body>\n</html>"
|
||||
);
|
||||
h
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::pillar4::{FusionTerm, FusionWeights};
|
||||
use crate::zeek::P1ExcludedCounts;
|
||||
|
||||
fn sample() -> AnalysisReport {
|
||||
let evil = "<script>alert(1)</script>";
|
||||
AnalysisReport {
|
||||
directory: "/logs/\"x\"<b>".into(),
|
||||
logs_seen: 2,
|
||||
dns_logs_seen: 1,
|
||||
records: 12345,
|
||||
alerts: vec![
|
||||
Alert {
|
||||
id: "aaaa".into(),
|
||||
pillar: 1,
|
||||
score: 0.91,
|
||||
summary: format!("Beaconing detected: {evil}:any -> 198.51.100.1:443 (period ~3600s, score 0.910)"),
|
||||
evidence: serde_json::json!({"period_detected_seconds": 3600.0, "observations": 42, "p_value": 1e-9}),
|
||||
created_at: "now".into(),
|
||||
},
|
||||
Alert {
|
||||
id: "bbbb".into(),
|
||||
pillar: 3,
|
||||
score: 0.7,
|
||||
summary: "DNS".into(),
|
||||
evidence: serde_json::json!({"orig_h": "10.0.0.9", "base_domain": "<img src=x onerror=alert(2)>.evil", "unique_subdomains": 200}),
|
||||
created_at: "now".into(),
|
||||
},
|
||||
],
|
||||
hosts: vec![HostScore {
|
||||
orig_h: evil.into(),
|
||||
score: 0.68,
|
||||
terms: vec![FusionTerm {
|
||||
pillar: 1,
|
||||
alert_id: Some("aaaa".into()),
|
||||
m: 0.91,
|
||||
w: 0.75,
|
||||
weighted: 0.6825,
|
||||
complement: 0.3175,
|
||||
}],
|
||||
product: 0.3175,
|
||||
method: "noisy_or",
|
||||
weights: FusionWeights {
|
||||
p1: 0.75,
|
||||
p2: 0.75,
|
||||
p3: 0.75,
|
||||
},
|
||||
order: [1, 2, 3],
|
||||
formula_version: "1.0",
|
||||
}],
|
||||
evidence_schema_version: 1,
|
||||
status: "ok",
|
||||
p1_excluded: P1ExcludedCounts::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contains_title_tlp_logo_and_paged_js() {
|
||||
let html = render_html(&sample());
|
||||
assert!(html.contains("<title>Acauã · Relatório executivo</title>"));
|
||||
assert!(html.contains("TLP:AMBER"));
|
||||
assert!(html.contains("src=\"data:image/png;base64,iVBOR"));
|
||||
assert!(html.contains("data:image/svg+xml;base64,"));
|
||||
assert!(html.contains(PAGED_JS_PATH));
|
||||
for id in [
|
||||
"resumo",
|
||||
"hosts",
|
||||
"pilar1",
|
||||
"pilar2",
|
||||
"pilar3",
|
||||
"pilar4",
|
||||
"alertas",
|
||||
"metodologia",
|
||||
"escopo",
|
||||
] {
|
||||
assert!(
|
||||
html.contains(&format!("id=\"{id}\"")),
|
||||
"missing section {id}"
|
||||
);
|
||||
assert!(
|
||||
html.contains(&format!("href=\"#{id}\"")),
|
||||
"missing toc entry {id}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escapes_attacker_controlled_strings() {
|
||||
let html = render_html(&sample());
|
||||
assert!(!html.contains("<script>alert(1)"));
|
||||
assert!(!html.contains("<img src=x"));
|
||||
assert!(!html.contains("\"x\"<b>"));
|
||||
assert!(html.contains("<script>alert(1)</script>"));
|
||||
assert!(html.contains("<img src=x onerror=alert(2)>.evil"));
|
||||
assert!(html.contains("/logs/"x"<b>"));
|
||||
// Only the Paged.js loader is a real script element.
|
||||
assert_eq!(html.matches("<script").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tlp_is_normalized() {
|
||||
assert_eq!(normalize_tlp("tlp:red"), "RED");
|
||||
assert_eq!(normalize_tlp("amber+strict"), "AMBER+STRICT");
|
||||
assert_eq!(normalize_tlp("\";}body{"), "AMBER");
|
||||
let html = render_html_with(
|
||||
&sample(),
|
||||
&ReportOptions {
|
||||
tlp: "green".into(),
|
||||
issued_at: Some("01/01/2026 00:00 UTC".into()),
|
||||
},
|
||||
);
|
||||
assert!(html.contains("TLP:GREEN"));
|
||||
assert!(html.contains("01/01/2026 00:00 UTC"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_report_renders() {
|
||||
let mut report = sample();
|
||||
report.alerts.clear();
|
||||
report.hosts.clear();
|
||||
let html = render_html(&report);
|
||||
assert!(html.contains("Nenhum alerta atingiu os limiares"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_matches_known_vectors() {
|
||||
assert_eq!(base64(b""), "");
|
||||
assert_eq!(base64(b"f"), "Zg==");
|
||||
assert_eq!(base64(b"fo"), "Zm8=");
|
||||
assert_eq!(base64(b"foo"), "Zm9v");
|
||||
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbers_use_portuguese_format() {
|
||||
assert_eq!(int(1234567), "1.234.567");
|
||||
assert_eq!(num(0.5, 2), "0,50");
|
||||
}
|
||||
}
|
||||
@@ -38,3 +38,18 @@ The interface communicates with `/api/health` and displays:
|
||||
|
||||
Posting a directory path to `/api/analyze` triggers the Zeek ingestion and
|
||||
analytical detection pipeline.
|
||||
|
||||
## Executive report
|
||||
|
||||
After an analysis, the **Relatório** button (Report, in English) opens
|
||||
`GET /relatorio` in a new tab: an A4 executive report of the latest analysis,
|
||||
paginated in the browser by the vendored Paged.js (`apps/gui/ui/vendor/`), so it
|
||||
works offline and prints to PDF with the browser's print dialog. It has a cover
|
||||
with the embedded logo and a motif drawn from the top hosts, a table of
|
||||
contents, executive summary with KPIs, the host ranking, one section per pillar
|
||||
(beaconing, persistent sessions, DNS tunnels, evidence fusion), every alert with
|
||||
its JSON evidence flattened, methodology and glossary, and the analysis scope.
|
||||
The report is classified `TLP:AMBER` by default; `/relatorio?tlp=GREEN` (or
|
||||
`CLEAR`, `AMBER+STRICT`, `RED`) changes the label, and unknown values fall back
|
||||
to AMBER. Every string read from the logs (hosts, domains, summaries) is
|
||||
HTML-escaped. Without a previous analysis the route answers 404.
|
||||
@@ -38,3 +38,18 @@ A interface comunica-se com `/api/health` e exibe:
|
||||
|
||||
Enviar um caminho de diretório para `/api/analyze` dispara a ingestão do Zeek e o
|
||||
pipeline analítico de detecção.
|
||||
|
||||
## Relatório executivo
|
||||
|
||||
Depois de uma análise, o botão **Relatório** abre `GET /relatorio` em uma nova
|
||||
aba: um relatório executivo A4 da última análise, paginado no navegador pelo
|
||||
Paged.js empacotado no projeto (`apps/gui/ui/vendor/`), então funciona offline e
|
||||
vira PDF pela janela de impressão do navegador. Ele traz capa com o logo
|
||||
embutido e um motivo desenhado a partir dos hosts do topo, sumário, sumário
|
||||
executivo com indicadores, ranking de hosts, uma seção por pilar (beaconing,
|
||||
sessões persistentes, túneis DNS, fusão de evidências), todos os alertas com a
|
||||
evidência JSON achatada, metodologia e glossário, e o escopo da análise. A
|
||||
classificação padrão é `TLP:AMBER`; `/relatorio?tlp=GREEN` (ou `CLEAR`,
|
||||
`AMBER+STRICT`, `RED`) troca o rótulo, e valores desconhecidos voltam para
|
||||
AMBER. Todo texto lido dos logs (hosts, domínios, resumos) é escapado em HTML.
|
||||
Sem uma análise anterior, a rota responde 404.
|
||||
Reference in new issue
Block a user