feat: 1.4.0 second firewall, egress analysis and HTML report
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 16s
CI / Tests (Linux, race detector) (push) Successful in 1m3s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 3s

Optional second firewall (URUTAU_ENFORCE off/observe/on) through the host
fail2ban, outbound traffic analysis (beaconing, mining, spam, DNS bypass,
unauthorised scans) with authorised scanner workloads, host kit in
deploy/host and a printable HTML report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-14 23:35:34 -03:00
1 parent 3adaa007ec
commit c33cca22e3
59 files changed
+7364 -24

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
package server
import (
"encoding/json"
"net/http"
"sort"
"sync/atomic"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
)
func init() {
registerUserRoute("GET /api/v1/egress", func(s *Server) http.HandlerFunc { return s.egressAPI })
}
var egressEngine atomic.Pointer[egress.Engine]
// SetEgress attaches the egress engine (nil disables the endpoints). It is
// called by the daemon wiring, before or after the server starts.
func SetEgress(e *egress.Engine) { egressEngine.Store(e) }
type egressOut struct {
Enabled bool `json:"enabled"`
Source egress.SourceInfo `json:"source"`
egress.Report
}
// egressAPI: GET /api/v1/egress?range=24h&host=all|<name>. On a hub the
// local engine and the peers' reports are merged, items carrying "host".
func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
host := r.URL.Query().Get("host")
if len(host) > 253 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host"})
return
}
local, peers, only, ok := s.studyHosts(w, host)
if !ok {
return
}
from, to := rg.Bounds(s.opt.Store.Now().Unix())
eng := egressEngine.Load()
out := egressOut{Source: egress.SourceInfo{State: "disabled"}}
if eng != nil {
out.Source = eng.Info()
out.Enabled = true
}
rep := egress.EmptyReport()
if local && eng != nil {
rep = eng.Report(from, to)
}
if peers && s.opt.Hub != nil {
merged := egress.EmptyReport()
merged.Timeline.Start = rep.Timeline.Start
if local && eng != nil {
rep.Stamp(s.opt.Store.Name())
merged.Merge(rep, s.opt.Store.Name())
}
raws := s.opt.Hub.EgressFor(r.Context(), from, to, only)
names := make([]string, 0, len(raws))
for n := range raws {
names = append(names, n)
}
sort.Strings(names)
for _, n := range names {
var pr egress.Report
if json.Unmarshal(raws[n], &pr) != nil {
continue
}
pr.Sanitize(n)
merged.Merge(pr, n)
out.Enabled = true
}
rep = merged
}
out.Report = rep
writeJSON(w, 200, out)
}
// peerEgress: GET /api/v1/peer/egress, the local report a hub merges; opened
// only by the peer token (and --peer-allow). It must be registered next to
// the other peer routes.
func (s *Server) peerEgress(w http.ResponseWriter, r *http.Request) {
if !s.peerGate(w, r) {
return
}
eng := egressEngine.Load()
if eng == nil {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "egress is not enabled"})
return
}
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
from, to := rg.Bounds(s.opt.Store.Now().Unix())
writeJSON(w, 200, eng.Report(from, to))
}
+99
View File
@@ -0,0 +1,99 @@
package server
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/netip"
"strconv"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestEgressAPI(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
h := New(Options{Token: userTok, Version: "t", Store: st})
auth := map[string]string{"Authorization": "Bearer " + userTok}
SetEgress(nil)
d := getJSON(t, h, "/api/v1/egress?range=24h", auth)
if d["enabled"] != false || d["findings"] == nil || d["top_dst"] == nil {
t.Fatalf("disabled: %v", d)
}
e, err := egress.New(egress.Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
if err != nil {
t.Fatal(err)
}
SetEgress(e)
defer SetEgress(nil)
now := time.Now()
ev := func(at time.Time, src, dst string, port uint16) egress.Event {
return egress.Event{Time: at, Src: netip.MustParseAddr(src), Dst: netip.MustParseAddr(dst), Proto: "tcp", DPort: port, In: "br-1"}
}
e.IngestEvent(ev(now.Add(-time.Hour), "10.0.3.5", "203.0.113.3", 6667))
e.IngestEvent(ev(now.Add(-time.Hour), "10.0.3.5", "203.0.113.4", 443))
for i := 0; i < 80; i++ {
e.IngestEvent(ev(now.Add(-30*time.Minute+time.Duration(i)*time.Second), "10.0.5.2", "198.18.0."+strconv.Itoa(i+1), 80))
}
d = getJSON(t, h, "/api/v1/egress?range=24h", auth)
if d["enabled"] != true || d["source"].(map[string]any)["state"] == nil {
t.Fatalf("enabled: %v", d)
}
var port map[string]any
for _, f := range d["findings"].([]any) {
if m := f.(map[string]any); m["kind"] == "port" {
port = m
}
}
if port == nil || port["severity"] != "medium" || port["dport"].(float64) != 6667 || port["workload"] != "container 10.0.3.5" {
t.Fatalf("findings: %v", d["findings"])
}
if len(d["scanner"].(map[string]any)["bursts"].([]any)) != 1 || len(d["workloads"].([]any)) != 2 {
t.Fatalf("scanner/workloads: %v", d)
}
if tl := d["timeline"].(map[string]any); tl["step"].(float64) != 3600 || len(tl["series"].(map[string]any)) != 2 {
t.Fatalf("timeline: %v", tl)
}
if w := do(h, "GET", "/api/v1/egress?range=bogus", cloneHdr(auth), nil); w.Code != 400 {
t.Fatalf("range: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/egress?host=nope", cloneHdr(auth), nil); w.Code != 404 {
t.Fatalf("host: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/egress?range=24h", nil, nil); w.Code != 401 {
t.Fatalf("auth: %d", w.Code)
}
if w := do(h, "GET", "/api/v1/egress?range=24h", map[string]string{"Authorization": "Bearer peer-secret"}, nil); w.Code == 200 {
t.Fatalf("peer token must not open the user route")
}
// peer endpoint (registered by the daemon next to the other peer routes)
s := &Server{opt: Options{PeerTokens: []string{"peer-secret"}, Token: userTok, Store: st, Now: time.Now}, ses: newSessions(), lim: newLimiter()}
m := http.NewServeMux()
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
call := func(tok string) *httptest.ResponseRecorder {
r := httptest.NewRequest("GET", "/api/v1/peer/egress?range=24h", nil)
r.RemoteAddr = "198.51.100.1:1234"
if tok != "" {
r.Header.Set("Authorization", "Bearer "+tok)
}
w := httptest.NewRecorder()
m.ServeHTTP(w, r)
return w
}
if w := call(""); w.Code != 401 {
t.Fatalf("peer no token: %d", w.Code)
}
if w := call(userTok); w.Code != 401 {
t.Fatalf("user token on peer route: %d", w.Code)
}
w := call("peer-secret")
var rep egress.Report
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &rep) != nil || len(rep.Findings) == 0 {
t.Fatalf("peer: %d %s", w.Code, w.Body)
}
}
+112
View File
@@ -0,0 +1,112 @@
package server
import (
"encoding/json"
"errors"
"io"
"net/http"
"strconv"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
)
// enforceEngine is the optional second firewall (nil when --enforce is off).
var enforceEngine atomic.Pointer[enforce.Engine]
// SetEnforce installs the engine the enforce endpoints talk to.
func SetEnforce(e *enforce.Engine) { enforceEngine.Store(e) }
// peerRoute is a route opened by the federation token, contributed by its own file.
type peerRoute struct {
pattern string
handler func(*Server) http.HandlerFunc
}
var peerRoutes []peerRoute
const maxDecisionBody = 64 << 10
func init() {
registerUserRoute("GET /api/v1/enforce", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rg, ok := s.rangeOf(w, r)
if !ok {
return
}
now := s.opt.Now()
from := now.Add(-rg.Dur).Unix()
if rg.From > 0 {
from = rg.From
}
out := map[string]any{"mode": enforce.ModeOff, "share": "off", "threshold": 0, "log_writable": false,
"coverage": enforce.Coverage{}, "counts": enforce.Counts{Skipped: map[string]int{}}, "recent": []enforce.Recent{}}
if e := enforceEngine.Load(); e != nil {
rep := e.Report(from)
share := "off"
if e.Share() {
share = "on"
}
out["mode"], out["share"], out["threshold"] = e.Mode(), share, e.Threshold()
out["log_writable"] = enforce.Writable(e.LogPath())
out["coverage"], out["counts"], out["recent"] = rep.Coverage, rep.Counts, rep.Recent
}
writeJSON(w, http.StatusOK, out)
}
})
peerRoutes = append(peerRoutes,
peerRoute{"GET /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
e := enforceEngine.Load()
if !s.peerGate(w, r) {
return
}
if e == nil || !e.Share() || e.Mode() != enforce.ModeOn {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
return
}
since, _ := strconv.ParseInt(r.URL.Query().Get("since"), 10, 64)
if min := s.opt.Now().Add(-24 * time.Hour).Unix(); since < min {
since = min
}
writeJSON(w, http.StatusOK, map[string]any{"decisions": e.LocalSince(since)})
}
}},
peerRoute{"POST /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
e := enforceEngine.Load()
if !s.peerGate(w, r) {
return
}
if e == nil || !e.Share() {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxDecisionBody))
if err != nil {
var mb *http.MaxBytesError
if errors.As(err, &mb) {
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "body too large"})
} else {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "unreadable body"})
}
return
}
var in struct {
Decisions []enforce.Wire `json:"decisions"`
}
if json.Unmarshal(body, &in) != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
if len(in.Decisions) > enforce.MaxWire {
writeJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "too many decisions"})
return
}
acc, bad := e.AcceptPeer(r.URL.Query().Get("from"), in.Decisions)
writeJSON(w, http.StatusOK, map[string]int{"accepted": acc, "invalid": bad})
}
}},
)
}
+181
View File
@@ -0,0 +1,181 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func enforceRig(t *testing.T, share bool) (http.Handler, *enforce.Engine, string) {
t.Helper()
log := filepath.Join(t.TempDir(), "decisions.log")
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
e := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: log, Host: "oracle", Threshold: 3, Share: share})
st.SetIngestHook(e.Observe)
SetEnforce(e)
t.Cleanup(func() { SetEnforce(nil) })
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, log
}
func TestEnforceAPI(t *testing.T) {
h, e, log := enforceRig(t, true)
auth := map[string]string{"Authorization": "Bearer " + userTok}
d := getJSON(t, h, "/api/v1/enforce?range=24h", auth)
if d["mode"] != "on" || d["share"] != "on" || d["threshold"].(float64) != 3 || d["log_writable"] != true {
t.Fatalf("%v", d)
}
for _, k := range []string{"coverage", "counts", "recent"} {
if d[k] == nil {
t.Fatalf("missing %s: %v", k, d)
}
}
if sk := d["counts"].(map[string]any)["skipped"].(map[string]any); len(sk) != 7 {
t.Fatalf("skipped %v", sk)
}
// feed events through the store hook and the engine worker
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go e.Run(ctx)
e.Observe(core.Event{Time: time.Now(), IP: "203.0.114.5", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
for i := 0; i < 200 && e.Report(0).Coverage.AttackIPs == 0; i++ {
time.Sleep(10 * time.Millisecond)
}
e.AcceptPeer("hostinger", []enforce.Wire{{T: time.Now().Unix(), IP: "203.0.114.5", Reason: "rce", Score: 90, TTL: 3600}})
d = getJSON(t, h, "/api/v1/enforce?range=24h", auth)
rec := d["recent"].([]any)
if len(rec) != 1 {
t.Fatalf("recent %v", d)
}
r := rec[0].(map[string]any)
if r["action"] != "ban" || r["src"] != "peer:hostinger" || r["ip"] != "203.0.114.5" {
t.Fatalf("%v", r)
}
if b, _ := os.ReadFile(log); !strings.Contains(string(b), "src=peer:hostinger") {
t.Fatalf("log %q", b)
}
if w := do(h, "GET", "/api/v1/enforce?range=24h", nil, nil); w.Code != 401 {
t.Fatalf("anonymous %d", w.Code)
}
if w := do(h, "GET", "/api/v1/enforce?range=24h", map[string]string{"Authorization": "Bearer " + peerTok}, nil); w.Code != 403 {
t.Fatalf("peer token %d", w.Code)
}
if w := do(h, "GET", "/api/v1/enforce?range=bad", cloneHdr(auth), nil); w.Code != 400 {
t.Fatalf("bad range %d", w.Code)
}
}
func TestEnforceAPIOff(t *testing.T) {
st := store.New(store.Config{Name: "oracle", Version: "t"})
SetEnforce(nil)
h := New(Options{Token: userTok, Store: st})
d := getJSON(t, h, "/api/v1/enforce", map[string]string{"Authorization": "Bearer " + userTok})
if d["mode"] != "off" {
t.Fatalf("%v", d)
}
}
func post(h http.Handler, path, tok, body string) *httptest.ResponseRecorder {
r := httptest.NewRequest("POST", path, strings.NewReader(body))
r.RemoteAddr = "198.51.100.1:1234"
r.Header.Set("Content-Type", "application/json")
if tok != "" {
r.Header.Set("Authorization", "Bearer "+tok)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
func TestPeerDecisionsEndpoints(t *testing.T) {
h, e, log := enforceRig(t, true)
good := `{"decisions":[{"t":` + strconv.FormatInt(time.Now().Unix(), 10) + `,"ip":"203.0.114.9","reason":"sqli","score":80,"ttl":3600},` +
`{"t":1,"ip":"203.0.114.10","reason":"x\ny","score":80,"ttl":3600},{"ip":"10.0.0.1","reason":"rce","ttl":60}]}`
p := "/api/v1/peer/decisions?from=hostinger"
for _, tok := range []string{"", "wrong-token-0123456789-abcdefghijklmnopqrs", userTok} {
if w := post(h, p, tok, good); w.Code != 401 && w.Code != 403 {
t.Fatalf("token %q: %d", tok, w.Code)
}
if w := do(h, "GET", "/api/v1/peer/decisions", map[string]string{"Authorization": "Bearer " + tok}, nil); w.Code != 401 && w.Code != 403 {
t.Fatalf("GET token %q: %d", tok, w.Code)
}
}
if w := post(h, p, peerTok, strings.Repeat(" ", 70<<10)); w.Code != 413 {
t.Fatalf("big body: %d", w.Code)
}
if w := post(h, p, peerTok, "{nope"); w.Code != 400 {
t.Fatalf("bad json: %d", w.Code)
}
var many strings.Builder
many.WriteString(`{"decisions":[`)
for i := 0; i < 501; i++ {
if i > 0 {
many.WriteString(",")
}
many.WriteString(`{"ip":"1.1.1.1"}`)
}
many.WriteString(`]}`)
if w := post(h, p, peerTok, many.String()); w.Code != 413 {
t.Fatalf("501 items: %d", w.Code)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go e.Run(ctx)
e.Observe(core.Event{Time: time.Now(), IP: "203.0.114.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x", Status: 404, UA: "x"}, "")
for i := 0; i < 200 && e.Report(0).Coverage.AttackIPs == 0; i++ {
time.Sleep(10 * time.Millisecond)
}
w := post(h, p, peerTok, good)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) || !strings.Contains(w.Body.String(), `"invalid":2`) {
t.Fatalf("%d %s", w.Code, w.Body)
}
b, _ := os.ReadFile(log)
if strings.Count(string(b), "\n") != 1 || !strings.Contains(string(b), "ip=203.0.114.9 reason=sqli") || !strings.Contains(string(b), "src=peer:hostinger") {
t.Fatalf("log %q", b)
}
// GET returns local decisions only
if len(e.LocalSince(0)) != 0 {
t.Fatal("peer decision leaked into the local list")
}
rr := do(h, "GET", "/api/v1/peer/decisions?since=0", map[string]string{"Authorization": "Bearer " + peerTok}, nil)
if rr.Code != 200 || !strings.Contains(rr.Body.String(), `"decisions":[]`) {
t.Fatalf("%d %s", rr.Code, rr.Body)
}
}
func TestPeerDecisionsShareOff(t *testing.T) {
h, _, _ := enforceRig(t, false)
if w := post(h, "/api/v1/peer/decisions", peerTok, `{"decisions":[]}`); w.Code != 404 {
t.Fatalf("share off: %d", w.Code)
}
}
func TestEnforceFromStoreHook(t *testing.T) {
log := filepath.Join(t.TempDir(), "d.log")
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
e := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: log, Host: "oracle", Threshold: 3})
st.SetIngestHook(e.Observe)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go e.Run(ctx)
for i := 0; i < 3; i++ {
st.Ingest(core.Event{Time: time.Now(), IP: "203.0.114.9", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/x" + strconv.Itoa(i), Status: 404, UA: "nuclei"})
}
deadline := time.Now().Add(2 * time.Second)
for time.Now().Before(deadline) {
if b, _ := os.ReadFile(log); strings.Contains(string(b), "ip=203.0.114.9 ") {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Fatal("no decision written")
}
+29 -7
View File
@@ -121,10 +121,31 @@ var attackCats = []string{"scanner", "exploit", "bruteforce", "ssh-fail", "ssh-p
// report: GET /api/v1/report, the aggregate behind the executive report.
func (s *Server) report(w http.ResponseWriter, r *http.Request) {
if f := r.URL.Query().Get("format"); f != "" && f != "json" {
badRequest(w, "format must be json")
f := r.URL.Query().Get("format")
if f != "" && f != "json" && f != "html" {
badRequest(w, "format must be json or html")
return
}
rc, ok := s.buildReport(w, r)
if !ok {
return
}
if f == "html" {
s.writeReportHTML(w, r, rc)
return
}
writeJSON(w, 200, rc.out)
}
// reportCtx is the computed report plus the window it covers.
type reportCtx struct {
out reportOut
rg store.Range
host string
from, to int64
}
func (s *Server) buildReport(w http.ResponseWriter, r *http.Request) (*reportCtx, bool) {
if r.URL.Query().Get("range") == "" && r.URL.Query().Get("from") == "" {
q := r.URL.Query()
q.Set("range", "7d")
@@ -132,14 +153,14 @@ func (s *Server) report(w http.ResponseWriter, r *http.Request) {
}
rg, ok := s.rangeOf(w, r)
if !ok {
return
return nil, false
}
host := r.URL.Query().Get("host")
if host == "" {
host = "all"
}
if !s.knownHost(w, host) {
return
return nil, false
}
now := s.opt.Now().Unix()
info := rg.Info(now)
@@ -149,7 +170,7 @@ func (s *Server) report(w http.ResponseWriter, r *http.Request) {
// period study (families, techniques, ASNs, campaigns, escalations)
per, ok := s.periodStudy(w, r)
if !ok {
return
return nil, false
}
// summary of the period and of the previous one
parts, all := s.parts(r.Context(), rg, host)
@@ -262,13 +283,14 @@ func (s *Server) report(w http.ResponseWriter, r *http.Request) {
// defence metrics (same study and slot as /metrics)
m, ok := s.reportMetrics(w, r, rg, host)
if !ok {
return
return nil, false
}
d := &out.Defense
d.MTTBMedianS, d.MTTBP90S, d.MTTBPrevMedianS, d.MTTBN = m.MTTB.MedianS, m.MTTB.P90S, m.MTTB.PrevMed, m.MTTB.N
d.BanCoverage, d.BanCoveragePrev = m.BanCoverage.Value, m.BanCoverage.Prev
d.BlocklistCover, d.ExposureRate, d.ExploitsRefused = m.BlocklistCoverage.Value, m.ExposureRate.Value, m.ExploitsRefused.Value
writeJSON(w, 200, out)
f, t := rg.Bounds(now)
return &reportCtx{out: out, rg: rg, host: host, from: f, to: t}, true
}
func capCounts(c []store.Count, n int) []store.Count {
+774
View File
@@ -0,0 +1,774 @@
package server
import (
"bytes"
"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"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// This file renders GET /api/v1/report?format=html: one self-contained A4 document
// (inline CSS, SVG charts, logo as data URI, no JavaScript). Every dynamic string
// goes through html/template; SVG is built here from escaped text and numbers.
// enforceView is the second-firewall data of the report (nil: engine not running).
type enforceView struct {
Mode string
Share bool
Coverage enforce.Coverage
Counts enforce.Counts
Recent []enforce.Recent
}
// egressView is the outbound-traffic data of the report (nil: analysis not running).
type egressView struct {
Source egress.SourceInfo
Report egress.Report
}
// reportInput is everything the renderer needs. To wire another source, fill a
// field here in reportExtras; the renderer skips sections whose pointer is nil.
type reportInput struct {
Out reportOut
Lang string
Traffic store.TrafficData
Classes [store.NumCls]uint32
HasHealth bool
Enforce *enforceView
Egress *egressView
Peers bool // other hosts included: health and egress cover only this server
}
var (
logoOnce sync.Once
logoURI string
)
// 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)
}
// 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
}
// ---- view model -------------------------------------------------------------
type kpiV struct{ Label, Value, Delta, Cls string }
type rowV struct{ Cells []string }
type tableV struct {
Head []string
Rows []rowV
Num map[int]bool // right-aligned columns
NoWrap map[int]bool
None string
}
type chartV struct {
Title string
SVG template.HTML
Legend []legendV
Empty bool
}
type legendV struct{ Label, Value, Color string }
type recV struct{ Level, Label, Text string }
type secV struct{ ID, Title string }
type viewV struct {
Lang, Title, RunHead, RunFoot, Kicker, CoverTitle, CoverSub string
Logo template.URL
Motif template.HTML
Servers, Period, Generated string
LPeriod, LServers, LGen, LConf, LToc string
CoverNums []kpiV
TOC []secV
KPIs []kpiV
VerdictCls, VerdictTitle string
Verdict []string
Recs []recV
Trunc string
Timeline chartV
Fams, Techs chartV
IPs, Camps, Escs tableV
Expo tableV
Countries, ASNs chartV
HealthLead string
HealthNotes []string
Classes, Status chartV
VisLead string
VisKPIs []kpiV
Pages, Browsers, Devices, Refs chartV
Defense tableV
HasEnf bool
EnfLead string
EnfNotes []string
EnfKPIs []kpiV
EnfRecent tableV
HasEgress bool
XLead string
XNotes []string
XWl, XFind tableV
XChart, XDst chartV
NoEnf, NoEgress, None, PeersNote, MethodP1, MethodP2, MethodP3 string
TThreats, TGeo, THealth, TVis, TDef, TEnf, TEgress, TRecs, TMethod, TSum string
TIPs, TCamps, TEscs, TExpo, TTimeline, TFams, TTechs, TCountries, TASNs string
TEnfRecent, TXFind, TXWl, TXChart, TXDst, TClasses, TStatus string
ShowPeers bool
}
var rptCCRe = regexp.MustCompile(`^[A-Za-z]{2}$`)
type renderer struct {
lang int
code string
}
func newRenderer(lang string) *renderer {
if strings.HasPrefix(strings.ToLower(lang), "en") {
return &renderer{1, "en"}
}
return &renderer{0, "pt-BR"}
}
func (r *renderer) t(key string, args ...any) string {
v, ok := reportText[key]
if !ok {
return key
}
s := v[r.lang]
if len(args) > 0 {
return fmt.Sprintf(s, args...)
}
return s
}
// num formats integers with the thousands separator of the language.
func (r *renderer) num(n float64) string {
neg := n < 0
if neg {
n = -n
}
s := fmt.Sprintf("%.0f", n)
sep := "."
if r.lang == 1 {
sep = ","
}
var out []byte
for i := range s {
if i > 0 && (len(s)-i)%3 == 0 {
out = append(out, sep...)
}
out = append(out, s[i])
}
if neg {
return "-" + string(out)
}
return string(out)
}
func (r *renderer) dec(v float64, d int) string {
s := fmt.Sprintf("%.*f", d, v)
if r.lang == 0 {
s = strings.Replace(s, ".", ",", 1)
}
return s
}
func (r *renderer) pct(v float64) string { return r.dec(v, 1) + "%" }
func (r *renderer) dur(sec float64) string {
s := int64(sec + 0.5)
switch {
case s < 60:
return fmt.Sprintf("%ds", s)
case s < 3600:
return fmt.Sprintf("%dmin", s/60)
case s < 86400:
return fmt.Sprintf("%dh%02d", s/3600, s%3600/60)
}
return fmt.Sprintf("%dd", s/86400)
}
func (r *renderer) date(ts int64) string {
if r.lang == 1 {
return time.Unix(ts, 0).UTC().Format("2006-01-02 15:04 UTC")
}
return time.Unix(ts, 0).UTC().Format("02/01/2006 15:04 UTC")
}
func (r *renderer) day(ts int64) string {
if r.lang == 1 {
return time.Unix(ts, 0).UTC().Format("2006-01-02")
}
return time.Unix(ts, 0).UTC().Format("02/01/2006")
}
func (r *renderer) yn(b bool) string {
if b {
return r.t("yes")
}
return r.t("no")
}
func (r *renderer) tr(prefix, k string) string {
if v, ok := reportText[prefix+k]; ok {
return v[r.lang]
}
return k
}
func ccOf(cc, name string) string {
switch {
case rptCCRe.MatchString(cc) && name != "":
return strings.ToUpper(cc) + " · " + name
case rptCCRe.MatchString(cc):
return strings.ToUpper(cc)
case name != "":
return name
}
return "-"
}
func (r *renderer) counts(c []store.Count, label func(store.Count) string, n int) []chartItem {
var out []chartItem
for i, x := range c {
if i >= n {
break
}
out = append(out, chartItem{label(x), float64(x.N)})
}
return out
}
func (r *renderer) barChart(title string, items []chartItem, color string) chartV {
if len(items) == 0 {
return chartV{Title: title, Empty: true}
}
return chartV{Title: title, SVG: template.HTML(svgBars(items, color, func(v float64) string { return r.num(v) }, title))}
}
func (r *renderer) donutChart(title string, items []chartItem) chartV {
var total float64
for _, it := range items {
total += it.N
}
if total <= 0 {
return chartV{Title: title, Empty: true}
}
c := chartV{Title: title, SVG: template.HTML(svgDonut(items, title))}
for i, it := range items {
c.Legend = append(c.Legend, legendV{it.Label, r.num(it.N) + " · " + r.pct(it.N/total*100), reportPalette[i%len(reportPalette)]})
}
return c
}
func delta(r *renderer, v float64, ok bool, prev float64) string {
if !ok {
return ""
}
a := "▲"
if v < 0 {
a = "▼"
}
if v > -0.5 && v < 0.5 {
a = "="
}
if v < 0 {
v = -v
}
return fmt.Sprintf("%s %s%% · %s", a, r.num(v+0.0001), r.t("k.before", r.num(prev)))
}
// build turns the data into the view model (all the report decisions live here).
func (r *renderer) build(in reportInput, genTS int64) viewV {
o, s := in.Out, in.Out.Summary
v := viewV{Lang: r.code, Logo: logoDataURI()}
v.Title, v.RunHead, v.RunFoot = r.t("doc.title"), r.t("run.head"), r.t("run.foot")
v.Kicker, v.CoverTitle, v.CoverSub = r.t("cover.kicker"), r.t("cover.title"), r.t("cover.sub")
v.LPeriod, v.LServers, v.LGen, v.LConf, v.LToc = r.t("cover.period"), r.t("cover.servers"), r.t("cover.gen"), r.t("cover.conf"), r.t("toc")
v.None, v.NoEnf, v.NoEgress, v.PeersNote = r.t("none"), r.t("noenf"), r.t("noegress"), r.t("peers.note")
v.MethodP1, v.MethodP2, v.MethodP3 = r.t("m.p1"), r.t("m.p2"), r.t("m.p3")
v.TSum, v.TThreats, v.TGeo, v.THealth, v.TVis = r.t("s.sum"), r.t("s.threats"), r.t("s.geo"), r.t("s.health"), r.t("s.visitors")
v.TDef, v.TEnf, v.TEgress, v.TRecs, v.TMethod = r.t("s.defense"), r.t("s.enforce"), r.t("s.egress"), r.t("s.recs"), r.t("s.method")
v.TIPs, v.TCamps, v.TEscs, v.TExpo, v.TTimeline = r.t("t.ips"), r.t("t.camp"), r.t("t.esc"), r.t("t.expo"), r.t("c.timeline")
v.TFams, v.TTechs, v.TCountries, v.TASNs = r.t("c.families"), r.t("c.techs"), r.t("c.countries"), r.t("c.asns")
v.TEnfRecent, v.TXFind, v.TXWl, v.TXChart, v.TXDst = r.t("t.enf"), r.t("t.find"), r.t("t.wl"), r.t("c.egress"), r.t("c.dst")
v.TClasses, v.TStatus = r.t("c.classes"), r.t("c.status")
v.ShowPeers = in.Peers
servers := r.t("cover.all")
if len(o.Hosts) > 0 {
servers = strings.Join(o.Hosts, ", ")
}
v.Servers = servers
v.Period = r.day(o.Range.From) + " – " + r.day(o.Range.To)
v.Generated = r.date(genTS)
cover := 0.0
if s.HostileIPs > 0 {
cover = o.Defense.BanCoverage
}
v.CoverNums = []kpiV{
{Label: r.t("k.attacks"), Value: r.num(float64(s.Attacks))},
{Label: r.t("k.hostile"), Value: r.num(float64(s.HostileIPs))},
{Label: r.t("k.bans"), Value: r.num(float64(s.Bans))},
{Label: r.t("k.coverage"), Value: r.dec(cover, 0) + "%"},
}
// signals for verdict and recommendations
expo := o.Exposures.Total
var xHigh int
if in.Egress != nil {
for _, f := range in.Egress.Report.Findings {
if f.Severity == "high" || f.Severity == "critical" {
xHigh++
}
}
}
level := "good"
switch {
case expo > 0 || xHigh > 0:
level = "bad"
case len(o.Escalations) > 0 || (s.HostileIPs > 0 && cover < 80):
level = "warn"
}
v.VerdictCls = level
v.VerdictTitle = r.t("verdict." + level)
// verdict paragraph, lay language
var vd []string
if s.Attacks == 0 {
vd = append(vd, r.t("v.none"))
} else {
vd = append(vd, r.t("v.intro", servers, r.num(float64(s.Attacks)), r.num(float64(s.UniqueIPs)), r.num(float64(s.HostileIPs)), r.num(float64(s.Bans))))
if dp, ok := s.DeltaPct["attacks"]; s.HasPrev && ok {
switch {
case dp > -5 && dp < 5:
vd = append(vd, r.t("v.flat"))
case dp > 0:
vd = append(vd, r.t("v.up", r.num(dp)))
default:
vd = append(vd, r.t("v.down", r.num(-dp)))
}
} else {
vd = append(vd, r.t("v.noprev"))
}
if len(o.Families) > 0 && len(o.Countries) > 0 {
vd = append(vd, r.t("v.top", o.Families[0].Key, o.Countries[0].Key))
}
if s.HostileIPs > 0 {
vd = append(vd, r.t("v.cover", r.dec(cover, 0)))
}
if o.Defense.MTTBN > 0 {
vd = append(vd, r.t("v.mttb", r.dur(o.Defense.MTTBMedianS)))
}
}
if expo > 0 {
vd = append(vd, r.t("v.expo", r.num(float64(expo))))
} else if s.Attacks > 0 {
vd = append(vd, r.t("v.expo0"))
}
if len(o.Escalations) > 0 {
vd = append(vd, r.t("v.esc", r.num(float64(len(o.Escalations)))))
}
if xHigh > 0 {
vd = append(vd, r.t("v.egress", r.num(float64(xHigh))))
}
v.Verdict = vd
if o.Truncated {
v.Trunc = r.t("trunc")
}
// KPIs
dl := func(k string, cur, prev uint64) string {
d, ok := s.DeltaPct[k]
return delta(r, d, s.HasPrev && ok, float64(prev))
}
kc := func(warn bool) string {
if warn {
return "warn"
}
return ""
}
v.KPIs = []kpiV{
{r.t("k.requests"), r.num(float64(s.Requests)), dl("requests", s.Requests, s.Prev.Requests), ""},
{r.t("k.attacks"), r.num(float64(s.Attacks)), dl("attacks", s.Attacks, s.Prev.Attacks), kc(s.Attacks > 0)},
{r.t("k.hostile"), r.num(float64(s.HostileIPs)), dl("hostile_ips", uint64(s.HostileIPs), uint64(s.Prev.HostileIPs)), kc(s.HostileIPs > 0)},
{r.t("k.bans"), r.num(float64(s.Bans)), dl("bans", uint64(s.Bans), uint64(s.Prev.Bans)), ""},
{r.t("k.visitors"), r.num(float64(s.Visitors)), dl("visitors", s.Visitors, s.Prev.Visitors), ""},
{r.t("k.coverage"), r.dec(cover, 0) + "%", "", kc(s.HostileIPs > 0 && cover < 80)},
}
// threats
vals := o.Timeline.Values
v.Timeline = chartV{Title: v.TTimeline, SVG: template.HTML(svgArea(vals, o.Timeline.Start, o.Timeline.Step, r.num, v.TTimeline))}
if len(vals) == 0 {
v.Timeline = chartV{Title: v.TTimeline, Empty: true}
}
v.Motif = template.HTML(svgMotif(vals))
v.Fams = r.donutChart(v.TFams, r.counts(o.Families, func(c store.Count) string { return c.Key }, 6))
v.Techs = r.barChart(v.TTechs, r.counts(o.Techniques, func(c store.Count) string {
if c.Label != "" {
return c.Key + " " + c.Label
}
return c.Key
}, 8), "#c2410c")
v.IPs = tableV{Head: []string{r.t("col.ip"), r.t("col.level"), r.t("col.score"), r.t("col.country"), r.t("col.net"), r.t("col.events"), r.t("col.banned")}, Num: map[int]bool{2: true, 5: true}, NoWrap: map[int]bool{0: true}}
for _, x := range o.TopIPs {
v.IPs.Rows = append(v.IPs.Rows, rowV{[]string{x.IP, r.tr("lvl.", x.Level), r.dec(x.Score, 1), ccOf(x.CC, x.Country), dash(x.ASOrg), r.num(float64(x.Events)), r.yn(x.Banned)}})
}
v.Camps = tableV{Head: []string{r.t("col.camp"), r.t("col.ips"), r.t("col.active"), r.t("col.techs")}, Num: map[int]bool{1: true}}
for _, c := range o.Campaigns {
v.Camps.Rows = append(v.Camps.Rows, rowV{[]string{c.ID, r.num(float64(c.IPsN)), r.day(c.First.Unix()) + " – " + r.day(c.Last.Unix()), strings.Join(firstN(c.Techs, 4), ", ")}})
}
v.Escs = tableV{Head: []string{r.t("col.ip"), r.t("col.stage"), r.t("col.host")}}
for _, e := range o.Escalations {
v.Escs.Rows = append(v.Escs.Rows, rowV{[]string{e.IP, r.tr("stage.", e.Stage), dash(e.Host)}})
}
v.Expo = tableV{Head: []string{r.t("col.when"), r.t("col.ip"), r.t("col.host"), r.t("col.path"), r.t("col.status"), r.t("col.fam")}, Num: map[int]bool{4: true}, NoWrap: map[int]bool{0: true, 1: true}}
for _, e := range o.Exposures.Items {
host := e.Domain
if host == "" {
host = e.Host
}
v.Expo.Rows = append(v.Expo.Rows, rowV{[]string{r.date(e.T), e.IP, dash(host), clip(e.Path, 56), fmt.Sprint(e.Status), dash(e.Fam)}})
}
// geography
v.Countries = r.barChart(v.TCountries, r.counts(o.Countries, func(c store.Count) string { return c.Key }, 10), "#087f68")
v.ASNs = r.barChart(v.TASNs, r.counts(o.ASNs, func(c store.Count) string {
if c.Label != "" {
return c.Key + " " + c.Label
}
return c.Key
}, 10), "#087f68")
// health: thwarted attacks are not application errors
c := in.Classes
if in.HasHealth {
good := float64(c[store.ClsAttack] + c[store.ClsBlocked] + c[store.ClsBot])
bad := float64(c[store.ClsApp] + c[store.ClsProxy])
v.HealthLead = r.t("h.lead")
if good > 0 {
v.HealthNotes = append(v.HealthNotes, r.t("h.good", r.num(good)))
}
if bad > 0 {
v.HealthNotes = append(v.HealthNotes, r.t("h.app", r.num(bad)))
}
var items []chartItem
for i, n := range store.ClsNames {
items = append(items, chartItem{r.tr("cls.", n), float64(c[i])})
}
sort.SliceStable(items, func(a, b int) bool { return items[a].N > items[b].N })
v.Classes = r.donutChart(v.TClasses, items)
if in.Traffic.P95 > 0 {
v.HealthNotes = append(v.HealthNotes, r.t("h.p95", r.num(in.Traffic.P50), r.num(in.Traffic.P95)))
}
} else {
v.HealthLead = r.t("h.nodata")
v.Classes = chartV{Title: v.TClasses, Empty: true}
}
st := in.Traffic.Status
v.Status = r.donutChart(v.TStatus, []chartItem{{r.t("st.2xx"), float64(st[0])}, {r.t("st.3xx"), float64(st[1])}, {r.t("st.4xx"), float64(st[2])}, {r.t("st.5xx"), float64(st[3])}})
// visitors
tr := in.Traffic
v.VisLead = r.t("vis.lead")
v.VisKPIs = []kpiV{{Label: r.t("k.visitors"), Value: r.num(float64(tr.Visitors))}, {Label: r.t("k.pages"), Value: r.num(float64(tr.Pages))}, {Label: r.t("k.nonhuman"), Value: r.num(float64(tr.NonHuman))}}
lab := func(c store.Count) string { return dash(c.Key) }
v.Pages = r.barChart(r.t("c.pages"), r.counts(tr.TopPages, lab, 8), "#f97316")
v.Browsers = r.donutChart(r.t("c.browsers"), r.counts(tr.Browsers, lab, 6))
v.Devices = r.donutChart(r.t("c.devices"), r.counts(tr.Devices, lab, 5))
v.Refs = r.barChart(r.t("c.refs"), r.counts(tr.Referrers, lab, 6), "#4b6b61")
// defence
d := o.Defense
nodata := d.MTTBN == 0
mt := func(x float64) string {
if nodata {
return "-"
}
return r.dur(x)
}
v.Defense = tableV{Head: []string{r.t("col.metric"), r.t("col.value"), r.t("col.meaning")}, Num: map[int]bool{1: true}, Rows: []rowV{
{[]string{r.t("d.cover"), r.pct(d.BanCoverage), r.t("d.cover.m")}},
{[]string{r.t("d.mttb"), mt(d.MTTBMedianS), r.t("d.mttb.m")}},
{[]string{r.t("d.mttbp90"), mt(d.MTTBP90S), ""}},
{[]string{r.t("d.mttbn"), r.num(float64(d.MTTBN)), ""}},
{[]string{r.t("d.block"), r.pct(d.BlocklistCover), r.t("d.block.m")}},
{[]string{r.t("d.expo"), r.pct(d.ExposureRate), r.t("d.expo.m")}},
{[]string{r.t("d.refused"), r.pct(d.ExploitsRefused), r.t("d.refused.m")}},
}}
// second firewall
if e := in.Enforce; e != nil && e.Mode != enforce.ModeOff {
v.HasEnf = true
v.EnfLead = r.t("e.lead")
v.EnfNotes = append(v.EnfNotes, r.t("e.mode")+": "+r.t("e.mode."+e.Mode))
cv := e.Coverage
if cv.AttackIPs > 0 {
v.EnfNotes = append(v.EnfNotes, r.t("e.cov", r.num(float64(cv.BlockedByFirewall+cv.BlockedByUrutau)), r.num(float64(cv.AttackIPs)), r.num(float64(cv.BlockedByFirewall)), r.num(float64(cv.BlockedByUrutau))))
}
if cv.WouldBlock > 0 {
v.EnfNotes = append(v.EnfNotes, r.t("e.would", r.num(float64(cv.WouldBlock))))
}
if cv.Unblocked > 0 {
v.EnfNotes = append(v.EnfNotes, r.t("e.unb", r.num(float64(cv.Unblocked))))
}
v.EnfKPIs = []kpiV{{Label: r.t("e.decided"), Value: r.num(float64(e.Counts.Decided))}, {Label: r.t("e.written"), Value: r.num(float64(e.Counts.Written))},
{Label: r.t("e.already"), Value: r.num(float64(e.Counts.AlreadyBlocked))}, {Label: r.t("e.werr"), Value: r.num(float64(e.Counts.WriteErrors)), Cls: kc(e.Counts.WriteErrors > 0)}}
v.EnfRecent = tableV{Head: []string{r.t("col.when"), r.t("col.ip"), r.t("col.reason"), r.t("col.action"), r.t("col.country")}, NoWrap: map[int]bool{0: true, 1: true}}
for i, x := range e.Recent {
if i >= 10 {
break
}
v.EnfRecent.Rows = append(v.EnfRecent.Rows, rowV{[]string{r.date(x.T), x.IP, dash(x.Reason), dash(x.Action), ccOf(x.CC, "")}})
}
}
// egress
if x := in.Egress; x != nil && x.Source.State != "disabled" && x.Source.State != "" {
v.HasEgress = true
v.XLead = r.t("x.lead")
rep := x.Report
if len(rep.Findings) == 0 {
v.XNotes = append(v.XNotes, r.t("x.nof"))
} else {
v.XNotes = append(v.XNotes, r.t("x.sev", r.num(float64(len(rep.Findings))), r.num(float64(xHigh))))
}
v.XNotes = append(v.XNotes, r.t("x.src", x.Source.State))
v.XWl = tableV{Head: []string{r.t("col.wl"), r.t("col.role"), r.t("col.conns"), r.t("col.dst")}, Num: map[int]bool{2: true, 3: true}}
var items []chartItem
for i, w := range rep.Workloads {
if i < 12 {
v.XWl.Rows = append(v.XWl.Rows, rowV{[]string{w.Name, dash(w.Role), r.num(float64(w.Conns)), r.num(float64(w.Dsts))}})
}
if i < 8 {
items = append(items, chartItem{w.Name, float64(w.Conns)})
}
}
v.XChart = r.barChart(v.TXChart, items, "#087f68")
var dst []chartItem
for i, d := range rep.TopDst {
if i >= 8 {
break
}
dst = append(dst, chartItem{d.IP + " " + d.CC, float64(d.Conns)})
}
v.XDst = r.barChart(v.TXDst, dst, "#c2410c")
v.XFind = tableV{Head: []string{r.t("col.sev"), r.t("col.kind"), r.t("col.wl"), r.t("col.dst"), r.t("col.detail")}}
for i, f := range rep.Findings {
if i >= 10 {
break
}
v.XFind.Rows = append(v.XFind.Rows, rowV{[]string{r.tr("sev.", f.Severity), dash(f.Kind), f.Workload, fmt.Sprintf("%s:%d/%s", f.Dst, f.DPort, f.Proto), clip(f.Detail, 80)}})
}
}
for _, tb := range []*tableV{&v.IPs, &v.Camps, &v.Escs, &v.Expo, &v.Defense, &v.EnfRecent, &v.XWl, &v.XFind} {
tb.None = v.None
}
v.Expo.None = r.t("v.expo0")
v.Recs = r.recommend(in, cover, xHigh)
v.TOC = []secV{{"sum", v.TSum}, {"threats", v.TThreats}, {"geo", v.TGeo}, {"health", v.THealth}, {"vis", v.TVis}, {"def", v.TDef}}
if v.HasEnf {
v.TOC = append(v.TOC, secV{"enf", v.TEnf})
}
if v.HasEgress {
v.TOC = append(v.TOC, secV{"egress", v.TEgress})
}
v.TOC = append(v.TOC, secV{"method", v.TMethod})
return v
}
func dash(s string) string {
if s == "" {
return "-"
}
return s
}
func firstN(s []string, n int) []string {
if len(s) > n {
return s[:n]
}
return s
}
// recommend turns the figures into actions with plain rules, most urgent first.
func (r *renderer) recommend(in reportInput, cover float64, xHigh int) []recV {
o, s := in.Out, in.Out.Summary
var rs []recV
add := func(l, k string, a ...any) { rs = append(rs, recV{l, r.t("rec." + l), r.t(k, a...)}) }
enfOn := in.Enforce != nil && in.Enforce.Mode == enforce.ModeOn
if o.Exposures.Total > 0 {
add("bad", "r.expo", r.num(float64(o.Exposures.Total)))
}
if xHigh > 0 {
add("bad", "r.egress", r.num(float64(xHigh)))
}
if len(o.Escalations) > 0 {
add("warn", "r.esc", r.num(float64(len(o.Escalations))))
}
switch {
case in.Enforce == nil || in.Enforce.Mode == enforce.ModeOff:
if s.Attacks > 0 && (s.HostileIPs > 0 && cover < 90) {
add("warn", "r.enforce", r.num(float64(maxInt(s.HostileIPs-s.Bans, 1))))
}
case in.Enforce.Mode == enforce.ModeObserve:
add("warn", "r.observe")
case enfOn && in.Enforce.Coverage.Unblocked > 0:
add("warn", "r.unblocked", r.num(float64(in.Enforce.Coverage.Unblocked)))
}
if s.HostileIPs > 0 && cover < 50 {
add("warn", "r.cover", r.dec(cover, 0))
}
if o.Defense.MTTBN > 0 && o.Defense.MTTBMedianS > 600 {
add("warn", "r.mttb", r.dur(o.Defense.MTTBMedianS))
}
if len(o.Campaigns) > 0 {
add("info", "r.camp", r.num(float64(len(o.Campaigns))))
}
if in.HasHealth {
if n := in.Classes[store.ClsApp] + in.Classes[store.ClsProxy]; n > 0 {
add("warn", "r.app", r.num(float64(n)))
}
}
if dp, ok := s.DeltaPct["attacks"]; s.HasPrev && ok && dp >= 50 && s.Attacks >= 20 {
add("info", "r.up", r.num(dp))
}
if in.Egress == nil || in.Egress.Source.State == "disabled" {
add("info", "r.noegress")
}
if len(rs) == 0 {
add("ok", "r.ok")
}
return rs
}
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
var reportTpl = template.Must(template.New("report").Parse(reportTemplate))
// renderReportHTML renders the document; the error is a template failure.
func renderReportHTML(in reportInput, now int64) ([]byte, error) {
r := newRenderer(in.Lang)
var buf bytes.Buffer
if err := reportTpl.Execute(&buf, r.build(in, now)); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
var fileSafe = regexp.MustCompile(`[^A-Za-z0-9._-]+`)
// reportExtras gathers what the JSON report does not carry: service health
// classes, traffic study, second firewall and outbound analysis.
func (s *Server) reportExtras(r *http.Request, rc *reportCtx) reportInput {
in := reportInput{Out: rc.out, Lang: r.URL.Query().Get("lang")}
self := s.opt.Store.Name()
in.Traffic = s.trafficOf(r, rc.rg, rc.host)
in.Peers = rc.host != self && s.opt.Hub != nil
if rc.host == "all" || rc.host == self {
for _, v := range s.opt.Store.Services(rc.from, rc.to, "", "") {
in.HasHealth = true
for i := range in.Classes {
in.Classes[i] += v.Tot.Cls[i]
}
}
if e := enforceEngine.Load(); e != nil {
rep := e.Report(rc.from)
in.Enforce = &enforceView{Mode: e.Mode(), Share: e.Share(), Coverage: rep.Coverage, Counts: rep.Counts, Recent: rep.Recent}
}
if e := egressEngine.Load(); e != nil {
in.Egress = &egressView{Source: e.Info(), Report: e.Report(rc.from, rc.to)}
}
}
return in
}
func (s *Server) writeReportHTML(w http.ResponseWriter, r *http.Request, rc *reportCtx) {
now := s.opt.Now().Unix()
body, err := renderReportHTML(s.reportExtras(r, rc), now)
if err != nil {
http.Error(w, "report failed", http.StatusInternalServerError)
return
}
name := fileSafe.ReplaceAllString(rc.host, "-")
if rc.host == "all" && len(rc.out.Hosts) == 1 {
name = fileSafe.ReplaceAllString(rc.out.Hosts[0], "-")
}
if name == "" {
name = "all"
}
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'")
disp := "attachment"
if r.URL.Query().Get("inline") == "1" {
disp = "inline"
}
w.Header().Set("Content-Disposition", fmt.Sprintf(`%s; filename="urutau-relatorio-%s-%s.html"`, disp, name, time.Unix(now, 0).UTC().Format("2006-01-02")))
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write(body)
}
+193
View File
@@ -0,0 +1,193 @@
package server
// reportText holds the strings of the exported HTML report: [pt-BR, en].
// Unknown keys fall back to the key itself so a typo is visible, not blank.
var reportText = map[string][2]string{
"rec.bad": {"Urgente", "Urgent"},
"rec.warn": {"Importante", "Important"},
"rec.info": {"Sugestão", "Suggestion"},
"rec.ok": {"Tudo certo", "All good"},
"doc.title": {"Urutau · Relatório de segurança", "Urutau · Security report"},
"cover.kicker": {"Ciberfauna · Defesa de servidores web", "Ciberfauna · Web server defence"},
"cover.title": {"Relatório de segurança", "Security report"},
"cover.sub": {"O que atacou, o que foi barrado e o que merece a sua atenção neste período.", "What attacked, what was stopped and what deserves your attention in this period."},
"cover.period": {"Período", "Period"},
"cover.servers": {"Servidor(es)", "Server(s)"},
"cover.gen": {"Gerado em", "Generated"},
"cover.all": {"todos os servidores", "all servers"},
"cover.conf": {"Confidencial · uso interno", "Confidential · internal use"},
"run.head": {"URUTAU · RELATÓRIO DE SEGURANÇA", "URUTAU · SECURITY REPORT"},
"run.foot": {"Ciberfauna · Urutau · uso interno", "Ciberfauna · Urutau · internal use"},
"toc": {"Sumário", "Contents"},
"s.sum": {"Sumário executivo", "Executive summary"},
"s.threats": {"Ameaças", "Threats"},
"s.geo": {"Geografia dos ataques", "Where attacks came from"},
"s.health": {"Erros e saúde dos serviços", "Errors and service health"},
"s.visitors": {"Visitantes", "Visitors"},
"s.defense": {"Defesa", "Defence"},
"s.enforce": {"Segundo firewall", "Second firewall"},
"s.egress": {"Tráfego de saída", "Outbound traffic"},
"s.recs": {"Recomendações", "Recommendations"},
"s.method": {"Como ler este relatório", "How to read this report"},
"k.requests": {"Requisições", "Requests"},
"k.attacks": {"Ataques", "Attacks"},
"k.unique": {"IPs únicos", "Unique IPs"},
"k.hostile": {"IPs hostis", "Hostile IPs"},
"k.bans": {"IPs banidos", "Banned IPs"},
"k.visitors": {"Visitantes", "Visitors"},
"k.nonhuman": {"Clientes não humanos", "Non-human clients"},
"k.pages": {"Páginas vistas", "Page views"},
"k.before": {"antes: %s", "before: %s"},
"k.coverage": {"Cobertura de bloqueio", "Block coverage"},
"verdict.good": {"Situação sob controle", "Under control"},
"verdict.warn": {"Requer atenção", "Needs attention"},
"verdict.bad": {"Ação necessária", "Action needed"},
"v.intro": {"No período, %s registrou %s tentativas de ataque vindas de %s endereços diferentes; %s deles foram classificados como hostis e %s estão banidos.", "In this period, %s recorded %s attack attempts from %s different addresses; %s of them were classified as hostile and %s are banned."},
"v.none": {"Não houve tentativas de ataque registradas no período. Isso é normal em servidores pouco expostos, mas confirme que os logs estão chegando.", "No attack attempts were recorded in this period. That is normal for lightly exposed servers, but make sure logs are arriving."},
"v.up": {"Os ataques aumentaram %s%% em relação ao período anterior.", "Attacks rose %s%% compared with the previous period."},
"v.down": {"Os ataques diminuíram %s%% em relação ao período anterior.", "Attacks fell %s%% compared with the previous period."},
"v.flat": {"O volume de ataques está em linha com o período anterior.", "Attack volume is in line with the previous period."},
"v.noprev": {"Não há período anterior para comparar.", "There is no previous period to compare with."},
"v.top": {"O tipo de ataque mais comum foi %s, e a maior parte veio de %s.", "The most common attack type was %s, and most of it came from %s."},
"v.expo0": {"Nenhuma requisição de ataque obteve resposta de sucesso: nada indica que algo tenha sido exposto.", "No attack request got a success answer: nothing suggests anything was exposed."},
"v.expo": {"Atenção: %s requisições de ataque receberam resposta de sucesso e precisam ser revisadas, pois podem ter alcançado algo que deveria estar protegido.", "Attention: %s attack requests received a success answer and must be reviewed, as they may have reached something that should be protected."},
"v.cover": {"%s%% dos endereços hostis já estão bloqueados.", "%s%% of hostile addresses are already blocked."},
"v.esc": {"%s sessão(ões) mostraram escalada, ou seja, o atacante avançou do reconhecimento para a exploração.", "%s session(s) showed escalation: the attacker moved from reconnaissance to exploitation."},
"v.egress": {"O tráfego de saída tem %s alerta(s) de severidade alta, o que pode indicar um servidor comprometido falando com o exterior.", "Outbound traffic has %s high-severity alert(s), which may indicate a compromised server talking to the outside."},
"v.trunc": {"O estudo foi cortado nos limites internos; os números podem estar parciais.", "The study was cut at its internal limits; figures may be partial."},
"v.mttb": {"Em mediana, um atacante levou %s até ser banido.", "On median, an attacker took %s to get banned."},
"c.timeline": {"Ataques ao longo do tempo", "Attacks over time"},
"c.families": {"Famílias de ataque", "Attack families"},
"c.techs": {"Técnicas MITRE ATT&CK", "MITRE ATT&CK techniques"},
"c.countries": {"Países de origem", "Origin countries"},
"c.asns": {"Redes de origem (ASN)", "Origin networks (ASN)"},
"c.classes": {"Como os pedidos com erro se dividem", "How failed requests split"},
"c.status": {"Respostas por classe", "Responses by class"},
"c.pages": {"Páginas mais acessadas", "Most visited pages"},
"c.browsers": {"Navegadores", "Browsers"},
"c.devices": {"Dispositivos", "Devices"},
"c.refs": {"Origens do acesso", "Referrers"},
"c.egress": {"Conexões por carga de trabalho", "Connections per workload"},
"c.dst": {"Destinos mais contatados", "Most contacted destinations"},
"t.ips": {"Endereços mais perigosos", "Most dangerous addresses"},
"t.camp": {"Campanhas coordenadas", "Coordinated campaigns"},
"t.esc": {"Sessões com escalada", "Escalating sessions"},
"t.expo": {"Requisições de ataque com resposta de sucesso", "Attack requests with a success answer"},
"t.enf": {"Decisões recentes do segundo firewall", "Recent second-firewall decisions"},
"t.find": {"Alertas de saída", "Outbound alerts"},
"t.wl": {"Cargas de trabalho", "Workloads"},
"col.ip": {"Endereço", "Address"},
"col.score": {"Pontuação", "Score"},
"col.level": {"Nível", "Level"},
"col.country": {"País", "Country"},
"col.net": {"Rede", "Network"},
"col.events": {"Eventos", "Events"},
"col.banned": {"Banido", "Banned"},
"col.camp": {"Campanha", "Campaign"},
"col.ips": {"IPs", "IPs"},
"col.active": {"Atividade", "Active"},
"col.techs": {"Técnicas", "Techniques"},
"col.stage": {"Estágio", "Stage"},
"col.host": {"Servidor", "Server"},
"col.path": {"Caminho", "Path"},
"col.status": {"Status", "Status"},
"col.fam": {"Família", "Family"},
"col.when": {"Quando", "When"},
"col.metric": {"Indicador", "Metric"},
"col.value": {"Valor", "Value"},
"col.meaning": {"O que significa", "What it means"},
"col.reason": {"Motivo", "Reason"},
"col.action": {"Ação", "Action"},
"col.sev": {"Severidade", "Severity"},
"col.kind": {"Tipo", "Kind"},
"col.wl": {"Carga", "Workload"},
"col.dst": {"Destino", "Destination"},
"col.conns": {"Conexões", "Connections"},
"col.role": {"Papel", "Role"},
"col.detail": {"Detalhe", "Detail"},
"yes": {"sim", "yes"},
"no": {"não", "no"},
"none": {"Nada a registrar neste período.", "Nothing to report in this period."},
"noenf": {"O segundo firewall não está ativo neste servidor.", "The second firewall is not active on this server."},
"noegress": {"A análise de tráfego de saída não está ativa neste servidor.", "Outbound traffic analysis is not active on this server."},
"unit.attacks": {"ataques", "attacks"},
"cls.attack": {"Ataque frustrado (barrado ou sondagem)", "Thwarted attack (blocked or probe)"},
"cls.blocked": {"Bloqueado pela defesa", "Blocked by the defence"},
"cls.bot": {"Robô ou ferramenta", "Bot or tool"},
"cls.app": {"Erro da aplicação (falha sua)", "Application error (your fault)"},
"cls.proxy": {"Falha do proxy ou serviço fora do ar", "Proxy failure or service down"},
"cls.client_broken": {"Link quebrado do lado do visitante", "Broken link on the visitor side"},
"cls.client_auth": {"Login ou permissão negados", "Login or permission denied"},
"cls.client_other": {"Outro erro do cliente", "Other client error"},
"h.lead": {"Nem todo erro é problema. Um ataque que foi barrado devolve erro e é sinal de que a defesa funcionou; já um erro de aplicação é uma falha do seu serviço e pede correção.", "Not every error is a problem. A thwarted attack returns an error and shows the defence working; an application error is a failure of your own service and needs a fix."},
"h.good": {"%s pedidos com erro foram ataques frustrados ou ruído de robôs, e não indicam defeito.", "%s failed requests were thwarted attacks or bot noise and do not indicate a defect."},
"h.app": {"%s pedidos terminaram em erro de aplicação ou de proxy; esses sim indicam falha de serviço.", "%s requests ended in application or proxy errors; those do indicate a service failure."},
"h.p95": {"Tempo de resposta: mediana %s ms, 95%% dos pedidos abaixo de %s ms.", "Response time: median %s ms, 95%% of requests under %s ms."},
"h.nodata": {"Sem dados de saúde de serviços neste período.", "No service health data in this period."},
"st.2xx": {"2xx sucesso", "2xx success"},
"st.3xx": {"3xx redirecionamento", "3xx redirect"},
"st.4xx": {"4xx erro do cliente", "4xx client error"},
"st.5xx": {"5xx erro do servidor", "5xx server error"},
"vis.lead": {"Visitantes são navegadores reais, contados uma vez por IP e dia. Robôs e ferramentas ficam à parte.", "Visitors are real browsers, counted once per IP and day. Bots and tools are kept apart."},
"d.mttb": {"Tempo mediano até o banimento", "Median time to ban"},
"d.mttbp90": {"Tempo até o banimento (percentil 90)", "Time to ban (90th percentile)"},
"d.mttbn": {"Banimentos medidos", "Bans measured"},
"d.cover": {"Cobertura de banimento", "Ban coverage"},
"d.block": {"Cobertura da lista de bloqueio", "Blocklist coverage"},
"d.expo": {"Taxa de exposição", "Exposure rate"},
"d.refused": {"Exploits recusados", "Exploits refused"},
"d.cover.m": {"Parte dos IPs hostis que já estava banida.", "Share of hostile IPs that were already banned."},
"d.mttb.m": {"Quanto menor, melhor: é a janela entre o primeiro ataque e o bloqueio.", "Lower is better: the window between the first attack and the block."},
"d.block.m": {"Parte dos atacantes que já constava em listas públicas de bloqueio.", "Share of attackers already in public blocklists."},
"d.expo.m": {"Parte dos ataques que recebeu resposta de sucesso. Deve ficar perto de zero.", "Share of attacks that got a success answer. Should stay near zero."},
"d.refused.m": {"Parte das tentativas de exploração recusada pelo servidor.", "Share of exploit attempts refused by the server."},
"e.mode": {"Modo", "Mode"},
"e.mode.on": {"ativo (bloqueia)", "active (blocks)"},
"e.mode.observe": {"observação (só registra o que bloquearia)", "observe (only logs what it would block)"},
"e.mode.off": {"desligado", "off"},
"e.lead": {"O segundo firewall é uma camada extra: o Urutau decide quem bloquear e grava a decisão para outro bloqueador aplicar na borda.", "The second firewall is an extra layer: Urutau decides who to block and writes the decision for another blocker to enforce at the edge."},
"e.cov": {"%s de %s endereços atacantes estão bloqueados (%s pelo firewall, %s pelo Urutau).", "%s of %s attacking addresses are blocked (%s by the firewall, %s by Urutau)."},
"e.would": {"%s endereços seriam bloqueados se o modo ativo estivesse ligado.", "%s addresses would be blocked if active mode were on."},
"e.unb": {"%s endereços atacantes continuam sem bloqueio.", "%s attacking addresses are still unblocked."},
"e.decided": {"Decisões", "Decisions"},
"e.written": {"Gravadas", "Written"},
"e.already": {"Já bloqueadas", "Already blocked"},
"e.rate": {"Descartadas por limite", "Dropped by rate limit"},
"e.werr": {"Erros de gravação", "Write errors"},
"x.lead": {"Tráfego de saída é o que os seus servidores iniciam em direção à internet. Um servidor sadio fala com poucos destinos conhecidos; conversas periódicas com destinos estranhos podem indicar invasão.", "Outbound traffic is what your servers start towards the internet. A healthy server talks to a few known destinations; periodic talks to strange destinations may indicate a breach."},
"x.nof": {"Nenhum alerta de saída no período.", "No outbound alerts in this period."},
"x.sev": {"%s alerta(s) de saída, %s de severidade alta.", "%s outbound alert(s), %s of high severity."},
"x.src": {"Fonte dos dados: %s.", "Data source: %s."},
"stage.recon": {"reconhecimento", "reconnaissance"},
"stage.probe": {"sondagem", "probing"},
"stage.exploit": {"exploração", "exploitation"},
"stage.access": {"acesso", "access"},
"lvl.low": {"baixo", "low"},
"lvl.suspicious": {"suspeito", "suspicious"},
"lvl.hostile": {"hostil", "hostile"},
"sev.high": {"alta", "high"},
"sev.medium": {"média", "medium"},
"sev.low": {"baixa", "low"},
"sev.critical": {"crítica", "critical"},
"r.enforce": {"Ative o segundo firewall (URUTAU_ENFORCE=on). %s atacantes passaram sem bloqueio na borda; hoje o Urutau só os enxerga depois do fato.", "Turn on the second firewall (URUTAU_ENFORCE=on). %s attackers passed without an edge block; today Urutau only sees them after the fact."},
"r.observe": {"O segundo firewall está só observando. Revise as decisões e passe para o modo ativo (URUTAU_ENFORCE=on) para bloquear de fato.", "The second firewall is only observing. Review its decisions and switch to active mode (URUTAU_ENFORCE=on) to actually block."},
"r.unblocked": {"Mesmo com o segundo firewall ativo, %s atacantes seguem sem bloqueio. Confira se o arquivo de decisões está sendo lido pelo bloqueador.", "Even with the second firewall active, %s attackers remain unblocked. Check that the blocker is reading the decisions file."},
"r.expo": {"Revise agora as %s requisições de ataque que receberam resposta de sucesso (seção Ameaças) e confirme que nenhum recurso sensível foi alcançado.", "Review now the %s attack requests that received a success answer (Threats section) and confirm no sensitive resource was reached."},
"r.cover": {"A cobertura de banimento é de apenas %s%%. Reduza o limiar de banimento do fail2ban ou ative a lista de bloqueio compartilhada.", "Ban coverage is only %s%%. Lower the fail2ban ban threshold or enable the shared blocklist."},
"r.mttb": {"O tempo mediano até o banimento (%s) é longo. Bans mais rápidos reduzem a janela de ataque.", "The median time to ban (%s) is long. Faster bans shrink the attack window."},
"r.esc": {"Investigue as %s sessão(ões) com escalada: o atacante passou da sondagem para a exploração.", "Investigate the %s escalating session(s): the attacker moved from probing to exploitation."},
"r.camp": {"Há %s campanha(s) coordenada(s). Considere bloquear as redes de origem inteiras em vez de IP a IP.", "There are %s coordinated campaign(s). Consider blocking whole source networks rather than IP by IP."},
"r.app": {"Corrija os erros de aplicação: %s pedidos falharam por defeito do seu serviço (veja a página Erros no painel).", "Fix the application errors: %s requests failed because of a defect in your service (see the Errors page in the dashboard)."},
"r.egress": {"Investigue os %s alerta(s) de saída de severidade alta; confirme se a carga de trabalho deveria falar com esses destinos.", "Investigate the %s high-severity outbound alert(s); confirm whether the workload should talk to those destinations."},
"r.noegress": {"Ative a análise de tráfego de saída para detectar servidor comprometido falando com o exterior.", "Enable outbound traffic analysis to detect a compromised server talking to the outside."},
"r.up": {"Os ataques cresceram %s%%. Acompanhe a evolução nos próximos dias.", "Attacks grew %s%%. Keep watching in the coming days."},
"r.ok": {"Nenhuma ação urgente. Mantenha os logs chegando e revise este relatório periodicamente.", "No urgent action. Keep logs flowing and review this report periodically."},
"m.p1": {"Os números vêm dos logs do proxy e do SSH lidos pelo Urutau. Endereços, caminhos e nomes aparecem como foram registrados e podem ser falsos: são dados de atacantes.", "Figures come from the proxy and SSH logs read by Urutau. Addresses, paths and names appear as recorded and may be forged: they are attacker-supplied data."},
"m.p2": {"Ataque é toda requisição classificada como varredura, exploração, força bruta ou sondagem SSH. IP hostil é o que acumulou pontuação suficiente para ser tratado como ameaça.", "An attack is any request classified as scanning, exploitation, brute force or SSH probing. A hostile IP is one that accumulated enough score to be treated as a threat."},
"m.p3": {"A comparação usa o período imediatamente anterior, de mesma duração. Datas e horas em UTC.", "Comparisons use the immediately preceding period of the same length. Dates and times are UTC."},
"trunc": {"O estudo foi cortado nos limites internos; os números podem estar parciais.", "The study was cut at its internal limits; figures may be partial."},
"other": {"outros", "other"},
"peers.note": {"Saúde e tráfego de saída refletem apenas o servidor que gerou o relatório.", "Health and outbound traffic reflect only the server that generated the report."},
}
+184
View File
@@ -0,0 +1,184 @@
package server
import (
"fmt"
"html"
"math"
"strings"
"time"
)
// Palette of the printed report (light theme, Ciberfauna identity).
var reportPalette = []string{"#f97316", "#087f68", "#f0b35b", "#45d6b0", "#c2410c", "#4b6b61", "#9aa9a2"}
type chartItem struct {
Label string
N float64
}
func clip(s string, n int) string {
r := []rune(s)
if len(r) <= n {
return s
}
return string(r[:n-1]) + "…"
}
// niceMax rounds a maximum up to 1, 2, 5 x 10^k so the axis reads well.
func niceMax(v float64) float64 {
if v <= 0 {
return 1
}
p := math.Pow(10, math.Floor(math.Log10(v)))
for _, m := range []float64{1, 2, 5, 10} {
if v <= m*p {
return m * p
}
}
return 10 * p
}
// svgArea draws a filled time series. All text is escaped; numbers are formatted here.
func svgArea(vals []uint32, start, step int64, fi func(float64) string, title string) string {
const w, h, ml, mr, mt, mb = 680.0, 150.0, 40.0, 8.0, 8.0, 20.0
var sb strings.Builder
fmt.Fprintf(&sb, `<svg class="chart" viewBox="0 0 %g %g" role="img" aria-label="%s" preserveAspectRatio="xMidYMid meet">`, w, h, html.EscapeString(title))
var mx float64
for _, v := range vals {
if float64(v) > mx {
mx = float64(v)
}
}
top := niceMax(mx)
pw, ph := w-ml-mr, h-mt-mb
for i := 0; i <= 4; i++ {
y := mt + ph - ph*float64(i)/4
fmt.Fprintf(&sb, `<line x1="%g" y1="%.1f" x2="%g" y2="%.1f" stroke="#d7e2dd" stroke-width="0.6"/>`, ml, y, w-mr, y)
fmt.Fprintf(&sb, `<text x="%g" y="%.1f" font-size="9" text-anchor="end" fill="#55665f">%s</text>`, ml-4, y+3, fi(top*float64(i)/4))
}
n := len(vals)
if n > 1 {
xs := func(i int) float64 { return ml + pw*float64(i)/float64(n-1) }
ys := func(v uint32) float64 { return mt + ph - ph*float64(v)/top }
var line strings.Builder
for i, v := range vals {
if i == 0 {
fmt.Fprintf(&line, "M%.1f %.1f", xs(i), ys(v))
} else {
fmt.Fprintf(&line, "L%.1f %.1f", xs(i), ys(v))
}
}
fmt.Fprintf(&sb, `<path d="%sL%.1f %.1f L%.1f %.1f Z" fill="#f97316" fill-opacity="0.18"/>`, line.String(), xs(n-1), mt+ph, xs(0), mt+ph)
fmt.Fprintf(&sb, `<path d="%s" fill="none" stroke="#f97316" stroke-width="1.4" stroke-linejoin="round"/>`, line.String())
if step > 0 {
for i := 0; i < 5; i++ {
idx := (n - 1) * i / 4
ts := start + int64(idx)*step
lbl := time.Unix(ts, 0).UTC().Format("02/01")
if step < 86400 && int64(n)*step <= 3*86400 {
lbl = time.Unix(ts, 0).UTC().Format("02/01 15h")
}
anchor := "middle"
if i == 0 {
anchor = "start"
} else if i == 4 {
anchor = "end"
}
fmt.Fprintf(&sb, `<text x="%.1f" y="%g" font-size="9" text-anchor="%s" fill="#55665f">%s</text>`, xs(idx), h-6, anchor, lbl)
}
}
} else if n == 1 {
fmt.Fprintf(&sb, `<circle cx="%g" cy="%.1f" r="2" fill="#f97316"/>`, ml+pw/2, mt+ph-ph*float64(vals[0])/top)
}
sb.WriteString(`</svg>`)
return sb.String()
}
// svgBars draws horizontal bars with the label on the left and the value on the right.
func svgBars(items []chartItem, color string, fi func(float64) string, title string) string {
const w, lw, rw, rh = 300.0, 112.0, 40.0, 19.0
if len(items) == 0 {
return ""
}
var mx float64
for _, it := range items {
if it.N > mx {
mx = it.N
}
}
if mx <= 0 {
mx = 1
}
h := rh*float64(len(items)) + 2
var sb strings.Builder
fmt.Fprintf(&sb, `<svg class="chart" viewBox="0 0 %g %g" role="img" aria-label="%s">`, w, h, html.EscapeString(title))
bw := w - lw - rw
for i, it := range items {
y := rh * float64(i)
l := it.N / mx * bw
if it.N > 0 && l < 1.5 {
l = 1.5
}
fmt.Fprintf(&sb, `<text x="%g" y="%.1f" font-size="10" text-anchor="end" fill="#22352f">%s</text>`, lw-6, y+13, html.EscapeString(clip(it.Label, 20)))
fmt.Fprintf(&sb, `<rect x="%g" y="%.1f" width="%.1f" height="11" rx="2" fill="%s"/>`, lw, y+3.5, l, color)
fmt.Fprintf(&sb, `<text x="%.1f" y="%.1f" font-size="10" fill="#55665f">%s</text>`, lw+l+4, y+13, fi(it.N))
}
sb.WriteString(`</svg>`)
return sb.String()
}
// svgDonut draws a ring; the legend is HTML next to it (see donutLegend).
func svgDonut(items []chartItem, title string) string {
var total float64
for _, it := range items {
total += it.N
}
var sb strings.Builder
fmt.Fprintf(&sb, `<svg class="donut" viewBox="0 0 120 120" role="img" aria-label="%s">`, html.EscapeString(title))
const r = 44.0
circ := 2 * math.Pi * r
sb.WriteString(`<circle cx="60" cy="60" r="44" fill="none" stroke="#eaf2ef" stroke-width="20"/>`)
if total > 0 {
off := 0.0
for i, it := range items {
if it.N <= 0 {
continue
}
l := it.N / total * circ
fmt.Fprintf(&sb, `<circle cx="60" cy="60" r="44" fill="none" stroke="%s" stroke-width="20" stroke-dasharray="%.2f %.2f" stroke-dashoffset="%.2f" transform="rotate(-90 60 60)"/>`,
reportPalette[i%len(reportPalette)], l, circ-l, -off)
off += l
}
}
sb.WriteString(`</svg>`)
return sb.String()
}
// svgMotif is the faint decoration of the cover, built from the attack series.
func svgMotif(vals []uint32) string {
var sb strings.Builder
sb.WriteString(`<svg class="motif" viewBox="0 0 210 120" preserveAspectRatio="none" aria-hidden="true">`)
for i := 1; i <= 7; i++ {
fmt.Fprintf(&sb, `<line x1="0" y1="%d" x2="210" y2="%d" stroke="#45d6b0" stroke-opacity="0.12" stroke-width="0.25"/>`, i*15, i*15)
}
n := len(vals)
if n > 1 {
var mx uint32 = 1
for _, v := range vals {
if v > mx {
mx = v
}
}
step := 1
if n > 120 {
step = n / 120
}
for i := 0; i < n; i += step {
x := 210 * float64(i) / float64(n-1)
hgt := 4 + 38*float64(vals[i])/float64(mx)
fmt.Fprintf(&sb, `<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="#f0b35b" stroke-opacity="0.55" stroke-width="0.7" stroke-linecap="round"/>`, x, 60-hgt/2, x, 60+hgt/2)
}
}
sb.WriteString(`</svg>`)
return sb.String()
}
+123
View File
@@ -0,0 +1,123 @@
package server
import (
"os"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func richReportInput(lang string) reportInput {
var in reportInput
in.Lang = lang
o := &in.Out
o.Range = store.RangeInfo{Name: "7d", From: 1763000000, To: 1763604800, Step: 3600}
o.Hosts = []string{"web-01.example.com", "web-02.example.com"}
o.Summary.reportFigures = reportFigures{Requests: 1843210, Attacks: 48211, UniqueIPs: 912, HostileIPs: 143, Bans: 97, Visitors: 5120, NonHuman: 733, PageViews: 18430}
o.Summary.Prev = reportFigures{Requests: 1500000, Attacks: 30100, UniqueIPs: 700, HostileIPs: 110, Bans: 90, Visitors: 4800, PageViews: 17000}
o.Summary.HasPrev = true
o.Summary.DeltaPct = map[string]float64{"requests": 22.9, "attacks": 60.2, "hostile_ips": 30, "bans": 7.7, "visitors": 6.7}
o.Timeline.Start, o.Timeline.Step = o.Range.From, 3600
for i := 0; i < 168; i++ {
o.Timeline.Values = append(o.Timeline.Values, uint32(200+(i*37)%400+(i%24)*10))
}
o.Families = []store.Count{{Key: "scanner", N: 21000}, {Key: "exploit", N: 14000}, {Key: "bruteforce", N: 8000}, {Key: "ssh-fail", N: 4000}, {Key: "ssh-probe", N: 1211}}
o.Techniques = []store.Count{{Key: "T1190", N: 9000, Label: "Exploit Public-Facing Application"}, {Key: "T1110", N: 4000, Label: "Brute Force"}, {Key: "T1595", N: 3000, Label: "Active Scanning"}}
o.Countries = []store.Count{{Key: "NL", N: 9000}, {Key: "US", N: 8000}, {Key: "DE", N: 5000}, {Key: "RU", N: 3000}, {Key: "BR", N: 900}}
o.ASNs = []store.Count{{Key: "AS64496", N: 9000, Label: "Example Hosting <b>Ltd</b>"}, {Key: "AS64497", N: 5000, Label: "Documentation Net"}}
for i := 0; i < 10; i++ {
o.TopIPs = append(o.TopIPs, reportTopIP{IP: "198.51.100." + string(rune('1'+i)), Score: 92.5 - float64(i), Level: "hostile", CC: "NL", Country: "Netherlands", ASOrg: "Example Hosting", Events: uint32(4000 - i*300), Banned: i%2 == 0})
}
o.Campaigns = []intel.Campaign{{ID: "camp-1", IPsN: 12, First: time.Unix(1763100000, 0), Last: time.Unix(1763500000, 0), Techs: []string{"T1190", "T1595"}}}
o.Escalations = []store.EscalationOut{{IP: "203.0.113.7", Host: "web-01.example.com", Stage: "exploit"}}
o.Exposures.Total = 3
for i := 0; i < 3; i++ {
o.Exposures.Items = append(o.Exposures.Items, reportExposure{T: 1763200000 + int64(i)*600, IP: "203.0.113.7", Domain: "app.example.com", Path: "/<script>alert(1)</script>?x=" + strings.Repeat("a", 120), Status: 200, Fam: "exploit"})
}
o.Defense.MTTBN, o.Defense.MTTBMedianS, o.Defense.MTTBP90S, o.Defense.BanCoverage = 40, 95, 700, 67.8
o.Defense.BlocklistCover, o.Defense.ExposureRate, o.Defense.ExploitsRefused = 31, 0.4, 99
in.Traffic = store.TrafficData{Visitors: 5120, Pages: 18430, NonHuman: 733, P50: 42, P95: 380, Status: [4]uint64{1500000, 200000, 140000, 3210},
TopPages: []store.Count{{Key: "/", N: 9000}, {Key: "/docs", N: 3000}}, Browsers: []store.Count{{Key: "Firefox", N: 3000}, {Key: "Chrome", N: 2000}},
Devices: []store.Count{{Key: "Desktop", N: 4000}, {Key: "Mobile", N: 1100}}, Referrers: []store.Count{{Key: "example.org", N: 400}}}
in.HasHealth = true
in.Classes = [store.NumCls]uint32{store.ClsApp: 120, store.ClsProxy: 12, store.ClsBlocked: 30000, store.ClsAttack: 9000, store.ClsBot: 4000, store.ClsClientBroken: 900, store.ClsClientAuth: 300, store.ClsClientOther: 50}
in.Enforce = &enforceView{Mode: enforce.ModeOn, Coverage: enforce.Coverage{AttackIPs: 143, BlockedByFirewall: 80, BlockedByUrutau: 20, Unblocked: 43},
Counts: enforce.Counts{Decided: 400, Written: 380, AlreadyBlocked: 20},
Recent: []enforce.Recent{{T: 1763300000, IP: "198.51.100.4", Reason: "exploit x12", Action: "ban", CC: "NL"}}}
in.Egress = &egressView{Source: egress.SourceInfo{State: "ok"}, Report: egress.Report{
Workloads: []egress.WorkloadOut{{Name: "app-1", Role: "web", Conns: 12000, Dsts: 14}, {Name: "db-1", Role: "db", Conns: 800, Dsts: 2}},
TopDst: []egress.DstOut{{IP: "192.0.2.10", CC: "US", Conns: 5000}},
Findings: []egress.Finding{{Severity: "high", Kind: "beacon", Workload: "app-1", Dst: "192.0.2.99", DPort: 4444, Proto: "tcp", Detail: "<img src=x onerror=1> periodic"}}}}
return in
}
func TestReportHTMLRenders(t *testing.T) {
for _, lang := range []string{"pt-BR", "en"} {
b, err := renderReportHTML(richReportInput(lang), 1763604800)
if err != nil {
t.Fatal(err)
}
s := string(b)
if strings.Contains(s, "<script") || strings.Contains(s, "<img src=x") || strings.Contains(s, "<b>Ltd") {
t.Fatalf("%s: unescaped attacker data", lang)
}
if !strings.Contains(s, "&lt;script&gt;") || !strings.Contains(s, "data:image/png;base64,") {
t.Fatalf("%s: missing escaped payload or logo", lang)
}
if len(b) > 400<<10 {
t.Fatalf("%s: %d bytes", lang, len(b))
}
want := "Segundo firewall"
if lang == "en" {
want = "Second firewall"
}
if !strings.Contains(s, want) {
t.Fatalf("%s: no %q", lang, want)
}
if dir := os.Getenv("URUTAU_REPORT_OUT"); dir != "" {
_ = os.WriteFile(dir+"/rich-"+lang+".html", b, 0o600)
}
}
}
func TestReportHTMLEmpty(t *testing.T) {
for _, lang := range []string{"", "en", "xx"} {
b, err := renderReportHTML(reportInput{Lang: lang}, 1763604800)
if err != nil || len(b) == 0 {
t.Fatal(err)
}
if dir := os.Getenv("URUTAU_REPORT_OUT"); dir != "" && lang == "" {
_ = os.WriteFile(dir+"/empty.html", b, 0o600)
}
}
}
func TestReportHTMLRoute(t *testing.T) {
h, _ := setup(t)
w := do(h, "GET", "/api/v1/report?range=7d&format=html&lang=en", copyHdr(opsAuth), nil)
if w.Code != 200 {
t.Fatalf("%d %s", w.Code, w.Body)
}
if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "text/html") {
t.Fatal(ct)
}
cd := w.Header().Get("Content-Disposition")
if !strings.HasPrefix(cd, `attachment; filename="urutau-relatorio-oracle-`) || !strings.HasSuffix(cd, `.html"`) {
t.Fatal(cd)
}
body := w.Body.String()
if strings.Contains(body, "<img src=x") {
t.Fatal("path not escaped")
}
if dir := os.Getenv("URUTAU_REPORT_OUT"); dir != "" {
_ = os.WriteFile(dir+"/route.html", w.Body.Bytes(), 0o600)
}
if w := do(h, "GET", "/api/v1/report?format=html&lang=pt-BR", nil, nil); w.Code != 401 && w.Code != 403 {
t.Fatalf("closed without token: %d", w.Code)
}
}
+185
View File
@@ -0,0 +1,185 @@
package server
// reportTemplate is the document skeleton (html/template; see report_html.go).
// The style block is static text: nothing dynamic reaches CSS.
const reportTemplate = `<!doctype html>
<html lang="{{.Lang}}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>{{.Title}}</title>
<style>
:root{--ink:#0d1f1a;--muted:#55665f;--line:#d7e2dd;--paper:#fff;--tint:#f2f8f5;--accent:#087f68;--accent2:#45d6b0;--gold:#f0b35b;--orange:#f97316;--orange2:#fb923c;--crit:#b42318;--high:#c2410c;--med:#a16207;--ok:#087f68;
--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:#e9eeec;color:var(--ink);font-family:var(--sans);font-size:10pt;line-height:1.5;-webkit-print-color-adjust:exact;print-color-adjust:exact}
body{padding:0}
.doc{max-width:210mm;margin:0 auto;background:var(--paper)}
.body{padding:0 16mm}
@page{size:A4;margin:22mm 16mm 20mm 16mm;
@top-left{content:"{{.RunHead}}";font-family:var(--mono);font-size:7pt;letter-spacing:.14em;color:#55665f;margin-top:8mm}
@top-right{content:"{{.LConf}}";font-family:var(--mono);font-size:7pt;font-weight:700;letter-spacing:.06em;color:#a15c00;margin-top:8mm}
@bottom-left{content:"{{.RunFoot}}";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-right{content:none}@bottom-left{content:none}@bottom-right{content:none}}
.cover{page:cover;break-after:page;position:relative;width:100%;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:72mm;top:112mm;width:calc(100% - 72mm);height:120mm;opacity:.9}
.cover .logo{position:absolute;left:88mm;top:100mm;width:112mm;height:112mm;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}
.auth{font-family:var(--mono);font-size:7.5pt;letter-spacing:.12em;color:#9fc7ba;text-transform:uppercase}
.cover .head{position:absolute;left:18mm;right:18mm;top:34mm}
.eyebrow{font-family:var(--mono);font-size:8pt;letter-spacing:.2em;color:var(--orange2);text-transform:uppercase}
.cover h1{font-size:44px;line-height:1.04;font-weight:800;letter-spacing:-.03em;margin:4mm 0;color:#fff;max-width:165mm}
.cover .sub{font-size:11.5pt;color:#b9d8cd;max-width:140mm;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(--accent2);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.7fr 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;overflow-wrap:anywhere}
section{margin:0 0 7mm}
section.pg{break-before:page}
section.keep{break-inside:avoid}
h2{font-size:17pt;font-weight:800;letter-spacing:-.02em;margin:0 0 3mm;padding-top:4mm;break-after:avoid;background:linear-gradient(var(--accent),var(--accent)) 0 0/14mm 3px no-repeat}
h3{font-size:10.5pt;margin:5mm 0 2mm;break-after:avoid}
p{margin:0 0 2.5mm;orphans:3;widows:3}
.lead{font-size:10.5pt;color:#22352f}
.muted{color:var(--muted)}
@media print{html,body{background:#fff}.doc{max-width:none;margin:0}.body{padding:0}}
.toc ol{list-style:none;padding:0;margin:3mm 0 6mm;counter-reset:t;columns:2;column-gap:8mm}
.toc li{border-bottom:1px solid var(--line);padding:1.3mm 0;counter-increment:t;break-inside:avoid}
.toc a{color:var(--ink);text-decoration:none;font-size:10.5pt}
.toc a::before{content:counter(t,decimal-leading-zero);font-family:var(--mono);color:var(--accent);display:inline-block;width:10mm}
.verdict{border:1px solid var(--line);border-left:5px solid var(--ok);background:var(--tint);padding:4mm 5mm;margin:3mm 0 4mm;break-inside:avoid}
.verdict.warn{border-left-color:var(--orange);background:#fff7ed}
.verdict.bad{border-left-color:var(--crit);background:#fef3f2}
.verdict strong{display:block;font-family:var(--mono);font-size:8pt;letter-spacing:.14em;text-transform:uppercase;color:var(--ok);margin-bottom:1.5mm}
.verdict.warn strong{color:var(--high)}.verdict.bad strong{color:var(--crit)}
.verdict p{margin:0 0 1.5mm;font-size:10.5pt}
.kpis{break-inside:avoid;display:grid;grid-template-columns:repeat(3,1fr);gap:3.5mm;margin:3mm 0 4mm}
.kpi{border-top:3px solid var(--accent);background:var(--tint);padding:2.5mm 3.5mm;break-inside:avoid}
.kpi.warn{border-top-color:var(--orange)}
.kpi b{display:block;font-size:19pt;font-weight:800;letter-spacing:-.02em;line-height:1.1}
.kpi span{display:block;font-family:var(--mono);font-size:6.8pt;letter-spacing:.1em;text-transform:uppercase;color:var(--muted)}
.kpi i{display:block;font-style:normal;font-size:7.5pt;color:var(--muted);margin-top:.5mm}
.kpis.k4{grid-template-columns:repeat(4,1fr)}
.recs{list-style:none;padding:0;margin:2mm 0}
.recs li{border-left:3px solid var(--accent);background:var(--tint);padding:2.5mm 4mm;margin:0 0 2.5mm;break-inside:avoid}
.recs li.bad{border-left-color:var(--crit);background:#fef3f2}.recs li.warn{border-left-color:var(--orange);background:#fff7ed}
.recs li b{font-family:var(--mono);font-size:7pt;letter-spacing:.14em;text-transform:uppercase;display:block;color:var(--accent)}
.recs li.bad b{color:var(--crit)}.recs li.warn b{color:var(--high)}
.grid2.wl{grid-template-columns:1.9fr 1fr}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:5mm}
.box{break-inside:avoid;margin:0 0 4mm;border:1px solid var(--line);border-radius:2mm;padding:2.5mm 3.5mm}
.box h3{margin:0 0 2mm;font-size:9.5pt}
.chart{width:100%;height:auto;display:block}
.donutwrap{display:flex;gap:4mm;align-items:center}
.grid2 .box+.box .donutwrap{flex-direction:column;align-items:flex-start}
.donut{width:25mm;height:25mm;flex:none}
.legend{list-style:none;margin:0;padding:0;font-size:8pt;flex:1;min-width:0}
.legend li{display:flex;flex-wrap:wrap;gap:0 2mm;align-items:baseline;margin:0 0 1.2mm}
.legend .sw{width:2.6mm;height:2.6mm;border-radius:50%;flex:none;position:relative;top:.2mm}
.legend .lb{flex:1 1 28mm;min-width:0;overflow-wrap:break-word}.legend .vl{font-family:var(--mono);color:var(--muted);white-space:nowrap}
.c0{background:#f97316}.c1{background:#087f68}.c2{background:#f0b35b}.c3{background:#45d6b0}.c4{background:#c2410c}.c5{background:#4b6b61}.c6{background:#9aa9a2}
table{width:100%;border-collapse:collapse;margin:1mm 0 3mm;font-size:8.3pt}
thead{display:table-header-group}
th{text-align:left;font-family:var(--mono);font-size:6.8pt;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);border-bottom:1.5px solid var(--ink);padding:1.5mm 2mm}
td{padding:1.5mm 2mm;border-bottom:1px solid var(--line);vertical-align:top;overflow-wrap:anywhere}
tbody tr:nth-child(even) td{background:var(--tint)}
tr{break-inside:avoid}
td.n,th.n{text-align:right;font-variant-numeric:tabular-nums}td.n,td.w{white-space:nowrap}
.tbl{break-inside:avoid-page}
.tbl h3{margin-top:4mm}
.empty{color:var(--muted);font-style:italic;margin:1mm 0 3mm}
.note{border-left:3px solid var(--accent);padding:1.5mm 3.5mm;margin:0 0 2mm;background:var(--tint);break-inside:avoid}
.warn-t{color:var(--high);font-weight:600}
</style>
</head>
<body>
<div class="doc">
<div class="cover">
<div class="glow"></div>
{{.Motif}}
<img class="logo" src="{{.Logo}}" alt="Urutau">
<div class="topbar"><span class="wordmark">URUTAU</span><span class="auth">{{.LConf}}</span></div>
<div class="head"><div class="eyebrow">{{.Kicker}}</div><h1>{{.CoverTitle}}</h1><p class="sub">{{.CoverSub}}</p></div>
<div class="numbers">{{range .CoverNums}}<div><b>{{.Value}}</b><span>{{.Label}}</span></div>{{end}}</div>
<div class="meta"><div><span>{{.LPeriod}}</span><b>{{.Period}}</b></div><div><span>{{.LServers}}</span><b>{{.Servers}}</b></div><div><span>{{.LGen}}</span><b>{{.Generated}}</b></div></div>
</div>
<div class="body">
<section class="toc"><h2>{{.LToc}}</h2><ol>{{range .TOC}}<li><a href="#{{.ID}}">{{.Title}}</a></li>{{end}}</ol>
<h2 id="sum">{{.TSum}}</h2>
<div class="verdict {{.VerdictCls}}"><strong>{{.VerdictTitle}}</strong>{{range .Verdict}}<p>{{.}}</p>{{end}}</div>
{{if .Trunc}}<p class="warn-t">{{.Trunc}}</p>{{end}}
<div class="kpis">{{range .KPIs}}<div class="kpi {{.Cls}}"><span>{{.Label}}</span><b>{{.Value}}</b>{{if .Delta}}<i>{{.Delta}}</i>{{end}}</div>{{end}}</div>
</section>
<section class="pg" id="recs"><h2>{{.TRecs}}</h2>
<ul class="recs">{{range .Recs}}<li class="{{.Level}}"><b>{{.Label}}</b>{{.Text}}</li>{{end}}</ul>
</section>
<section id="threats"><h2>{{.TThreats}}</h2>
<div class="box"><h3>{{.Timeline.Title}}</h3>{{if .Timeline.Empty}}<p class="empty">{{.None}}</p>{{else}}{{.Timeline.SVG}}{{end}}</div>
<div class="grid2">
{{template "donut" .Fams}}
{{template "bars" .Techs}}
</div>
<div class="tbl"><h3>{{.TIPs}}</h3>{{template "table" .IPs}}</div>
<div class="tbl"><h3>{{.TCamps}}</h3>{{template "table" .Camps}}</div>
<div class="tbl"><h3>{{.TEscs}}</h3>{{template "table" .Escs}}</div>
<div class="tbl"><h3>{{.TExpo}}</h3>{{template "table" .Expo}}</div>
</section>
<section class="keep" id="geo"><h2>{{.TGeo}}</h2>
<div class="grid2">{{template "bars" .Countries}}{{template "bars" .ASNs}}</div>
</section>
<section id="health"><h2>{{.THealth}}</h2>
<p class="lead">{{.HealthLead}}</p>
{{range .HealthNotes}}<div class="note">{{.}}</div>{{end}}
<div class="grid2 wl" style="margin-top:3mm">{{template "donut" .Classes}}{{template "donut" .Status}}</div>
{{if .ShowPeers}}<p class="muted">{{.PeersNote}}</p>{{end}}
</section>
<section class="keep" id="vis"><h2>{{.TVis}}</h2>
<p class="lead">{{.VisLead}}</p>
<div class="kpis">{{range .VisKPIs}}<div class="kpi"><span>{{.Label}}</span><b>{{.Value}}</b></div>{{end}}</div>
<div class="grid2">{{template "bars" .Pages}}{{template "bars" .Refs}}{{template "donut" .Browsers}}{{template "donut" .Devices}}</div>
</section>
<section class="keep" id="def"><h2>{{.TDef}}</h2>
{{template "table" .Defense}}
</section>
{{if .HasEnf}}<section class="keep" id="enf"><h2>{{.TEnf}}</h2>
<p class="lead">{{.EnfLead}}</p>
{{range .EnfNotes}}<div class="note">{{.}}</div>{{end}}
<div class="kpis k4">{{range .EnfKPIs}}<div class="kpi {{.Cls}}"><span>{{.Label}}</span><b>{{.Value}}</b></div>{{end}}</div>
<div class="tbl"><h3>{{.TEnfRecent}}</h3>{{template "table" .EnfRecent}}</div>
</section>{{end}}
{{if .HasEgress}}<section class="keep" id="egress"><h2>{{.TEgress}}</h2>
<p class="lead">{{.XLead}}</p>
{{range .XNotes}}<div class="note">{{.}}</div>{{end}}
<div class="grid2" style="margin-top:3mm">{{template "bars" .XChart}}{{template "bars" .XDst}}</div>
<div class="tbl"><h3>{{.TXFind}}</h3>{{template "table" .XFind}}</div>
<div class="tbl"><h3>{{.TXWl}}</h3>{{template "table" .XWl}}</div>
</section>{{end}}
<section class="keep" id="method"><h2>{{.TMethod}}</h2>
<p>{{.MethodP1}}</p><p>{{.MethodP2}}</p><p>{{.MethodP3}}</p>
</section>
</div>
</div>
</body>
</html>
{{define "table"}}{{if .Rows}}{{$n := .Num}}{{$w := .NoWrap}}<table><thead><tr>{{range $i, $h := .Head}}<th{{if index $n $i}} class="n"{{end}}>{{$h}}</th>{{end}}</tr></thead><tbody>{{range .Rows}}<tr>{{range $i, $c := .Cells}}<td{{if index $n $i}} class="n"{{else if index $w $i}} class="w"{{end}}>{{$c}}</td>{{end}}</tr>{{end}}</tbody></table>{{else}}<p class="empty">{{.None}}</p>{{end}}{{end}}
{{define "bars"}}<div class="box"><h3>{{.Title}}</h3>{{if .Empty}}<p class="empty">-</p>{{else}}{{.SVG}}{{end}}</div>{{end}}
{{define "donut"}}<div class="box"><h3>{{.Title}}</h3>{{if .Empty}}<p class="empty">-</p>{{else}}<div class="donutwrap">{{.SVG}}<ul class="legend">{{range $i, $l := .Legend}}<li><span class="sw c{{$i}}"></span><span class="lb">{{$l.Label}}</span><span class="vl">{{$l.Value}}</span></li>{{end}}</ul></div>{{end}}</div>{{end}}
`
+5 -1
View File
@@ -102,6 +102,7 @@ func New(opt Options) http.Handler {
m.HandleFunc("GET /api/v1/peer/export", s.peerExport)
m.HandleFunc("GET /api/v1/peer/stream", s.peerStream)
m.HandleFunc("GET /api/v1/peer/period", s.peerPeriod)
m.HandleFunc("GET /api/v1/peer/egress", s.peerEgress)
m.HandleFunc("GET /api/v1/geo", s.api(s.geoAPI))
m.HandleFunc("GET /api/v1/live/recent", s.api(s.liveRecent))
m.HandleFunc("GET /api/v1/summary", s.api(s.summary))
@@ -119,6 +120,9 @@ func New(opt Options) http.Handler {
for _, r := range userRoutes {
m.HandleFunc(r.pattern, s.api(r.handler(s)))
}
for _, r := range peerRoutes { // peer-token routes of api_<name>.go files
m.HandleFunc(r.pattern, r.handler(s))
}
m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream))
m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false)))
m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true)))
@@ -196,7 +200,7 @@ func (s *Server) api(h http.HandlerFunc) http.HandlerFunc {
switch s.authKind(r) {
case "session", "bearer":
case "peer":
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export, /api/v1/peer/stream and /api/v1/peer/period"})
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export, /api/v1/peer/stream, /api/v1/peer/period and /api/v1/peer/egress"})
return
default:
ip := clientIP(r, s.opt.TrustedProxy)
+20
View File
@@ -3,3 +3,23 @@
.df-kpis .card-metric { min-width: 0; }
.df-sum { padding: 0 0 8px; }
.df-bl { color: var(--ink-muted); font-size: .875rem; margin: 4px 0 12px; overflow-wrap: anywhere; }
.df-en { margin-top: var(--grid-gap, 16px); }
.df-en .panel { min-width: 0; }
.df-en-title { font-size: 1.125rem; margin: 0 0 4px; }
.df-mode { margin: 0 0 8px; }
.df-en-p { margin: 0 0 8px; overflow-wrap: anywhere; }
.df-en-meta { overflow-wrap: anywhere; }
.df-en-how { margin: 8px 0 0; padding: 8px 12px; border-left: 3px solid var(--info); background: var(--info-soft); border-radius: 4px; overflow-wrap: anywhere; }
.df-en-sum { font-size: 1.0625rem; font-weight: 600; margin: 0 0 4px; overflow-wrap: anywhere; }
.df-skips { list-style: none; margin: 12px 0 0; padding: 0; display: flex; flex-wrap: wrap; gap: 4px 16px; color: var(--ink-muted); font-size: .875rem; }
.df-skips .num { font-weight: 600; color: var(--ink); }
.df-scroll { max-height: 440px; overflow: auto; }
.df-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.df-table th, .df-table td { padding: 5px var(--s-3, 10px); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; vertical-align: top; }
.df-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
.df-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.df-act { display: inline-flex; flex-direction: column; align-items: flex-start; gap: 2px; }
.df-skipwhy { color: var(--ink-muted); font-size: .75rem; }
@media (max-width: 900px) { .df-en .span-4, .df-en .span-8 { grid-column: 1 / -1; } }
.df-nowrap { white-space: nowrap; }
@media (max-width: 700px) { .df-table { min-width: 640px; } .df-table td, .df-table th { overflow-wrap: normal; } }
+257 -4
View File
@@ -44,7 +44,76 @@
'df.disabled': 'The event registry is off',
'df.disabled.sub': 'Defense is computed from the event registry; enable it to see this page.',
'df.partial': 'Partial result: the study hit its time or size limit.',
'df.admin': 'your account'
'df.admin': 'your account',
'df.en.title': 'Second firewall',
'df.en.hint': 'Urutau can also block attackers by itself, as a safety net next to fail2ban.',
'df.en.mode': 'Mode',
'df.en.mode.off': 'Off',
'df.en.mode.observe': 'Observing only',
'df.en.mode.on': 'Active',
'df.en.mode.off.sub': 'Urutau does not block anyone. Nothing is written; the coverage below shows what you would gain by turning it on.',
'df.en.mode.observe.sub': 'Urutau decides who it would block and records it, but blocks nobody. Use it to check the decisions before trusting them.',
'df.en.mode.on.sub': 'Urutau blocks the attackers it recognises, on its own, for a limited time.',
'df.en.mode.where': 'The mode is chosen at deploy time with the variable URUTAU_ENFORCE (off, observe or on). It cannot be changed from this page.',
'df.en.how.title': 'How to turn it on',
'df.en.how.body': 'Set URUTAU_ENFORCE=observe on the server and restart Urutau. Watch the decisions for a few days; when they look right, change it to on.',
'df.en.share': 'Sharing with peers',
'df.en.share.on': 'on: bans are shared with other servers',
'df.en.share.off': 'off: bans stay on this server',
'df.en.threshold': 'Blocks from score {n}',
'df.en.nolog.title': 'Blocks are not being saved',
'df.en.nolog.body': 'The mode is active but the block file cannot be written, so nobody is really blocked. Check the permissions of the folder where Urutau writes the blocklist.',
'df.en.lead': '{b} of {a} attacking addresses were blocked {range}',
'df.en.lead.sub': '{fw} by the server firewall, {ur} by Urutau, {wb} would be blocked in observation mode and {un} got through.',
'df.en.lead.none': 'No attacking addresses {range}',
'df.en.lead.none.sub': 'Nothing to block in this window.',
'df.en.cov': 'Who was blocked',
'df.en.cov.hint': 'Each attacking address counted once, by the first line of defense that stopped it.',
'df.en.cov.center': 'addresses',
'df.en.cov.fw': 'Blocked by the server firewall',
'df.en.cov.ur': 'Blocked by Urutau',
'df.en.cov.wb': 'Would be blocked (observation mode)',
'df.en.cov.un': 'Got through without a block',
'df.en.counts': 'What Urutau decided',
'df.en.counts.hint': 'Counts in this window. "Skipped" are attackers it deliberately left alone.',
'df.en.c.decided': 'Decisions',
'df.en.c.written': 'Blocks written',
'df.en.c.dropped': 'Dropped by rate limit',
'df.en.c.already': 'Already blocked',
'df.en.recent': 'Recent decisions',
'df.en.recent.hint': 'The latest decisions, newest first.',
'df.en.recent.none': 'No decisions in this window.',
'df.en.col.time': 'Time',
'df.en.col.ip': 'Address',
'df.en.col.cc': 'Country',
'df.en.col.reason': 'Reason',
'df.en.col.score': 'Score',
'df.en.col.ttl': 'Duration',
'df.en.col.action': 'Action',
'df.en.col.src': 'Origin',
'df.en.act.ban': 'Blocked',
'df.en.act.would_ban': 'Would block',
'df.en.act.skip': 'Not blocked',
'df.en.src.local': 'this server',
'df.en.src.peer': 'peer {n}',
'df.en.skip.trusted': 'Trusted address (your own list)',
'df.en.skip.private': 'Private network (not on the internet)',
'df.en.skip.crawler': 'Verified search engine',
'df.en.skip.legit_visitor': 'Looks like a legitimate visitor',
'df.en.skip.peer': 'Peer server (yours)',
'df.en.reason.scanner-flood': 'Many vulnerability probes in a short time',
'df.en.reason.exploit-flood': 'Repeated exploit attempts',
'df.en.reason.web-bruteforce': 'Password guessing on a website',
'df.en.reason.wp-bruteforce': 'Password guessing on WordPress',
'df.en.reason.ssh-bruteforce': 'Password guessing on SSH',
'df.en.reason.rce': 'Attempt to run commands on the server',
'df.en.reason.path-traversal': 'Attempt to read files outside the site',
'df.en.reason.env-probe': 'Hunting for secret configuration files (.env)',
'df.en.reason.vcs-probe': 'Hunting for source code history (.git)',
'df.en.reason.webshell': 'Looking for or uploading a backdoor (webshell)',
'df.en.reason.sqli': 'Attempt to tamper with the database (SQL injection)',
'df.en.reason.log4shell': 'Log4Shell exploit attempt',
'df.en.error': 'Could not load the second firewall data.'
},
'pt-BR': {
'df.title': 'Defesa',
@@ -79,7 +148,76 @@
'df.disabled': 'O registro de eventos está desligado',
'df.disabled.sub': 'A defesa é calculada a partir do registro de eventos; ative-o para ver esta página.',
'df.partial': 'Resultado parcial: o estudo atingiu o limite de tempo ou de tamanho.',
'df.admin': 'sua conta'
'df.admin': 'sua conta',
'df.en.title': 'Segundo firewall',
'df.en.hint': 'O Urutau também pode bloquear atacantes por conta própria, como uma rede de segurança ao lado do fail2ban.',
'df.en.mode': 'Modo',
'df.en.mode.off': 'Desligado',
'df.en.mode.observe': 'Só observando',
'df.en.mode.on': 'Ativo',
'df.en.mode.off.sub': 'O Urutau não bloqueia ninguém e não grava nada. A cobertura abaixo mostra o quanto você ganharia ao ligá-lo.',
'df.en.mode.observe.sub': 'O Urutau decide quem bloquearia e registra, mas não bloqueia ninguém. Use para conferir as decisões antes de confiar nelas.',
'df.en.mode.on.sub': 'O Urutau bloqueia sozinho os atacantes que reconhece, por tempo limitado.',
'df.en.mode.where': 'O modo é escolhido no deploy, pela variável URUTAU_ENFORCE (off, observe ou on). Não dá para mudá-lo por esta página.',
'df.en.how.title': 'Como ligar',
'df.en.how.body': 'Defina URUTAU_ENFORCE=observe no servidor e reinicie o Urutau. Acompanhe as decisões por alguns dias; quando estiverem certas, troque para on.',
'df.en.share': 'Compartilhamento com parceiros',
'df.en.share.on': 'ligado: os bloqueios são compartilhados com outros servidores',
'df.en.share.off': 'desligado: os bloqueios ficam só neste servidor',
'df.en.threshold': 'Bloqueia a partir da pontuação {n}',
'df.en.nolog.title': 'Os bloqueios não estão sendo salvos',
'df.en.nolog.body': 'O modo está ativo, mas o arquivo de bloqueios não pode ser gravado; na prática ninguém está sendo bloqueado. Confira as permissões da pasta onde o Urutau grava a blocklist.',
'df.en.lead': '{b} de {a} endereços atacantes foram bloqueados {range}',
'df.en.lead.sub': '{fw} pelo firewall do servidor, {ur} pelo Urutau, {wb} seriam bloqueados no modo observação e {un} passaram.',
'df.en.lead.none': 'Nenhum endereço atacante {range}',
'df.en.lead.none.sub': 'Nada a bloquear nesta janela.',
'df.en.cov': 'Quem foi bloqueado',
'df.en.cov.hint': 'Cada endereço atacante conta uma vez, pela primeira linha de defesa que o barrou.',
'df.en.cov.center': 'endereços',
'df.en.cov.fw': 'Bloqueado pelo firewall do servidor',
'df.en.cov.ur': 'Bloqueado pelo Urutau',
'df.en.cov.wb': 'Seria bloqueado (modo observação)',
'df.en.cov.un': 'Passou sem bloqueio',
'df.en.counts': 'O que o Urutau decidiu',
'df.en.counts.hint': 'Contagens desta janela. "Ignorados" são atacantes que ele deixou passar de propósito.',
'df.en.c.decided': 'Decisões',
'df.en.c.written': 'Bloqueios gravados',
'df.en.c.dropped': 'Descartados pelo limite de ritmo',
'df.en.c.already': 'Já estavam bloqueados',
'df.en.recent': 'Decisões recentes',
'df.en.recent.hint': 'As últimas decisões, da mais nova para a mais antiga.',
'df.en.recent.none': 'Nenhuma decisão nesta janela.',
'df.en.col.time': 'Hora',
'df.en.col.ip': 'Endereço',
'df.en.col.cc': 'País',
'df.en.col.reason': 'Motivo',
'df.en.col.score': 'Pontuação',
'df.en.col.ttl': 'Duração',
'df.en.col.action': 'Ação',
'df.en.col.src': 'Origem',
'df.en.act.ban': 'Bloqueado',
'df.en.act.would_ban': 'Bloquearia',
'df.en.act.skip': 'Não bloqueado',
'df.en.src.local': 'este servidor',
'df.en.src.peer': 'parceiro {n}',
'df.en.skip.trusted': 'Endereço confiável (sua própria lista)',
'df.en.skip.private': 'Rede privada (fora da internet)',
'df.en.skip.crawler': 'Buscador verificado',
'df.en.skip.legit_visitor': 'Parece um visitante legítimo',
'df.en.skip.peer': 'Servidor parceiro (seu)',
'df.en.reason.scanner-flood': 'Muitas sondagens de vulnerabilidade em pouco tempo',
'df.en.reason.exploit-flood': 'Tentativas repetidas de exploração',
'df.en.reason.web-bruteforce': 'Tentativa de adivinhar senha num site',
'df.en.reason.wp-bruteforce': 'Tentativa de adivinhar senha no WordPress',
'df.en.reason.ssh-bruteforce': 'Tentativa de adivinhar senha no SSH',
'df.en.reason.rce': 'Tentativa de executar comandos no servidor',
'df.en.reason.path-traversal': 'Tentativa de ler arquivos fora do site',
'df.en.reason.env-probe': 'Caça a arquivos de configuração secretos (.env)',
'df.en.reason.vcs-probe': 'Caça ao histórico do código-fonte (.git)',
'df.en.reason.webshell': 'Procura ou envio de porta dos fundos (webshell)',
'df.en.reason.sqli': 'Tentativa de adulterar o banco de dados (injeção de SQL)',
'df.en.reason.log4shell': 'Tentativa de explorar o Log4Shell',
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.'
}
});
@@ -172,7 +310,122 @@
root.appendChild(grid);
}
var enData = null, enSeq = 0, enBox = null;
function ttlTxt(s) { return s > 0 ? dur(s) : '-'; }
function reasonTxt(r) {
if (!r) return '-';
var k = 'df.en.reason.' + r;
if (t(k) !== k) return t(k);
var parts = String(r).split(/[-_:]/);
for (var i = 0; i < parts.length; i++) { var c = 'df.en.reason.' + parts[i]; if (t(c) !== c) return t(c) + ' (' + r + ')'; }
return r;
}
function tbl(cols, rows) {
var tb = el('tbody');
rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); });
return el('div', { class: 'df-scroll' }, el('table', { class: 'df-table' },
el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb));
}
function paintEnforce() {
if (!enBox) return;
clear(enBox);
if (!enData) return;
var e = enData, cv = e.coverage || {}, cn = e.counts || {}, sk = cn.skipped || {}, range = U.rangeLabel({ inline: true });
var mode = /^(off|observe|on)$/.test(e.mode) ? e.mode : 'off';
var head = el('div', { class: 'df-en-head' });
var mt = el('h2', { class: 'df-en-title' }, t('df.en.title'));
if (U.help) U.help(mt, 'term.second_firewall');
head.appendChild(mt);
head.appendChild(el('p', { class: 'hint' }, t('df.en.hint')));
enBox.appendChild(head);
var grid = el('div', { class: 'grid-12' });
var mp = U.ui.panel({ title: t('df.en.mode'), cls: 'span-4', help: mode === 'observe' ? 'term.observe_mode' : null });
var tone = mode === 'on' ? 'ok' : mode === 'observe' ? 'info' : 'warn';
mp.body.appendChild(el('p', { class: 'df-mode' }, U.ui.badge(t('df.en.mode.' + mode), tone)));
mp.body.appendChild(el('p', { class: 'df-en-p' }, t('df.en.mode.' + mode + '.sub')));
mp.body.appendChild(el('p', { class: 'hint' }, t('df.en.mode.where')));
var meta = el('p', { class: 'hint df-en-meta' }, t('df.en.threshold', { n: nf(e.threshold || 0) }) + ' · ' + t('df.en.share') + ': ' + (e.share === 'on' ? t('df.en.share.on') : t('df.en.share.off')));
if (U.help) U.help(meta, 'term.ban_ttl');
mp.body.appendChild(meta);
if (mode === 'on' && e.log_writable === false) mp.body.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.en.nolog.title')), el('span', null, t('df.en.nolog.body'))));
if (mode === 'off') {
mp.body.appendChild(el('p', { class: 'df-en-how' }, el('strong', null, t('df.en.how.title') + ': '), t('df.en.how.body')));
}
grid.appendChild(mp);
var total = (cv.blocked_by_firewall || 0) + (cv.blocked_by_urutau || 0) + (cv.would_block || 0) + (cv.unblocked || 0);
var cp = U.ui.panel({ title: t('df.en.cov'), hint: t('df.en.cov.hint'), cls: 'span-8' });
var rows = [
{ key: 'fw', label: t('df.en.cov.fw'), value: cv.blocked_by_firewall || 0, color: '--ok' },
{ key: 'ur', label: t('df.en.cov.ur'), value: cv.blocked_by_urutau || 0, color: '--info' },
{ key: 'wb', label: t('df.en.cov.wb'), value: cv.would_block || 0, color: '--warn' },
{ key: 'un', label: t('df.en.cov.un'), value: cv.unblocked || 0, color: '--danger' }
];
var blocked = (cv.blocked_by_firewall || 0) + (cv.blocked_by_urutau || 0);
cp.body.appendChild(el('p', { class: 'df-en-sum' }, total ? t('df.en.lead', { b: nf(blocked), a: nf(cv.attack_ips || total), range: range }) : t('df.en.lead.none', { range: range })));
if (total) {
cp.body.appendChild(el('p', { class: 'hint' }, t('df.en.lead.sub', { fw: nf(rows[0].value), ur: nf(rows[1].value), wb: nf(rows[2].value), un: nf(rows[3].value) })));
if (U.charts && U.charts.donut) {
cp.body.appendChild(U.charts.donut(rows, { title: t('df.en.cov'), centerLabel: t('df.en.cov.center'), format: nf, colors: rows.map(function (r) { return r.color; }) }));
if (U.help) { var lis = cp.body.querySelectorAll('.vz-legend li'); if (lis[2]) U.help(lis[2], 'term.observe_mode'); }
}
} else cp.body.appendChild(U.ui.empty(t('df.en.lead.none', { range: range }), t('df.en.lead.none.sub')));
grid.appendChild(cp);
var np = U.ui.panel({ title: t('df.en.counts'), hint: t('df.en.counts.hint'), cls: 'span-12' });
var kp = el('div', { class: 'grid-12 df-kpis' });
function k(node) { node.classList.add('span-3'); kp.appendChild(node); }
k(U.ui.metric(t('df.en.c.decided'), nf(cn.decided || 0)));
k(U.ui.metric(t('df.en.c.written'), nf(cn.written || 0), { tone: 'ok' }));
k(U.ui.metric(t('df.en.c.dropped'), nf(cn.dropped_rate || 0), { tone: cn.dropped_rate ? 'warn' : 'neutral' }));
k(U.ui.metric(t('df.en.c.already'), nf(cn.already_blocked || 0)));
np.body.appendChild(kp);
var skl = el('ul', { class: 'df-skips' });
['trusted', 'private', 'crawler', 'legit_visitor', 'peer'].forEach(function (key) {
if (!sk[key]) return;
skl.appendChild(el('li', null, el('span', { class: 'num' }, nf(sk[key])), ' ' + t('df.en.skip.' + key)));
});
if (skl.firstChild) np.body.appendChild(skl);
grid.appendChild(np);
var rp = U.ui.panel({ title: t('df.en.recent'), hint: t('df.en.recent.hint'), cls: 'span-12', variant: 'list' });
var rec = e.recent || [];
if (!rec.length) rp.body.appendChild(U.ui.empty(t('df.en.recent.none')));
else {
var cols = [{ label: t('df.en.col.time') }, { label: t('df.en.col.ip'), cls: 'mono' }, { label: t('df.en.col.cc') }, { label: t('df.en.col.reason') },
{ label: t('df.en.col.score'), cls: 'num' }, { label: t('df.en.col.ttl'), cls: 'num' }, { label: t('df.en.col.action') }, { label: t('df.en.col.src') }];
rp.body.appendChild(tbl(cols, rec.map(function (r) {
var act = /^(ban|would_ban|skip)$/.test(r.action) ? r.action : 'skip';
var actNode = el('span', { class: 'df-act' }, U.ui.badge(t('df.en.act.' + act), act === 'ban' ? 'ok' : act === 'would_ban' ? 'warn' : 'neutral'));
if (act === 'skip' && r.skip_reason) {
var sk2 = 'df.en.skip.' + r.skip_reason;
actNode.appendChild(el('small', { class: 'df-skipwhy' }, t(sk2) !== sk2 ? t(sk2) : r.skip_reason));
}
var peer = String(r.src || 'local');
var src = peer.indexOf('peer:') === 0 ? t('df.en.src.peer', { n: peer.slice(5) }) : t('df.en.src.local');
return [el('span', { class: 'df-nowrap' }, U.fmt.clock(r.t)), el('a', { href: U.href('ip', [r.ip]) }, r.ip), (r.cc ? U.fmt.flag(r.cc) + ' ' : '') + (r.cc || '-'),
reasonTxt(r.reason), nf(r.score || 0), ttlTxt(r.ttl || 0), actNode, src];
})));
}
grid.appendChild(rp);
enBox.appendChild(grid);
}
function loadEnforce() {
var my = ++enSeq;
U.api('/api/v1/enforce', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
if (!alive || my !== enSeq) return;
enData = d; paintEnforce();
}).catch(function () {
if (!alive || my !== enSeq || enData || !enBox) return;
clear(enBox);
enBox.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.en.error'))));
});
}
function load() {
loadEnforce();
var my = ++seq;
U.api('/api/v1/defense', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) {
if (!alive || my !== seq) return;
@@ -187,10 +440,10 @@
U.registerPage({
id: 'defense', group: 'operate', titleKey: 'df.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M12 3l8 3v6c0 4.5-3.2 7.8-8 9-4.8-1.2-8-4.5-8-9V6z"/><path d="M9 12l2 2 4-4"/></svg>',
mount: function (node, cx) { root = el('div', { class: 'df-page' }); node.appendChild(root); ctx = cx; alive = true; data = null; paint(); load(); },
mount: function (node, cx) { root = el('div', { class: 'df-page' }); node.appendChild(root); enBox = el('div', { class: 'df-page df-en' }); node.appendChild(enBox); ctx = cx; alive = true; data = null; enData = null; paint(); load(); },
update: function (cx) { ctx = cx; load(); },
refresh: function () { load(); },
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = null; data = null; }
unmount: function () { alive = false; seq++; enSeq++; if (root && root.parentNode) root.parentNode.removeChild(root); if (enBox && enBox.parentNode) enBox.parentNode.removeChild(enBox); root = null; enBox = null; data = null; enData = null; }
});
return true;
}
+30
View File
@@ -0,0 +1,30 @@
/* Egress page */
.eg-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; }
.eg-page .panel, .eg-kpis .card-metric { min-width: 0; }
.eg-wl-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 240px), 1fr)); gap: 12px; }
.eg-wl { min-width: 0; }
.eg-wl-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; margin-bottom: 8px; }
.eg-wl-head .badge { white-space: normal; }
.eg-wl-name { margin: 0; font-size: 1rem; overflow-wrap: anywhere; }
.eg-wl-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin: 0; }
.eg-wl-stats div { min-width: 0; }
.eg-wl-stats dd { margin: 0; font-size: 1.125rem; font-weight: 600; }
.eg-wl-stats dt { color: var(--ink-muted); font-size: .75rem; overflow-wrap: anywhere; }
.eg-warn { color: var(--danger); font-weight: 600; }
.eg-findings { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
.eg-f { border: 1px solid var(--line); border-left-width: 4px; border-radius: 6px; padding: 10px 12px; min-width: 0; }
.eg-sev-high { border-left-color: var(--danger); }
.eg-sev-medium { border-left-color: var(--warn); }
.eg-sev-low { border-left-color: var(--info); }
.eg-f-top { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 10px; }
.eg-f p { margin: 6px 0 0; overflow-wrap: anywhere; }
.eg-f-why { color: var(--ink-muted); }
.eg-f-detail { font-size: .8125rem; }
.eg-scroll { max-height: 440px; overflow: auto; }
.eg-table { width: 100%; border-collapse: collapse; font-size: .875rem; }
.eg-table th, .eg-table td { padding: 5px var(--s-3, 10px); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; vertical-align: top; }
.eg-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
.eg-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.eg-scanwarn { margin-bottom: 10px; }
@media (max-width: 600px) { .eg-kpis .span-4 { grid-column: 1 / -1; } }
@media (max-width: 700px) { .eg-table { min-width: 560px; } }
+355
View File
@@ -0,0 +1,355 @@
/* Urutau - EGRESS page: what the workloads of your servers talk to on the
internet (outbound traffic). Beacons, scans, odd ports, known-bad
destinations, DNS bypass, new countries, and the summarised scans of the
authorised scanner. Data: /api/v1/egress. Log data is hostile: dynamic text
goes through textContent only. */
(function () {
'use strict';
var SEV = { high: 0, medium: 1, low: 2 };
var SEV_TONE = { high: 'danger', medium: 'warn', low: 'info' };
var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', 'new_geo'];
var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.c2', dns_bypass: 'term.dot', new_geo: 'term.new_geo' };
function boot() {
var U = window.Urutau;
if (!U || !U.registerPage) return false;
U.registerI18n({
en: {
'eg.title': 'Outbound traffic',
'eg.error': 'Could not load the outbound traffic data.',
'eg.retry': 'Try again',
'eg.disabled': 'Outbound traffic is not being watched',
'eg.disabled.sub': 'This page shows connections that leave your servers. To see them, add an outbound firewall rule on the server that logs new connections, and set the variable URUTAU_EGRESS so Urutau reads that log.',
'eg.lead.none': 'No outbound connections {range}',
'eg.lead.none.sub': 'Nothing left the watched workloads in this window.',
'eg.lead.ok': '{n} outbound connections {range}, nothing suspicious',
'eg.lead.ok.sub': 'No findings in this window. Authorised scans, if any, are summarised below.',
'eg.lead.bad': '{f} findings in {n} outbound connections {range}',
'eg.lead.bad.sub': '{h} high, {m} medium and {l} low severity. Start with the high ones.',
'eg.src': 'Log source: {state} · {lines} lines read · {bad} unreadable',
'eg.src.following': 'being followed',
'eg.src.waiting': 'waiting for the file',
'eg.src.missing': 'file not found',
'eg.src.error': 'error',
'eg.kpi.conns': 'Connections',
'eg.kpi.conns.sub': 'new outbound connections',
'eg.kpi.dsts': 'Destinations',
'eg.kpi.dsts.sub': 'different addresses reached',
'eg.kpi.find': 'Findings',
'eg.kpi.find.sub': '{h} high · {m} medium · {l} low',
'eg.workloads': 'Workloads',
'eg.workloads.hint': 'Each workload is a program or container that makes outbound connections.',
'eg.wl.conns': 'connections',
'eg.wl.dsts': 'destinations',
'eg.wl.ports': 'ports',
'eg.wl.findings': 'findings',
'eg.wl.suppressed': '{n} scan connections summarised',
'eg.role.scanner': 'authorised scans summarised',
'eg.role.app': 'application',
'eg.role.proxy': 'proxy',
'eg.role.database': 'database',
'eg.role.system': 'system',
'eg.timeline': 'Connections over time',
'eg.timeline.hint': 'Stacked by workload.',
'eg.findings': 'Findings',
'eg.findings.hint': 'Sorted by severity. Each one explains what the pattern usually means.',
'eg.findings.none': 'No findings in this window.',
'eg.sev.high': 'High',
'eg.sev.medium': 'Medium',
'eg.sev.low': 'Low',
'eg.kind.beacon': 'Regular conversation',
'eg.kind.scan': 'Mass connection attempts',
'eg.kind.port': 'Unusual port',
'eg.kind.bad_dst': 'Known-bad destination',
'eg.kind.dns_bypass': 'DNS outside the resolver',
'eg.kind.new_geo': 'New country',
'eg.why.beacon': 'The workload talks to the same destination at regular intervals, like a clock. This is the typical pattern of malware checking in with its controller.',
'eg.why.scan': 'The workload tried to connect to many different addresses in a short time. A server that scans the internet usually means it was taken over.',
'eg.why.port': 'Connection to a port used by mining pools or remote-control tools, which normal software on this server does not use.',
'eg.why.bad_dst': 'The destination is on a list of addresses known for malware or attacks. Nothing on your server should talk to it.',
'eg.why.dns_bypass': 'The workload asked for names directly from an outside DNS server instead of your resolver. Malware does this to hide what it looks up.',
'eg.why.new_geo': 'The workload connected to a country it had never reached before in this window. It may be harmless, but is worth a look.',
'eg.f.to': 'To',
'eg.f.count': '{n} connections',
'eg.f.interval': 'every {s} s (variation {j}%)',
'eg.f.first': 'first {t}',
'eg.f.last': 'last {t}',
'eg.f.host': 'server {h}',
'eg.dst': 'Top destinations',
'eg.dst.hint': 'Where the connections went.',
'eg.dst.none': 'No destinations in this window.',
'eg.col.ip': 'Address',
'eg.col.country': 'Country',
'eg.col.asn': 'Network (ASN)',
'eg.col.conns': 'Connections',
'eg.col.who': 'Workloads',
'eg.col.ports': 'Ports',
'eg.scan': 'Authorised scans',
'eg.scan.hint': 'Scans your own scanner runs on purpose. They are summarised here instead of raising findings.',
'eg.scan.none': 'No scan bursts in this window.',
'eg.scan.warn': 'A scan reached {n} known-bad destinations: check that the scanner is not aiming at the wrong targets.',
'eg.scan.targets': '{n} targets',
'eg.scan.nets': 'networks',
'eg.scan.ports': 'ports',
'eg.scan.conns': '{n} connections',
'eg.scan.when': '{a} to {b}',
'eg.col.who1': 'Workload',
'eg.col.when': 'When',
'eg.col.targets': 'Targets',
'eg.col.nets': 'Networks',
'eg.col.badhits': 'Bad destinations hit'
},
'pt-BR': {
'eg.title': 'Tráfego de saída',
'eg.error': 'Não foi possível carregar os dados de tráfego de saída.',
'eg.retry': 'Tentar de novo',
'eg.disabled': 'O tráfego de saída não está sendo monitorado',
'eg.disabled.sub': 'Esta página mostra as conexões que saem dos seus servidores. Para vê-las, crie no servidor uma regra de firewall de saída que registre as conexões novas e defina a variável URUTAU_EGRESS para o Urutau ler esse registro.',
'eg.lead.none': 'Nenhuma conexão de saída {range}',
'eg.lead.none.sub': 'Nada saiu dos workloads monitorados nesta janela.',
'eg.lead.ok': '{n} conexões de saída {range}, nada suspeito',
'eg.lead.ok.sub': 'Nenhum achado nesta janela. As varreduras autorizadas, se houver, aparecem resumidas abaixo.',
'eg.lead.bad': '{f} achados em {n} conexões de saída {range}',
'eg.lead.bad.sub': '{h} de gravidade alta, {m} média e {l} baixa. Comece pelos de gravidade alta.',
'eg.src': 'Origem do registro: {state} · {lines} linhas lidas · {bad} ilegíveis',
'eg.src.following': 'sendo acompanhado',
'eg.src.waiting': 'aguardando o arquivo',
'eg.src.missing': 'arquivo não encontrado',
'eg.src.error': 'erro',
'eg.kpi.conns': 'Conexões',
'eg.kpi.conns.sub': 'novas conexões de saída',
'eg.kpi.dsts': 'Destinos',
'eg.kpi.dsts.sub': 'endereços diferentes alcançados',
'eg.kpi.find': 'Achados',
'eg.kpi.find.sub': '{h} altos · {m} médios · {l} baixos',
'eg.workloads': 'Workloads',
'eg.workloads.hint': 'Cada workload é um programa ou contêiner que faz conexões de saída.',
'eg.wl.conns': 'conexões',
'eg.wl.dsts': 'destinos',
'eg.wl.ports': 'portas',
'eg.wl.findings': 'achados',
'eg.wl.suppressed': '{n} conexões de varredura resumidas',
'eg.role.scanner': 'varreduras autorizadas resumidas',
'eg.role.app': 'aplicação',
'eg.role.proxy': 'proxy',
'eg.role.database': 'banco de dados',
'eg.role.system': 'sistema',
'eg.timeline': 'Conexões ao longo do tempo',
'eg.timeline.hint': 'Empilhadas por workload.',
'eg.findings': 'Achados',
'eg.findings.hint': 'Ordenados por gravidade. Cada um explica o que o padrão costuma significar.',
'eg.findings.none': 'Nenhum achado nesta janela.',
'eg.sev.high': 'Alta',
'eg.sev.medium': 'Média',
'eg.sev.low': 'Baixa',
'eg.kind.beacon': 'Conversa em intervalos regulares',
'eg.kind.scan': 'Tentativas de conexão em massa',
'eg.kind.port': 'Porta incomum',
'eg.kind.bad_dst': 'Destino sabidamente ruim',
'eg.kind.dns_bypass': 'DNS fora do resolvedor',
'eg.kind.new_geo': 'País novo',
'eg.why.beacon': 'O workload fala com o mesmo destino em intervalos regulares, como um relógio. É o padrão típico de um malware avisando seu controlador que está vivo.',
'eg.why.scan': 'O workload tentou conectar a muitos endereços diferentes em pouco tempo. Um servidor que varre a internet costuma ter sido invadido.',
'eg.why.port': 'Conexão a uma porta usada por mineração de criptomoeda ou ferramentas de controle remoto, que os programas normais deste servidor não usam.',
'eg.why.bad_dst': 'O destino está numa lista de endereços conhecidos por malware ou ataques. Nada no seu servidor deveria falar com ele.',
'eg.why.dns_bypass': 'O workload consultou nomes direto num servidor DNS de fora, em vez do seu resolvedor. Malware faz isso para esconder o que procura.',
'eg.why.new_geo': 'O workload conectou a um país que ainda não tinha alcançado nesta janela. Pode ser inofensivo, mas vale olhar.',
'eg.f.to': 'Para',
'eg.f.count': '{n} conexões',
'eg.f.interval': 'a cada {s} s (variação {j}%)',
'eg.f.first': 'primeira {t}',
'eg.f.last': 'última {t}',
'eg.f.host': 'servidor {h}',
'eg.dst': 'Principais destinos',
'eg.dst.hint': 'Para onde foram as conexões.',
'eg.dst.none': 'Nenhum destino nesta janela.',
'eg.col.ip': 'Endereço',
'eg.col.country': 'País',
'eg.col.asn': 'Rede (ASN)',
'eg.col.conns': 'Conexões',
'eg.col.who': 'Workloads',
'eg.col.ports': 'Portas',
'eg.scan': 'Varreduras autorizadas',
'eg.scan.hint': 'Varreduras que o seu próprio scanner faz de propósito. Aparecem resumidas aqui em vez de gerar achados.',
'eg.scan.none': 'Nenhuma rajada de varredura nesta janela.',
'eg.scan.warn': 'Uma varredura atingiu {n} destinos sabidamente ruins: confira se o scanner não está mirando os alvos errados.',
'eg.scan.targets': '{n} alvos',
'eg.scan.nets': 'redes',
'eg.scan.ports': 'portas',
'eg.scan.conns': '{n} conexões',
'eg.scan.when': '{a} a {b}',
'eg.col.who1': 'Workload',
'eg.col.when': 'Quando',
'eg.col.targets': 'Alvos',
'eg.col.nets': 'Redes',
'eg.col.badhits': 'Destinos ruins atingidos'
}
});
var el = U.el, t = U.t, nf = U.fmt.num;
var root = null, seq = 0, alive = false, ctx = null, data = null, failed = false;
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function tbl(cols, rows) {
var tb = el('tbody');
rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); });
return el('div', { class: 'eg-scroll' }, el('table', { class: 'eg-table' },
el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb));
}
function ipLink(ip) { return el('a', { href: U.href('ip', [ip]), class: 'mono' }, ip); }
function when(ts) { return ts ? U.fmt.clock(ts) : '-'; }
function help(node, key) { if (U.help) U.help(node, key); return node; }
function roleLabel(r) { var k = 'eg.role.' + r; return t(k) !== k ? t(k) : (r || '-'); }
function list(a) { return (a || []).join(', ') || '-'; }
function workloadCard(w, multi) {
var scanner = w.role === 'scanner';
var h = el('h3', { class: 'eg-wl-name' }, w.name);
var head = el('div', { class: 'eg-wl-head' }, h);
if (w.role) {
var b = U.ui.badge(roleLabel(w.role), scanner ? 'info' : 'neutral');
head.appendChild(b);
if (scanner) help(head, 'term.authorized_scanner');
}
var stats = el('dl', { class: 'eg-wl-stats' });
[['conns', w.conns], ['dsts', w.dsts], ['ports', w.ports], ['findings', w.findings]].forEach(function (p) {
stats.appendChild(el('div', null, el('dd', { class: 'num' + (p[0] === 'findings' && p[1] ? ' eg-warn' : '') }, nf(p[1] || 0)), el('dt', null, t('eg.wl.' + p[0]))));
});
var card = el('div', { class: 'card-metric eg-wl' }, head, stats);
if (w.suppressed_scan_conns) card.appendChild(el('p', { class: 'cm-sub' }, t('eg.wl.suppressed', { n: nf(w.suppressed_scan_conns) })));
if (multi && w.host) card.appendChild(el('p', { class: 'cm-sub' }, t('eg.f.host', { h: w.host })));
return card;
}
function findingNode(f, multi) {
var kind = KINDS.indexOf(f.kind) >= 0 ? f.kind : null;
var sev = SEV[f.severity] !== undefined ? f.severity : 'low';
var title = el('strong', { class: 'eg-f-title' }, kind ? t('eg.kind.' + kind) : String(f.kind || '-'));
if (kind) help(title, KIND_HELP[kind]);
var top = el('div', { class: 'eg-f-top' }, U.ui.badge(t('eg.sev.' + sev), SEV_TONE[sev]), title);
var bits = [];
bits.push(el('span', { class: 'mono' }, f.workload || '-'));
bits.push(' → ');
if (f.dst) bits.push(ipLink(f.dst));
if (f.dport) bits.push(el('span', { class: 'mono' }, ':' + f.dport + (f.proto ? '/' + f.proto : '')));
var meta = [];
if (f.count) meta.push(t('eg.f.count', { n: nf(f.count) }));
if (f.interval_s) meta.push(t('eg.f.interval', { s: Math.round(f.interval_s * 10) / 10, j: Math.round((f.jitter || 0) * 100) }));
if (f.first) meta.push(t('eg.f.first', { t: when(f.first) }));
if (f.last) meta.push(t('eg.f.last', { t: when(f.last) }));
if (multi && f.host) meta.push(t('eg.f.host', { h: f.host }));
var li = el('li', { class: 'eg-f eg-sev-' + sev }, top, el('p', { class: 'eg-f-line' }, bits));
if (kind) li.appendChild(el('p', { class: 'eg-f-why' }, t('eg.why.' + kind)));
if (f.detail) li.appendChild(el('p', { class: 'eg-f-detail mono' }, f.detail));
if (meta.length) li.appendChild(el('p', { class: 'hint eg-f-meta' }, meta.join(' · ')));
return li;
}
function paint() {
if (!root) return;
clear(root);
if (!data) { root.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } })); return; }
if (!data.enabled) { root.appendChild(U.ui.empty(t('eg.disabled'), t('eg.disabled.sub'))); return; }
var d = data, range = U.rangeLabel({ inline: true });
var wls = d.workloads || [], fnd = (d.findings || []).slice();
fnd.sort(function (a, b) { var x = SEV[a.severity], y = SEV[b.severity]; x = x === undefined ? 3 : x; y = y === undefined ? 3 : y; return x - y || (b.count || 0) - (a.count || 0); });
var conns = 0, nsev = { high: 0, medium: 0, low: 0 };
wls.forEach(function (w) { conns += w.conns || 0; });
fnd.forEach(function (f) { if (nsev[f.severity] !== undefined) nsev[f.severity]++; });
var hosts = {};
wls.forEach(function (w) { if (w.host) hosts[w.host] = 1; });
fnd.forEach(function (f) { if (f.host) hosts[f.host] = 1; });
var multi = Object.keys(hosts).length > 1;
var dsts = d.top_dst || [];
if (!conns && !fnd.length) root.appendChild(U.ui.lead(t('eg.lead.none', { range: range }), t('eg.lead.none.sub'), 'neutral'));
else if (!fnd.length) root.appendChild(U.ui.lead(t('eg.lead.ok', { n: nf(conns), range: range }), t('eg.lead.ok.sub'), 'ok'));
else root.appendChild(U.ui.lead(t('eg.lead.bad', { f: nf(fnd.length), n: nf(conns), range: range }), t('eg.lead.bad.sub', { h: nsev.high, m: nsev.medium, l: nsev.low }), nsev.high ? 'danger' : 'ok'));
var src = d.source || {};
var sk = 'eg.src.' + src.state;
root.appendChild(el('p', { class: 'hint' }, t('eg.src', { state: t(sk) !== sk ? t(sk) : (src.state || '-'), lines: nf(src.lines || 0), bad: nf(src.malformed || 0) })));
var kp = el('div', { class: 'grid-12 eg-kpis' });
function k(node) { node.classList.add('span-4'); kp.appendChild(node); }
k(U.ui.metric(t('eg.kpi.conns'), nf(conns), { sub: t('eg.kpi.conns.sub') }));
k(U.ui.metric(t('eg.kpi.dsts'), nf(dsts.length), { sub: t('eg.kpi.dsts.sub') }));
k(U.ui.metric(t('eg.kpi.find'), nf(fnd.length), { sub: t('eg.kpi.find.sub', { h: nsev.high, m: nsev.medium, l: nsev.low }), tone: nsev.high ? 'danger' : fnd.length ? 'warn' : 'ok' }));
root.appendChild(kp);
var grid = el('div', { class: 'grid-12' });
if (wls.length) {
var wp = U.ui.panel({ title: t('eg.workloads'), hint: t('eg.workloads.hint'), cls: 'span-12', help: 'term.workload' });
var wg = el('div', { class: 'eg-wl-grid' });
wls.forEach(function (w) { wg.appendChild(workloadCard(w, multi)); });
wp.body.appendChild(wg);
grid.appendChild(wp);
}
var tl = d.timeline || {}, ser = tl.series || {}, names = Object.keys(ser);
var tp = U.ui.panel({ title: t('eg.timeline'), hint: t('eg.timeline.hint'), cls: 'span-12', variant: 'chart' });
if (U.charts && U.charts.stackedArea && names.length) tp.body.appendChild(U.charts.stackedArea(names.map(function (n) { return { key: n, label: n, values: ser[n] }; }), tl.step || 3600, { start: tl.start || 0, title: t('eg.timeline') }));
else tp.body.appendChild(U.ui.empty(t('eg.lead.none', { range: range })));
grid.appendChild(tp);
var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12' });
if (!fnd.length) fp.body.appendChild(U.ui.empty(t('eg.findings.none')));
else { var ul = el('ul', { class: 'eg-findings' }); fnd.forEach(function (f) { ul.appendChild(findingNode(f, multi)); }); fp.body.appendChild(ul); }
grid.appendChild(fp);
var dp = U.ui.panel({ title: t('eg.dst'), hint: t('eg.dst.hint'), cls: 'span-12', variant: 'list' });
if (!dsts.length) dp.body.appendChild(U.ui.empty(t('eg.dst.none')));
else dp.body.appendChild(tbl([{ label: t('eg.col.ip') }, { label: t('eg.col.country') }, { label: t('eg.col.asn') }, { label: t('eg.col.conns'), cls: 'num' }, { label: t('eg.col.who') }, { label: t('eg.col.ports') }],
dsts.map(function (x) {
return [ipLink(x.ip), (x.cc ? U.fmt.flag(x.cc) + ' ' + U.fmt.country(x.cc) : '-'), (x.asn || '') + (x.org ? ' ' + x.org : '') || '-', nf(x.conns || 0), list(x.workloads), list(x.ports)];
})));
grid.appendChild(dp);
var bursts = (d.scanner && d.scanner.bursts) || [];
var sp = U.ui.panel({ title: t('eg.scan'), hint: t('eg.scan.hint'), cls: 'span-12', variant: 'list', help: 'term.authorized_scanner' });
if (!bursts.length) sp.body.appendChild(U.ui.empty(t('eg.scan.none')));
else {
var bad = 0;
bursts.forEach(function (b) { bad += b.bad_dst_hits || 0; });
if (bad > 0) sp.body.appendChild(el('div', { class: 'state-error eg-scanwarn' }, el('strong', null, t('eg.scan.warn', { n: nf(bad) }))));
sp.body.appendChild(tbl([{ label: t('eg.col.who1') }, { label: t('eg.col.when') }, { label: t('eg.col.targets'), cls: 'num' }, { label: t('eg.col.nets') }, { label: t('eg.col.ports') }, { label: t('eg.col.conns'), cls: 'num' }, { label: t('eg.col.badhits'), cls: 'num' }],
bursts.map(function (b) {
return [b.workload || '-', t('eg.scan.when', { a: when(b.start), b: when(b.end) }), nf(b.targets || 0), list(b.nets), list(b.ports), nf(b.conns || 0),
el('span', { class: b.bad_dst_hits ? 'eg-warn' : '' }, nf(b.bad_dst_hits || 0))];
})));
}
grid.appendChild(sp);
root.appendChild(grid);
}
function load() {
var my = ++seq;
var p = Object.assign({}, U.rangeParams());
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
U.api('/api/v1/egress', p).then(function (d) {
if (!alive || my !== seq) return;
data = d; paint();
}).catch(function () {
if (!alive || my !== seq || data) return;
clear(root);
var b = el('button', { type: 'button', class: 'btn' }, t('eg.retry'));
b.addEventListener('click', load);
root.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('eg.error')), b));
});
}
U.registerPage({
id: 'egress', group: 'investigate', titleKey: 'eg.title',
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><rect x="3" y="5" width="12" height="14" rx="2"/><path d="M11 12h10"/><path d="M17 8l4 4-4 4"/></svg>',
mount: function (node, cx) { root = el('div', { class: 'eg-page' }); node.appendChild(root); ctx = cx; alive = true; data = null; paint(); load(); },
update: function (cx) { ctx = cx; load(); },
refresh: function () { load(); },
unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = null; data = null; }
});
return true;
}
if (!boot()) {
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
}
})();
+44
View File
@@ -443,6 +443,28 @@ window.URUTAU_I18N = {
'help.term.slo.do': 'Compare the real number with the target; the gap is the error budget.',
'help.term.error_budget': 'How many failures the SLO still allows in the period. When it reaches zero, the target is broken.',
'help.term.error_budget.do': 'If the budget burns fast, pause risky changes and fix the cause first.',
'help.term.second_firewall': 'A second line of defense: besides fail2ban, Urutau can itself block addresses it recognises as attackers, for a limited time.',
'help.term.second_firewall.do': 'Start in observe mode and compare its decisions with what you expect before turning it on.',
'help.term.observe_mode': 'Observation mode: Urutau decides who it would block and records it, but blocks nobody. A dry run.',
'help.term.observe_mode.do': 'Watch the decisions for a few days. If they look right, switch URUTAU_ENFORCE to on.',
'help.term.beaconing': 'Beaconing: a program that contacts the same destination at regular intervals, like a heartbeat. Normal software rarely does this so evenly; malware does, to ask for orders.',
'help.term.beaconing.do': 'Find out which workload it is and whether the destination is something you know. If not, isolate the workload.',
'help.term.c2': 'C2 (command and control): the server an attacker uses to give orders to infected machines. A connection to one means your machine may be taking orders.',
'help.term.c2.do': 'Treat it as an incident: isolate the workload, then investigate.',
'help.term.fanout': 'Fan-out or scan: one machine trying to connect to many different addresses in a short time, looking for something to attack.',
'help.term.fanout.do': 'If it is not your own scanner, the workload may have been compromised.',
'help.term.stratum': 'Stratum is the protocol of cryptocurrency mining pools. A server connecting to one is probably mining coins for someone else, on your electricity.',
'help.term.stratum.do': 'Look for unknown processes using lots of CPU and remove them.',
'help.term.dot': 'DoT (DNS over TLS): encrypted name lookups sent straight to an outside server, skipping your resolver. Malware uses it so you cannot see what it looks up.',
'help.term.dot.do': 'Confirm the workload is allowed to do this; block outbound port 853 if not.',
'help.term.workload': 'Workload: a program or container running on a server that makes its own network connections.',
'help.term.workload.do': 'Compare each workload with what it should be doing; a database talking to the internet is suspicious.',
'help.term.authorized_scanner': 'Authorised scanner: a workload you run on purpose to scan networks. Its mass connections are summarised instead of raised as alerts.',
'help.term.authorized_scanner.do': 'Make sure it only aims at targets you own or may test.',
'help.term.ban_ttl': 'Block duration (TTL): how long an address stays blocked before being released. Repeat offenders get longer blocks.',
'help.term.ban_ttl.do': 'Short blocks are safer against mistakes; long ones stop persistent attackers.',
'help.term.new_geo': 'New country: the workload connected to a country it had not reached before in this window.',
'help.term.new_geo.do': 'Check whether the destination is a service you use.',
'help.term.error_class.app': 'Errors caused by your own application (5xx coming from the app).',
'help.term.error_class.app.do': 'These are yours to fix: read the application logs.',
'help.term.error_class.proxy': 'Errors produced by the reverse proxy itself (bad gateway, timeout, no backend).',
@@ -915,6 +937,28 @@ window.URUTAU_I18N = {
'help.term.slo.do': 'Compare o número real com a meta; a diferença é o orçamento de erro.',
'help.term.error_budget': 'Quantas falhas o SLO ainda permite no período. Quando chega a zero, a meta foi quebrada.',
'help.term.error_budget.do': 'Se o orçamento queima rápido, pause mudanças arriscadas e corrija a causa primeiro.',
'help.term.second_firewall': 'Uma segunda linha de defesa: além do fail2ban, o próprio Urutau pode bloquear endereços que reconhece como atacantes, por tempo limitado.',
'help.term.second_firewall.do': 'Comece no modo observação e compare as decisões com o que você espera antes de ligar.',
'help.term.observe_mode': 'Modo observação: o Urutau decide quem bloquearia e registra, mas não bloqueia ninguém. Um ensaio.',
'help.term.observe_mode.do': 'Acompanhe as decisões por alguns dias. Se estiverem certas, mude URUTAU_ENFORCE para on.',
'help.term.beaconing': 'Beaconing (sinal periódico): um programa que contata o mesmo destino em intervalos regulares, como um batimento. Software normal raramente é tão regular; malware faz isso para pedir ordens.',
'help.term.beaconing.do': 'Descubra qual workload é e se você conhece o destino. Se não conhece, isole o workload.',
'help.term.c2': 'C2 (comando e controle): o servidor que um atacante usa para dar ordens às máquinas infectadas. Uma conexão com ele indica que a sua máquina pode estar recebendo ordens.',
'help.term.c2.do': 'Trate como incidente: isole o workload e investigue.',
'help.term.fanout': 'Fan-out ou varredura: uma máquina tentando conectar a muitos endereços diferentes em pouco tempo, procurando algo para atacar.',
'help.term.fanout.do': 'Se não for o seu scanner, o workload pode ter sido comprometido.',
'help.term.stratum': 'Stratum é o protocolo dos grupos de mineração de criptomoedas. Um servidor conectado a um deles provavelmente está minerando moedas para outra pessoa, gastando a sua energia.',
'help.term.stratum.do': 'Procure processos desconhecidos gastando muita CPU e remova-os.',
'help.term.dot': 'DoT (DNS sobre TLS): consultas de nomes criptografadas, enviadas direto a um servidor de fora, sem passar pelo seu resolvedor. Malware usa para você não ver o que ele consulta.',
'help.term.dot.do': 'Confirme se o workload tem permissão para isso; bloqueie a porta 853 de saída se não tiver.',
'help.term.workload': 'Workload (carga de trabalho): um programa ou contêiner rodando no servidor que faz as próprias conexões de rede.',
'help.term.workload.do': 'Compare cada workload com o que ele deveria fazer; um banco de dados falando com a internet é suspeito.',
'help.term.authorized_scanner': 'Scanner autorizado: um workload que você mantém de propósito para varrer redes. As conexões em massa dele são resumidas, em vez de virar alerta.',
'help.term.authorized_scanner.do': 'Garanta que ele só mire alvos seus ou que você pode testar.',
'help.term.ban_ttl': 'Duração do bloqueio (TTL): por quanto tempo o endereço fica bloqueado antes de ser liberado. Reincidentes recebem bloqueios mais longos.',
'help.term.ban_ttl.do': 'Bloqueios curtos são mais seguros contra enganos; longos barram atacantes persistentes.',
'help.term.new_geo': 'País novo: o workload conectou a um país que ainda não tinha alcançado nesta janela.',
'help.term.new_geo.do': 'Confira se o destino é um serviço que você usa.',
'help.term.error_class.app': 'Erros causados pela sua própria aplicação (5xx vindos do app).',
'help.term.error_class.app.do': 'São seus para corrigir: leia os logs da aplicação.',
'help.term.error_class.proxy': 'Erros produzidos pelo próprio proxy reverso (bad gateway, timeout, sem backend).',
+4
View File
@@ -67,6 +67,10 @@
{
"name": "reports",
"css": true
},
{
"name": "egress",
"css": true
}
]
}
+4 -1
View File
@@ -2,7 +2,10 @@
@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; }
.rpt-bar { display: flex; flex-wrap: wrap; gap: 8px; 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); }
+39
View File
@@ -26,6 +26,12 @@
'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',
@@ -97,6 +103,12 @@
'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',
@@ -231,8 +243,34 @@
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);
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');
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 toolbar() {
var bar = h('div', 'rpt-bar');
var dl = U.el('button', { type: 'button', class: 'btn' }, t('rpt.dl'));
dl.addEventListener('click', function () {
var a = document.createElement('a');
a.href = htmlUrl(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'));
@@ -240,6 +278,7 @@
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;
}