diff --git a/internal/server/report_html.go b/internal/server/report_html.go index 5171a65..2c1850f 100644 --- a/internal/server/report_html.go +++ b/internal/server/report_html.go @@ -2,17 +2,14 @@ package server import ( "bytes" + _ "embed" "encoding/base64" "fmt" "html/template" - "image" - "image/color" - "image/png" "net/http" "regexp" "sort" "strings" - "sync" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress" @@ -52,61 +49,16 @@ type reportInput struct { Peers bool // other hosts included: health and egress cover only this server } -var ( - logoOnce sync.Once - logoURI string -) +// reportLogo is the repository logo.png (1254 px) scaled to 800 px WebP, sharp +// on the cover even when printed. Regenerate it from ./logo.png when the logo changes. +// +//go:embed report_logo.webp +var reportLogo []byte -// logoDataURI returns web/logo.png scaled to 200px as a data URI (computed once). -func logoDataURI() template.URL { - logoOnce.Do(func() { - raw, err := webFS.ReadFile("web/logo.png") - if err != nil { - return - } - src, err := png.Decode(bytes.NewReader(raw)) - if err != nil { - return - } - dst := scaleRGBA(src, 200) - var buf bytes.Buffer - if png.Encode(&buf, dst) == nil { - logoURI = "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()) - } - }) - return template.URL(logoURI) -} +var logoURI = "data:image/webp;base64," + base64.StdEncoding.EncodeToString(reportLogo) -// scaleRGBA shrinks to a square of side n by averaging premultiplied pixels. -func scaleRGBA(src image.Image, n int) *image.NRGBA { - b := src.Bounds() - w, h := b.Dx(), b.Dy() - dst := image.NewNRGBA(image.Rect(0, 0, n, n)) - for y := 0; y < n; y++ { - y0, y1 := y*h/n, (y+1)*h/n - if y1 <= y0 { - y1 = y0 + 1 - } - for x := 0; x < n; x++ { - x0, x1 := x*w/n, (x+1)*w/n - if x1 <= x0 { - x1 = x0 + 1 - } - var r, g, bl, a, c uint64 - for yy := y0; yy < y1 && yy < h; yy++ { - for xx := x0; xx < x1 && xx < w; xx++ { - pr, pg, pb, pa := src.At(b.Min.X+xx, b.Min.Y+yy).RGBA() - r, g, bl, a, c = r+uint64(pr), g+uint64(pg), bl+uint64(pb), a+uint64(pa), c+1 - } - } - if c == 0 || a == 0 { - continue - } - dst.SetNRGBA(x, y, color.NRGBA{R: uint8(r * 255 / a), G: uint8(g * 255 / a), B: uint8(bl * 255 / a), A: uint8(a / c >> 8)}) - } - } - return dst -} +// logoDataURI returns the report logo as a data URI. +func logoDataURI() template.URL { return template.URL(logoURI) } // ---- view model ------------------------------------------------------------- @@ -763,7 +715,8 @@ func (s *Server) writeReportHTML(w http.ResponseWriter, r *http.Request, rc *rep } w.Header().Set("Content-Type", "text/html; charset=utf-8") // the document is self-contained: inline CSS and data: images only, no script - w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'") + w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'self'") + w.Header().Set("X-Frame-Options", "SAMEORIGIN") // previewed in an iframe by the Reports page only disp := "attachment" if r.URL.Query().Get("inline") == "1" { disp = "inline" diff --git a/internal/server/report_html_test.go b/internal/server/report_html_test.go index a59f2a8..de155f2 100644 --- a/internal/server/report_html_test.go +++ b/internal/server/report_html_test.go @@ -66,7 +66,7 @@ func TestReportHTMLRenders(t *testing.T) { if strings.Contains(s, "Ltd") { t.Fatalf("%s: unescaped attacker data", lang) } - if !strings.Contains(s, "<script>") || !strings.Contains(s, "data:image/png;base64,") { + if !strings.Contains(s, "<script>") || !strings.Contains(s, "data:image/webp;base64,") { t.Fatalf("%s: missing escaped payload or logo", lang) } if len(b) > 400<<10 { diff --git a/internal/server/report_logo.webp b/internal/server/report_logo.webp new file mode 100644 index 0000000..df8f3f3 Binary files /dev/null and b/internal/server/report_logo.webp differ diff --git a/internal/server/survival_blocker_test.go b/internal/server/survival_blocker_test.go new file mode 100644 index 0000000..fbf8cf9 --- /dev/null +++ b/internal/server/survival_blocker_test.go @@ -0,0 +1,37 @@ +package server + +import ( + "path/filepath" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +// Bans applied by the "urutau" jail (second firewall) are reported apart from +// the host fail2ban jails in /api/v1/survival. +func TestSurvivalByBlocker(t *testing.T) { + st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour}) + l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")}) + st.SetEventLog(l) + now := time.Now() + attack := func(ip string, at time.Time) { + st.Ingest(core.Event{Time: at, IP: ip, Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/.env", Status: 404}) + } + attack("20.0.0.1", now.Add(-2*time.Hour)) + st.Ingest(core.Event{Time: now.Add(-2*time.Hour + 10*time.Minute), IP: "20.0.0.1", Cat: core.Ban, Source: "fail2ban", Jail: "traefik-varredura"}) + attack("20.0.0.2", now.Add(-time.Hour)) + st.Ingest(core.Event{Time: now.Add(-time.Hour + time.Minute), IP: "20.0.0.2", Cat: core.Ban, Source: "fail2ban", Jail: "urutau"}) + h := New(Options{Token: userTok, Version: "t", Store: st}) + v := getJSON(t, h, "/api/v1/survival?range=24h", map[string]string{"Authorization": "Bearer " + userTok}) + got := map[string]float64{} + for _, b := range v["by_blocker"].([]any) { + m := b.(map[string]any) + got[m["blocker"].(string)] = m["median_s"].(float64) + } + if got["fail2ban"] != 600 || got["urutau"] != 60 { + t.Fatalf("by_blocker = %v", v["by_blocker"]) + } +} diff --git a/internal/server/web/reports.css b/internal/server/web/reports.css index 66d402b..d77462a 100644 --- a/internal/server/web/reports.css +++ b/internal/server/web/reports.css @@ -1,81 +1,14 @@ -/* Urutau - REPORTS page. Selectors prefixed rpt-. On screen the report is a sheet; with - @media print it fills A4 pages and the shell chrome disappears. */ -.rpt { min-width: 0; } -.rpt-box { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; } -.rpt-bar { display: flex; flex-wrap: wrap; gap: 8px; align-items: flex-end; } +/* Urutau - REPORTS page. Selectors prefixed rpt-. The report itself is the + HTML document shown in the iframe (its own A4 print styles); this file only + lays out the toolbar and the preview frame. */ +.rpt { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; } +.rpt-bar { display: flex; flex-wrap: wrap; gap: 10px 16px; align-items: flex-end; } .rpt-opt { display: flex; flex-direction: column; gap: 2px; font-size: .75rem; color: var(--ink-muted); } .rpt-sel { min-height: 34px; padding: 4px 8px; border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); background: var(--surface-raised, transparent); color: var(--ink); font: inherit; } -.rpt-hint { flex-basis: 100%; margin: 0; font-size: .75rem; color: var(--ink-muted); } -.rpt-sheet { background: var(--surface-panel); border: 1px solid var(--line); border-radius: var(--radius, 10px); padding: clamp(14px, 3vw, 32px); display: flex; flex-direction: column; gap: 22px; min-width: 0; color: var(--ink); } -.rpt-cover { border-bottom: 2px solid var(--accent); padding-bottom: 14px; } -.rpt-kicker { margin: 0; font-size: .75rem; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-muted); } -.rpt-cover h1 { margin: 4px 0 10px; font: 700 1.75rem/1.15 var(--font-display); color: var(--heading); } -.rpt-meta { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 3px 14px; margin: 0; font-size: .875rem; } -.rpt-meta dt { color: var(--ink-muted); } -.rpt-meta dd { margin: 0; overflow-wrap: anywhere; } -.rpt-sec h2 { margin: 0 0 10px; font: 650 1.0625rem/1.2 var(--font-display); color: var(--heading); } -.rpt-sents p { margin: 0 0 6px; font-size: .9375rem; line-height: 1.5; max-width: 90ch; overflow-wrap: anywhere; } -.rpt-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-top: 12px; } -.rpt-kpi { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); min-width: 0; } -.rpt-kl { font-size: .75rem; color: var(--ink-muted); } -.rpt-kpi strong { font-size: 1.375rem; color: var(--heading); } -.rpt-kd { font-size: .6875rem; color: var(--ink-muted); } -.rpt-warn { color: var(--warn); font-size: .8125rem; } -.rpt-charts { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; } -@media (min-width: 900px) { .rpt-charts { grid-template-columns: repeat(2, minmax(0, 1fr)); } .rpt-wide { grid-column: 1 / -1; } } -.rpt-chart { min-width: 0; border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); padding: 10px 12px; } -.rpt-chart h3 { margin: 0 0 8px; font-size: .8125rem; font-weight: 600; color: var(--ink-muted); } -.rpt-p2 { display: flex; flex-direction: column; gap: 18px; min-width: 0; } -.rpt-scroll { overflow-x: auto; max-width: 100%; } -.rpt-table { width: 100%; border-collapse: collapse; font-size: .8125rem; } -.rpt-table th { text-align: left; font-weight: 600; color: var(--ink-muted); padding: 5px 8px; border-bottom: 1px solid var(--line-strong, var(--line)); } -.rpt-table td { padding: 5px 8px; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; vertical-align: top; } -.rpt-none { margin: 0; color: var(--ink-muted); font-size: .8125rem; } -.rpt-foot { margin: 0; font-size: .75rem; color: var(--ink-faint); } - -@page { size: A4; margin: 12mm; } -@media print { - :root, :root[data-theme] { - --surface-base: #fff; --surface-panel: #fff; --surface-sunken: #f4f6f8; --surface-raised: #fff; - --line: #cfd6dc; --line-strong: #8a96a0; --ink: #14202a; --ink-muted: #46545f; --ink-faint: #5d6b76; --heading: #000; - --accent: #0a78b5; --warn: #8a5a00; - color-scheme: light; - } - html, body { background: #fff !important; color: #14202a; } - .rail, .topbar, .slice, .tabbar, .more-sheet, .err-banner, .shell-foot, .toasts, .scrim, .skip, .rpt-bar, #detail { display: none !important; } - .app { display: block !important; background: none !important; min-height: 0; } - .main, main#view { display: block !important; padding: 0 !important; margin: 0 !important; overflow: visible !important; } - .rpt-sheet { border: 0; padding: 0; gap: 12px; border-radius: 0; } - .rpt-cover h1 { font-size: 1.5rem; } - .rpt-sec, .rpt-chart, .rpt-kpi { break-inside: avoid; } - .rpt-charts { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } - .rpt-wide { grid-column: 1 / -1; } - .rpt-p2 { break-before: page; gap: 10px; } - .rpt-p2 .rpt-sec { break-inside: avoid; } - .rpt-scroll { overflow: visible; } - .rpt-table { font-size: 8.5pt; } - .rpt-sents p { font-size: 10pt; } - .rpt-kpi strong { font-size: 1.125rem; } -} -.rpt .vz svg, .rpt .chart-wrap svg { max-width: 100%; height: auto; } -@media print { - .rpt-sec-charts { break-inside: auto; } - .rpt-kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; } - .rpt-kpi { padding: 6px 8px; } - .rpt-chart { padding: 6px 8px; } - .rpt-chart svg { max-height: 150px; width: 100%; } - .rpt-chart .vz-legend, .rpt-chart ul { font-size: 8pt; } - .rpt-sheet { gap: 10px; } -} -@media print { - .rpt-chart svg { max-height: 120px; } - .rpt-chart .vz-donut, .rpt-chart .vz-donut svg { max-height: 120px; } - .rpt-chart .bar-row, .rpt-chart .vz-row { font-size: 8.5pt; } - .rpt-chart .vz-row { margin: 2px 0; } -} -@media print { - .rpt-noprint { display: none !important; } - .rpt-charts { grid-template-columns: repeat(3, minmax(0, 1fr)); } - .rpt-table td, .rpt-table th { padding: 3px 6px; } - .rpt-p2 .rpt-sec h2 { margin-bottom: 4px; font-size: 11pt; } -} +.rpt-hint { flex: 1 1 220px; margin: 0; font-size: .75rem; color: var(--ink-muted); align-self: center; } +.rpt-actions { display: flex; gap: 8px; margin-left: auto; } +.rpt-status { display: flex; gap: 10px; align-items: center; font-size: .8125rem; color: var(--ink-muted); } +.rpt-status[hidden] { display: none; } +.rpt-sheetwrap { background: var(--surface-sunken, rgba(127, 127, 127, .12)); border: 1px solid var(--line); border-radius: var(--radius, 10px); padding: clamp(6px, 2vw, 20px); min-width: 0; } +.rpt-frame { display: block; width: 100%; max-width: 900px; height: calc(100vh - 220px); min-height: 520px; margin: 0 auto; border: 0; border-radius: 4px; background: #fff; box-shadow: 0 6px 24px rgba(0, 0, 0, .25); } +@media (max-width: 600px) { .rpt-actions { margin-left: 0; width: 100%; } .rpt-actions .btn { flex: 1; } .rpt-frame { height: 75vh; min-height: 420px; } } diff --git a/internal/server/web/reports.js b/internal/server/web/reports.js index bbbc30e..3b1e587 100644 --- a/internal/server/web/reports.js +++ b/internal/server/web/reports.js @@ -1,21 +1,13 @@ -/* 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). */ +/* Urutau - REPORTS page: a live preview of the HTML report (the same document + that is downloaded and printed), following the period and host chosen in the + header, plus the report language. Two actions only: download and print. + The report is served by GET /api/v1/report?format=html (self-contained, no + script); the preview is a same-origin iframe of it with inline=1. */ (function () { 'use strict'; var ICON = ''; - - 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; - } + var LANG_KEY = 'urutau.report.lang'; function boot() { var U = window.Urutau; @@ -23,369 +15,111 @@ U.registerI18n({ en: { 'rpt.title': 'Reports', + 'rpt.dl': 'Download', 'rpt.print': 'Print', - 'rpt.json': 'Export JSON', - 'rpt.csv': 'Export CSV', - 'rpt.dl': 'Download report (HTML)', - 'rpt.pdf': 'Print / PDF', - 'rpt.opt.period': 'Report period', - 'rpt.opt.panel': 'Same as the dashboard', - 'rpt.opt.lang': 'Report language', - 'rpt.opt.hint': 'The HTML report is one self-contained file, ready to print on A4. Open it and use Print to save as PDF.', - '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.' + 'rpt.lang': 'Report language', + 'rpt.scope': 'Period and server follow the selection at the top of the page.', + 'rpt.preview': 'Report preview', + 'rpt.loading': 'Building the report...', + 'rpt.err': 'Could not build the report.', + 'rpt.retry': 'Try again' }, 'pt-BR': { 'rpt.title': 'Relatórios', + 'rpt.dl': 'Baixar', 'rpt.print': 'Imprimir', - 'rpt.json': 'Exportar JSON', - 'rpt.csv': 'Exportar CSV', - 'rpt.dl': 'Baixar relatório (HTML)', - 'rpt.pdf': 'Imprimir / PDF', - 'rpt.opt.period': 'Período do relatório', - 'rpt.opt.panel': 'Igual ao do painel', - 'rpt.opt.lang': 'Idioma do relatório', - 'rpt.opt.hint': 'O relatório HTML é um arquivo único, pronto para imprimir em A4. Abra e use Imprimir para salvar em PDF.', - '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.' + 'rpt.lang': 'Idioma do relatório', + 'rpt.scope': 'O período e o servidor seguem a seleção no topo da página.', + 'rpt.preview': 'Prévia do relatório', + 'rpt.loading': 'Montando o relatório...', + 'rpt.err': 'Não foi possível montar o relatório.', + 'rpt.retry': 'Tentar de novo' } }); - 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 t = U.t, el = U.el; + var ctx0 = null, root = null, frame = null, status = null, lang = ''; - var root = null, box = null, ctx0 = null, seq = 0, alive = false, data = null; + try { lang = localStorage.getItem(LANG_KEY) || ''; } catch (e) { lang = ''; } - 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 reportLang() { + if (lang === 'en' || lang === 'pt-BR') return lang; + return ctx0 && ctx0.lang === 'en' ? 'en' : 'pt-BR'; } - 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) { + function url(inline) { 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'; - } - - var opt = { range: '', lang: '' }; - function htmlUrl(inline) { - var p = params(ctx0); + if (ctx0 && ctx0.host && ctx0.host !== 'all') p.host = ctx0.host; p.format = 'html'; - if (opt.range) { delete p.from; delete p.to; p.range = opt.range; } - p.lang = opt.lang || (ctx0 && ctx0.lang === 'en' ? 'en' : 'pt-BR'); + p.lang = reportLang(); if (inline) p.inline = '1'; return '/api/v1/report?' + new URLSearchParams(p).toString(); } - function select(label, key, choices) { - var sel = U.el('select', { class: 'rpt-sel', 'aria-label': label }); - choices.forEach(function (c) { var o = U.el('option', { value: c[0] }, c[1]); if (opt[key] === c[0]) o.selected = true; sel.appendChild(o); }); - sel.addEventListener('change', function () { opt[key] = sel.value; }); - return h('label', 'rpt-opt', h('span', null, label), sel); + function showStatus(key, retry) { + while (status.firstChild) status.removeChild(status.firstChild); + status.hidden = !key; + if (!key) return; + status.appendChild(el('span', null, t(key))); + if (retry) { + var b = el('button', { type: 'button', class: 'btn' }, t('rpt.retry')); + b.addEventListener('click', refresh); + status.appendChild(b); + } } - function toolbar() { - var bar = h('div', 'rpt-bar'); - var dl = U.el('button', { type: 'button', class: 'btn' }, t('rpt.dl')); + function refresh() { + if (!frame) return; + showStatus('rpt.loading'); + frame.src = url(true); + } + + function build(c) { + ctx0 = c; + root = el('div', { class: 'rpt' }); + var bar = el('div', { class: 'rpt-bar' }); + var sel = el('select', { class: 'rpt-sel', 'aria-label': t('rpt.lang') }); + [['pt-BR', 'Português'], ['en', 'English']].forEach(function (o) { + var opt = el('option', { value: o[0] }, o[1]); + if (reportLang() === o[0]) opt.selected = true; + sel.appendChild(opt); + }); + sel.addEventListener('change', function () { + lang = sel.value; + try { localStorage.setItem(LANG_KEY, lang); } catch (e) { /* private mode */ } + refresh(); + }); + bar.appendChild(el('label', { class: 'rpt-opt' }, el('span', null, t('rpt.lang')), sel)); + bar.appendChild(el('p', { class: 'rpt-hint' }, t('rpt.scope'))); + var actions = el('div', { class: 'rpt-actions' }); + var dl = el('button', { type: 'button', class: 'btn' }, t('rpt.dl')); dl.addEventListener('click', function () { var a = document.createElement('a'); - a.href = htmlUrl(false); a.download = ''; + a.href = url(false); a.download = ''; document.body.appendChild(a); a.click(); document.body.removeChild(a); }); - var pr = U.el('button', { type: 'button', class: 'btn' }, t('rpt.pdf')); - pr.addEventListener('click', function () { window.open(htmlUrl(true), '_blank', 'noopener'); }); - bar.appendChild(select(t('rpt.opt.period'), 'range', [['', t('rpt.opt.panel')], ['24h', '24h'], ['7d', '7d'], ['30d', '30d'], ['90d', '90d']])); - bar.appendChild(select(t('rpt.opt.lang'), 'lang', [['', ctx0 && ctx0.lang === 'en' ? 'English' : 'Português'], ['pt-BR', 'Português'], ['en', 'English']])); - bar.appendChild(dl); bar.appendChild(pr); - 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); - bar.appendChild(h('p', 'rpt-hint', t('rpt.opt.hint'))); - 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 pr = el('button', { type: 'button', class: 'btn btn-primary' }, t('rpt.print')); + pr.addEventListener('click', function () { + try { frame.contentWindow.focus(); frame.contentWindow.print(); } + catch (e) { window.open(url(true), '_blank', 'noopener'); } }); - 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')); + actions.appendChild(dl); actions.appendChild(pr); + bar.appendChild(actions); - // 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); + status = el('div', { class: 'rpt-status', role: 'status' }); + frame = el('iframe', { class: 'rpt-frame', title: t('rpt.preview') }); + frame.addEventListener('load', function () { + var ok = false; + try { ok = !!(frame.contentDocument && frame.contentDocument.querySelector('h1')); } catch (e) { ok = false; } + showStatus(ok ? '' : 'rpt.err', !ok); + }); + root.appendChild(bar); + root.appendChild(status); + root.appendChild(el('div', { class: 'rpt-sheetwrap' }, frame)); + return root; } 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; } + mount: function (host, c) { host.appendChild(build(c)); refresh(); }, + update: function (c) { ctx0 = c; refresh(); }, + unmount: function () { if (root && root.parentNode) root.parentNode.removeChild(root); root = frame = status = null; } }); return true; } diff --git a/internal/server/web/survival.css b/internal/server/web/survival.css index f2b82f9..9492d34 100644 --- a/internal/server/web/survival.css +++ b/internal/server/web/survival.css @@ -24,3 +24,11 @@ .an-list .an-bad { color: var(--danger); } .an-list .an-good { color: var(--ok); } .an-rec li { margin-right: var(--s-5); } + +/* who blocked: fail2ban vs the Urutau second firewall */ +.sv-blk-bar { display: flex; height: 12px; border-radius: 6px; overflow: hidden; background: var(--line, rgba(127,127,127,.2)); margin: 4px 0 12px; } +.sv-blk-seg { display: block; min-width: 3px; } +.sv-blk-fail2ban { background: var(--accent, #3b82f6); } +.sv-blk-urutau { background: var(--warn, #f59e0b); } +.sv-blk li { display: flex; flex-wrap: wrap; gap: 6px 10px; align-items: center; } +.sv-blk-dot { width: 10px; height: 10px; border-radius: 50%; flex: none; } diff --git a/internal/server/web/survival.js b/internal/server/web/survival.js index c173007..4a26754 100644 --- a/internal/server/web/survival.js +++ b/internal/server/web/survival.js @@ -10,6 +10,13 @@ U.registerI18n({ en: { + 'an.sv.blk': 'Who blocked, and how fast', + 'an.sv.blk.hint': 'Bans applied by the server firewall (fail2ban jails) and by the Urutau second firewall, with the time from the start of the attack episode to the ban.', + 'an.sv.blk.fail2ban': 'Server firewall (fail2ban)', + 'an.sv.blk.urutau': 'Urutau second firewall', + 'an.sv.blk.row': '{n} bans ({pct}) · median {p50} · 90% within {p90}', + 'an.sv.blk.none': 'No bans in this slice.', + 'an.sv.blk.off': 'The Urutau second firewall has not banned anyone in this slice. Turn it on with URUTAU_ENFORCE=on (see Defense).', 'an.sv.title': 'Survival', 'an.sv.lead': 'Half of the attack episodes end in a ban within {dur}', 'an.sv.lead.unknown': 'Fewer than half of the attack episodes ended in a ban', @@ -41,6 +48,13 @@ 'an.sv.retry': 'Try again' }, 'pt-BR': { + 'an.sv.blk': 'Quem bloqueou, e com que rapidez', + 'an.sv.blk.hint': 'Bans aplicados pelo firewall do servidor (jails do fail2ban) e pelo segundo firewall do Urutau, com o tempo entre o início do episódio de ataque e o ban.', + 'an.sv.blk.fail2ban': 'Firewall do servidor (fail2ban)', + 'an.sv.blk.urutau': 'Segundo firewall do Urutau', + 'an.sv.blk.row': '{n} bans ({pct}) · mediana {p50} · 90% em até {p90}', + 'an.sv.blk.none': 'Nenhum ban neste recorte.', + 'an.sv.blk.off': 'O segundo firewall do Urutau não baniu ninguém neste recorte. Ligue com URUTAU_ENFORCE=on (veja Defesa).', 'an.sv.title': 'Sobrevivência', 'an.sv.lead': 'Metade dos episódios de ataque termina em ban em até {dur}', 'an.sv.lead.unknown': 'Menos da metade dos episódios de ataque terminou em ban', @@ -148,16 +162,19 @@ tip(curve, 'term.kaplan_meier'); var fam = U.ui.panel({ title: t('an.sv.fam'), hint: t('an.sv.fam.hint'), loading: true }); tip(fam, 'metric.mttb'); + var blk = U.ui.panel({ title: t('an.sv.blk'), hint: t('an.sv.blk.hint'), loading: true }); + tip(blk, 'term.second_firewall'); var rec = U.ui.panel({ title: t('an.sv.rec'), hint: t('an.sv.rec.hint'), loading: true }); tip(rec, 'term.recidivism'); grid.appendChild(lead); grid.appendChild(curve); curve.classList.add('span-8'); grid.appendChild(fam); fam.classList.add('span-4'); + grid.appendChild(blk); blk.classList.add('span-12'); grid.appendChild(rec); rec.classList.add('span-12'); root.appendChild(grid); function paint() { - clear(lead); [curve, fam, rec].forEach(function (p) { clear(p.body); }); + clear(lead); [curve, fam, blk, rec].forEach(function (p) { clear(p.body); }); if (!data) return; var d = data, range = U.rangeLabel({ inline: true }); if (!d.enabled) { lead.appendChild(U.ui.empty(t('an.sv.off'), t('an.sv.off.d'))); return; } @@ -166,6 +183,7 @@ curve.body.appendChild(U.ui.empty(t('charts.empty'))); fam.body.appendChild(U.ui.empty(t('charts.empty'))); rec.body.appendChild(U.ui.empty(t('charts.empty'))); + blk.body.appendChild(U.ui.empty(t('charts.empty'))); return; } var med = d.median_to_ban_s, p90 = d.p90_to_ban_s, recpct = U.fmt.pct(d.recidivism_pct / 100); @@ -174,6 +192,7 @@ lead.appendChild(U.ui.lead(title, t(typeof p90 === 'number' ? 'an.sv.lead.body' : 'an.sv.lead.body.nop90', vars), typeof med === 'number' && med <= 3600 ? 'ok' : 'danger')); curve.body.appendChild(km(d.km || [], typeof med === 'number' ? med : null)); fam.body.appendChild(boxes(d.by_family || [])); + blockers(d.by_blocker || []); if (!d.recidivists || !d.recidivists.length) { rec.body.appendChild(U.ui.empty(t('an.sv.rec.none'))); return; } var ul = el('ul', { class: 'an-list an-rec' }); d.recidivists.forEach(function (r) { @@ -182,6 +201,28 @@ }); rec.body.appendChild(ul); } + function blockers(list) { + var total = 0, byB = {}; + list.forEach(function (b) { total += b.bans; byB[b.blocker] = b; }); + if (!total) { blk.body.appendChild(U.ui.empty(t('an.sv.blk.none'))); return; } + var bar = el('div', { class: 'sv-blk-bar', role: 'img', 'aria-label': t('an.sv.blk') }); + var ul = el('ul', { class: 'an-list sv-blk' }); + ['fail2ban', 'urutau'].forEach(function (k) { + var b = byB[k]; + var row = el('li', null, el('span', { class: 'sv-blk-dot sv-blk-' + k }), el('strong', null, t('an.sv.blk.' + k))); + if (b) { + var share = b.bans / total; + bar.appendChild(el('span', { class: 'sv-blk-seg sv-blk-' + k })); + bar.lastChild.style.flexGrow = String(b.bans); + row.appendChild(el('span', { class: 'an-n' }, t('an.sv.blk.row', { n: U.fmt.num(b.bans), pct: U.fmt.pct(share), p50: dur(b.median_s), p90: dur(b.p90_s) }))); + } else if (k === 'urutau') { + row.appendChild(el('span', { class: 'an-n' }, t('an.sv.blk.off'))); + } + ul.appendChild(row); + }); + blk.body.appendChild(bar); + blk.body.appendChild(ul); + } function load() { var my = ++seq; var p = Object.assign({}, U.rangeParams()); diff --git a/internal/store/analytics.go b/internal/store/analytics.go index bee0e18..d682991 100644 --- a/internal/store/analytics.go +++ b/internal/store/analytics.go @@ -103,6 +103,7 @@ type SurvivalOut struct { P90ToBanS *int64 `json:"p90_to_ban_s"` KM []KMPoint `json:"km"` ByFamily []FamTTB `json:"by_family"` + ByBlocker []BlockerTTB `json:"by_blocker"` Recidivists []Recidivist `json:"recidivists"` RecidivismPct float64 `json:"recidivism_pct"` } @@ -149,6 +150,7 @@ func anPareto(sorted []AnItem, total uint64) []AnItem { type anSubject struct { T int64 Event bool + Ban int64 // time of the ban that ended the episode (Event only) } // anKaplanMeier returns the survival curve (starting at t=0, S=1) with one @@ -436,9 +438,26 @@ func (s *Store) Survival(from, to int64, host string) SurvivalOut { } type anIPState struct { - mal []int64 - bans []int64 - fam string + mal []int64 + bans []int64 + banJail map[int64]string + fam string +} + +// BlockerTTB is the time to ban of the bans applied by one blocker: the host +// fail2ban jails, or Urutau's second firewall (its "urutau" jail). +type BlockerTTB struct { + Blocker string `json:"blocker"` // "fail2ban" or "urutau" + Bans int `json:"bans"` + MedianS int64 `json:"median_s"` + P90S int64 `json:"p90_s"` +} + +func blockerOf(jail string) string { + if jail == "urutau" { + return "urutau" + } + return "fail2ban" } // anEpisodes splits the activity of one address into attack episodes. An @@ -472,7 +491,7 @@ func anEpisodes(mal, bans []int64, end int64) []anSubject { } i = j if next >= 0 && next-last <= episodeGap { - out = append(out, anSubject{next - start, true}) + out = append(out, anSubject{T: next - start, Event: true, Ban: next}) prev = next bi++ continue @@ -485,7 +504,7 @@ func anEpisodes(mal, bans []int64, end int64) []anSubject { if d < 0 { d = 0 } - out = append(out, anSubject{d, false}) + out = append(out, anSubject{T: d}) prev = last } return out @@ -514,6 +533,12 @@ func (s *Store) survival(from, to int64, host string) SurvivalOut { } if isBan { st.bans = append(st.bans, r.T) + if r.Jail != "" { + if st.banJail == nil { + st.banJail = map[int64]string{} + } + st.banJail[r.T] = r.Jail + } return true } if len(st.mal) < 5000 { @@ -530,6 +555,7 @@ func (s *Store) survival(from, to int64, host string) SurvivalOut { } var subs []anSubject famT := map[string][]int64{} + blockT := map[string][]int64{} var banned, recid, attackers int var rec []Recidivist for ip, st := range ips { @@ -540,6 +566,10 @@ func (s *Store) survival(from, to int64, host string) SurvivalOut { eps := anEpisodes(st.mal, st.bans, end) subs = append(subs, eps...) for _, e := range eps { + if e.Event { + b := blockerOf(st.banJail[e.Ban]) + blockT[b] = append(blockT[b], e.T) + } if e.Event && st.fam != "" { famT[st.fam] = append(famT[st.fam], e.T) } @@ -557,6 +587,15 @@ func (s *Store) survival(from, to int64, host string) SurvivalOut { if banned > 0 { out.RecidivismPct = math.Round(float64(recid)/float64(banned)*1000) / 10 } + out.ByBlocker = []BlockerTTB{} + for _, b := range []string{"fail2ban", "urutau"} { + v := blockT[b] + if len(v) == 0 { + continue + } + sort.Slice(v, func(i, j int) bool { return v[i] < v[j] }) + out.ByBlocker = append(out.ByBlocker, BlockerTTB{b, len(v), anQuant(v, .5), anQuant(v, .9)}) + } for f, v := range famT { sort.Slice(v, func(i, j int) bool { return v[i] < v[j] }) out.ByFamily = append(out.ByFamily, FamTTB{f, anQuant(v, .25), anQuant(v, .5), anQuant(v, .75), len(v)}) diff --git a/internal/store/analytics_test.go b/internal/store/analytics_test.go index c70b45a..fb7201b 100644 --- a/internal/store/analytics_test.go +++ b/internal/store/analytics_test.go @@ -36,7 +36,7 @@ func TestPareto(t *testing.T) { func TestKaplanMeierCensoring(t *testing.T) { // times 10(ban) 20(censored) 30(ban) 40(ban): S(10)=3/4, at 30 risk=2 -> 3/4*1/2, at 40 risk=1 -> 0 - c, med, p90 := anKaplanMeier([]anSubject{{10, true}, {20, false}, {30, true}, {40, true}}) + c, med, p90 := anKaplanMeier([]anSubject{{T: 10, Event: true}, {T: 20, Event: false}, {T: 30, Event: true}, {T: 40, Event: true}}) want := []KMPoint{{0, 1}, {10, 0.75}, {30, 0.375}, {40, 0}} if len(c) != len(want) { t.Fatalf("%+v", c) @@ -50,7 +50,7 @@ func TestKaplanMeierCensoring(t *testing.T) { t.Fatalf("median %v p90 %v", med, p90) } // everybody censored: no event, no median - c, med, p90 = anKaplanMeier([]anSubject{{5, false}, {9, false}}) + c, med, p90 = anKaplanMeier([]anSubject{{T: 5, Event: false}, {T: 9, Event: false}}) if len(c) != 1 || med != nil || p90 != nil { t.Fatalf("censored %+v", c) } @@ -60,7 +60,7 @@ func TestKaplanMeierCensoring(t *testing.T) { } var many []anSubject for i := 1; i <= 1000; i++ { - many = append(many, anSubject{int64(i), true}) + many = append(many, anSubject{T: int64(i), Event: true}) } if c, _, _ := anKaplanMeier(many); len(c) != anKMPoints || c[len(c)-1].Survival != 0 { t.Fatalf("downsample %d", len(c)) @@ -165,7 +165,7 @@ func TestAnEpisodes(t *testing.T) { // episode 1: 0..60, banned at 100 (observed 100); episode 2: 200 alone, silent until 10000 (censored 200+1800-200); // episode 3: 10000, 10100 then end of data (censored at last+30min) got := anEpisodes([]int64{0, 60, 200, 10000, 10100}, []int64{100}, end) - want := []anSubject{{100, true}, {1800, false}, {1900, false}} + want := []anSubject{{T: 100, Event: true, Ban: 100}, {T: 1800, Event: false}, {T: 1900, Event: false}} if len(got) != len(want) { t.Fatalf("%+v", got) } @@ -176,7 +176,7 @@ func TestAnEpisodes(t *testing.T) { } // a ban long after the last event does not end that episode; censoring is capped at the window end got = anEpisodes([]int64{0}, []int64{5000}, 600) - if len(got) != 1 || got[0] != (anSubject{600, false}) { + if len(got) != 1 || got[0] != (anSubject{T: 600, Event: false}) { t.Fatalf("%+v", got) } if len(anEpisodes(nil, []int64{5}, end)) != 0 {