Files
urutau/internal/server/web/reports.js
T
Lucas RayanandClaude Opus 5.5 2ebda1e4d7
Release / Plan (reuse the published image?) (push) Successful in 3s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 20s
CI / Tests (Linux, race detector) (push) Successful in 1m10s
Release / ci (push) Successful in 1m10s
Release / Build image (arm64) (push) Successful in 55s
Release / Build image (amd64) (push) Successful in 1m16s
Release / Publish tags (push) Successful in 14s
Release / Gitea release (push) Skipped
feat: 1.3.0 thirteen new pages, charts, tooltips and error analysis
New pages grouped in the rail (Monitor, Investigate, Analyze, Operate,
Reports): Services (SLO, Apdex, latency app vs proxy), Sessions (stage
funnel), Campaigns, Event search, MITRE ATT&CK matrix, Evolution,
Concentration (Pareto, Gini), Survival (Kaplan-Meier per attack
episode, recidivists), Where errors come from (application vs failed
attack vs proxy vs client), Protocols and TLS, Defense (fail2ban, SSH,
blocklist), Integrity, and a printable executive report.

Chart library (donut, radar, stacked area, bars, heatmap, gauge),
glossary with accessible "?" tooltips, self-explanatory category names
(nonexistent page 404), page loader through pages.json.

Unique visitors fixed: real browsers opening a page, one per IP per day,
deduplicated across domains, with non-human clients counted apart.
Anonymous legitimate visits on the Live page (?visits=1, no IP).
Traefik origin, service, protocol and TLS fields parsed. Paths and
Referer paths drop e-mail and token segments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 22:39:33 -03:00

358 lines
20 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Urutau - REPORTS page: executive report of the chosen period, printable on A4
(window.print() with @page / @media print in reports.css, no libraries) and
exportable as JSON or CSV. Data: GET /api/v1/report. Log data is hostile:
every dynamic string goes through textContent; CSV cells that start with
= + - @ get a leading apostrophe (spreadsheet formula injection). */
(function () {
'use strict';
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7 3h7l5 5v13H7z"/><path d="M14 3v5h5M10 13h6M10 17h6"/></svg>';
function csvCell(v) {
if (v === null || v === undefined) return '';
if (typeof v === 'number') return isFinite(v) ? String(v) : '';
var s = String(v);
if (/^[=+\-@\t\r]/.test(s)) s = "'" + s;
if (/[",\n\r]/.test(s)) s = '"' + s.replace(/"/g, '""') + '"';
return s;
}
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'rpt.title': 'Reports',
'rpt.print': 'Print',
'rpt.json': 'Export JSON',
'rpt.csv': 'Export CSV',
'rpt.cover.kicker': 'Executive report',
'rpt.cover.title': 'Security report',
'rpt.cover.period': 'Period',
'rpt.cover.hosts': 'Hosts',
'rpt.cover.generated': 'Generated',
'rpt.cover.all': 'all hosts',
'rpt.sum.title': 'Executive summary',
'rpt.sum.lead': 'In this period {hosts} recorded {attacks} attacks from {ips} distinct addresses; {hostile} of them were hostile and {bans} are banned.',
'rpt.sum.up': 'Attacks rose {pct}% against the previous period.',
'rpt.sum.down': 'Attacks fell {pct}% against the previous period.',
'rpt.sum.flat': 'Attack volume is in line with the previous period.',
'rpt.sum.noPrev': 'There is no previous period to compare with.',
'rpt.sum.top': 'The most frequent attack family was {fam}, and most traffic came from {cc}.',
'rpt.sum.ban': 'The median time to ban was {t}; {cov}% of hostile addresses are covered by a ban.',
'rpt.sum.expo': '{n} attack requests were answered with success and deserve review.',
'rpt.sum.noExpo': 'No attack request reached an exposed resource.',
'rpt.k.requests': 'Requests',
'rpt.k.attacks': 'Attacks',
'rpt.k.unique_ips': 'Unique IPs',
'rpt.k.hostile_ips': 'Hostile IPs',
'rpt.k.bans': 'Bans',
'rpt.k.visitors': 'Visitors',
'rpt.k.nonhuman': 'Non-human clients',
'rpt.k.page_views': 'Page views',
'rpt.k.prev': 'before: {v}',
'rpt.chart.timeline': 'Attacks over time',
'rpt.chart.families': 'Attack families',
'rpt.chart.countries': 'Origin countries',
'rpt.chart.asns': 'Networks (ASN)',
'rpt.chart.techniques': 'Techniques',
'rpt.table.ips': 'Top addresses',
'rpt.table.campaigns': 'Main campaigns',
'rpt.table.escalations': 'Escalations',
'rpt.table.exposure': 'Exposures',
'rpt.table.defense': 'Defence',
'rpt.col.ip': 'Address',
'rpt.col.score': 'Score',
'rpt.col.level': 'Level',
'rpt.col.country': 'Country',
'rpt.col.network': 'Network',
'rpt.col.events': 'Events',
'rpt.col.banned': 'Banned',
'rpt.col.campaign': 'Campaign',
'rpt.col.ips': 'IPs',
'rpt.col.period': 'Active',
'rpt.col.techs': 'Techniques',
'rpt.col.stage': 'Stage',
'rpt.col.host': 'Host',
'rpt.col.path': 'Path',
'rpt.col.status': 'Status',
'rpt.col.family': 'Family',
'rpt.col.when': 'When',
'rpt.yes': 'yes',
'rpt.no': 'no',
'rpt.empty': 'Nothing to report in this period.',
'rpt.none': 'None in this period.',
'rpt.def.mttb': 'Median time to ban',
'rpt.def.mttbP90': 'Time to ban (90th percentile)',
'rpt.def.cover': 'Ban coverage',
'rpt.def.blocklist': 'Blocklist coverage',
'rpt.def.exposure': 'Exposure rate',
'rpt.def.refused': 'Exploits refused',
'rpt.def.n': 'Bans measured',
'rpt.truncated': 'The study was cut at its limits; the figures may be partial.',
'rpt.foot': 'Generated by Urutau. Addresses come from logs and are shown as recorded.'
},
'pt-BR': {
'rpt.title': 'Relatórios',
'rpt.print': 'Imprimir',
'rpt.json': 'Exportar JSON',
'rpt.csv': 'Exportar CSV',
'rpt.cover.kicker': 'Relatório executivo',
'rpt.cover.title': 'Relatório de segurança',
'rpt.cover.period': 'Período',
'rpt.cover.hosts': 'Hosts',
'rpt.cover.generated': 'Gerado em',
'rpt.cover.all': 'todos os hosts',
'rpt.sum.title': 'Sumário executivo',
'rpt.sum.lead': 'Neste período {hosts} registrou {attacks} ataques de {ips} endereços distintos; {hostile} deles foram hostis e {bans} estão banidos.',
'rpt.sum.up': 'Os ataques subiram {pct}% em relação ao período anterior.',
'rpt.sum.down': 'Os ataques caíram {pct}% em relação ao período anterior.',
'rpt.sum.flat': 'O volume de ataques está em linha com o período anterior.',
'rpt.sum.noPrev': 'Não há período anterior para comparar.',
'rpt.sum.top': 'A família de ataque mais frequente foi {fam}, e a maior parte do tráfego veio de {cc}.',
'rpt.sum.ban': 'O tempo mediano até o banimento foi {t}; {cov}% dos endereços hostis estão cobertos por um ban.',
'rpt.sum.expo': '{n} requisições de ataque foram respondidas com sucesso e merecem revisão.',
'rpt.sum.noExpo': 'Nenhuma requisição de ataque chegou a um recurso exposto.',
'rpt.k.requests': 'Requisições',
'rpt.k.attacks': 'Ataques',
'rpt.k.unique_ips': 'IPs únicos',
'rpt.k.hostile_ips': 'IPs hostis',
'rpt.k.bans': 'Bans',
'rpt.k.visitors': 'Visitantes',
'rpt.k.nonhuman': 'Clientes não humanos',
'rpt.k.page_views': 'Páginas vistas',
'rpt.k.prev': 'antes: {v}',
'rpt.chart.timeline': 'Ataques ao longo do tempo',
'rpt.chart.families': 'Famílias de ataque',
'rpt.chart.countries': 'Países de origem',
'rpt.chart.asns': 'Redes (ASN)',
'rpt.chart.techniques': 'Técnicas',
'rpt.table.ips': 'Principais endereços',
'rpt.table.campaigns': 'Principais campanhas',
'rpt.table.escalations': 'Escaladas',
'rpt.table.exposure': 'Exposições',
'rpt.table.defense': 'Defesa',
'rpt.col.ip': 'Endereço',
'rpt.col.score': 'Pontuação',
'rpt.col.level': 'Nível',
'rpt.col.country': 'País',
'rpt.col.network': 'Rede',
'rpt.col.events': 'Eventos',
'rpt.col.banned': 'Banido',
'rpt.col.campaign': 'Campanha',
'rpt.col.ips': 'IPs',
'rpt.col.period': 'Atividade',
'rpt.col.techs': 'Técnicas',
'rpt.col.stage': 'Estágio',
'rpt.col.host': 'Host',
'rpt.col.path': 'Caminho',
'rpt.col.status': 'Status',
'rpt.col.family': 'Família',
'rpt.col.when': 'Quando',
'rpt.yes': 'sim',
'rpt.no': 'não',
'rpt.empty': 'Nada a relatar neste período.',
'rpt.none': 'Nenhum neste período.',
'rpt.def.mttb': 'Tempo mediano até o ban',
'rpt.def.mttbP90': 'Tempo até o ban (percentil 90)',
'rpt.def.cover': 'Cobertura de bans',
'rpt.def.blocklist': 'Cobertura da lista de bloqueio',
'rpt.def.exposure': 'Taxa de exposição',
'rpt.def.refused': 'Exploits recusados',
'rpt.def.n': 'Bans medidos',
'rpt.truncated': 'O estudo foi cortado nos seus limites; os números podem estar parciais.',
'rpt.foot': 'Gerado pelo Urutau. Os endereços vêm dos logs e aparecem como registrados.'
}
});
var t = U.t, nf = U.fmt.num;
var h = function (tag, cls) { return U.el.apply(null, [tag, cls ? { class: cls } : null].concat([].slice.call(arguments, 2))); };
var root = null, box = null, ctx0 = null, seq = 0, alive = false, data = null;
function dur(s) {
s = Math.round(s || 0);
if (s < 60) return t('dur.s', { n: nf(s) });
if (s < 3600) return t('dur.m', { n: nf(Math.round(s / 60)) });
if (s < 86400) return t('dur.h', { n: nf(Math.round(s / 3600)) });
return t('dur.d', { n: nf(Math.round(s / 86400)) });
}
function day(ts) { return new Date(ts * 1000).toLocaleDateString((ctx0 && ctx0.lang) || undefined, { day: 'numeric', month: 'short', year: 'numeric' }); }
function pctTxt(v) { return nf(Math.round(v * 10) / 10) + '%'; }
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function params(c) {
var p = U.rangeParams();
if (c && c.host && c.host !== 'all') p.host = c.host;
p.format = 'json';
return p;
}
function load(c) {
var my = ++seq;
U.api('/api/v1/report', params(c || ctx0)).then(function (d) {
if (!alive || my !== seq) return;
data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
clear(box);
box.appendChild(U.ui.empty(t('error.load')));
});
}
function save(name, type, text) {
try {
var url = URL.createObjectURL(new Blob([text], { type: type }));
var a = document.createElement('a');
a.href = url; a.download = name;
document.body.appendChild(a); a.click(); document.body.removeChild(a);
setTimeout(function () { URL.revokeObjectURL(url); }, 2000);
} catch (e) { console.error(e); }
}
function stamp(ext) {
var r = data && data.range ? data.range : { from: 0, to: 0 };
var f = function (x) { return new Date(x * 1000).toISOString().slice(0, 10); };
return 'urutau-report-' + f(r.from) + '_' + f(r.to) + '.' + ext;
}
function toCSV(d) {
var rows = [['section', 'key', 'value', 'extra']];
function add() { rows.push([].slice.call(arguments)); }
add('range', 'from', new Date(d.range.from * 1000).toISOString());
add('range', 'to', new Date(d.range.to * 1000).toISOString());
add('range', 'hosts', (d.hosts || []).join(' '));
Object.keys(d.summary || {}).forEach(function (k) {
var v = d.summary[k];
if (typeof v === 'number') add('summary', k, v, d.summary.prev && typeof d.summary.prev[k] === 'number' ? d.summary.prev[k] : '');
});
['families', 'techniques', 'countries', 'asns'].forEach(function (s) { (d[s] || []).forEach(function (r) { add(s, r.key, r.n, r.label || ''); }); });
(d.top_ips || []).forEach(function (r) { add('top_ips', r.ip, r.score, [r.level, r.cc, r.as_org, r.events, r.banned ? 'banned' : ''].join(' ')); });
(d.campaigns || []).forEach(function (c) { add('campaigns', c.id, c.ips_n, (c.techs || []).join(' ')); });
(d.escalations || []).forEach(function (e) { add('escalations', e.ip, e.stage, e.host || ''); });
((d.exposures || {}).items || []).forEach(function (e) { add('exposures', e.ip, e.path, [e.host, e.domain, e.status, e.fam].join(' ')); });
Object.keys(d.defense || {}).forEach(function (k) { add('defense', k, d.defense[k]); });
return rows.map(function (r) { return r.map(csvCell).join(','); }).join('\r\n') + '\r\n';
}
function toolbar() {
var bar = h('div', 'rpt-bar');
var b1 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.print'));
b1.addEventListener('click', function () { window.print(); });
var b2 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.json'));
b2.addEventListener('click', function () { if (data) save(stamp('json'), 'application/json', JSON.stringify(data, null, 2)); });
var b3 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.csv'));
b3.addEventListener('click', function () { if (data) save(stamp('csv'), 'text/csv;charset=utf-8', '' + toCSV(data)); });
bar.appendChild(b1); bar.appendChild(b2); bar.appendChild(b3);
return bar;
}
function table(headers, rows) {
var tb = h('table', 'rpt-table'), tr = h('tr');
headers.forEach(function (x) { tr.appendChild(h('th', null, x)); });
tb.appendChild(h('thead', null, tr));
var body = h('tbody');
rows.forEach(function (r) { var row = h('tr'); r.forEach(function (c) { row.appendChild(h('td', null, c)); }); body.appendChild(row); });
tb.appendChild(body);
return h('div', 'rpt-scroll', tb);
}
function section(title, body, cls) {
return h('section', 'rpt-sec' + (cls ? ' ' + cls : ''), h('h2', null, title), body);
}
function emptyNote(key) { return h('p', 'rpt-none', t(key || 'rpt.none')); }
function barRows(list) { return (list || []).map(function (r) { return { key: r.key, label: r.label ? r.key + ' ' + r.label : r.key, value: r.n }; }); }
function paint() {
if (!data) return;
clear(box);
var d = data, s = d.summary || {}, doc = h('article', 'rpt-sheet');
var hosts = (d.hosts && d.hosts.length) ? d.hosts.join(', ') : t('rpt.cover.all');
// cover
doc.appendChild(h('header', 'rpt-cover',
h('p', 'rpt-kicker', t('rpt.cover.kicker')),
h('h1', null, t('rpt.cover.title')),
h('dl', 'rpt-meta',
h('dt', null, t('rpt.cover.period')), h('dd', null, day(d.range.from) + ' - ' + day(d.range.to)),
h('dt', null, t('rpt.cover.hosts')), h('dd', null, hosts),
h('dt', null, t('rpt.cover.generated')), h('dd', null, U.fmt.date(d.generated)))));
// executive summary
var sents = [];
sents.push(t('rpt.sum.lead', { hosts: hosts, attacks: nf(s.attacks), ips: nf(s.unique_ips), hostile: nf(s.hostile_ips), bans: nf(s.bans) }));
var dp = s.delta_pct && typeof s.delta_pct.attacks === 'number' ? s.delta_pct.attacks : null;
if (!s.has_prev || dp === null) sents.push(t('rpt.sum.noPrev'));
else if (Math.abs(dp) < 5) sents.push(t('rpt.sum.flat'));
else sents.push(t(dp > 0 ? 'rpt.sum.up' : 'rpt.sum.down', { pct: nf(Math.round(Math.abs(dp))) }));
if ((d.families || []).length && (d.countries || []).length) sents.push(t('rpt.sum.top', { fam: d.families[0].key, cc: U.fmt.country(d.countries[0].key) }));
var df = d.defense || {};
if (df.mttb_n > 0) sents.push(t('rpt.sum.ban', { t: dur(df.mttb_median_s), cov: nf(Math.round(df.ban_coverage)) }));
var ex = d.exposures || {};
sents.push(ex.total > 0 ? t('rpt.sum.expo', { n: nf(ex.total) }) : t('rpt.sum.noExpo'));
var kp = h('div', 'rpt-kpis');
['requests', 'attacks', 'unique_ips', 'hostile_ips', 'bans', 'visitors', 'nonhuman', 'page_views'].forEach(function (k) {
var delta = s.delta_pct && typeof s.delta_pct[k] === 'number' ? s.delta_pct[k] : null;
kp.appendChild(h('div', 'rpt-kpi', h('span', 'rpt-kl', t('rpt.k.' + k)), h('strong', 'num', nf(s[k] || 0)),
s.has_prev ? h('span', 'rpt-kd', (delta === null ? '' : (delta > 0 ? '▲ ' : delta < 0 ? '▼ ' : '') + nf(Math.abs(Math.round(delta))) + '% · ') + t('rpt.k.prev', { v: nf((s.prev || {})[k] || 0) })) : null));
});
var sumBox = h('div', null, h('div', 'rpt-sents', sents.map(function (x) { return h('p', null, x); })), kp);
if (d.truncated) sumBox.appendChild(h('p', 'rpt-warn', t('rpt.truncated')));
doc.appendChild(section(t('rpt.sum.title'), sumBox, 'rpt-first'));
// charts
var tl = d.timeline || {};
var chartsBox = h('div', 'rpt-charts');
var c1 = h('div', 'rpt-chart rpt-wide', h('h3', null, t('rpt.chart.timeline')));
c1.appendChild(U.charts.stackedArea([{ key: 'attacks', label: t('rpt.k.attacks'), values: tl.values || [] }], tl.step, { start: tl.start, title: t('rpt.chart.timeline') }));
chartsBox.appendChild(c1);
function cbox(title, node, cls) { var c = h('div', 'rpt-chart' + (cls ? ' ' + cls : ''), h('h3', null, title)); c.appendChild(node); chartsBox.appendChild(c); }
cbox(t('rpt.chart.families'), (d.families || []).length ? U.charts.donut(d.families.slice(0, 5).map(function (r) { return { key: r.key, label: r.key, value: r.n }; }), { title: t('rpt.chart.families') }) : emptyNote());
cbox(t('rpt.chart.countries'), (d.countries || []).length ? U.charts.bars((d.countries || []).slice(0, 5).map(function (r) { return { key: r.key, label: U.fmt.country(r.key), value: r.n }; }), { title: t('rpt.chart.countries') }) : emptyNote());
cbox(t('rpt.chart.asns'), (d.asns || []).length ? U.charts.bars(barRows(d.asns.slice(0, 5)), { title: t('rpt.chart.asns') }) : emptyNote());
cbox(t('rpt.chart.techniques'), (d.techniques || []).length ? U.charts.bars(barRows(d.techniques.slice(0, 5)), { title: t('rpt.chart.techniques') }) : emptyNote(), 'rpt-noprint');
doc.appendChild(section(t('rpt.chart.timeline'), chartsBox, 'rpt-sec-charts'));
// tables (page 2)
var p2 = h('div', 'rpt-p2');
p2.appendChild(section(t('rpt.table.ips'), (d.top_ips || []).length ? table([t('rpt.col.ip'), t('rpt.col.score'), t('rpt.col.level'), t('rpt.col.country'), t('rpt.col.network'), t('rpt.col.events'), t('rpt.col.banned')],
d.top_ips.map(function (r) { return [r.ip, nf(r.score), r.level, r.cc ? U.fmt.country(r.cc) : '-', r.as_org || '-', nf(r.events), t(r.banned ? 'rpt.yes' : 'rpt.no')]; })) : emptyNote()));
p2.appendChild(section(t('rpt.table.campaigns'), (d.campaigns || []).length ? table([t('rpt.col.campaign'), t('rpt.col.ips'), t('rpt.col.period'), t('rpt.col.techs')],
d.campaigns.map(function (c) { return [c.id, nf(c.ips_n), day(Date.parse(c.first) / 1000) + ' - ' + day(Date.parse(c.last) / 1000), (c.techs || []).slice(0, 4).join(', ')]; })) : emptyNote()));
p2.appendChild(section(t('rpt.table.escalations'), (d.escalations || []).length ? table([t('rpt.col.ip'), t('rpt.col.stage'), t('rpt.col.host')],
d.escalations.map(function (e) { return [e.ip, e.stage, e.host || '-']; })) : emptyNote()));
p2.appendChild(section(t('rpt.table.exposure'), (ex.items || []).length ? table([t('rpt.col.when'), t('rpt.col.ip'), t('rpt.col.host'), t('rpt.col.path'), t('rpt.col.status'), t('rpt.col.family')],
ex.items.map(function (e) { return [U.fmt.date(e.t), e.ip, e.domain || e.host || '-', e.path, String(e.status), e.fam || '-']; })) : emptyNote('rpt.sum.noExpo')));
p2.appendChild(section(t('rpt.table.defense'), table(['', ''], [
[t('rpt.def.mttb'), df.mttb_n > 0 ? dur(df.mttb_median_s) : '-'],
[t('rpt.def.mttbP90'), df.mttb_n > 0 ? dur(df.mttb_p90_s) : '-'],
[t('rpt.def.n'), nf(df.mttb_n || 0)],
[t('rpt.def.cover'), pctTxt(df.ban_coverage || 0)],
[t('rpt.def.blocklist'), pctTxt(df.blocklist_coverage || 0)],
[t('rpt.def.exposure'), pctTxt(df.exposure_rate || 0)],
[t('rpt.def.refused'), pctTxt(df.exploits_refused_pct || 0)]
])));
p2.appendChild(h('p', 'rpt-foot', t('rpt.foot')));
doc.appendChild(p2);
box.appendChild(toolbar());
box.appendChild(doc);
}
U.registerPage({
id: 'reports', group: 'reports', icon: ICON, titleKey: 'rpt.title',
mount: function (el, c) {
ctx0 = c; alive = true; data = null;
root = h('div', 'rpt');
box = h('div', 'rpt-box');
root.appendChild(box);
box.appendChild(h('div', 'skeleton'));
el.appendChild(root);
load(c);
},
update: function (c) { ctx0 = c; load(c); },
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = box = data = null; }
});
return true;
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();