From 2ebda1e4d70049747168fe8156546949c410b591 Mon Sep 17 00:00:00 2001 From: Lucas Rayan Date: Sat, 14 Nov 2026 22:39:33 -0300 Subject: [PATCH] feat: 1.3.0 thirteen new pages, charts, tooltips and error analysis New pages grouped in the rail (Monitor, Investigate, Analyze, Operate, Reports): Services (SLO, Apdex, latency app vs proxy), Sessions (stage funnel), Campaigns, Event search, MITRE ATT&CK matrix, Evolution, Concentration (Pareto, Gini), Survival (Kaplan-Meier per attack episode, recidivists), Where errors come from (application vs failed attack vs proxy vs client), Protocols and TLS, Defense (fail2ban, SSH, blocklist), Integrity, and a printable executive report. Chart library (donut, radar, stacked area, bars, heatmap, gauge), glossary with accessible "?" tooltips, self-explanatory category names (nonexistent page 404), page loader through pages.json. Unique visitors fixed: real browsers opening a page, one per IP per day, deduplicated across domains, with non-human clients counted apart. Anonymous legitimate visits on the Live page (?visits=1, no IP). Traefik origin, service, protocol and TLS fields parsed. Paths and Referer paths drop e-mail and token segments. Co-Authored-By: Claude Opus 5.5 --- internal/app/serve.go | 15 + internal/app/sources.go | 1 + internal/app/version.go | 2 +- internal/core/errclass.go | 198 +++++++++ internal/core/errclass_test.go | 61 +++ internal/core/event.go | 15 +- internal/core/parse.go | 24 ++ internal/core/review_test.go | 20 + internal/fed/live.go | 43 +- internal/fed/live_test.go | 36 ++ internal/server/api_analytics.go | 71 ++++ internal/server/api_analytics_test.go | 57 +++ internal/server/api_campaigns.go | 93 ++++ internal/server/api_campaigns_test.go | 81 ++++ internal/server/api_defense.go | 16 + internal/server/api_defense_test.go | 61 +++ internal/server/api_errors.go | 211 +++++++++ internal/server/api_integrity.go | 132 ++++++ internal/server/api_report.go | 308 ++++++++++++++ internal/server/api_report_test.go | 80 ++++ internal/server/api_services.go | 208 +++++++++ internal/server/api_services_test.go | 65 +++ internal/server/api_sessions.go | 36 ++ internal/server/api_techniques.go | 37 ++ internal/server/live_test.go | 32 ++ internal/server/routes.go | 18 + internal/server/server.go | 42 +- internal/server/web/app.js | 460 +++++++++++++++++--- internal/server/web/campaigns.css | 38 ++ internal/server/web/campaigns.js | 263 ++++++++++++ internal/server/web/concentration.css | 20 + internal/server/web/concentration.js | 208 +++++++++ internal/server/web/defense.css | 5 + internal/server/web/defense.js | 201 +++++++++ internal/server/web/errors.css | 10 + internal/server/web/errors.js | 146 +++++++ internal/server/web/evolution.css | 9 + internal/server/web/evolution.js | 158 +++++++ internal/server/web/i18n.js | 400 ++++++++++++++++- internal/server/web/index.html | 8 - internal/server/web/integrity.css | 24 ++ internal/server/web/integrity.js | 279 ++++++++++++ internal/server/web/live.css | 16 + internal/server/web/live.js | 220 ++++++++-- internal/server/web/mitre.css | 28 ++ internal/server/web/mitre.js | 236 +++++++++++ internal/server/web/pages.json | 72 ++++ internal/server/web/protocol.css | 10 + internal/server/web/protocol.js | 141 ++++++ internal/server/web/reports.css | 78 ++++ internal/server/web/reports.js | 357 ++++++++++++++++ internal/server/web/search.css | 25 ++ internal/server/web/search.js | 220 ++++++++++ internal/server/web/sessions.css | 34 ++ internal/server/web/sessions.js | 216 ++++++++++ internal/server/web/slo.css | 31 ++ internal/server/web/slo.js | 157 +++++++ internal/server/web/style.css | 60 +++ internal/server/web/survival.css | 26 ++ internal/server/web/survival.js | 218 ++++++++++ internal/store/analytics.go | 589 ++++++++++++++++++++++++++ internal/store/analytics_test.go | 185 ++++++++ internal/store/campaigns.go | 263 ++++++++++++ internal/store/campaigns_test.go | 34 ++ internal/store/defense.go | 328 ++++++++++++++ internal/store/defense_test.go | 32 ++ internal/store/integrity.go | 118 ++++++ internal/store/integrity_test.go | 27 ++ internal/store/privacy_path_test.go | 34 ++ internal/store/services.go | 510 ++++++++++++++++++++++ internal/store/services_test.go | 95 +++++ internal/store/snapshot.go | 7 +- internal/store/store.go | 2 + internal/store/techniques.go | 169 ++++++++ internal/store/traffic.go | 236 +++++++++-- internal/store/traffic_test.go | 148 +++++++ internal/store/traffic_visits.go | 145 +++++++ pid | 1 + scripts/ui-overflow.mjs | 2 +- 79 files changed, 9091 insertions(+), 171 deletions(-) create mode 100644 internal/core/errclass.go create mode 100644 internal/core/errclass_test.go create mode 100644 internal/server/api_analytics.go create mode 100644 internal/server/api_analytics_test.go create mode 100644 internal/server/api_campaigns.go create mode 100644 internal/server/api_campaigns_test.go create mode 100644 internal/server/api_defense.go create mode 100644 internal/server/api_defense_test.go create mode 100644 internal/server/api_errors.go create mode 100644 internal/server/api_integrity.go create mode 100644 internal/server/api_report.go create mode 100644 internal/server/api_report_test.go create mode 100644 internal/server/api_services.go create mode 100644 internal/server/api_services_test.go create mode 100644 internal/server/api_sessions.go create mode 100644 internal/server/api_techniques.go create mode 100644 internal/server/routes.go create mode 100644 internal/server/web/campaigns.css create mode 100644 internal/server/web/campaigns.js create mode 100644 internal/server/web/concentration.css create mode 100644 internal/server/web/concentration.js create mode 100644 internal/server/web/defense.css create mode 100644 internal/server/web/defense.js create mode 100644 internal/server/web/errors.css create mode 100644 internal/server/web/errors.js create mode 100644 internal/server/web/evolution.css create mode 100644 internal/server/web/evolution.js create mode 100644 internal/server/web/integrity.css create mode 100644 internal/server/web/integrity.js create mode 100644 internal/server/web/mitre.css create mode 100644 internal/server/web/mitre.js create mode 100644 internal/server/web/pages.json create mode 100644 internal/server/web/protocol.css create mode 100644 internal/server/web/protocol.js create mode 100644 internal/server/web/reports.css create mode 100644 internal/server/web/reports.js create mode 100644 internal/server/web/search.css create mode 100644 internal/server/web/search.js create mode 100644 internal/server/web/sessions.css create mode 100644 internal/server/web/sessions.js create mode 100644 internal/server/web/slo.css create mode 100644 internal/server/web/slo.js create mode 100644 internal/server/web/survival.css create mode 100644 internal/server/web/survival.js create mode 100644 internal/store/analytics.go create mode 100644 internal/store/analytics_test.go create mode 100644 internal/store/campaigns.go create mode 100644 internal/store/campaigns_test.go create mode 100644 internal/store/defense.go create mode 100644 internal/store/defense_test.go create mode 100644 internal/store/integrity.go create mode 100644 internal/store/integrity_test.go create mode 100644 internal/store/privacy_path_test.go create mode 100644 internal/store/services.go create mode 100644 internal/store/services_test.go create mode 100644 internal/store/techniques.go create mode 100644 internal/store/traffic_visits.go create mode 100644 pid diff --git a/internal/app/serve.go b/internal/app/serve.go index ea4cce8..f72fd09 100644 --- a/internal/app/serve.go +++ b/internal/app/serve.go @@ -72,6 +72,21 @@ func Serve(c Config) error { st.SetEnricher(en) st.SetAttribution(Attribution) runner.Extra = func() []store.SourceStatus { return []store.SourceStatus{geoStatus(gr, c.GeoDir)} } + // Real build dates of the geo databases for /api/v1/integrity (0 = unknown). + store.GeoBuilds = func() (int64, int64) { + if gr == nil { + return 0, 0 + } + s := gr.Status() + var city, asn int64 + if !s.City.Build.IsZero() { + city = s.City.Build.Unix() + } + if !s.ASN.Build.IsZero() { + asn = s.ASN.Build.Unix() + } + return city, asn + } var hub *fed.Hub if len(peers) > 0 { hub = fed.NewHub(peers, c.PeerToken) diff --git a/internal/app/sources.go b/internal/app/sources.go index c168d46..ff4e621 100644 --- a/internal/app/sources.go +++ b/internal/app/sources.go @@ -172,6 +172,7 @@ func (r *Runner) handle(s *source) func([]byte) { ev.Soft, ev.Strong = ev.Status < 400, ev.Status >= 400 } r.St.Ingest(ev) + r.St.ObserveService(ev) if ev.Source == "traefik" && !ev.Forged && (ev.Cat == core.OK || ev.Cat == core.NotFound) { r.St.Traffic(ev) } diff --git a/internal/app/version.go b/internal/app/version.go index 7a95263..8591d34 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -2,4 +2,4 @@ package app // Version is the release version (SemVer). Release builds may override it with // -ldflags "-X .../internal/app.Version=...". -var Version = "1.2.0" +var Version = "1.3.0" diff --git a/internal/core/errclass.go b/internal/core/errclass.go new file mode 100644 index 0000000..3c4f1da --- /dev/null +++ b/internal/core/errclass.go @@ -0,0 +1,198 @@ +package core + +import ( + "net" + "net/url" + "regexp" + "strings" +) + +// Error classes: where a 4xx/5xx comes from. The answer to "is this a bug in my +// application or a failed attack?". +const ( + ClassAttack = "attack" // a probe, exploit or scanner: a frustrated attack + ClassBlocked = "blocked" // refused by a middleware or rate limit before the app + ClassProxy = "proxy" // the proxy could not reach the backend, or the client gave up + ClassApp = "app" // the backend itself answered 5xx + ClassBot = "bot" // a known crawler asking for something that is not there + ClassClient = "client" // an ordinary client mistake (broken link, auth, bad input) + ClassUnknown = "unknown" +) + +// Subtypes of the client class. +const ( + SubBrokenLink = "broken_link" + SubExternalLink = "external_link" + SubAuth = "auth" + SubAuthChallenge = "auth_challenge" + SubValidation = "validation" + SubCancelled = "cancelled" + SubOther = "other" +) + +var okMethods = map[string]bool{"GET": true, "HEAD": true, "POST": true, "PUT": true, "PATCH": true, "DELETE": true, "OPTIONS": true} + +var toolUARe = regexp.MustCompile(`(?i)(^|[^a-z])(curl|wget|python-requests|python-urllib|aiohttp|go-http-client|libwww-perl|okhttp|httpie|scrapy|sqlmap|nikto|nmap|masscan|zgrab|nuclei|dirbuster|gobuster|feroxbuster|wfuzz|hydra|httpx|fasthttp|java/|axios|node-fetch)([^a-z]|$)`) +var crawlerUARe = regexp.MustCompile(`(?i)(bot|crawler|spider|slurp|bingpreview|facebookexternalhit|embedly|ia_archiver|archive\.org|mediapartners|headlesschrome|lighthouse|pingdom|uptime|monitor)`) +var registryUARe = regexp.MustCompile(`(?i)(docker|containerd|buildkit|act_runner|gitea-runner|connect-go|skopeo|podman|go-containerregistry|oras|crane)`) + +// rich reports whether the log line carried the origin fields. Without them +// (older Traefik, demo data) OriginStatus is unknown and is taken as equal to +// the downstream status. +func rich(ev Event) bool { + return ev.Proto != "" || ev.Scheme != "" || ev.Router != "" || ev.Service != "" +} + +func originOf(ev Event) int { + if !rich(ev) { + return ev.Status + } + return ev.OriginStatus +} + +func isIPHost(h string) bool { + if i := strings.LastIndexByte(h, ':'); i > 0 && !strings.Contains(h[i:], "]") { + h = h[:i] + } + h = strings.Trim(h, "[]") + return net.ParseIP(h) != nil +} + +// NoRouter: the request matched no application router (the catch-all answered, +// or Traefik had nothing for the host): internet noise by definition. +func NoRouter(ev Event) bool { + if isIPHost(ev.Domain) { + return true + } + if !rich(ev) { + return false + } + return ev.Router == "" || strings.HasPrefix(ev.Router, "catchall") || strings.HasPrefix(ev.Service, "error-pages") +} + +// AuthChallenge: the normal 401 a container registry or CI runner gets before +// presenting a token. Never an attack. +func AuthChallenge(ev Event) bool { + if ev.Status != 401 && ev.Status != 403 { + return false + } + p := ev.Path + if !(p == "/v2" || strings.HasPrefix(p, "/v2/") || strings.HasPrefix(p, "/api/actions")) { + return false + } + return registryUARe.MatchString(ev.UA) +} + +// RunnerCall: a CI runner polling the forge API (never an attack, whatever the +// status): act_runner, gitea-runner or connect-go under /api/actions/. +func RunnerCall(ev Event) bool { + return strings.HasPrefix(ev.Path, "/api/actions") && registryUARe.MatchString(ev.UA) +} + +func sameSite(ev Event) bool { + if ev.FetchSite == "same-origin" { + return true + } + if ev.Referer == "" || ev.Referer == "-" { + return false + } + u, err := url.Parse(ev.Referer) + if err != nil || u.Host == "" { + return false + } + h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + d := strings.TrimPrefix(strings.ToLower(ev.Domain), "www.") + if i := strings.LastIndexByte(d, ':'); i > 0 { + d = d[:i] + } + return h == d || strings.HasSuffix(h, "."+d) || strings.HasSuffix(d, "."+h) +} + +var botPaths = []string{"/robots.txt", "/sitemap", "/favicon", "/apple-touch-icon", "/.well-known/"} + +func isBotPath(p string) bool { + p = strings.ToLower(p) + for _, b := range botPaths { + if strings.HasPrefix(p, b) { + return true + } + } + return false +} + +func browserLike(ev Event) bool { + switch ev.E.Device { + case "desktop", "mobile", "tablet": + return !ev.E.Bot + } + return ev.E.Device == "" && strings.HasPrefix(ev.UA, "Mozilla/") && !crawlerUARe.MatchString(ev.UA) && !toolUARe.MatchString(ev.UA) +} + +// ErrorClass classifies a 4xx/5xx answer; "" for anything else. susp says the +// source address is suspicious, hostile or banned. +func ErrorClass(ev Event, susp bool) string { + c, _, _ := ErrorClassify(ev, susp) + return c +} + +// ErrorClassify is ErrorClass with the client subtype and the under_attack mark +// (a real application failure on a request that looks like an attack). +func ErrorClassify(ev Event, susp bool) (class, sub string, underAttack bool) { + st := ev.Status + if st < 400 || st > 599 { + return "", "", false + } + origin := originOf(ev) + challenge := AuthChallenge(ev) || (RunnerCall(ev) && st < 500) + if challenge { + return ClassClient, SubAuthChallenge, false + } + attackish := ev.Cat == Scanner || ev.Cat == Exploit || ev.Cat == BruteForce || + (ev.Method != "" && !okMethods[strings.ToUpper(ev.Method)]) || + ev.UA == "" || ev.E.Tool || (toolUARe.MatchString(ev.UA) && !registryUARe.MatchString(ev.UA)) || + susp || NoRouter(ev) + if RunnerCall(ev) { + attackish = false + } + // the backend really failed: an application error, even if an attacker caused it + if ev.Retries > 0 && st >= 500 && !NoRouter(ev) { + return ClassProxy, "", false + } + if origin >= 500 && st >= 500 && !NoRouter(ev) { + return ClassApp, "", attackish + } + if attackish { + return ClassAttack, "", false + } + if st == 429 || ((st == 403 || st == 401) && origin == 0) { + return ClassBlocked, "", false + } + if ((st == 502 || st == 503 || st == 504) && origin == 0) || (ev.Retries > 0 && st >= 500) { + return ClassProxy, "", false + } + if st >= 500 { + return ClassProxy, "", false // a 5xx the backend did not produce + } + if st == 499 { + return ClassClient, SubCancelled, false // the client gave up: not a server error + } + if ev.E.Bot || crawlerUARe.MatchString(ev.UA) || (st == 404 && isBotPath(ev.Path)) { + return ClassBot, "", false + } + switch st { + case 404: + if sameSite(ev) { + return ClassClient, SubBrokenLink, false + } + if ev.Referer != "" && ev.Referer != "-" { + return ClassClient, SubExternalLink, false + } + case 401, 403: + if origin == st && browserLike(ev) { + return ClassClient, SubAuth, false + } + case 400, 405, 413, 422: + return ClassClient, SubValidation, false + } + return ClassClient, SubOther, false +} diff --git a/internal/core/errclass_test.go b/internal/core/errclass_test.go new file mode 100644 index 0000000..08ec7de --- /dev/null +++ b/internal/core/errclass_test.go @@ -0,0 +1,61 @@ +package core + +import "testing" + +func TestErrorClass(t *testing.T) { + rich := func(e Event) Event { + e.Proto, e.Scheme = "HTTP/2.0", "https" + if e.Router == "" { + e.Router, e.Service = "https-0-abc-gitea@docker", "https-0-abc-gitea@docker" + } + return e + } + moz := "Mozilla/5.0 (Windows NT 10.0) Chrome/120" + cases := []struct { + name string + ev Event + susp bool + class string + sub string + attack bool + }{ + {"catchall env probe", Event{Status: 503, OriginStatus: 503, Method: "GET", Path: "/.env", UA: moz, Domain: "blog.example.com", Router: "catchall@file", Service: "error-pages@file", Proto: "HTTP/2.0"}, false, "attack", "", false}, + {"no router 404", Event{Status: 404, Method: "GET", Path: "/x", UA: moz, Domain: "a.example.com", Proto: "HTTP/1.1"}, false, "attack", "", false}, + {"ip host", Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/", UA: moz, Domain: "136.0.0.1", Router: "x@docker", Proto: "HTTP/1.1"}, false, "attack", "", false}, + {"scanner cat", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/wp-login.php", UA: moz, Cat: Scanner}), false, "attack", "", false}, + {"weird method", rich(Event{Status: 405, OriginStatus: 405, Method: "PROPFIND", UA: moz}), false, "attack", "", false}, + {"empty ua", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/a"}), false, "attack", "", false}, + {"curl", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/a", UA: "curl/8.1"}), false, "attack", "", false}, + {"suspicious ip", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", Path: "/a", UA: moz}), true, "attack", "", false}, + {"429", rich(Event{Status: 429, Method: "GET", UA: moz}), false, "blocked", "", false}, + {"401 origin 0", rich(Event{Status: 401, OriginStatus: 0, Method: "GET", UA: moz, Path: "/x"}), false, "blocked", "", false}, + {"504 origin 0", rich(Event{Status: 504, OriginStatus: 0, Method: "GET", UA: moz, Path: "/x"}), false, "proxy", "", false}, + {"499 is the client", rich(Event{Status: 499, OriginStatus: 0, Method: "GET", UA: moz, Path: "/x"}), false, "client", "cancelled", false}, + {"runner poll", rich(Event{Status: 404, OriginStatus: 404, Method: "POST", UA: "connect-go/1.16 (go1.22)", Path: "/api/actions/runner.v1.RunnerService/FetchTask", Cat: Scanner}), true, "client", "auth_challenge", false}, + {"gitea-runner", rich(Event{Status: 401, OriginStatus: 0, Method: "POST", UA: "gitea-runner/0.2", Path: "/api/actions/x"}), true, "client", "auth_challenge", false}, + {"502 retry", rich(Event{Status: 502, OriginStatus: 502, Retries: 2, Method: "GET", UA: moz}), false, "proxy", "", false}, + {"app 500", rich(Event{Status: 500, OriginStatus: 500, Method: "POST", UA: moz, Path: "/api/x"}), false, "app", "", false}, + {"app 500 under attack", rich(Event{Status: 500, OriginStatus: 500, Method: "GET", UA: moz, Path: "/a?x=../", Cat: Exploit}), false, "app", "", true}, + {"crawler 404", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: "Mozilla/5.0 (compatible; ElevenlabsCrawler/1.0)", Path: "/z"}), false, "bot", "", false}, + {"robots 404", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/robots.txt"}), false, "bot", "", false}, + {"broken link", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/old", Domain: "a.example.com", Referer: "https://a.example.com/index"}), false, "client", "broken_link", false}, + {"fetch same-origin", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/old", FetchSite: "same-origin"}), false, "client", "broken_link", false}, + {"external link", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/old", Domain: "a.example.com", Referer: "https://news.ycombinator.com/"}), false, "client", "external_link", false}, + {"auth browser", rich(Event{Status: 401, OriginStatus: 401, Method: "GET", UA: moz, Path: "/admin", E: Enrich{Device: "desktop"}}), false, "client", "auth", false}, + {"registry challenge", rich(Event{Status: 401, OriginStatus: 401, Method: "GET", UA: "docker/27.0 go/go1.22", Path: "/v2/"}), true, "client", "auth_challenge", false}, + {"actions challenge", rich(Event{Status: 401, OriginStatus: 401, Method: "GET", UA: "act_runner/0.2", Path: "/api/actions/x"}), false, "client", "auth_challenge", false}, + {"validation", rich(Event{Status: 422, OriginStatus: 422, Method: "POST", UA: moz, Path: "/api/x"}), false, "client", "validation", false}, + {"404 plain", rich(Event{Status: 404, OriginStatus: 404, Method: "GET", UA: moz, Path: "/nope"}), false, "client", "other", false}, + {"legacy log 500", Event{Status: 500, Method: "GET", UA: moz, Path: "/x", Domain: "a.example.com"}, false, "app", "", false}, + {"200", Event{Status: 200}, false, "", "", false}, + } + for _, c := range cases { + cl, sub, ua := ErrorClassify(c.ev, c.susp) + if cl != c.class || sub != c.sub || ua != c.attack { + t.Errorf("%s: got %q/%q/%v want %q/%q/%v", c.name, cl, sub, ua, c.class, c.sub, c.attack) + } + if ErrorClass(c.ev, c.susp) != c.class { + t.Errorf("%s: ErrorClass mismatch", c.name) + } + } +} diff --git a/internal/core/event.go b/internal/core/event.go index 901b87b..9cc39f0 100644 --- a/internal/core/event.go +++ b/internal/core/event.go @@ -149,7 +149,20 @@ type Event struct { DurationNS int64 Bytes int64 Referer string - E Enrich + // FetchDest is Sec-Fetch-Dest ("document", "empty", "image"...), "" when the + // browser did not send it. Prefetch: Sec-Purpose / Purpose said prefetch. + FetchDest string + Prefetch bool + // Origin details (Traefik only, empty on older logs): what the backend + // answered and where the time went. + OriginStatus int + OriginNS, OverheadNS int64 + OriginBytes int64 + Retries int + Router, Service string + Proto, Scheme, TLSVer, TLSCiph string + EntryPoint, FetchSite string + E Enrich } // Enrich holds what the geo and user-agent databases say about an event. It is diff --git a/internal/core/parse.go b/internal/core/parse.go index 7525326..2cb8bf4 100644 --- a/internal/core/parse.go +++ b/internal/core/parse.go @@ -51,8 +51,23 @@ type traefikLine struct { Referer string `json:"request_Referer"` FetchSite string `json:"request_Sec-Fetch-Site"` FetchDest string `json:"request_Sec-Fetch-Dest"` + SecPurpose string `json:"request_Sec-Purpose"` + Purpose string `json:"request_Purpose"` Duration int64 `json:"Duration"` Size int64 `json:"DownstreamContentSize"` + + OriginStatus int `json:"OriginStatus"` + OriginDur int64 `json:"OriginDuration"` + Overhead int64 `json:"Overhead"` + OriginSize int64 `json:"OriginContentSize"` + Retries int `json:"RetryAttempts"` + Router string `json:"RouterName"` + Service string `json:"ServiceName"` + Proto string `json:"RequestProtocol"` + Scheme string `json:"RequestScheme"` + TLSVer string `json:"TLSVersion"` + TLSCipher string `json:"TLSCipher"` + EntryPoint string `json:"entryPointName"` } // ParseTraefik parses one Traefik JSON access log line. @@ -82,6 +97,15 @@ func ParseTraefik(line []byte) (Event, error) { DurationNS: l.Duration, Bytes: l.Size, Referer: clip(l.Referer, 300), } ev.Framed = Framed(l.FetchSite, l.FetchDest) + ev.OriginStatus, ev.OriginNS, ev.OverheadNS, ev.OriginBytes, ev.Retries = l.OriginStatus, l.OriginDur, l.Overhead, l.OriginSize, l.Retries + ev.Router, ev.Service = clip(l.Router, 64), clip(l.Service, 64) + ev.Proto, ev.Scheme, ev.TLSVer, ev.TLSCiph = clip(l.Proto, 12), clip(l.Scheme, 8), clip(l.TLSVer, 8), clip(l.TLSCipher, 64) + ev.EntryPoint, ev.FetchSite = clip(l.EntryPoint, 64), clip(strings.ToLower(l.FetchSite), 16) + ev.FetchDest = strings.ToLower(strings.TrimSpace(l.FetchDest)) + if len(ev.FetchDest) > 20 { + ev.FetchDest = ev.FetchDest[:20] + } + ev.Prefetch = strings.Contains(strings.ToLower(l.SecPurpose+" "+l.Purpose), "prefetch") c := Classify(l.Method, l.Path, l.Status) ev.Cat, ev.Soft, ev.Strong, ev.Weak = c.Cat, c.Soft, c.Strong, c.Weak return ev, nil diff --git a/internal/core/review_test.go b/internal/core/review_test.go index c99670d..9f130f3 100644 --- a/internal/core/review_test.go +++ b/internal/core/review_test.go @@ -31,3 +31,23 @@ func TestTraefikSecFetchFraming(t *testing.T) { } } } + +func TestTraefikFetchDestAndPrefetch(t *testing.T) { + base := `{"ClientHost":"8.8.8.8","RequestHost":"a.example","RequestMethod":"GET","RequestPath":"/","DownstreamStatus":200,"StartUTC":"2026-11-14T10:00:00Z"` + for _, tc := range []struct { + extra string + dest string + prefetch bool + }{ + {``, "", false}, + {`,"request_Sec-Fetch-Dest":"Document"`, "document", false}, + {`,"request_Sec-Fetch-Dest":"empty"`, "empty", false}, + {`,"request_Sec-Purpose":"prefetch;prerender"`, "", true}, + {`,"request_Purpose":"prefetch"`, "", true}, + } { + ev, err := ParseTraefik([]byte(base + tc.extra + `}`)) + if err != nil || ev.FetchDest != tc.dest || ev.Prefetch != tc.prefetch { + t.Errorf("%s: dest=%q prefetch=%v err=%v", tc.extra, ev.FetchDest, ev.Prefetch, err) + } + } +} diff --git a/internal/fed/live.go b/internal/fed/live.go index ba4d2c8..111a73b 100644 --- a/internal/fed/live.go +++ b/internal/fed/live.go @@ -32,6 +32,34 @@ type liveState struct { recent []store.LiveEvent // ring of the newest peer events head int subs map[chan store.LiveEvent]struct{} + vsubs map[chan store.VisitMsg]struct{} // legitimate visits: relayed, never kept +} + +// SubscribeVisits returns the legitimate visits relayed from peers. +func (h *Hub) SubscribeVisits() (<-chan store.VisitMsg, func()) { + ch := make(chan store.VisitMsg, 64) + h.lmu.Lock() + if h.live.vsubs == nil { + h.live.vsubs = map[chan store.VisitMsg]struct{}{} + } + h.live.vsubs[ch] = struct{}{} + h.lmu.Unlock() + return ch, func() { + h.lmu.Lock() + delete(h.live.vsubs, ch) + h.lmu.Unlock() + } +} + +func (h *Hub) publishVisit(m store.VisitMsg) { + h.lmu.Lock() + defer h.lmu.Unlock() + for ch := range h.live.vsubs { + select { + case ch <- m: + default: + } + } } // Subscribe returns the live events relayed from peers; call stop when done. @@ -133,7 +161,7 @@ var errLive = errors.New("live stream refused") func (h *Hub) consume(ctx context.Context, p Peer) error { rctx, cancel := context.WithCancel(ctx) defer cancel() - req, err := http.NewRequestWithContext(rctx, http.MethodGet, p.URL+"/api/v1/peer/stream", nil) + req, err := http.NewRequestWithContext(rctx, http.MethodGet, p.URL+"/api/v1/peer/stream?visits=1", nil) if err != nil { return err } @@ -181,7 +209,7 @@ func (h *Hub) consume(ctx context.Context, p Peer) error { switch { case bytes.HasPrefix(line, []byte("event:")): evName = strings.TrimSpace(string(line[6:])) - case bytes.HasPrefix(line, []byte("data:")) && evName == "ev": + case bytes.HasPrefix(line, []byte("data:")) && (evName == "ev" || evName == "visit"): now := time.Now() tokens += now.Sub(last).Seconds() * maxLiveRate if tokens > maxLiveRate { @@ -192,6 +220,17 @@ func (h *Hub) consume(ctx context.Context, p Peer) error { continue // over the budget: discard } tokens-- + if evName == "visit" { + var v store.VisitMsg + if json.Unmarshal(bytes.TrimSpace(line[5:]), &v) == nil && v.Sanitize(now.Unix()) { + v.Host = p.Name + if v.Kind == "visit" && v.Dst == nil { + v.Dst = h.peerLocation(p.Name) + } + h.publishVisit(v) + } + continue + } var e store.LiveEvent if json.Unmarshal(bytes.TrimSpace(line[5:]), &e) != nil || !e.Sanitize(now.Unix()) { continue diff --git a/internal/fed/live_test.go b/internal/fed/live_test.go index 7b76dfc..677b8ff 100644 --- a/internal/fed/live_test.go +++ b/internal/fed/live_test.go @@ -2,6 +2,7 @@ package fed_test import ( "context" + "encoding/json" "fmt" "net/http" "net/http/httptest" @@ -178,3 +179,38 @@ func TestLiveByteFloodDropsConnection(t *testing.T) { time.Sleep(20 * time.Millisecond) } } + +func TestVisitRelayHasNoAddressAndNoRecent(t *testing.T) { + var conns atomic.Int32 + srv := fakeStream(t, &conns, func(w http.ResponseWriter) { + fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit","t":`+fmt.Sprint(time.Now().Unix())+`,"host":"evil","ip":"9.9.9.9","ua":"Mozilla","domain":"a.example","path":"/x","status":200,"device":"mobile","src":{"lat":-8,"lon":-34.9,"cc":"BR","city":"Recife"}}`+"\n\n") + fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"visit_batch","t":`+fmt.Sprint(time.Now().Unix())+`,"n":7}`+"\n\n") + fmt.Fprint(w, "event: visit\ndata: "+`{"kind":"nope"}`+"\n\n") + }) + defer srv.Close() + p, _ := fed.ParsePeer("edge=" + srv.URL) + h := fed.NewHub([]fed.Peer{p}, "tok") + ch, stop := h.SubscribeVisits() + defer stop() + ctx, cancel := context.WithCancel(context.Background()) + defer func() { cancel(); h.WaitStream() }() + h.Stream(ctx) + var got []store.VisitMsg + for len(got) < 2 { + select { + case m := <-ch: + got = append(got, m) + case <-time.After(5 * time.Second): + t.Fatalf("timeout, got %+v", got) + } + } + for _, m := range got { + b, _ := json.Marshal(m) + if strings.Contains(string(b), "9.9.9.9") || strings.Contains(string(b), `"ip"`) || strings.Contains(string(b), "Mozilla") || m.Host != "edge" { + t.Fatalf("relayed %s", b) + } + } + if got[0].Device != "mobile" || got[1].Kind != "visit_batch" || got[1].N != 7 || len(h.Recent(10)) != 0 { + t.Fatalf("%+v recent=%d", got, len(h.Recent(10))) + } +} diff --git a/internal/server/api_analytics.go b/internal/server/api_analytics.go new file mode 100644 index 0000000..8abc8de --- /dev/null +++ b/internal/server/api_analytics.go @@ -0,0 +1,71 @@ +package server + +import ( + "net/http" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +// Temporal analytics: GET /api/v1/evolution, /concentration and /survival. +// They accept range|from&to and host, study the event registry within the +// study budget and deadline (cached 30 s) and share the user-side study slots. + +func init() { + registerUserRoute("GET /api/v1/evolution", func(s *Server) http.HandlerFunc { return s.analytics("evolution") }) + registerUserRoute("GET /api/v1/concentration", func(s *Server) http.HandlerFunc { return s.analytics("concentration") }) + registerUserRoute("GET /api/v1/survival", func(s *Server) http.HandlerFunc { return s.analytics("survival") }) +} + +func (s *Server) analytics(kind string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + q := r.URL.Query() + if q.Get("range") == "" && q.Get("from") == "" { + if kind == "evolution" { + q.Set("range", "30d") + } else { + q.Set("range", "7d") + } + r.URL.RawQuery = q.Encode() + } + rg, ok := s.rangeOf(w, r) + if !ok { + return + } + host := q.Get("host") + if len(host) > 64 { + badRequest(w, "invalid host") + return + } + if host == "all" { + host = "" + } + if host != "" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"}) + return + } + dim := q.Get("dim") + if kind == "concentration" { + if dim == "" { + dim = "ip" + } + if !store.ConcentrationDims[dim] { + badRequest(w, "dim must be ip, asn, country, path or domain") + return + } + } + if !s.userSlot(w) { + return + } + defer func() { <-s.user }() + from, to := rg.Bounds(s.opt.Now().Unix()) + st := s.opt.Store + switch kind { + case "evolution": + writeJSON(w, 200, st.Evolution(from, to, host)) + case "concentration": + writeJSON(w, 200, st.Concentration(from, to, host, dim)) + default: + writeJSON(w, 200, st.Survival(from, to, host)) + } + } +} diff --git a/internal/server/api_analytics_test.go b/internal/server/api_analytics_test.go new file mode 100644 index 0000000..36c799c --- /dev/null +++ b/internal/server/api_analytics_test.go @@ -0,0 +1,57 @@ +package server + +import ( + "path/filepath" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func TestAnalyticsAPI(t *testing.T) { + st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour}) + l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")}) + st.SetEventLog(l) + now := time.Now() + for i := 0; i < 5; i++ { + st.Ingest(core.Event{Time: now.Add(-time.Hour - time.Duration(i)*time.Minute), IP: "20.0.0.1", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/.env", Status: 404, UA: "zgrab/0.x"}) + } + st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: "20.0.0.2", Cat: core.Scanner, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/x", Status: 404}) + st.Ingest(core.Event{Time: now.Add(-30 * time.Minute), IP: "20.0.0.1", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}) + h := New(Options{Token: userTok, Version: "t", Store: st}) + auth := map[string]string{"Authorization": "Bearer " + userTok} + + e := getJSON(t, h, "/api/v1/evolution", auth) + if e["total"].(float64) != 6 || len(e["days"].([]any)) < 30 || len(e["hour_dow"].([]any)) != 7 { + t.Fatalf("evolution: %v", e) + } + for _, k := range []string{"new_families", "gone_families", "delta_pct"} { + if _, ok := e[k]; !ok { + t.Errorf("evolution misses %s", k) + } + } + c := getJSON(t, h, "/api/v1/concentration?dim=ip&range=24h", auth) + items := c["items"].([]any) + if c["total"].(float64) != 6 || len(items) != 2 || items[0].(map[string]any)["key"] != "20.0.0.1" { + t.Fatalf("concentration: %v", c) + } + v := getJSON(t, h, "/api/v1/survival?range=24h", auth) + if v["km"] == nil || v["by_family"] == nil || v["recidivists"] == nil || v["banned"].(float64) != 1 { + t.Fatalf("survival: %v", v) + } + for path, want := range map[string]int{ + "/api/v1/concentration?dim=nope": 400, + "/api/v1/survival?range=bogus": 400, + "/api/v1/evolution?host=nowhere": 404, + "/api/v1/concentration?dim=path&host": 200, + } { + if w := do(h, "GET", path, cloneHdr(auth), nil); w.Code != want { + t.Errorf("%s: %d want %d", path, w.Code, want) + } + } + if w := do(h, "GET", "/api/v1/survival", nil, nil); w.Code != 401 && w.Code != 302 && w.Code != 403 { + t.Errorf("anonymous: %d", w.Code) + } +} diff --git a/internal/server/api_campaigns.go b/internal/server/api_campaigns.go new file mode 100644 index 0000000..82ab7e3 --- /dev/null +++ b/internal/server/api_campaigns.go @@ -0,0 +1,93 @@ +package server + +import ( + "net/http" + "regexp" + "strconv" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +var campaignIDRe = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) + +func init() { + registerUserRoute("GET /api/v1/campaigns", func(s *Server) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + p, ok := s.periodStudy(w, r) + if !ok { + return + } + writeJSON(w, 200, store.CampaignsOf(p)) + } + }) + registerUserRoute("GET /api/v1/campaigns/{id}", func(s *Server) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + if !campaignIDRe.MatchString(id) { + badRequest(w, "invalid campaign id") + return + } + p, ok := s.periodStudy(w, r) + if !ok { + return + } + d, found := store.CampaignOf(p, id) + if !found { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown campaign"}) + return + } + writeJSON(w, 200, d) + } + }) +} + +// periodStudy runs the same study as /api/v1/period (same filters, user +// semaphore, peers merged) and answers the errors itself. +func (s *Server) periodStudy(w http.ResponseWriter, r *http.Request) (store.PeriodOut, bool) { + eq, ok := s.eventFilter(w, r, 24*time.Hour) + if !ok { + return store.PeriodOut{}, false + } + if !s.userSlot(w) { + return store.PeriodOut{}, false + } + defer func() { <-s.user }() + pq := store.PeriodQuery{From: eq.From, To: eq.To, IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam} + if v := r.URL.Query().Get("gap"); v != "" { + n, err := strconv.ParseInt(v, 10, 64) + if err != nil || n < 60 || n > 86400 { + badRequest(w, "gap must be 60..86400 seconds") + return store.PeriodOut{}, false + } + pq.Gap = n + } + local, peers, only, ok := s.studyHosts(w, eq.Host) + if !ok { + return store.PeriodOut{}, false + } + var parts []store.PeriodOut + var studies map[string]store.PeerStudy + if peers { + studies = s.opt.Hub.StudiesFor(r.Context(), pq, only) + } + if local || len(studies) == 0 { + lq := pq + switch { + case !local: + lq.Host = only + case s.opt.Hub != nil: + lq.Host = s.opt.Store.Name() + } + parts = append(parts, s.opt.Store.Period(lq)) + } + for _, p := range s.opt.Hub.PeerNames() { + if st, ok := studies[p]; ok { + parts = append(parts, st.Period) + } + } + out := store.MergePeriods(parts) + rg, _ := s.opt.Store.ResolveRange(r.URL.Query().Get("range"), r.URL.Query().Get("from"), r.URL.Query().Get("to")) + out.Range = rg.Info(s.opt.Now().Unix()) + return out, true +} diff --git a/internal/server/api_campaigns_test.go b/internal/server/api_campaigns_test.go new file mode 100644 index 0000000..4a94f38 --- /dev/null +++ b/internal/server/api_campaigns_test.go @@ -0,0 +1,81 @@ +package server + +import ( + "net/http" + "path/filepath" + "strconv" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func campaignServer(t *testing.T) http.Handler { + st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour}) + l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")}) + st.SetEventLog(l) + now := time.Now() + for _, ip := range []string{"20.0.0.1", "20.0.0.2", "20.0.0.3"} { + for _, p := range []string{"/wp-login.php", "/xmlrpc.php"} { + st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: p, Status: 404, UA: "zgrab/0.x"}) + } + } + return New(Options{Token: userTok, Version: "t", Store: st}) +} + +func TestCampaignsAndSessionsAPI(t *testing.T) { + h := campaignServer(t) + auth := map[string]string{"Authorization": "Bearer " + userTok} + list := getJSON(t, h, "/api/v1/campaigns?range=24h", auth) + cs := list["campaigns"].([]any) + if len(cs) != 1 || list["ips_n"].(float64) != 3 { + t.Fatalf("campaigns: %v", list) + } + id := cs[0].(map[string]any)["id"].(string) + d := getJSON(t, h, "/api/v1/campaigns/"+id+"?range=24h", auth) + if len(d["members"].([]any)) != 3 { + t.Fatalf("members: %v", d) + } + f := getJSON(t, h, "/api/v1/sessions/funnel?range=24h", auth) + if f["sessions_n"].(float64) < 3 || f["stages"] == nil { + t.Fatalf("funnel: %v", f) + } + for path, want := range map[string]int{ + "/api/v1/campaigns/c-zzzz?range=24h": 404, + "/api/v1/campaigns/bad%20id?range=24h": 400, + "/api/v1/campaigns?range=24h&gap=1": 400, + "/api/v1/campaigns?range=24h&host=nowhere": 404, + } { + if w := do(h, "GET", path, cloneHdr(auth), nil); w.Code != want { + t.Errorf("%s: %d want %d", path, w.Code, want) + } + } + if w := do(h, "GET", "/api/v1/campaigns", nil, nil); w.Code != 401 && w.Code != 302 && w.Code != 403 { + t.Errorf("anonymous: %d", w.Code) + } +} + +func TestFunnelCountsEverySession(t *testing.T) { + st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour}) + l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")}) + st.SetEventLog(l) + now := time.Now() + for i := 0; i < 260; i++ { + ip := "30.0." + strconv.Itoa(i/250) + "." + strconv.Itoa(i%250+1) + st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, UA: "curl/8"}) + } + h := New(Options{Token: userTok, Version: "t", Store: st}) + f := getJSON(t, h, "/api/v1/sessions/funnel?range=24h", map[string]string{"Authorization": "Bearer " + userTok}) + if f["sessions_n"].(float64) != 260 || f["sampled"] != true || len(f["sessions"].([]any)) > 200 { + t.Fatalf("funnel: sessions_n=%v sampled=%v list=%d", f["sessions_n"], f["sampled"], len(f["sessions"].([]any))) + } + sum := 0.0 + for _, v := range f["stages"].(map[string]any) { + sum += v.(float64) + } + if sum != 260 || f["reached"].(map[string]any)["recon"].(float64) != 260 { + t.Fatalf("stages %v reached %v", f["stages"], f["reached"]) + } +} diff --git a/internal/server/api_defense.go b/internal/server/api_defense.go new file mode 100644 index 0000000..70d4e80 --- /dev/null +++ b/internal/server/api_defense.go @@ -0,0 +1,16 @@ +package server + +import "net/http" + +func init() { + registerUserRoute("GET /api/v1/defense", func(s *Server) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + pq, ok := s.windowQuery(w, r) + if !ok { + return + } + defer func() { <-s.user }() + writeJSON(w, 200, s.opt.Store.Defense(pq)) + } + }) +} diff --git a/internal/server/api_defense_test.go b/internal/server/api_defense_test.go new file mode 100644 index 0000000..c0a858b --- /dev/null +++ b/internal/server/api_defense_test.go @@ -0,0 +1,61 @@ +package server + +import ( + "path/filepath" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func TestDefenseAndTechniquesAPI(t *testing.T) { + st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour, AdminUsers: []string{"lucas"}}) + l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")}) + st.SetEventLog(l) + now := time.Now() + for i := 0; i < 5; i++ { + st.Ingest(core.Event{Time: now.Add(-time.Duration(50-i) * time.Minute), IP: "8.8.4.4", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404, UA: "nuclei"}) + } + st.Ingest(core.Event{Time: now.Add(-30 * time.Minute), IP: "8.8.4.4", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}) + st.Ingest(core.Event{Time: now.Add(-10 * time.Minute), IP: "8.8.4.4", Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/.env", Status: 404}) + for _, u := range []string{"root", "lucas", "root"} { + st.Ingest(core.Event{Time: now.Add(-20 * time.Minute), IP: "9.9.9.9", Cat: core.SSHFail, Source: "ssh", User: u}) + } + h := New(Options{Token: userTok, Version: "t", Store: st}) + auth := map[string]string{"Authorization": "Bearer " + userTok} + + d := getJSON(t, h, "/api/v1/defense?range=24h", auth) + if d["bans_total"].(float64) != 1 || d["bans_active"].(float64) != 1 { + t.Fatalf("bans %v", d) + } + ssh := d["ssh"].(map[string]any) + if ssh["fails"].(float64) != 3 || ssh["sources"].(float64) != 1 { + t.Fatalf("ssh %v", ssh) + } + us := ssh["users"].([]any) + if us[0].(map[string]any)["user"] != "root" || us[0].(map[string]any)["admin"] != false || us[1].(map[string]any)["admin"] != true { + t.Fatalf("users %v", us) + } + if d["leak"].(map[string]any)["ips"].(float64) != 1 { + t.Fatalf("leak %v", d["leak"]) + } + if d["ttb"].(map[string]any)["median_s"].(float64) <= 0 { + t.Fatalf("ttb %v", d["ttb"]) + } + if w := do(h, "GET", "/api/v1/defense?range=nope", cloneHdr(auth), nil); w.Code != 400 { + t.Fatalf("bad range: %d", w.Code) + } + if w := do(h, "GET", "/api/v1/defense?range=24h&host=zzz", cloneHdr(auth), nil); w.Code != 404 { + t.Fatalf("unknown host: %d", w.Code) + } + + tq := getJSON(t, h, "/api/v1/techniques?range=24h", auth) + if tq["total"].(float64) < 1 || len(tq["tactics"].([]any)) == 0 { + t.Fatalf("techniques %v", tq) + } + if w := do(h, "GET", "/api/v1/techniques?range=24h", nil, nil); w.Code != 401 { + t.Fatalf("anonymous: %d", w.Code) + } +} diff --git a/internal/server/api_errors.go b/internal/server/api_errors.go new file mode 100644 index 0000000..5686ada --- /dev/null +++ b/internal/server/api_errors.go @@ -0,0 +1,211 @@ +package server + +import ( + "net/http" + "sort" + "strings" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func init() { + registerUserRoute("GET /api/v1/errors", func(s *Server) http.HandlerFunc { return s.errorsAPI }) +} + +// svcWindow resolves range, service and host filters shared by the health routes. +func (s *Server) svcWindow(w http.ResponseWriter, r *http.Request) (from, to int64, svc, host string, ok bool) { + rg, ok := s.rangeOf(w, r) + if !ok { + return + } + q := r.URL.Query() + now := s.opt.Store.Now().Unix() + from, to = rg.Bounds(now) + svc = q.Get("svc") + host = q.Get("host") + if host == "all" || host == s.opt.Store.Name() { + host = "" + } + if len(host) > 253 || len(svc) > 128 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host or svc"}) + return 0, 0, "", "", false + } + return from, to, svc, host, true +} + +type kv struct { + Key string + N uint32 +} + +func topKV(m map[string]uint32, n int) []kv { + out := make([]kv, 0, len(m)) + for k, v := range m { + out = append(out, kv{k, v}) + } + sort.Slice(out, func(a, b int) bool { + if out[a].N != out[b].N { + return out[a].N > out[b].N + } + return out[a].Key < out[b].Key + }) + if len(out) > n { + out = out[:n] + } + return out +} + +func errCount(c [store.NumCls]uint32) uint32 { + var n uint32 + for _, v := range c { + n += v + } + return n +} + +func (s *Server) errorsAPI(w http.ResponseWriter, r *http.Request) { + from, to, svc, host, ok := s.svcWindow(w, r) + if !ok { + return + } + views := s.opt.Store.Services(from, to, svc, host) + var tot [store.NumCls]uint32 + var req, legit uint32 + startH, endH := from/3600, to/3600 + if endH-startH > 719 { + startH = endH - 719 + } + nb := int(endH-startH) + 1 + series := map[string][]uint32{} + for _, n := range store.ClsNames { + series[n] = make([]uint32, nb) + } + type routeOut struct { + Svc string `json:"svc"` + Route string `json:"route"` + Class string `json:"class"` + N uint32 `json:"n"` + } + var routes []routeOut + broken := map[string]*struct { + n uint32 + last int64 + ref string + path string + }{} + type heat struct { + alias string + total uint32 + byH map[int64]uint32 + } + var heats []heat + for _, v := range views { + req += v.Tot.Req + legit += v.Tot.Legit + h := heat{alias: v.Alias, byH: map[int64]uint32{}} + for i := range tot { + tot[i] += v.Tot.Cls[i] + } + for _, hr := range v.Hours { + if hr.Hour < startH || hr.Hour > endH { + continue + } + for i, n := range store.ClsNames { + series[n][hr.Hour-startH] += hr.Cls[i] + } + if c := hr.Cls[store.ClsApp]; c > 0 { + h.byH[hr.Hour] = c + h.total += c + } + } + heats = append(heats, h) + for _, e := range topKV(v.ErrRoutes, 50) { + cl, rt, _ := strings.Cut(e.Key, "|") + routes = append(routes, routeOut{v.Alias, rt, cl, e.N}) + } + for k, n := range v.Broken { + p, ref, _ := strings.Cut(k, "\x00") + b := broken[k] + if b == nil { + b = &struct { + n uint32 + last int64 + ref string + path string + }{ref: ref, path: p} + broken[k] = b + } + b.n += n + if t := v.BrokenLast[k]; t > b.last { + b.last = t + } + } + } + sort.Slice(routes, func(a, b int) bool { return routes[a].N > routes[b].N }) + if len(routes) > 50 { + routes = routes[:50] + } + type brokenOut struct { + Path string `json:"path"` + Ref string `json:"ref"` + N uint32 `json:"n"` + Last int64 `json:"last"` + } + bl := make([]brokenOut, 0, len(broken)) + for _, b := range broken { + bl = append(bl, brokenOut{b.path, b.ref, b.n, b.last}) + } + sort.Slice(bl, func(a, b int) bool { + if bl[a].N != bl[b].N { + return bl[a].N > bl[b].N + } + return bl[a].Path < bl[b].Path + }) + if len(bl) > 50 { + bl = bl[:50] + } + // heatmap: services with most app errors, last 168 hours of the window + sort.Slice(heats, func(a, b int) bool { return heats[a].total > heats[b].total }) + if len(heats) > 64 { + heats = heats[:64] + } + hStart := startH + if endH-hStart > 167 { + hStart = endH - 167 + } + hours := make([]int64, 0, int(endH-hStart)+1) + for h := hStart; h <= endH; h++ { + hours = append(hours, h*3600) + } + svcs := make([]string, len(heats)) + grid := make([][]uint32, len(heats)) + for i, h := range heats { + svcs[i] = h.alias + grid[i] = make([]uint32, len(hours)) + for j := range hours { + grid[i][j] = h.byH[hStart+int64(j)] + } + } + client := tot[store.ClsClientBroken] + tot[store.ClsClientAuth] + tot[store.ClsClientOther] + classes := map[string]uint32{ + "app": tot[store.ClsApp], "proxy": tot[store.ClsProxy], "blocked": tot[store.ClsBlocked], + "attack": tot[store.ClsAttack], "bot": tot[store.ClsBot], "client": client, + } + for i, n := range store.ClsNames { + if strings.HasPrefix(n, "client_") { + classes[n] = tot[i] + } + } + errs := errCount(tot) + var rate float64 + if legit > 0 { + rate = float64(tot[store.ClsApp]+tot[store.ClsProxy]) / float64(legit) + } + writeJSON(w, 200, map[string]any{ + "instance": s.opt.Store.Name(), "range": map[string]int64{"from": from, "to": to}, "requests": req, "errors": errs, "legit": legit, + "app_error_rate": rate, "classes": classes, + "timeline": map[string]any{"start": startH * 3600, "step": 3600, "series": series}, + "heatmap": map[string]any{"svcs": svcs, "hours": hours, "err": grid}, + "broken": bl, "top_routes": routes, + }) +} diff --git a/internal/server/api_integrity.go b/internal/server/api_integrity.go new file mode 100644 index 0000000..f6e8cdd --- /dev/null +++ b/internal/server/api_integrity.go @@ -0,0 +1,132 @@ +package server + +import ( + "net/http" + "sort" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +type integritySource struct { + Name string `json:"name"` + State string `json:"state"` + Lines uint64 `json:"lines"` + Malformed uint64 `json:"malformed"` + Last int64 `json:"last"` +} + +type integrityHost struct { + Name string `json:"name"` + Online bool `json:"online"` + LastEvent int64 `json:"last_event"` + LagS int64 `json:"lag_s"` + Hourly []uint32 `json:"hourly"` + Gaps []store.Gap `json:"gaps"` + Sources []integritySource `json:"sources"` + ParseErrorRate float64 `json:"parse_error_rate"` +} + +type integrityPeer struct { + Name string `json:"name"` + Online bool `json:"online"` + Live bool `json:"live"` + LastSync int64 `json:"last_sync"` +} + +type integrityGeo struct { + CityBuild int64 `json:"city_build"` + ASNBuild int64 `json:"asn_build"` + State string `json:"state"` + LastUpdate int64 `json:"last_update"` + Error string `json:"error,omitempty"` +} + +type integrityOut struct { + Range store.RangeInfo `json:"range"` + FromHour int64 `json:"from_hour"` + Hosts []integrityHost `json:"hosts"` + Peers []integrityPeer `json:"peers"` + EventLog store.LogStats `json:"eventlog"` + Geo integrityGeo `json:"geo"` +} + +func init() { + registerUserRoute("GET /api/v1/integrity", func(s *Server) http.HandlerFunc { return s.integrity }) +} + +// integrity answers "is the data complete?": events ingested per hour and +// host, silences, source and peer states, parse errors, event log and geo base. +func (s *Server) integrity(w http.ResponseWriter, r *http.Request) { + rg, ok := s.rangeOf(w, r) + if !ok { + return + } + host := r.URL.Query().Get("host") + if host == "" { + host = "all" + } + if !s.knownHost(w, host) { + return + } + now := s.opt.Now().Unix() + info := rg.Info(now) + parts, all := s.parts(r.Context(), rg, host) + fromH, toH := info.From/3600, info.To/3600 + if toH-fromH > 24*31-1 { + fromH = toH - (24*31 - 1) + } + out := integrityOut{Range: info, FromHour: fromH, Hosts: []integrityHost{}, Peers: []integrityPeer{}} + seen := map[string]bool{} + for _, p := range parts { + name := p.Host + if name == "" && len(p.Hosts) > 0 { + name = p.Hosts[0].Name + } + seen[name] = true + hh := integrityHost{Name: name, Online: true, Sources: []integritySource{}} + hh.Hourly = store.HourlyFromTimeline(p.Timeline, fromH, toH) + hh.Gaps = store.FindGaps(hh.Hourly, fromH) + var lines, bad uint64 + for _, src := range p.Sources { + if src.Name == "geo" { + if name == s.opt.Store.Name() { + out.Geo = integrityGeo{State: src.State, LastUpdate: src.LastEvent, Error: src.Error} + if store.GeoBuilds != nil { + out.Geo.CityBuild, out.Geo.ASNBuild = store.GeoBuilds() + } + } + continue + } + hh.Sources = append(hh.Sources, integritySource{Name: src.Name, State: src.State, Lines: src.Lines, Malformed: src.Malformed, Last: src.LastEvent}) + lines += src.Lines + bad += src.Malformed + if src.LastEvent > hh.LastEvent { + hh.LastEvent = src.LastEvent + } + } + if lines+bad > 0 { + hh.ParseErrorRate = float64(bad) / float64(lines+bad) + } + if hh.LastEvent > 0 { + hh.LagS = now - hh.LastEvent + if hh.LagS < 0 { + hh.LagS = 0 + } + } + out.Hosts = append(out.Hosts, hh) + } + for _, hi := range all { + if hi.Self { + continue + } + out.Peers = append(out.Peers, integrityPeer{Name: hi.Name, Online: hi.Online, Live: hi.Live, LastSync: hi.LastSeen}) + if !seen[hi.Name] && (host == "all" || host == hi.Name) { + out.Hosts = append(out.Hosts, integrityHost{Name: hi.Name, Online: hi.Online, LastEvent: hi.LastSeen, + Hourly: make([]uint32, toH-fromH+1), Gaps: []store.Gap{}, Sources: []integritySource{}}) + } + } + sort.SliceStable(out.Hosts, func(i, j int) bool { return out.Hosts[i].Name < out.Hosts[j].Name }) + sort.SliceStable(out.Peers, func(i, j int) bool { return out.Peers[i].Name < out.Peers[j].Name }) + out.EventLog = s.opt.Store.LogStats() + writeJSON(w, 200, out) +} diff --git a/internal/server/api_report.go b/internal/server/api_report.go new file mode 100644 index 0000000..89f7248 --- /dev/null +++ b/internal/server/api_report.go @@ -0,0 +1,308 @@ +package server + +import ( + "net/http" + "sort" + "strconv" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +type reportFigures struct { + Requests uint64 `json:"requests"` + Attacks uint64 `json:"attacks"` + UniqueIPs int `json:"unique_ips"` + HostileIPs int `json:"hostile_ips"` + Bans int `json:"bans"` + Visitors uint64 `json:"visitors"` + NonHuman uint64 `json:"nonhuman"` + PageViews uint64 `json:"page_views"` +} + +type reportTopIP struct { + IP string `json:"ip"` + Score float64 `json:"score"` + Level string `json:"level"` + CC string `json:"cc,omitempty"` + Country string `json:"country,omitempty"` + ASOrg string `json:"as_org,omitempty"` + Events uint32 `json:"events"` + Banned bool `json:"banned"` +} + +type reportExposure struct { + T int64 `json:"t"` + IP string `json:"ip"` + Host string `json:"host"` + Domain string `json:"domain"` + Path string `json:"path"` + Status int `json:"status"` + Fam string `json:"fam"` +} + +type reportOut struct { + Range store.RangeInfo `json:"range"` + Generated int64 `json:"generated"` + Hosts []string `json:"hosts"` + Summary struct { + reportFigures + Prev reportFigures `json:"prev"` + DeltaPct map[string]float64 `json:"delta_pct"` + HasPrev bool `json:"has_prev"` + } `json:"summary"` + Timeline struct { + Start int64 `json:"start"` + Step int64 `json:"step"` + Values []uint32 `json:"values"` + } `json:"timeline"` + Families []store.Count `json:"families"` + Techniques []store.Count `json:"techniques"` + Countries []store.Count `json:"countries"` + ASNs []store.Count `json:"asns"` + TopIPs []reportTopIP `json:"top_ips"` + Campaigns []intel.Campaign `json:"campaigns"` + Escalations []store.EscalationOut `json:"escalations"` + Exposures struct { + Total int `json:"total"` + ByFamily []store.Count `json:"by_family"` + Items []reportExposure `json:"items"` + } `json:"exposures"` + Defense struct { + MTTBMedianS float64 `json:"mttb_median_s"` + MTTBP90S float64 `json:"mttb_p90_s"` + MTTBPrevMedianS float64 `json:"mttb_prev_median_s"` + MTTBN int `json:"mttb_n"` + BanCoverage float64 `json:"ban_coverage"` + BanCoveragePrev float64 `json:"ban_coverage_prev"` + BlocklistCover float64 `json:"blocklist_coverage"` + ExposureRate float64 `json:"exposure_rate"` + ExploitsRefused float64 `json:"exploits_refused_pct"` + } `json:"defense"` + Truncated bool `json:"truncated,omitempty"` +} + +func init() { + registerUserRoute("GET /api/v1/report", func(s *Server) http.HandlerFunc { return s.report }) +} + +// figuresOf builds the headline numbers; visitors, non-human clients and page +// views come from the traffic study (real browsers, deduplicated per IP and day). +func figuresOf(t store.Totals, tr store.TrafficData) reportFigures { + return reportFigures{Requests: t.Requests, Attacks: t.Malicious, UniqueIPs: t.UniqueIPs, HostileIPs: t.HostileIPs, + Bans: t.ActiveBans, Visitors: tr.Visitors, NonHuman: tr.NonHuman, PageViews: tr.Pages} +} + +// trafficOf is what /api/v1/traffic answers for all domains, merged with the peers. +func (s *Server) trafficOf(r *http.Request, rg store.Range, host string) store.TrafficData { + var parts []store.TrafficData + self := s.opt.Store.Name() + if host == "all" || host == self { + parts = append(parts, s.opt.Store.TrafficFor(rg, "all")) + } + if s.opt.Hub != nil && host != self { + only := "" + if host != "all" { + only = host + } + parts = append(parts, s.opt.Hub.TrafficFor(r.Context(), rg, "all", only)...) + } + return store.MergeTraffic(host, parts) +} + +func pctChange(v, prev float64) (float64, bool) { + if prev <= 0 { + return 0, false + } + return (v - prev) / prev * 100, true +} + +var attackCats = []string{"scanner", "exploit", "bruteforce", "ssh-fail", "ssh-probe"} + +// 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") + return + } + if r.URL.Query().Get("range") == "" && r.URL.Query().Get("from") == "" { + q := r.URL.Query() + q.Set("range", "7d") + r.URL.RawQuery = q.Encode() + } + rg, ok := s.rangeOf(w, r) + if !ok { + return + } + host := r.URL.Query().Get("host") + if host == "" { + host = "all" + } + if !s.knownHost(w, host) { + return + } + now := s.opt.Now().Unix() + info := rg.Info(now) + var out reportOut + out.Range, out.Generated = info, now + + // period study (families, techniques, ASNs, campaigns, escalations) + per, ok := s.periodStudy(w, r) + if !ok { + return + } + // summary of the period and of the previous one + parts, all := s.parts(r.Context(), rg, host) + var sum store.Summary + if len(parts) > 0 { + sum = store.Merge(host, parts) + } + out.Hosts = []string{} + for _, hi := range all { + if host == "all" || hi.Name == host { + out.Hosts = append(out.Hosts, hi.Name) + } + } + sort.Strings(out.Hosts) + out.Summary.reportFigures = figuresOf(sum.Totals, s.trafficOf(r, rg, host)) + span := info.To - info.From + if span > 0 { + if prg, err := s.opt.Store.ResolveRange("", strconv.FormatInt(info.From-span, 10), strconv.FormatInt(info.From, 10)); err == nil { + pp, _ := s.parts(r.Context(), prg, host) + if len(pp) > 0 { + ps := store.Merge(host, pp) + out.Summary.Prev = figuresOf(ps.Totals, s.trafficOf(r, prg, host)) + out.Summary.HasPrev = ps.Totals.Requests > 0 || ps.Totals.Malicious > 0 + } + } + } + out.Summary.DeltaPct = map[string]float64{} + if out.Summary.HasPrev { + cur, prev := out.Summary.reportFigures, out.Summary.Prev + for k, p := range map[string][2]float64{ + "requests": {float64(cur.Requests), float64(prev.Requests)}, "attacks": {float64(cur.Attacks), float64(prev.Attacks)}, + "unique_ips": {float64(cur.UniqueIPs), float64(prev.UniqueIPs)}, "hostile_ips": {float64(cur.HostileIPs), float64(prev.HostileIPs)}, + "bans": {float64(cur.Bans), float64(prev.Bans)}, "visitors": {float64(cur.Visitors), float64(prev.Visitors)}, + "nonhuman": {float64(cur.NonHuman), float64(prev.NonHuman)}, "page_views": {float64(cur.PageViews), float64(prev.PageViews)}, + } { + if d, ok := pctChange(p[0], p[1]); ok { + out.Summary.DeltaPct[k] = d + } + } + } + // attacks timeline + tl := sum.Timeline + out.Timeline.Start, out.Timeline.Step = tl.Start, tl.Step + out.Timeline.Values = []uint32{} + for _, c := range attackCats { + for i, v := range tl.Series[c] { + for len(out.Timeline.Values) <= i { + out.Timeline.Values = append(out.Timeline.Values, 0) + } + out.Timeline.Values[i] += v + } + } + // tops + out.Families, out.Techniques, out.ASNs = capCounts(per.TopFams, 10), capCounts(per.TopTechs, 10), capCounts(per.TopASNs, 10) + out.Countries = capCounts(sum.Countries, 10) + out.Campaigns = per.Campaigns + if len(out.Campaigns) > 8 { + out.Campaigns = out.Campaigns[:8] + } + if out.Campaigns == nil { + out.Campaigns = []intel.Campaign{} + } + out.Escalations = per.Escalations + if len(out.Escalations) > 8 { + out.Escalations = out.Escalations[:8] + } + if out.Escalations == nil { + out.Escalations = []store.EscalationOut{} + } + out.Truncated = per.Truncated + ips := append([]store.IPSummary(nil), sum.IPs...) + sort.SliceStable(ips, func(i, j int) bool { return ips[i].Score > ips[j].Score }) + out.TopIPs = []reportTopIP{} + out.Exposures.ByFamily, out.Exposures.Items = []store.Count{}, []reportExposure{} + fam := map[string]uint32{} + for i, x := range ips { + var ev uint32 + for _, n := range x.Counts { + ev += n + } + if i < 10 { + out.TopIPs = append(out.TopIPs, reportTopIP{IP: x.IP, Score: x.Score, Level: string(x.Level), CC: x.CC, Country: x.Country, ASOrg: x.ASOrg, Events: ev, Banned: x.Banned}) + } + if i < 30 { + if inf, ok := s.opt.Store.IPInfoOf(x.IP); ok { + for _, e := range inf.Expo { + if e.T < info.From || e.T > info.To { + continue + } + out.Exposures.Total++ + if e.Fam != "" { + fam[e.Fam]++ + } + if len(out.Exposures.Items) < 10 { + out.Exposures.Items = append(out.Exposures.Items, reportExposure{T: e.T, IP: x.IP, Host: e.Host, Domain: e.Domain, Path: e.Path, Status: e.Status, Fam: e.Fam}) + } + } + } + } + } + for k, n := range fam { + out.Exposures.ByFamily = append(out.Exposures.ByFamily, store.Count{Key: k, N: n}) + } + sort.Slice(out.Exposures.ByFamily, func(i, j int) bool { + a, b := out.Exposures.ByFamily[i], out.Exposures.ByFamily[j] + return a.N > b.N || (a.N == b.N && a.Key < b.Key) + }) + sort.Slice(out.Exposures.Items, func(i, j int) bool { return out.Exposures.Items[i].T > out.Exposures.Items[j].T }) + + // defence metrics (same study and slot as /metrics) + m, ok := s.reportMetrics(w, r, rg, host) + if !ok { + return + } + 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) +} + +func capCounts(c []store.Count, n int) []store.Count { + if len(c) > n { + c = c[:n] + } + if c == nil { + return []store.Count{} + } + return c +} + +func (s *Server) reportMetrics(w http.ResponseWriter, r *http.Request, rg store.Range, host string) (store.MetricsOut, bool) { + local, peers, only, ok := s.studyHosts(w, host) + if !ok { + return store.MetricsOut{}, false + } + if !s.userSlot(w) { + return store.MetricsOut{}, false + } + defer func() { <-s.user }() + var parts []store.MetricsOut + var studies map[string]store.PeerStudy + if peers { + from, to := rg.Bounds(s.opt.Now().Unix()) + studies = s.opt.Hub.StudiesFor(r.Context(), store.PeriodQuery{From: from, To: to}, only) + } + if local || len(studies) == 0 { + parts = append(parts, s.opt.Store.Metrics(rg)) + } + for _, p := range s.opt.Hub.PeerNames() { + if st, ok := studies[p]; ok { + parts = append(parts, st.Metrics) + } + } + return store.MergeMetrics(parts), true +} diff --git a/internal/server/api_report_test.go b/internal/server/api_report_test.go new file mode 100644 index 0000000..01b59d4 --- /dev/null +++ b/internal/server/api_report_test.go @@ -0,0 +1,80 @@ +package server + +import ( + "encoding/json" + "testing" +) + +var opsAuth = map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"} + +func TestIntegrityAPI(t *testing.T) { + h, _ := setup(t) + if w := do(h, "GET", "/api/v1/integrity?range=24h", nil, nil); w.Code != 401 && w.Code != 403 { + t.Fatalf("closed without token: %d", w.Code) + } + w := do(h, "GET", "/api/v1/integrity?range=24h", copyHdr(opsAuth), nil) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + var o struct { + Hosts []struct { + Name string `json:"name"` + Online bool `json:"online"` + Hourly []uint32 `json:"hourly"` + } `json:"hosts"` + Peers []any `json:"peers"` + } + if err := json.Unmarshal(w.Body.Bytes(), &o); err != nil { + t.Fatal(err) + } + if len(o.Hosts) != 1 || o.Hosts[0].Name != "oracle" || !o.Hosts[0].Online || len(o.Hosts[0].Hourly) < 24 { + t.Fatalf("%+v", o) + } + var sum uint32 + for _, v := range o.Hosts[0].Hourly { + sum += v + } + if sum == 0 { + t.Fatal("the ingested event must show in the hourly series") + } + if w := do(h, "GET", "/api/v1/integrity?host=nope", copyHdr(opsAuth), nil); w.Code != 404 { + t.Fatalf("unknown host: %d", w.Code) + } +} + +func TestReportAPI(t *testing.T) { + h, _ := setup(t) + w := do(h, "GET", "/api/v1/report?range=7d&format=json", copyHdr(opsAuth), nil) + if w.Code != 200 { + t.Fatalf("%d %s", w.Code, w.Body) + } + var o struct { + Hosts []string `json:"hosts"` + Summary struct { + Attacks uint64 `json:"attacks"` + } `json:"summary"` + TopIPs []struct { + IP string `json:"ip"` + } `json:"top_ips"` + } + if err := json.Unmarshal(w.Body.Bytes(), &o); err != nil { + t.Fatal(err) + } + if o.Summary.Attacks != 1 || len(o.TopIPs) != 1 || len(o.Hosts) != 1 { + t.Fatalf("%s", w.Body) + } + if w := do(h, "GET", "/api/v1/report?format=pdf", copyHdr(opsAuth), nil); w.Code != 400 { + t.Fatalf("format: %d", w.Code) + } + if w := do(h, "GET", "/api/v1/report?host=nope", copyHdr(opsAuth), nil); w.Code != 404 { + t.Fatalf("host: %d", w.Code) + } +} + +func copyHdr(m map[string]string) map[string]string { + c := map[string]string{} + for k, v := range m { + c[k] = v + } + return c +} diff --git a/internal/server/api_services.go b/internal/server/api_services.go new file mode 100644 index 0000000..70800d9 --- /dev/null +++ b/internal/server/api_services.go @@ -0,0 +1,208 @@ +package server + +import ( + "math" + "net/http" + "sort" + "strings" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +const sloTarget = 0.995 + +func init() { + registerUserRoute("GET /api/v1/services", func(s *Server) http.HandlerFunc { return s.servicesAPI }) + registerUserRoute("GET /api/v1/services/{svc}", func(s *Server) http.HandlerFunc { return s.serviceAPI }) + registerUserRoute("GET /api/v1/protocols", func(s *Server) http.HandlerFunc { return s.protocolsAPI }) +} + +type tri struct { + Total float64 `json:"total"` + Origin float64 `json:"origin"` + Overhead float64 `json:"overhead"` +} + +func errRate(h store.SvcHourOut) float64 { + if h.Legit == 0 { + return 0 + } + return float64(h.Cls[store.ClsApp]+h.Cls[store.ClsProxy]) / float64(h.Legit) +} + +func round(f float64, d int) float64 { + p := math.Pow(10, float64(d)) + return math.Round(f*p) / p +} + +func serviceItem(v store.SvcView, to int64) map[string]any { + t := v.Tot + rate := errRate(t) + var peak uint32 + for _, h := range v.Hours { + if h.Req > peak { + peak = h.Req + } + } + burn := func(hours int64) float64 { + var sum store.SvcHourOut + for _, h := range v.Hours { + if h.Hour > to/3600-hours { + sum.Legit += h.Legit + sum.Cls[store.ClsApp] += h.Cls[store.ClsApp] + sum.Cls[store.ClsProxy] += h.Cls[store.ClsProxy] + } + } + return round(errRate(sum)/(1-sloTarget), 2) + } + apdex := 1.0 + if t.ApN > 0 { + apdex = (float64(t.ApSat) + float64(t.ApTol)/2) / float64(t.ApN) + } + var retries float64 + if t.Req > 0 { + retries = float64(t.Retries) / float64(t.Req) * 100 + } + spark := make([]uint32, 0, 48) + for _, h := range v.Hours { + spark = append(spark, h.Req) + } + if len(spark) > 48 { + spark = spark[len(spark)-48:] + } + mix := map[string]uint32{} + for i, n := range store.ClsNames { + mix[n] = t.Cls[i] + } + mix["ok"] = t.Req - errCount(t.Cls) + q := func(h [13]uint32, p float64) float64 { return round(store.Quantile(h, p), 1) } + return map[string]any{ + "svc": v.Key, "alias": v.Alias, "req": t.Req, "rps_peak": round(float64(peak)/3600, 3), + "sli": round(1-rate, 5), "slo": sloTarget, "budget_left": round(math.Max(0, 1-rate/(1-sloTarget)), 4), + "burn_1h": burn(1), "burn_6h": burn(6), "apdex": round(apdex, 3), + "p50": tri{q(t.Dur, .5), q(t.Org, .5), q(t.Ov, .5)}, + "p95": tri{q(t.Dur, .95), q(t.Org, .95), q(t.Ov, .95)}, + "p99": tri{q(t.Dur, .99), q(t.Org, .99), q(t.Ov, .99)}, + "retries_pct": round(retries, 3), "mix": mix, "spark": spark, + } +} + +func (s *Server) servicesAPI(w http.ResponseWriter, r *http.Request) { + from, to, _, host, ok := s.svcWindow(w, r) + if !ok { + return + } + views := s.opt.Store.Services(from, to, "", host) + out := make([]map[string]any, 0, len(views)) + for _, v := range views { + out = append(out, serviceItem(v, to)) + } + writeJSON(w, 200, out) +} + +func (s *Server) serviceAPI(w http.ResponseWriter, r *http.Request) { + from, to, _, host, ok := s.svcWindow(w, r) + if !ok { + return + } + views := s.opt.Store.Services(from, to, r.PathValue("svc"), host) + if len(views) == 0 { + writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown service"}) + return + } + v := views[0] + n := len(v.Hours) + req, errs, p95 := make([]uint32, n), make([]uint32, n), make([]float64, n) + hours := make([]int64, n) + for i, h := range v.Hours { + hours[i], req[i] = h.Hour*3600, h.Req + errs[i] = h.Cls[store.ClsApp] + h.Cls[store.ClsProxy] + p95[i] = round(store.Quantile(h.Dur, .95), 1) + } + type routeOut struct { + Route string `json:"route"` + Class string `json:"class"` + N uint32 `json:"n"` + } + var routes []routeOut + for _, e := range topKV(v.ErrRoutes, 50) { + cl, rt, _ := strings.Cut(e.Key, "|") + routes = append(routes, routeOut{rt, cl, e.N}) + } + bounds := store.SvcBounds + writeJSON(w, 200, map[string]any{ + "summary": serviceItem(v, to), + "timeline": map[string]any{"hours": hours, "req": req, "errors": errs, "p95": p95}, + "histograms": map[string]any{"bounds": bounds[:], "total": v.Tot.Dur, "origin": v.Tot.Org, "overhead": v.Tot.Ov}, + "top_routes": routes, + }) +} + +func (s *Server) protocolsAPI(w http.ResponseWriter, r *http.Request) { + from, to, svc, host, ok := s.svcWindow(w, r) + if !ok { + return + } + views := s.opt.Store.Services(from, to, svc, host) + protos, tls, methods := map[string]map[string]uint32{}, map[string]map[string]uint32{}, map[string]map[string]uint32{} + ciphers := map[string]uint32{} + add := func(dst map[string]map[string]uint32, src map[string]uint32) { + for k, n := range src { + a, b, _ := strings.Cut(k, "|") + if dst[a] == nil { + dst[a] = map[string]uint32{} + } + dst[a][b] += n + } + } + for _, v := range views { + add(protos, v.ProtoCls) + add(tls, v.TLSCls) + add(methods, v.Methods) + for k, n := range v.Ciphers { + ciphers[k] += n + } + } + // methods: the standard ones first, anomalous ones flagged + std := map[string]bool{"GET": true, "HEAD": true, "POST": true, "PUT": true, "PATCH": true, "DELETE": true, "OPTIONS": true} + type mOut struct { + Method string `json:"method"` + Odd bool `json:"odd"` + N uint32 `json:"n"` + Classes map[string]uint32 `json:"classes"` + } + var ms []mOut + for m, c := range methods { + var n uint32 + for _, v := range c { + n += v + } + ms = append(ms, mOut{m, !std[m], n, c}) + } + sort.Slice(ms, func(a, b int) bool { return ms[a].N > ms[b].N }) + if len(ms) > 30 { + ms = ms[:30] + } + type cOut struct { + Name string `json:"name"` + N uint32 `json:"n"` + } + var cs []cOut + for _, e := range topKV(ciphers, 50) { + cs = append(cs, cOut{e.Key, e.N}) + } + var https, plain uint32 + for k, c := range tls { + for _, n := range c { + if k == "none" { + plain += n + } else { + https += n + } + } + } + writeJSON(w, 200, map[string]any{ + "protocols": protos, "tls": tls, "ciphers": cs, "methods": ms, + "scheme": map[string]uint32{"https": https, "http": plain}, + }) +} diff --git a/internal/server/api_services_test.go b/internal/server/api_services_test.go new file mode 100644 index 0000000..631654e --- /dev/null +++ b/internal/server/api_services_test.go @@ -0,0 +1,65 @@ +package server + +import ( + "encoding/json" + "net/http" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func TestServicesAndErrorsAPI(t *testing.T) { + st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour}) + now := time.Now() + mk := func(status, origin int, path, ref string, cat core.Category) core.Event { + return core.Event{Time: now.Add(-30 * time.Minute), IP: "20.0.0.9", Cat: cat, Source: "traefik", Domain: "a.example", Method: "GET", Path: path, Referer: ref, + UA: "Mozilla/5.0 x", Status: status, OriginStatus: origin, DurationNS: 30e6, OriginNS: 28e6, Router: "r-app@docker", Service: "r-app@docker", + Proto: "HTTP/2.0", Scheme: "https", TLSVer: "1.3", TLSCiph: "TLS_AES_128_GCM_SHA256", E: core.Enrich{Device: "desktop"}} + } + for i := 0; i < 8; i++ { + st.ObserveService(mk(200, 200, "/", "", core.OK)) + } + st.ObserveService(mk(500, 500, "/api/a", "", core.OK)) + st.ObserveService(mk(404, 404, "/gone", "https://a.example/", core.NotFound)) + st.ObserveService(mk(404, 404, "/.env", "", core.Scanner)) + h := New(Options{Token: userTok, Version: "t", Store: st}) + auth := map[string]string{"Authorization": "Bearer " + userTok} + + e := getJSON(t, h, "/api/v1/errors?range=24h", auth) + cl := e["classes"].(map[string]any) + if cl["app"].(float64) != 1 || cl["attack"].(float64) != 1 || cl["client"].(float64) != 1 || e["errors"].(float64) != 3 { + t.Fatalf("errors: %v", e) + } + if len(e["broken"].([]any)) != 1 || len(e["top_routes"].([]any)) != 3 { + t.Fatalf("lists: %v", e) + } + s := getJSONList(t, h, "/api/v1/services?range=24h", auth) + if len(s) != 1 || s[0].(map[string]any)["svc"] != "r-app" { + t.Fatalf("services: %v", s) + } + d := getJSON(t, h, "/api/v1/services/r-app?range=24h", auth) + if d["histograms"] == nil || d["timeline"] == nil { + t.Fatalf("service: %v", d) + } + if w := do(h, "GET", "/api/v1/services/nope?range=24h", cloneHdr(auth), nil); w.Code != 404 { + t.Fatalf("404 expected, got %d", w.Code) + } + p := getJSON(t, h, "/api/v1/protocols?range=24h", auth) + if p["protocols"].(map[string]any)["http2"] == nil || p["scheme"].(map[string]any)["https"].(float64) != 11 { + t.Fatalf("protocols: %v", p) + } +} + +func getJSONList(t *testing.T, h http.Handler, path string, hd map[string]string) []any { + w := do(h, "GET", path, cloneHdr(hd), nil) + if w.Code != 200 { + t.Fatalf("%s: %d %s", path, w.Code, w.Body) + } + var m []any + if err := json.Unmarshal(w.Body.Bytes(), &m); err != nil { + t.Fatal(err) + } + return m +} diff --git a/internal/server/api_sessions.go b/internal/server/api_sessions.go new file mode 100644 index 0000000..b7f66d0 --- /dev/null +++ b/internal/server/api_sessions.go @@ -0,0 +1,36 @@ +package server + +import ( + "net/http" + "strconv" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func init() { + // GET /api/v1/sessions/funnel?range|from&to&host: every session of the + // period counted by stage, plus the 200 sessions the study keeps and the + // escalation chains. With peers the counts fall back to the merged sample. + registerUserRoute("GET /api/v1/sessions/funnel", func(s *Server) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + p, ok := s.periodStudy(w, r) + if !ok { + return + } + var counts *store.StageCounts + if eq, ok := s.eventFilter(w, r, 24*time.Hour); ok { + if local, peers, _, ok := s.studyHosts(w, eq.Host); ok && local && !peers && s.userSlot(w) { + defer func() { <-s.user }() + pq := store.PeriodQuery{From: eq.From, To: eq.To, IP: eq.IP, Cat: eq.Cat, Fam: eq.Fam} + if n, err := strconv.ParseInt(r.URL.Query().Get("gap"), 10, 64); err == nil { + pq.Gap = n + } + c := s.opt.Store.CountStages(pq) + counts = &c + } + } + writeJSON(w, 200, store.FunnelOf(p, counts)) + } + }) +} diff --git a/internal/server/api_techniques.go b/internal/server/api_techniques.go new file mode 100644 index 0000000..3fe9dfc --- /dev/null +++ b/internal/server/api_techniques.go @@ -0,0 +1,37 @@ +package server + +import ( + "net/http" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" +) + +func init() { + registerUserRoute("GET /api/v1/techniques", func(s *Server) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + pq, ok := s.windowQuery(w, r) + if !ok { + return + } + defer func() { <-s.user }() + writeJSON(w, 200, s.opt.Store.Techniques(pq)) + } + }) +} + +// windowQuery parses range|from&to&host like /period and takes a user slot; +// on success the caller releases it with <-s.user. +func (s *Server) windowQuery(w http.ResponseWriter, r *http.Request) (store.PeriodQuery, bool) { + eq, ok := s.eventFilter(w, r, 24*time.Hour) + if !ok { + return store.PeriodQuery{}, false + } + if eq.Host != "" && !s.knownHost(w, eq.Host) { + return store.PeriodQuery{}, false + } + if !s.userSlot(w) { + return store.PeriodQuery{}, false + } + return store.PeriodQuery{From: eq.From, To: eq.To, Host: eq.Host}, true +} diff --git a/internal/server/live_test.go b/internal/server/live_test.go index 79c4813..32c09cc 100644 --- a/internal/server/live_test.go +++ b/internal/server/live_test.go @@ -4,6 +4,7 @@ import ( "bufio" "context" "encoding/json" + "io" "net/http" "net/http/httptest" "strings" @@ -271,3 +272,34 @@ func TestPeerBlocklistOffUsesLocalOnly(t *testing.T) { } } } + +func TestPeerStreamVisitsOnlyOnRequestAndNoIP(t *testing.T) { + const ptok = "peer-secret-0123456789-abcdefghijklmnopqr" + for _, q := range []string{"", "?visits=1"} { + st := store.New(store.Config{Name: "edge", Version: "t"}) + st.SetEnricher(fakeGeo{}) + ts := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Version: "t", Store: st})) + req, _ := http.NewRequest("GET", ts.URL+"/api/v1/peer/stream"+q, nil) + req.Header.Set("Authorization", "Bearer "+ptok) + resp, err := http.DefaultClient.Do(req) + if err != nil || resp.StatusCode != 200 { + t.Fatal(err, resp) + } + go func() { + time.Sleep(200 * time.Millisecond) + st.Traffic(core.Event{Time: time.Now(), IP: "200.1.1.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200, UA: "Mozilla/5.0 x", + E: core.Enrich{Device: "desktop"}}) + time.Sleep(300 * time.Millisecond) + resp.Body.Close() + }() + body, _ := io.ReadAll(resp.Body) + got := strings.Contains(string(body), "event: visit") + if got != (q != "") { + t.Fatalf("query %q: visit event present=%v\n%s", q, got, body) + } + if strings.Contains(string(body), "200.1.1.9") || strings.Contains(string(body), `"ip"`) || strings.Contains(string(body), "Mozilla") { + t.Fatalf("address in stream: %s", body) + } + ts.Close() + } +} diff --git a/internal/server/routes.go b/internal/server/routes.go new file mode 100644 index 0000000..913b34e --- /dev/null +++ b/internal/server/routes.go @@ -0,0 +1,18 @@ +package server + +import "net/http" + +// userRoute is an authenticated /api/v1 route contributed by its own file +// (api_.go) so that new analysis endpoints never edit server.go. +type userRoute struct { + pattern string + handler func(*Server) http.HandlerFunc +} + +var userRoutes []userRoute + +// registerUserRoute is called from init() in api_.go files. The route +// is wrapped by Server.api: session or URUTAU_TOKEN only, peer token 403. +func registerUserRoute(pattern string, h func(*Server) http.HandlerFunc) { + userRoutes = append(userRoutes, userRoute{pattern, h}) +} diff --git a/internal/server/server.go b/internal/server/server.go index 53c509f..b40423b 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -114,6 +114,11 @@ func New(opt Options) http.Handler { m.HandleFunc("GET /api/v1/ip/{ip}/stix", s.api(s.stixAPI)) m.HandleFunc("GET /api/v1/events", s.api(s.eventsAPI)) m.HandleFunc("GET /api/v1/events/sessions", s.api(s.sessionsAPI)) + // Analysis routes added by api_.go files through registerUserRoute + // (init): user auth only, same wrapper as every /api/v1 route. + for _, r := range userRoutes { + m.HandleFunc(r.pattern, s.api(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))) @@ -633,21 +638,34 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) { defer stopHub() hubCh = c } + // ?visits=1 also streams the legitimate visits (no address in them); nil blocks forever + var visCh, hubVisCh <-chan store.VisitMsg + if r.URL.Query().Get("visits") == "1" { + c, stopV := s.opt.Store.SubscribeVisits() + defer stopV() + visCh = c + if s.opt.Hub != nil { + c, stopHV := s.opt.Hub.SubscribeVisits() + defer stopHV() + hubVisCh = c + } + } fmt.Fprint(w, "retry: 3000\n: connected\n\n") fl.Flush() tick := time.NewTicker(sseHeartbeat) defer tick.Stop() - send := func(e store.LiveEvent) bool { + sendAs := func(name string, e any) bool { if k := s.authKind(r); k != "session" && k != "bearer" { return false } b, _ := json.Marshal(e) - if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil { + if _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", name, b); err != nil { return false } fl.Flush() return true } + send := func(e store.LiveEvent) bool { return sendAs("ev", e) } for { select { case <-r.Context().Done(): @@ -668,6 +686,14 @@ func (s *Server) stream(w http.ResponseWriter, r *http.Request) { if !send(e) { return } + case e := <-visCh: + if !sendAs("visit", e) { + return + } + case e := <-hubVisCh: + if !sendAs("visit", e) { + return + } } } } @@ -697,6 +723,12 @@ func (s *Server) peerStream(w http.ResponseWriter, r *http.Request) { h.Set("X-Accel-Buffering", "no") ch, stop := s.opt.Store.Subscribe() defer stop() + var visCh <-chan store.VisitMsg // only with ?visits=1; carries no address + if r.URL.Query().Get("visits") == "1" { + c, stopV := s.opt.Store.SubscribeVisits() + defer stopV() + visCh = c + } fmt.Fprint(w, "retry: 3000\n: connected\n\n") fl.Flush() tick := time.NewTicker(sseHeartbeat) @@ -705,6 +737,12 @@ func (s *Server) peerStream(w http.ResponseWriter, r *http.Request) { select { case <-r.Context().Done(): return + case v := <-visCh: + b, _ := json.Marshal(v) + if _, err := fmt.Fprintf(w, "event: visit\ndata: %s\n\n", b); err != nil { + return + } + fl.Flush() case <-tick.C: if !s.opt.NoAuth && s.authKind(r) != "peer" { return diff --git a/internal/server/web/app.js b/internal/server/web/app.js index e37abe3..f5968ef 100644 --- a/internal/server/web/app.js +++ b/internal/server/web/app.js @@ -28,6 +28,19 @@ * pt-BR "nas últimas 6 horas" / "na última hora" / "nos últimos 7 dias" / "entre 12 nov 10:00 e 14 nov 18:00" * Urutau.href(pageId, segments?, query?) -> hash that keeps the current slice * Urutau.toast(msg) short confirmation toast + * Urutau.help(node, key) appends an accessible "?" button to node (keyboard focus, aria-describedby, + * popover with a short text and "what to do"). Urutau.glossary = { has(key), get(key) -> {text, action} }. + * Keys (central dictionary, en + pt-BR, each with a ".do" companion): help.cat., + * help.metric. (requests, malicious, unique_ips, attacks_per_hour_24h, moving_avg_7d_per_hour, trend, + * active_attackers_24h/_1h, new_attackers, returning_rate, sessions_per_day, exposure_rate, exploits_refused_pct, + * ban_coverage, blocklist_coverage, blocklist_leak, mttb, visitors, pages, bytes, latency, bots) and + * help.term. (session, stage.recon|probe|exploit|access|banned, campaign, family, mitre, net_type, cadence, + * score, level, fcrdns, exposure, blocklist, peer, hub, client_type, status_class, attack_profile). + * Pass the key WITHOUT the "help." prefix: Urutau.help(el, 'metric.mttb'). Metric cards accept {help:'metric.x'}, + * panels accept {help:'term.x'}. Category names: t('cat.') is the long name, t('cat.short.') the short one. + * Groups: registerPage({..., group:'monitor|investigate|analyze|operate|reports'}); known ids are placed by the built-in + * order, unknown ids go to the end of their group (default group: analyze). + * Page scripts load from /pages.json ({"pages":[{"name":"geo","css":true}]}): add your name there when you create .js. * Urutau.registerI18n({ en: {...}, 'pt-BR': {...} }) merge keys (existing keys win) * Urutau.t(key, vars?) vars: a number (fills {n}) or an object ({name: ...}) * Urutau.api(path, params) -> Promise GET with query params; 401 goes to @@ -45,6 +58,16 @@ * function handlers, any other attribute as a string. SVG tags work. * Urutau.css(name) reads a design token, e.g. css('accent') or css('--cat-exploit') * Urutau.setSliceNote(text) optional extra words appended to the slice sentence + * Urutau.charts: own SVG chart library (no dependencies, CSP-safe, theme tokens, ResizeObserver, + * every chart also renders a visually hidden for screen readers, and an empty + * state when there is nothing to draw). Every function returns a DOM node; append it. + * donut(data[{key,label,value}], {title, colors:['--viz-3',...], centerLabel, format}) + * radar(axes[{key,label}], series[{label,values[]}], {max, format, colors, title}) + * stackedArea(series[{key,label,values[]}], stepSeconds, {start (unix), colors, title}) + * bars(rows[{key,label,value,color?:'--token',parts?:[{label,value,color?}]}], {horizontal=true, stacked, format, colors, title}) + * heatmap(matrix[row][col], xLabels[], yLabels[], {format, title}) cells use --seq-1..5 + * sparkline(values[]) gauge(value, max, thresholds[{at,tone:'ok|warn|danger|info'}], {label, format}) + * colors are CSS token names ("--viz-1"); the default palette is --viz-1..8 in order. * Urutau.ui = { panel, stat, metric, lead, empty, badge, bars, chart, sparkline } shared primitives * (the same ones the core pages use; see their definitions below) * @@ -357,6 +380,7 @@ var acts = opts.actions ? [].concat(opts.actions) : null; var head = h('div', 'panel-h', h('h2', null, opts.title), acts ? h('div', 'acts', acts) : null); var body = h('div', 'panel-b', kids); + if (opts.help) help(head.firstChild, opts.help); var variant = pick(['list', 'chart', 'map'], opts.variant, ''); var foot = opts.footer ? h('div', 'panel-f', opts.footer) : null; var node = h('section', 'panel' + (variant ? ' card-' + variant : '') + (opts.cls ? ' ' + opts.cls : ''), head, opts.hint ? h('p', 'hint', opts.hint) : null, body, foot); @@ -384,11 +408,13 @@ var arrow = o.delta === 0 ? '\u25A0' : up ? '\u25B2' : '\u25BC'; dl = h('p', 'cm-delta' + (big && o.delta !== 0 ? (good ? ' good' : ' bad') : ''), arrow + ' ' + nfFor({ maximumFractionDigits: 0 }, 'd0').format(Math.abs(o.delta)) + '%'); } - var n = h('div', 'card-metric' + (tn === 'neutral' ? '' : ' tone-' + tn), h('p', 'cm-label', label), h('p', 'cm-value num', value), dl, o.sub ? h('p', 'cm-sub', o.sub) : null, sparkline(o.spark)); + var lab = h('p', 'cm-label', label); + if (o.help) help(lab, o.help); + var n = h('div', 'card-metric' + (tn === 'neutral' ? '' : ' tone-' + tn), lab, h('p', 'cm-value num', value), dl, o.sub ? h('p', 'cm-sub', o.sub) : null, sparkline(o.spark)); if (o.hint) n.title = o.hint; return n; } - function stat(label, value, sub, tone, hint) { return metric(label, value, { sub: sub, tone: tone, hint: hint }); } + function stat(label, value, sub, tone, hint, helpKey) { return metric(label, value, { sub: sub, tone: tone, hint: hint, help: helpKey }); } function lead(title, body, tone) { var tn = pick(['ok', 'danger', 'neutral'], tone, 'ok'); return h('section', 'lead tone-' + tn, h('div', null, h('h2', null, title), body ? h('p', null, body) : null), h('span', 'pulse', '')); @@ -402,7 +428,47 @@ function showSkeleton(box, n, cls) { clear(box); for (var i = 0; i < n; i++) box.appendChild(h('div', cls || 'skeleton')); } function badge(text, tone) { var tn = pick(KNOWN_TONES, tone, 'neutral'); return h('span', 'badge' + (tn === 'neutral' ? '' : ' tone-' + tn), text); } function levelBadge(l) { l = pick(KNOWN_LEVELS, l, 'low'); return badge(t('level.' + l), LEVEL_TONE[l]); } - function catPill(c, label) { var k = pick(KNOWN_CATS, c, 'ok'); return h('span', 'cat c-' + k, label || t('cat.' + k)); } + function catShort(c) { var k = pick(KNOWN_CATS, c, 'ok'); return t('cat.short.' + k); } + function catPill(c, label) { var k = pick(KNOWN_CATS, c, 'ok'), n = h('span', 'cat c-' + k, label || catShort(k)); n.title = t('cat.' + k); return n; } + + // ---------------------------------------------------------------- help and glossary + // help.cat., help.metric., help.term. (+ ".do" = what to do) live in the central dictionary + var glossary = { + has: function (key) { var k = 'help.' + key; return t(k) !== k; }, + get: function (key) { var k = 'help.' + key, tx = t(k); if (tx === k) return null; var dk = k + '.do', d = t(dk); return { text: tx, action: d === dk ? '' : d }; } + }; + var helpPop = null, helpBtn = null, helpPinned = false; + function ensureHelpPop() { + if (!helpPop) { helpPop = h('div', 'help-pop'); helpPop.id = 'help-pop'; helpPop.setAttribute('role', 'tooltip'); helpPop.hidden = true; document.body.appendChild(helpPop); } + return helpPop; + } + function hideHelp() { if (helpPop) helpPop.hidden = true; helpBtn = null; helpPinned = false; } + function showHelp(btn, key) { + var g = glossary.get(key), pop = ensureHelpPop(); + if (!g) return; + clear(pop); + pop.appendChild(h('p', 'help-t', g.text)); + if (g.action) pop.appendChild(h('p', 'help-do', h('strong', null, t('help.do') + ': '), g.action)); + pop.hidden = false; helpBtn = btn; + var r = btn.getBoundingClientRect(), w = pop.offsetWidth, ph = pop.offsetHeight; + var left = Math.max(8, Math.min(r.left, window.innerWidth - w - 8)), top = r.bottom + 6; + if (top + ph > window.innerHeight - 8) top = Math.max(8, r.top - ph - 6); + pop.style.left = left + 'px'; pop.style.top = top + 'px'; + } + // append an accessible "?" to a node: focusable, aria-describedby, popover with short text + what to do + function help(node, key) { + if (!node || !glossary.has(key)) return null; + var b = el('button', { type: 'button', class: 'help-btn', 'aria-label': t('help.label'), 'aria-describedby': 'help-pop' }, '?'); + ensureHelpPop(); + b.addEventListener('mouseenter', function () { if (!helpPinned) showHelp(b, key); }); + b.addEventListener('focus', function () { if (!helpPinned) showHelp(b, key); }); + b.addEventListener('mouseleave', function () { if (!helpPinned) hideHelp(); }); + b.addEventListener('blur', function () { if (!helpPinned) hideHelp(); }); + b.addEventListener('click', function (e) { e.stopPropagation(); if (helpBtn === b && helpPinned) hideHelp(); else { showHelp(b, key); helpPinned = true; } }); + node.appendChild(b); + return b; + } + // ranked list with a proportional bar; rows: [{key, n, label?}] function bars(rows, opts) { @@ -628,6 +694,8 @@ }); th.appendChild(b); } else th.textContent = colLabel(x.k); + var hk = { score: 'term.score', level: 'term.level', cats: 'term.categories', origin: 'term.net_type' }[x.k]; + if (hk) help(th, hk); tr.appendChild(th); }); thead.appendChild(tr); @@ -665,7 +733,7 @@ var chips = h('span'); var kinds = Object.keys(x.counts || {}).filter(function (k) { return k !== 'ok' && k !== 'ssh-ok' && KNOWN_CATS.indexOf(k) >= 0; }) .sort(function (a, b) { return x.counts[b] - x.counts[a]; }); - kinds.slice(0, 2).forEach(function (k) { chips.appendChild(h('span', 'chip', t('cat.' + k) + ' ' + nf(x.counts[k]))); }); + kinds.slice(0, 2).forEach(function (k) { { var cp = h('span', 'chip', catShort(k) + ' ' + nf(x.counts[k])); cp.title = t('cat.' + k); chips.appendChild(cp); } }); if (kinds.length > 2) chips.appendChild(h('span', 'chip', '+' + (kinds.length - 2))); cell('cats', chips); break; } @@ -822,7 +890,7 @@ bar.appendChild(fill); [[1, 'drawer.cut.susp'], [5, 'drawer.cut.host']].forEach(function (c) { var tk = h('b', 'tick'); tk.style.left = c[0] + '%'; tk.title = t(c[1]); bar.appendChild(tk); }); var verdict = h('section', 'ip-verdict lv-' + pick(KNOWN_LEVELS, level, 'low'), - h('div', 'iv-top', levelBadge(level), h('span', 'iv-score num', nf(score)), h('span', 'iv-max', '/ 1000')), bar, + h('div', 'iv-top', (function () { var w = h('span', 'iv-lv', levelBadge(level)); help(w, 'term.level'); return w; })(), h('span', 'iv-score num', nf(score)), h('span', 'iv-max', '/ 1000'), (function () { var w = h('span', 'iv-h'); help(w, 'term.score'); return w; })()), bar, h('p', 'note iv-cuts', t('drawer.cuts')), origin ? h('p', 'iv-origin', origin) : null, first && last ? h('p', 'note', t('drawer.active', { v: spanText(last - first) }) + ' \u00b7 ' + t('detail.last') + ': ' + ago(last)) : null); @@ -836,7 +904,7 @@ var days = typeof tm.active_days === 'number' ? nf(tm.active_days) : '\u2014'; var nbans = (d.bans && d.bans.length) || (d.jails || []).length; box.appendChild(h('div', 'drawer-metrics', - metric(t('drawer.m.events'), nf(evs)), metric(t('drawer.m.days'), days), metric(t('drawer.m.hosts'), nf((d.hosts || []).length)), metric(t('drawer.m.bans'), nf(nbans), { hint: t('drawer.m.bans') }))); + metric(t('drawer.m.events'), nf(evs)), metric(t('drawer.m.days'), days), metric(t('drawer.m.hosts'), nf((d.hosts || []).length)), metric(t('drawer.m.bans'), nf(nbans), { hint: t('drawer.m.bans'), help: 'cat.ban' }))); var tstep = (d.timeline && d.timeline.step) || 3600, all = numbersOf(d.timeline), keep = Math.round(7 * 86400 / tstep), vals = all.slice(-keep); if (vals.length > 1 && Math.max.apply(null, vals) > 0) { var t0 = ((d.timeline && d.timeline.start) || 0) + (all.length - vals.length) * tstep; @@ -845,10 +913,11 @@ if (Array.isArray(d.techniques) && d.techniques.length) { var chips = h('div', 'chip-group'); d.techniques.slice(0, 8).forEach(function (x) { chips.appendChild(h('span', 'chip-mitre', (x.id ? x.id + ' ' : '') + (x.name || '') + (x.n ? ' \u00d7' + nf(x.n) : ''))); }); - box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.techniques')), chips)); + var th3 = h('h3', null, t('drawer.techniques')); help(th3, 'term.mitre'); + box.appendChild(h('section', 'drawer-sec', th3, chips)); } var kinds = Object.keys(d.counts || {}).filter(function (c) { return KNOWN_CATS.indexOf(c) >= 0 && c !== 'ok' && c !== 'ssh-ok'; }); - if (kinds.length) { var cc = h('div', 'chip-group'); kinds.forEach(function (c) { cc.appendChild(h('span', 'chip', (c === 'ban' ? t('drawer.banEvents') : t('cat.' + c)) + ' ' + nf(d.counts[c]))); }); box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.categories')), cc)); } + if (kinds.length) { var cc = h('div', 'chip-group'); kinds.forEach(function (c) { cc.appendChild(h('span', 'chip', (c === 'ban' ? t('drawer.banEvents') : t('cat.' + c)) + ' ' + nf(d.counts[c]))); }); var ch3 = h('h3', null, t('drawer.categories')); help(ch3, 'term.categories'); box.appendChild(h('section', 'drawer-sec', ch3, cc)); } if (Array.isArray(v.reasons) && v.reasons.length) { var ul = h('ul'); v.reasons.slice(0, 3).forEach(function (r) { ul.appendChild(h('li', null, reasonText(r))); }); box.appendChild(h('section', 'drawer-sec', h('h3', null, t('drawer.reasons')), ul)); @@ -874,8 +943,203 @@ setTimeout(function () { if (n.parentNode) n.parentNode.removeChild(n); }, 2600); } + // ---------------------------------------------------------------- charts library (own SVG, no dependencies) + var VIZ = ['--viz-1', '--viz-2', '--viz-3', '--viz-4', '--viz-5', '--viz-6', '--viz-7', '--viz-8']; + function vizColor(i, colors) { return 'var(' + ((colors && colors[i % colors.length]) || VIZ[i % VIZ.length]) + ')'; } + // run fn(width) now and whenever the box is resized + function watch(node, fn) { + if (!window.ResizeObserver) { fn(node.clientWidth || 320); return; } + var last = 0; + new ResizeObserver(function (es) { var w = Math.round(es[0].contentRect.width); if (w > 0 && w !== last) { last = w; fn(w); } }).observe(node); + } + // screen-reader alternative: a real table with the same numbers + function srTable(caption, head, rows) { + return h('table', 'sr-only', h('caption', null, caption || ''), h('thead', null, h('tr', null, head.map(function (x) { return el('th', { scope: 'col' }, x); }))), + h('tbody', null, rows.map(function (r) { return h('tr', null, r.map(function (c) { return h('td', null, String(c)); })); }))); + } + function sumOf(a) { var s = 0; a.forEach(function (x) { s += x; }); return s; } + function legendList(items, colors, fmt, onHover) { + var ul = h('ul', 'vz-legend'); + items.forEach(function (d, i) { + var li = h('li', null, h('span', 'sw'), h('span', 'vz-l', d.label), h('span', 'vz-v num', fmt(d))); + li.firstChild.style.background = vizColor(i, colors); + if (onHover) { li.addEventListener('mouseenter', function () { onHover(i); }); li.addEventListener('mouseleave', function () { onHover(-1); }); } + ul.appendChild(li); + }); + return ul; + } + // donut(data [{key,label,value}], {title, colors:[token], centerLabel, format}) + function donut(data, o) { + o = o || {}; + data = (data || []).filter(function (x) { return x && x.value > 0; }); + var total = sumOf(data.map(function (x) { return x.value; })), fmt = o.format || nf; + if (!total) return empty(t('charts.empty')); + var R = 70, C = 2 * Math.PI * R, acc = 0, segs = []; + var svg = svgEl('svg', { viewBox: '0 0 200 200', 'class': 'vz-donut', role: 'img', 'aria-label': o.title || '' }); + var cv = svgEl('text', { x: 100, y: 102, 'text-anchor': 'middle', 'class': 'vz-c-v' }), cl = svgEl('text', { x: 100, y: 124, 'text-anchor': 'middle', 'class': 'vz-c-l' }); + function center(i) { + if (i < 0) { cv.textContent = fmt(total); cl.textContent = o.centerLabel || t('charts.total'); return; } + cv.textContent = pct(data[i].value, total); cl.textContent = data[i].label; + } + data.forEach(function (d, i) { + var len = d.value / total * C, vis = Math.max(0.5, len - (data.length > 1 ? 1.5 : 0)); + var c = svgEl('circle', { cx: 100, cy: 100, r: R, fill: 'none', 'stroke-width': 26, 'stroke-dasharray': vis + ' ' + (C - vis), 'stroke-dashoffset': -acc, transform: 'rotate(-90 100 100)', 'class': 'vz-seg', tabindex: 0, 'aria-label': d.label + ': ' + fmt(d.value) + ' (' + pct(d.value, total) + ')' }); + c.style.stroke = vizColor(i, o.colors); + c.addEventListener('mouseenter', function () { center(i); }); c.addEventListener('focus', function () { center(i); }); + c.addEventListener('mouseleave', function () { center(-1); }); c.addEventListener('blur', function () { center(-1); }); + segs.push(c); svg.appendChild(c); acc += len; + }); + svg.appendChild(cv); svg.appendChild(cl); center(-1); + var legend = legendList(data, o.colors, function (d) { return fmt(d.value) + ' · ' + pct(d.value, total); }, function (i) { center(i); segs.forEach(function (s, k) { s.classList.toggle('dim', i >= 0 && k !== i); }); }); + return h('div', 'vz vz-donut-wrap', h('div', 'vz-donut-svg', svg), legend, srTable(o.title, [t('charts.item'), t('charts.value')], data.map(function (d) { return [d.label, fmt(d.value) + ' (' + pct(d.value, total) + ')']; }))); + } + // radar(axes [{key,label}], series [{label, values[]}], {max, format, colors}) + function radar(axes, series, o) { + o = o || {}; + var n = axes.length; + series = (series || []).filter(function (s) { return s && s.values && s.values.length; }); + var mx = o.max || Math.max.apply(null, [0].concat.apply([], series.map(function (s) { return s.values; }))); + if (n < 3 || !series.length || !(mx > 0)) return empty(t('charts.empty')); + var fmt = o.format || nf, W = 360, H = 290, cx = 180, cy = 145, R = 82; + var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, 'class': 'vz-radar', role: 'img', 'aria-label': o.title || '' }); + function pt(i, f) { var a = -Math.PI / 2 + i * 2 * Math.PI / n; return [cx + Math.cos(a) * R * f, cy + Math.sin(a) * R * f, Math.cos(a), Math.sin(a)]; } + [.25, .5, .75, 1].forEach(function (f) { + svg.appendChild(svgEl('polygon', { points: axes.map(function (_, i) { var p = pt(i, f); return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '), 'class': 'vz-ring' })); + }); + var rl = svgEl('text', { x: cx + 4, y: cy - R + 12, 'class': 'axis' }); rl.textContent = fmt(mx); svg.appendChild(rl); + axes.forEach(function (a, i) { + var p = pt(i, 1), q = pt(i, 1.14); + svg.appendChild(svgEl('line', { x1: cx, y1: cy, x2: p[0], y2: p[1], 'class': 'gridline' })); + var tx = svgEl('text', { x: q[0], y: q[1] + 4, 'text-anchor': q[2] > .3 ? 'start' : q[2] < -.3 ? 'end' : 'middle', 'class': 'vz-axl' }); + tx.textContent = a.label; svg.appendChild(tx); + }); + series.forEach(function (s, k) { + var col = vizColor(k, o.colors); + var poly = svgEl('polygon', { points: axes.map(function (_, i) { var p = pt(i, Math.min(1, (s.values[i] || 0) / mx)); return p[0].toFixed(1) + ',' + p[1].toFixed(1); }).join(' '), 'class': 'vz-rs' }); + poly.style.stroke = col; poly.style.fill = col; svg.appendChild(poly); + axes.forEach(function (a, i) { + var p = pt(i, Math.min(1, (s.values[i] || 0) / mx)), c = svgEl('circle', { cx: p[0], cy: p[1], r: 3, 'class': 'vz-dot', tabindex: 0, 'aria-label': s.label + ', ' + a.label + ': ' + fmt(s.values[i] || 0) }); + c.style.fill = col; var ti = svgEl('title', {}); ti.textContent = s.label + ' · ' + a.label + ': ' + fmt(s.values[i] || 0); c.appendChild(ti); svg.appendChild(c); + }); + }); + var legend = legendList(series.map(function (s) { return { label: s.label }; }), o.colors, function () { return ''; }); + return h('div', 'vz vz-radar-wrap', svg, legend, srTable(o.title, [t('charts.item')].concat(series.map(function (s) { return s.label; })), axes.map(function (a, i) { return [a.label].concat(series.map(function (s) { return fmt(s.values[i] || 0); })); }))); + } + // stackedArea(series [{key,label,values[]}], step seconds, {start, colors, title}) + function stackedArea(series, step, o) { + o = o || {}; + series = (series || []).filter(function (s) { return s && s.values && s.values.length; }); + var n = series.length ? series[0].values.length : 0, tot = [], mx = 0, i; + if (n < 2) return empty(t('charts.empty')); + for (i = 0; i < n; i++) { var v = 0; series.forEach(function (s) { v += s.values[i] || 0; }); tot.push(v); if (v > mx) mx = v; } + var wrap = h('div', 'chart-wrap vz-area'), box = h('div', 'vz'); + var colors = o.colors; + function draw(Wpx) { + clear(wrap); + var W = Math.max(280, Wpx), H = 220, L = 40, R = 6, Tp = 8, B = 22, top = niceMax(mx), ph = H - Tp - B, dx = (W - L - R) / (n - 1); + var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), k; + for (k = 0; k <= 4; k++) { + var y = Tp + ph - ph * k / 4; + svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' })); + var lb = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' }); lb.textContent = top >= 10000 ? nfCompact(Math.round(top * k / 4)) : nf(Math.round(top * k / 4)); svg.appendChild(lb); + } + var nt = W < 520 ? 3 : 5, longSpan = step * n > 2 * 86400; + for (k = 0; k < nt; k++) { + var ix = Math.round((n - 1) * k / (nt - 1)), xl = svgEl('text', { x: L + dx * ix, y: H - 6, 'text-anchor': k === 0 ? 'start' : k === nt - 1 ? 'end' : 'middle', 'class': 'axis' }); + xl.textContent = tickLabel((o.start || 0) + ix * step, longSpan); svg.appendChild(xl); + } + var base = []; for (i = 0; i < n; i++) base.push(0); + series.forEach(function (s, si) { + var up = [], down = []; + for (i = 0; i < n; i++) { var lo = base[i], hi = lo + (s.values[i] || 0); up.push((L + dx * i).toFixed(1) + ',' + (Tp + ph - hi / top * ph).toFixed(1)); down.unshift((L + dx * i).toFixed(1) + ',' + (Tp + ph - lo / top * ph).toFixed(1)); base[i] = hi; } + var p = svgEl('polygon', { points: up.concat(down).join(' '), 'class': 'vz-area-s' }); p.style.fill = vizColor(si, colors); svg.appendChild(p); + }); + var tip = h('div', 'tip'); tip.hidden = true; + var guide = svgEl('line', { y1: Tp, y2: Tp + ph, 'class': 'vz-guide' }); guide.style.display = 'none'; svg.appendChild(guide); + var hit = svgEl('rect', { x: L, y: Tp, width: W - L - R, height: ph, fill: 'transparent' }); + function at(ev) { + var r = svg.getBoundingClientRect(), px = (ev.clientX - r.left) * W / r.width, ix = Math.max(0, Math.min(n - 1, Math.round((px - L) / dx))); + clear(tip); tip.appendChild(h('strong', null, new Date(((o.start || 0) + ix * step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }))); + series.forEach(function (s) { tip.appendChild(h('div', null, h('span', null, s.label), h('span', 'num', nf(s.values[ix] || 0)))); }); + tip.hidden = false; tip.style.left = Math.max(0, Math.min(L + dx * ix + 12, W - 170)) + 'px'; tip.style.top = '4px'; + guide.setAttribute('x1', L + dx * ix); guide.setAttribute('x2', L + dx * ix); guide.style.display = ''; + } + hit.addEventListener('mousemove', at); hit.addEventListener('click', at); + hit.addEventListener('mouseleave', function () { tip.hidden = true; guide.style.display = 'none'; }); + svg.appendChild(hit); wrap.appendChild(svg); wrap.appendChild(tip); + } + box.appendChild(wrap); + box.appendChild(legendList(series.map(function (s) { return { label: s.label }; }), colors, function (d, j) { return ''; })); + box.appendChild(srTable(o.title, [t('charts.item'), t('charts.value')], series.map(function (s) { return [s.label, nf(sumOf(s.values))]; }))); + watch(wrap, draw); + return box; + } + // bars(rows [{key,label,value,color?,parts?:[{label,value,color?}]}], {horizontal (default true), stacked, format, colors}) + function barChart(rows, o) { + o = o || {}; + rows = (rows || []).filter(function (r) { return r; }); + var fmt = o.format || nf, hor = o.horizontal !== false; + function rowTotal(r) { return r.parts ? sumOf(r.parts.map(function (p) { return p.value; })) : r.value; } + var mx = Math.max.apply(null, [0].concat(rows.map(rowTotal))); + if (!mx) return empty(t('charts.empty')); + var box = h('div', 'vz vz-bars' + (hor ? '' : ' vz-cols')); + rows.forEach(function (r, i) { + var tot = rowTotal(r), track = h('div', 'vz-track'); + var parts = r.parts && o.stacked !== false ? r.parts : [{ label: r.label, value: r.value, color: r.color }]; + parts.forEach(function (p, j) { + var seg = h('i'); seg.style[hor ? 'width' : 'height'] = Math.max(p.value ? 1 : 0, p.value / mx * 100) + '%'; + seg.style.background = p.color ? 'var(' + p.color + ')' : vizColor(r.parts ? j : (r.color ? 0 : i), r.color ? [r.color] : o.colors); + seg.title = p.label + ': ' + fmt(p.value); track.appendChild(seg); + }); + box.appendChild(h('div', 'vz-row', h('span', 'vz-l', r.label), track, h('span', 'vz-v num', fmt(tot)))); + }); + box.appendChild(srTable(o.title, [t('charts.item'), t('charts.value')], rows.map(function (r) { return [r.label, fmt(rowTotal(r))]; }))); + return box; + } + // heatmap(matrix [row][col] numbers, xLabels, yLabels, {format, title}); cell colour from --seq-1..5 + function heatmap(matrix, xl, yl, o) { + o = o || {}; + var mx = 0; (matrix || []).forEach(function (r) { r.forEach(function (v) { if (v > mx) mx = v; }); }); + if (!mx) return empty(t('charts.empty')); + var fmt = o.format || nf, wrap = h('div', 'vz vz-heat'); + function draw(Wpx) { + clear(wrap); + var ny = matrix.length, nx = matrix[0].length, LW = 56, W = Math.max(240, Wpx), cw = (W - LW) / nx, ch = Math.min(26, Math.max(12, cw)), H = ny * ch + 22; + var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': o.title || '' }), step = Math.ceil(26 / cw); + matrix.forEach(function (row, y) { + var yt = svgEl('text', { x: LW - 6, y: y * ch + ch / 2 + 4, 'text-anchor': 'end', 'class': 'axis' }); yt.textContent = yl[y]; svg.appendChild(yt); + row.forEach(function (v, x) { + var lvl = v ? Math.min(5, 1 + Math.floor(v / mx * 4.999)) : 0; + var r = svgEl('rect', { x: LW + x * cw + 1, y: y * ch + 1, width: Math.max(1, cw - 2), height: ch - 2, rx: 2, 'class': 'vz-cell s' + lvl, tabindex: 0, 'aria-label': yl[y] + ' ' + xl[x] + ': ' + fmt(v) }); + var ti = svgEl('title', {}); ti.textContent = yl[y] + ' ' + xl[x] + ': ' + fmt(v); r.appendChild(ti); svg.appendChild(r); + }); + }); + for (var x = 0; x < nx; x += step) { var xt = svgEl('text', { x: LW + x * cw + cw / 2, y: ny * ch + 15, 'text-anchor': 'middle', 'class': 'axis' }); xt.textContent = xl[x]; svg.appendChild(xt); } + wrap.appendChild(svg); + } + var box = h('div', null, wrap, srTable(o.title, [''].concat(xl), matrix.map(function (r, y) { return [yl[y]].concat(r.map(fmt)); }))); + watch(wrap, draw); + return box; + } + // gauge(value, max, thresholds [{at, tone: ok|warn|danger|info}], {label, format}) + function gauge(value, max, thr, o) { + o = o || {}; + max = max > 0 ? max : 1; + var fmt = o.format || nf, v = Math.max(0, Math.min(max, Number(value) || 0)); + thr = thr && thr.length ? thr : [{ at: 0, tone: 'ok' }, { at: max * .5, tone: 'warn' }, { at: max * .8, tone: 'danger' }]; + var tone = 'ok'; thr.forEach(function (x) { if (v >= x.at) tone = pick(['ok', 'warn', 'danger', 'info'], x.tone, 'ok'); }); + var d = 'M20 100 A80 80 0 0 1 180 100'; + var svg = svgEl('svg', { viewBox: '0 0 200 120', 'class': 'vz-gauge', role: 'img', 'aria-label': (o.label || '') + ' ' + fmt(v) + ' / ' + fmt(max) }); + svg.appendChild(svgEl('path', { d: d, pathLength: 100, 'class': 'vz-g-bg' })); + svg.appendChild(svgEl('path', { d: d, pathLength: 100, 'class': 'vz-g-fg tone-' + tone, 'stroke-dasharray': (v / max * 100) + ' 100' })); + var tv = svgEl('text', { x: 100, y: 92, 'text-anchor': 'middle', 'class': 'vz-c-v' }); tv.textContent = fmt(v); svg.appendChild(tv); + var lo = svgEl('text', { x: 20, y: 116, 'text-anchor': 'middle', 'class': 'axis' }); lo.textContent = '0'; svg.appendChild(lo); + var hi = svgEl('text', { x: 180, y: 116, 'text-anchor': 'middle', 'class': 'axis' }); hi.textContent = fmt(max); svg.appendChild(hi); + return h('div', 'vz vz-gauge-wrap', svg, o.label ? h('div', 'vz-c-l', o.label) : null); + } + var charts = { donut: donut, radar: radar, stackedArea: stackedArea, bars: barChart, heatmap: heatmap, sparkline: sparkline, gauge: gauge }; + // ---------------------------------------------------------------- page registry - var ORDER = ['overview', 'threats', 'geo', 'live', 'replay', 'traffic', 'ips', 'sources']; var pages = {}; var current = null; // { page, el } function registerPage(p) { @@ -883,9 +1147,27 @@ pages[p.id] = p; if (booted) { renderNav(); route(); } } + // rail groups; ids not listed go to the end of their group (page.group, else Analyze) + var GROUPS = [ + ['monitor', ['overview', 'live', 'slo']], + ['investigate', ['ips', 'sessions', 'campaigns', 'replay', 'search']], + ['analyze', ['threats', 'mitre', 'geo', 'evolution', 'concentration', 'survival', 'traffic', 'errors', 'protocol']], + ['operate', ['defense', 'sources', 'integrity']], + ['reports', ['reports']] + ]; + function groupOf(p) { + if (p.group) for (var i = 0; i < GROUPS.length; i++) if (GROUPS[i][0] === p.group) return p.group; + for (var j = 0; j < GROUPS.length; j++) if (GROUPS[j][1].indexOf(p.id) >= 0) return GROUPS[j][0]; + return 'analyze'; + } function orderedPages() { - var ids = Object.keys(pages); - return ORDER.filter(function (id) { return pages[id]; }).concat(ids.filter(function (id) { return ORDER.indexOf(id) < 0; }).sort()).map(function (id) { return pages[id]; }).filter(function (p) { return p.nav !== false && p.id !== 'ip'; }); + var visible = Object.keys(pages).map(function (id) { return pages[id]; }).filter(function (p) { return p.nav !== false && p.id !== 'ip'; }), out = []; + GROUPS.forEach(function (g) { + var mine = visible.filter(function (p) { return groupOf(p) === g[0]; }); + g[1].forEach(function (id) { mine.filter(function (p) { return p.id === id; }).forEach(function (p) { out.push(p); }); }); + mine.filter(function (p) { return g[1].indexOf(p.id) < 0; }).sort(function (a, b) { return a.id < b.id ? -1 : 1; }).forEach(function (p) { out.push(p); }); + }); + return out; } function sp(n, node) { node.classList.add('span-' + n); return node; } function grid12() { return h('div', 'grid-12'); } @@ -937,7 +1219,7 @@ function bucketNote(step) { return step ? t('timeline.bucket', { n: nf(Math.max(1, Math.round(step / 60))) }) : ''; } function timelinePanel() { var wrap = h('div', 'chart-wrap'), legend = h('div', 'legend'), note = h('span', 'note bucket-note'); - var node = panel({ title: t('timeline.title'), hint: t('timeline.hint'), variant: 'chart', loading: true }, wrap, legend); + var node = panel({ title: t('timeline.title'), hint: t('timeline.hint'), variant: 'chart', loading: true, help: 'metric.attacks_per_hour_24h' }, wrap, legend); var data = null; function renderLegend() { clear(legend); @@ -945,7 +1227,9 @@ var b = el('button', { type: 'button', 'aria-pressed': state.hidden[c] ? 'false' : 'true' }, h('span', 'sw b-' + c), h('span', null, t('cat.' + c))); b.addEventListener('click', function () { state.hidden[c] = !state.hidden[c]; renderLegend(); draw(); }); legend.appendChild(b); + b.title = t('cat.' + c); }); + help(legend, 'term.categories'); legend.appendChild(note); } function draw() { @@ -1003,7 +1287,7 @@ clear(box); keys.forEach(function (k) { var x = m[k]; - box.appendChild(metric(metricLabel(k), metricValue(k, x.value), { delta: typeof x.delta_pct === 'number' ? x.delta_pct : undefined, goodUp: !!GOOD_UP[k], spark: Array.isArray(x.spark) ? x.spark : null, sub: metricSub(k, x) })); + box.appendChild(metric(metricLabel(k), metricValue(k, x.value), { delta: typeof x.delta_pct === 'number' ? x.delta_pct : undefined, goodUp: !!GOOD_UP[k], spark: Array.isArray(x.spark) ? x.spark : null, sub: metricSub(k, x), help: 'metric.' + k })); }); return true; } @@ -1012,12 +1296,12 @@ var T = s.totals, hosts = s.hosts || [], on = hosts.filter(function (x) { return x.online; }).length; var range = rangeLower(); clear(box); - box.appendChild(stat(t('kpi.requests'), nf(T.requests), hosts.length > 1 ? t('kpi.sub.hosts', { n: on, m: hosts.length }) : t('kpi.sub.range', { range: range }))); - box.appendChild(stat(t('kpi.malicious'), nf(T.malicious), t('kpi.sub.malicious'), T.malicious > 0 ? 'warn' : 'neutral')); - box.appendChild(stat(t('kpi.hostile'), nf(T.hostile_ips), t('kpi.sub.share', { p: pct(T.hostile_ips, T.unique_ips), n: nf(T.unique_ips) }), T.hostile_ips > 0 ? 'danger' : 'neutral')); - box.appendChild(stat(t('kpi.suspicious'), nf(T.suspicious_ips), t('kpi.sub.share', { p: pct(T.suspicious_ips, T.unique_ips), n: nf(T.unique_ips) }), T.suspicious_ips > 0 ? 'warn' : 'neutral')); - box.appendChild(stat(t('kpi.bans'), nf(T.active_bans), t('kpi.sub.bans'))); - box.appendChild(stat(t('kpi.ips'), nf(T.unique_ips), t('kpi.sub.range', { range: range }))); + box.appendChild(stat(t('kpi.requests'), nf(T.requests), hosts.length > 1 ? t('kpi.sub.hosts', { n: on, m: hosts.length }) : t('kpi.sub.range', { range: range }), 'neutral', null, 'metric.requests')); + box.appendChild(stat(t('kpi.malicious'), nf(T.malicious), t('kpi.sub.malicious'), T.malicious > 0 ? 'warn' : 'neutral', null, 'metric.malicious')); + box.appendChild(stat(t('kpi.hostile'), nf(T.hostile_ips), t('kpi.sub.share', { p: pct(T.hostile_ips, T.unique_ips), n: nf(T.unique_ips) }), T.hostile_ips > 0 ? 'danger' : 'neutral', null, 'term.level')); + box.appendChild(stat(t('kpi.suspicious'), nf(T.suspicious_ips), t('kpi.sub.share', { p: pct(T.suspicious_ips, T.unique_ips), n: nf(T.unique_ips) }), T.suspicious_ips > 0 ? 'warn' : 'neutral', null, 'term.level')); + box.appendChild(stat(t('kpi.bans'), nf(T.active_bans), t('kpi.sub.bans'), 'neutral', null, 'cat.ban')); + box.appendChild(stat(t('kpi.ips'), nf(T.unique_ips), t('kpi.sub.range', { range: range }), 'neutral', null, 'metric.unique_ips')); } function overviewLead(s) { var T = s.totals; @@ -1043,17 +1327,19 @@ } // ---------------------------------------------------------------- page: overview + var RADAR_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe']; var pOverview = corePage({ id: 'overview', icon: ICONS.overview, titleKey: 'nav.overview', build: function (root) { var v = {}, g = grid12(); v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6); v.timeline = timelinePanel(); + v.radar = panel({ title: t('ov.radar'), hint: t('ov.radar.hint'), loading: true, help: 'term.attack_profile' }); v.countries = panel({ title: t('ov.countries'), hint: t('ov.countries.hint'), variant: 'list', loading: true, footer: el('a', { href: '#/geo' }, t('ov.all')) }); v.topips = panel({ title: t('ov.topips'), hint: t('ov.topips.hint'), variant: 'list', loading: true, footer: el('a', { href: '#/ips' }, t('ov.all')) }); v.feedList = feedList(30); v.feed = panel({ title: t('ov.feed'), hint: t('ov.feed.hint'), variant: 'list', footer: el('a', { href: '#/live' }, t('ov.all')) }, v.feedList.node); - g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline.node)); + g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(8, v.timeline.node)); g.appendChild(sp(4, v.radar)); g.appendChild(sp(4, v.countries)); g.appendChild(sp(4, v.topips)); g.appendChild(sp(4, v.feed)); root.appendChild(g); v.offResize = onResize(function () { v.timeline.draw(); }); @@ -1061,9 +1347,21 @@ v.feedList.render(); return v; }, - load: function (c) { return getSummary(c).then(function (s) { return getMetrics(c).then(function (m) { return Object.assign({}, s, { metrics: m }); }); }); }, + load: function (c) { + return getSummary(c).then(function (s) { + var hosts = (s.hosts || []).filter(function (x) { return x.online !== false; }).slice(0, 4); + var rq = c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range }; + var jobs = hosts.length > 1 ? hosts.map(function (x) { return api('/api/v1/summary', Object.assign({ host: x.name }, rq)).then(function (r) { return { label: x.name, s: r }; }, function () { return null; }); }) : [Promise.resolve({ label: (hosts[0] && hosts[0].name) || t('host.all'), s: s })]; + return Promise.all(jobs).then(function (rs) { return getMetrics(c).then(function (m) { return Object.assign({}, s, { metrics: m, radar: rs.filter(Boolean) }); }); }); + }); + }, render: function (v, s) { clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel'); v.lead.appendChild(overviewLead(s)); + ready(v.radar); clear(v.radar.body); + v.radar.body.appendChild(charts.radar(RADAR_CATS.map(function (c) { return { key: c, label: catShort(c) }; }), (s.radar || []).map(function (r) { + var vals = RADAR_CATS.map(function (c) { var n = 0; ((r.s.timeline.series || {})[c] || []).forEach(function (x) { n += x; }); return n; }), tot = sumOf(vals) || 1; + return { label: r.label, values: vals.map(function (x) { return Math.round(x / tot * 1000) / 10; }) }; + }), { title: t('ov.radar'), format: function (x) { return nf(x) + '%' } })); kpiRow(s, v.kpis, s.metrics, 'overview'); v.timeline.set(s); clear(v.countries.body); v.countries.body.appendChild(bars(s.countries, { label: function (r) { return countryLabel(r.key); } })); @@ -1097,13 +1395,13 @@ v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6); v.mon = sp(12, h('p', 'note')); v.timeline = timelinePanel(); v.mapbox = mapBox(); - v.map = panel({ title: t('map.attacks'), hint: t('map.attacks.hint'), variant: 'map', loading: true }, v.mapbox); + v.map = panel({ title: t('map.attacks'), hint: t('map.attacks.hint'), variant: 'map', loading: true, help: 'term.categories' }, v.mapbox); v.tbl = ipTable(false); - v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), actions: el('a', { class: 'btn', href: '#/ips' }, t('ov.all')) }, v.tbl.node); + v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), help: 'term.score', actions: el('a', { class: 'btn', href: '#/ips' }, t('ov.all')) }, v.tbl.node); v.feedList = feedList(100); v.feed = panel({ title: t('feed.title'), variant: 'list', footer: el('a', { href: '#/live' }, t('ov.all')) }, v.feedList.node); - v.paths = panel({ title: t('top.paths'), variant: 'list', loading: true }); v.domains = panel({ title: t('top.domains'), variant: 'list', loading: true }); - v.uas = panel({ title: t('top.uas'), variant: 'list', loading: true }); v.users = panel({ title: t('top.users'), variant: 'list', loading: true }); + v.paths = panel({ title: t('top.paths'), variant: 'list', loading: true, help: 'cat.scanner' }); v.domains = panel({ title: t('top.domains'), variant: 'list', loading: true, help: 'metric.requests' }); + v.uas = panel({ title: t('top.uas'), variant: 'list', loading: true, help: 'term.family' }); v.users = panel({ title: t('top.users'), variant: 'list', loading: true, help: 'cat.ssh-fail' }); g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(v.mon); g.appendChild(sp(12, v.timeline.node)); g.appendChild(sp(8, v.map)); g.appendChild(sp(4, v.feed)); g.appendChild(sp(12, v.ips)); [v.paths, v.domains, v.uas, v.users].forEach(function (x) { g.appendChild(sp(3, x)); }); @@ -1149,24 +1447,31 @@ sel.value = state.domain; if (sel.value !== state.domain) sel.value = 'all'; } + var CLIENT_COLORS = { desktop: '--viz-1', mobile: '--viz-6', tablet: '--viz-5', bot: '--viz-3', tool: '--viz-7', unknown: '--viz-8', misc: '--viz-2' }; + var CLIENT_ORDER = ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown', 'misc']; + var STATUS_TOKENS = ['--ok', '--info', '--warn', '--danger']; var pTraffic = corePage({ id: 'traffic', icon: ICONS.traffic, titleKey: 'nav.traffic', domain: true, build: function (root) { var v = {}, g = grid12(); v.lead = sp(12, h('div', 'skeleton lead-skel')); v.kpis = h('div', 'kpi-row'); skeletonCards(v.kpis, 6); - v.wrap = h('div', 'chart-wrap'); v.note = h('span', 'note bucket-note'); - v.legend = h('div', 'legend', h('span', 'li', h('span', 'sw b-treq'), t('traffic.requests')), h('span', 'li', h('span', 'sw b-tpages'), t('traffic.pages')), v.note); - v.timeline = panel({ title: t('traffic.timeline'), hint: t('traffic.timeline.hint'), variant: 'chart', loading: true }, v.wrap, v.legend); + v.wrap = h('div'); v.note = h('span', 'note bucket-note'); + v.timeline = panel({ title: t('traffic.timeline'), hint: t('traffic.area.hint'), variant: 'chart', loading: true, help: 'metric.pages' }, v.wrap, h('div', 'legend', v.note)); v.mapbox = mapBox(); v.map = panel({ title: t('map.visitors'), hint: t('map.visitors.hint'), variant: 'map', loading: true }, v.mapbox); - var ids = [['pages', 'traffic.topPages'], ['refs', 'traffic.referrers'], ['cities', 'traffic.cities'], ['browsers', 'traffic.browsers'], ['oses', 'traffic.oses'], ['devices', 'traffic.devices'], ['bots', 'traffic.bots'], ['status', 'traffic.status']]; + var ids = [['pages', 'traffic.topPages'], ['refs', 'traffic.referrers'], ['cities', 'traffic.cities'], ['bots', 'traffic.bots']]; ids.forEach(function (p) { v[p[0]] = panel({ title: t(p[1]), variant: 'list', loading: true }); }); + v.client = panel({ title: t('traffic.client'), hint: t('traffic.client.hint'), loading: true, help: 'term.client_type' }); + v.browsers = panel({ title: t('traffic.browsers'), hint: t('traffic.browsers.hint'), loading: true }); + v.oses = panel({ title: t('traffic.oses'), hint: t('traffic.oses.hint'), loading: true }); + v.status = panel({ title: t('traffic.status'), hint: t('traffic.status.hint'), loading: true, help: 'term.status_class' }); v.privacy = sp(12, h('p', 'note', t('traffic.privacy'))); g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline)); g.appendChild(sp(12, v.map)); - ['pages', 'refs', 'cities', 'browsers', 'oses', 'devices'].forEach(function (k) { g.appendChild(sp(4, v[k])); }); - g.appendChild(sp(6, v.bots)); g.appendChild(sp(6, v.status)); g.appendChild(v.privacy); + g.appendChild(sp(4, v.client)); g.appendChild(sp(4, v.browsers)); g.appendChild(sp(4, v.oses)); + g.appendChild(sp(6, v.status)); g.appendChild(sp(6, v.bots)); + ['pages', 'refs', 'cities'].forEach(function (k) { g.appendChild(sp(4, v[k])); }); + g.appendChild(v.privacy); root.appendChild(g); - v.offResize = onResize(function () { if (v.data) drawTraffic(v, v.data); }); return v; }, load: function (c) { return api('/api/v1/traffic', Object.assign({ host: c.host, domain: c.domain }, c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range })); }, @@ -1179,31 +1484,35 @@ ? lead(t('tr.lead.some', { n: nf(d.visitors), p: nf(d.pages) }), t('tr.lead.body', { r: nf(d.requests), b: nf(d.bots), a: nf(Math.round(d.p50_ms)), c: nf(Math.round(d.p95_ms)) }), 'ok') : lead(t('tr.lead.none'), t('tr.lead.noneBody'), 'neutral')); clear(v.kpis); - v.kpis.appendChild(stat(t('traffic.requests'), nf(d.requests), t('traffic.sub.requests'))); - v.kpis.appendChild(stat(t('traffic.pages'), nf(d.pages), t('traffic.sub.pages', { n: nf(d.requests) }))); - v.kpis.appendChild(stat(t('traffic.visitors'), nf(d.visitors), t('traffic.sub.visitors'))); - v.kpis.appendChild(stat(t('traffic.bytes'), fmtBytes(d.bytes), t('kpi.sub.range', { range: rangeLower() }))); - v.kpis.appendChild(stat(t('traffic.latency'), Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms) + ' ms', t('kpi.sub.range', { range: rangeLower() }))); - v.kpis.appendChild(stat(t('traffic.bots'), nf(d.bots), t('traffic.sub.bots', { n: nf(d.requests) }))); - ready(v.timeline); ready(v.map); - drawTraffic(v, d); + var rg = rangeLower(); + v.kpis.appendChild(stat(t('traffic.requests'), nf(d.requests), t('traffic.sub.requests'), 'neutral', null, 'metric.requests')); + v.kpis.appendChild(stat(t('traffic.pages'), nf(d.pages), t('traffic.sub.pages', { n: nf(d.requests) }), 'neutral', null, 'metric.pages')); + v.kpis.appendChild(stat(t('traffic.visitors'), nf(d.visitors), t('traffic.sub.visitors'), 'neutral', null, 'metric.visitors')); + v.kpis.appendChild(stat(t('traffic.bytes'), fmtBytes(d.bytes), t('kpi.sub.range', { range: rg }), 'neutral', null, 'metric.bytes')); + v.kpis.appendChild(stat(t('traffic.latency'), Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms), 'ms \u00b7 ' + t('kpi.sub.range', { range: rg }), 'neutral', null, 'metric.latency')); + v.kpis.appendChild(stat(t('traffic.bots'), nf(d.bots), t('traffic.sub.bots', { n: nf(d.requests) }), 'neutral', null, 'metric.bots')); + // time series: page views and the rest of the requests + var tl = d.timeline, pg = tl.pages || [], other = (tl.req || []).map(function (x, i) { return Math.max(0, x - (pg[i] || 0)); }); + ready(v.timeline); clear(v.wrap); + v.note.textContent = bucketNote(tl.step); + v.wrap.appendChild(charts.stackedArea([{ key: 'pages', label: t('traffic.pages'), values: pg }, { key: 'other', label: t('traffic.otherReq'), values: other }], tl.step, { start: tl.start, colors: ['--accent', '--viz-8'], title: t('traffic.timeline') })); + ready(v.map); renderMap(v.mapbox, d.countries, true, t('map.visitors')); function fill(key, rows, mono) { clear(v[key].body); v[key].body.appendChild(bars(rows, { mono: mono })); } - fill('pages', d.top_pages, true); fill('refs', d.referrers, true); fill('cities', d.cities, false); - fill('browsers', d.browsers, false); fill('oses', d.oses, false); - fill('devices', (d.devices || []).map(function (x) { return { key: t('device.' + pick(['desktop', 'mobile', 'tablet', 'bot', 'tool'], x.key, 'unknown')), n: x.n }; }), false); - fill('bots', d.bot_names, false); - fill('status', ['2xx', '3xx', '4xx', '5xx'].map(function (k, i) { return { key: k, n: d.status[i] }; }).filter(function (x) { return x.n > 0; }), true); + fill('pages', d.top_pages, true); fill('refs', d.referrers, true); fill('cities', d.cities, false); fill('bots', d.bot_names, false); + // client type: devices as reported, plus bots when the devices list has no bot entry + var dev = (d.devices || []).map(function (x) { return { k: pick(CLIENT_ORDER, x.key, 'misc'), n: x.n }; }); + dev.sort(function (a, b) { return CLIENT_ORDER.indexOf(a.k) - CLIENT_ORDER.indexOf(b.k); }); + function donutOf(box, data, colors, title) { ready(box); clear(box.body); box.body.appendChild(charts.donut(data, { title: title, colors: colors })); } + donutOf(v.client, dev.map(function (x) { return { key: x.k, label: t('device.' + x.k), value: x.n }; }), dev.map(function (x) { return CLIENT_COLORS[x.k]; }), t('traffic.client')); + donutOf(v.browsers, (d.browsers || []).map(function (x) { return { key: x.key, label: x.key, value: x.n }; }), null, t('traffic.browsers')); + donutOf(v.oses, (d.oses || []).map(function (x) { return { key: x.key, label: x.key, value: x.n }; }), null, t('traffic.oses')); + var cls = ['2xx', '3xx', '4xx', '5xx']; + ready(v.status); clear(v.status.body); + v.status.body.appendChild(charts.bars(cls.map(function (k, i) { return { key: k, label: t('traffic.status.' + k), value: (d.status || [])[i] || 0, color: STATUS_TOKENS[i] }; }), { title: t('traffic.status') })); }, - dispose: function (v) { v.offResize(); } + dispose: function () { } }); - function drawTraffic(v, d) { - var tl = d.timeline; - v.note.textContent = bucketNote(tl.step); - chart(v.wrap, { start: tl.start, step: tl.step, stacked: false, aria: t('traffic.timeline'), layers: [ - { cls: 'b-treq', label: t('traffic.requests'), vals: tl.req }, { cls: 'b-tpages', label: t('traffic.pages'), vals: tl.pages } - ] }); - } // ---------------------------------------------------------------- page: ips var pIPs = corePage({ @@ -1213,7 +1522,7 @@ v.lead = sp(12, h('div')); v.tbl = ipTable(true); v.tbl.onTotal(function (n) { setSliceNote(pl('slice.ips', n, { n: nf(n) })); }); - v.ips = panel({ title: t('ips.title'), hint: t('ips.hint') }, v.tbl.node); + v.ips = panel({ title: t('ips.title'), hint: t('ips.hint'), help: 'term.score' }, v.tbl.node); g.appendChild(v.lead); g.appendChild(sp(12, v.ips)); root.appendChild(g); return v; }, @@ -1242,7 +1551,7 @@ var copy = el('button', { type: 'button', class: 'btn primary' }, t('blocklist.copy')); var dlTxt = el('a', { class: 'btn', href: '/api/v1/blocklist.txt' }, t('blocklist.download')); var dlJson = el('a', { class: 'btn', href: '/api/v1/blocklist.json' }, t('blocklist.downloadJson')); - var node = panel({ title: t('blocklist.title'), hint: t('blocklist.help') }, + var node = panel({ title: t('blocklist.title'), hint: t('blocklist.help'), help: 'term.blocklist' }, h('div', 'toolbar', h('label', 'check', h('span', null, t('blocklist.minScore')), minScore), fam, copy, dlTxt, dlJson), count, msg); var timer = 0, alive = true; function query(extra) { @@ -1294,11 +1603,11 @@ var v = {}, g = grid12(); v.lead = sp(12, h('div')); v.hostsBox = h('div', 'hosts'); - v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint') }, v.hostsBox); + v.hosts = panel({ title: t('hosts.title'), hint: t('hosts.hint'), help: 'term.peer' }, v.hostsBox); var thead = h('thead', null, h('tr', null, ['col.host', 'col.source', 'col.state', 'col.lines', 'col.malformed', 'col.lastEvent'].map(function (k) { return el('th', { scope: 'col' }, t(k)); }))); v.tbody = h('tbody'); v.srcEmpty = h('div'); - v.sources = panel({ title: t('sources.title'), hint: t('sources.hint') }, h('div', 'tbl-wrap', h('table', 'stack tbl-cards', thead, v.tbody)), v.srcEmpty); + v.sources = panel({ title: t('sources.title'), hint: t('sources.hint'), help: 'term.integrity_gap' }, h('div', 'tbl-wrap', h('table', 'stack tbl-cards', thead, v.tbody)), v.srcEmpty); v.geoBox = h('div'); v.geo = panel({ title: t('src.geo.title'), hint: t('src.geo.hint') }, v.geoBox); v.bl = blocklistPanel(); @@ -1504,8 +1813,10 @@ function renderNav() { var list = orderedPages(), nav = $('#nav'), bar = $('#tabbar'), more = $('#more'), cur = navId(); clear(nav); clear(bar); clear(more); + var lastGroup = null; list.forEach(function (p) { - var label = t(p.titleKey); + var label = t(p.titleKey), gr = groupOf(p); + if (gr !== lastGroup) { nav.appendChild(h('div', 'nav-group', t('nav.group.' + gr))); lastGroup = gr; } var a = el('a', { class: 'nav-item', href: hrefFor(p.id), title: label }, h('span', 'nav-ico', iconNode(p.icon)), h('span', 'nav-label', label)); if (cur === p.id) a.setAttribute('aria-current', 'page'); nav.appendChild(a); @@ -1522,7 +1833,10 @@ if (rest.some(function (p) { return p.id === cur; })) mb.setAttribute('aria-current', 'page'); mb.addEventListener('click', function () { setMore(more.hidden); }); bar.appendChild(mb); + var rg = null; rest.forEach(function (p) { + var g2 = groupOf(p); + if (g2 !== rg) { more.appendChild(h('div', 'nav-group', t('nav.group.' + g2))); rg = g2; } var a = el('a', { href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey))); if (cur === p.id) a.setAttribute('aria-current', 'page'); more.appendChild(a); @@ -1639,7 +1953,7 @@ }); $('#scrim').addEventListener('click', closeDetail); document.addEventListener('keydown', function (e) { - if (e.key === 'Escape') { closeDetail(); setMore(false); closeRangePicker(true); return; } + if (e.key === 'Escape') { hideHelp(); closeDetail(); setMore(false); closeRangePicker(true); return; } var box = $('#detail'); if (e.key === 'Tab' && !box.hidden) { var f = Array.prototype.slice.call(box.querySelectorAll('button, a[href], [tabindex="0"]')); @@ -1660,6 +1974,7 @@ var more = $('#more'); if (!more.hidden && !more.contains(e.target) && !$('#tabbar').contains(e.target)) setMore(false); if (rp.open && !$('#range-picker').contains(e.target)) closeRangePicker(false); + if (helpPinned) hideHelp(); }); window.addEventListener('hashchange', route); window.matchMedia && matchMedia('(prefers-color-scheme: light)').addEventListener && matchMedia('(prefers-color-scheme: light)').addEventListener('change', notifyPage); @@ -1680,8 +1995,33 @@ rangeParams: rangeParams, rangeLabel: rangeLabel, href: hrefFor, toast: toast, fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime }, world: world, el: el, css: cssVar, setSliceNote: setSliceNote, + charts: charts, help: help, glossary: glossary, ui: { panel: panel, stat: stat, metric: metric, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart, sparkline: sparkline } }; - if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else setTimeout(boot, 0); + // page scripts are listed in /pages.json ({"pages":[{"name":"geo","css":true}, ...]}); only files that exist + // are listed, so nothing 404s. Each name loads /.js (and /.css) in order, then the app boots. + var DEFAULT_PAGES = [{ name: 'geo', css: true }, { name: 'live', css: true }, { name: 'ip', css: true }, { name: 'replay', css: true }]; + function loadScript(src) { + return new Promise(function (ok) { + var sc = document.createElement('script'); + sc.src = src; sc.async = false; + sc.onload = ok; sc.onerror = function () { console.warn('page script failed: ' + src); ok(); }; + document.head.appendChild(sc); + }); + } + function loadPages() { + return fetch('/pages.json', { credentials: 'same-origin' }).then(function (r) { return r.ok ? r.json() : null; }, function () { return null; }).then(function (m) { + var list = m && Array.isArray(m.pages) ? m.pages : DEFAULT_PAGES, chain = Promise.resolve(); + list.forEach(function (p) { + var name = p && String(p.name || ''); + if (!/^[a-z][a-z0-9-]*$/.test(name)) return; + if (p.css) { var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = '/' + name + '.css'; document.head.appendChild(l); } + chain = chain.then(function () { return loadScript('/' + name + '.js'); }); + }); + return chain; + }); + } + function start() { loadPages().then(boot, boot); } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else setTimeout(start, 0); })(); diff --git a/internal/server/web/campaigns.css b/internal/server/web/campaigns.css new file mode 100644 index 0000000..148c928 --- /dev/null +++ b/internal/server/web/campaigns.css @@ -0,0 +1,38 @@ +/* Urutau - CAMPAIGNS page. Selectors prefixed cp-. */ +.cp { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; } +.cp-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr)); gap: 12px; } +.cp-card { display: flex; flex-direction: column; gap: 8px; min-width: 0; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius, 10px); background: var(--surface-raised); } +.cp-card.cp-wide { background: var(--surface-panel); } +.cp-card header { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 10px; align-items: baseline; } +.cp-id { font-weight: 650; color: var(--accent); text-decoration: none; } +.cp-win { font-size: .75rem; color: var(--ink-muted); } +.cp-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; } +.cp-st { display: flex; flex-direction: column; min-width: 0; } +.cp-st b { font-size: 1.125rem; color: var(--heading, var(--ink)); } +.cp-sk { font-size: .6875rem; text-transform: uppercase; letter-spacing: .06em; color: var(--ink-muted); } +.cp-sig { margin: 0; display: flex; flex-direction: column; gap: 3px; min-width: 0; } +.cp-chips { display: flex; flex-wrap: wrap; gap: 4px; min-width: 0; } +.cp-chip { max-width: 100%; padding: 1px 8px; border: 1px solid var(--line); border-radius: 999px; background: var(--accent-soft); font-size: .75rem; font-family: var(--font-mono, monospace); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cp-more { font-family: inherit; color: var(--ink-muted); } +.cp-card footer { display: flex; flex-wrap: wrap; gap: 8px; margin-top: auto; } +.cp-card footer .btn { min-height: 34px; } +.cp-ip { color: var(--accent); text-decoration: none; overflow-wrap: anywhere; } +.cp-back { align-self: flex-start; } +.cp-gwrap { overflow: hidden; } +.cp-gantt { width: 100%; height: auto; display: block; } +.cp-gl { stroke: var(--line); stroke-width: 1; } +.cp-gt { fill: var(--ink-muted); font-size: 11px; font-family: var(--font-mono, monospace); } +.cp-bar { fill: var(--accent); } +.cp-b-recon { fill: var(--info); } .cp-b-probe { fill: var(--warn); } .cp-b-exploit { fill: var(--danger); } +.cp-b-access { fill: #c026d3; } .cp-b-banned { fill: var(--ink-faint); } +.cp-badge { display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: .75rem; font-weight: 600; color: #04121c; } +.cp-s-recon { background: var(--info); } .cp-s-probe { background: var(--warn); } .cp-s-exploit { background: var(--danger); } +.cp-s-access { background: #c026d3; } .cp-s-banned { background: var(--ink-faint); } +.cp-matrix { display: grid; grid-template-columns: repeat(calc(var(--n) + 1), minmax(0, 1fr)); gap: 2px; max-width: 640px; } +.cp-mh { font-size: .625rem; font-family: var(--font-mono, monospace); color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; align-self: center; } +.cp-mc { display: flex; align-items: center; justify-content: center; aspect-ratio: 1; min-height: 20px; border-radius: 3px; font-size: .625rem; color: var(--ink); background: var(--surface-sunken); } +.cp-lv1 { background: color-mix(in srgb, var(--accent) 22%, var(--surface-sunken)); } +.cp-lv2 { background: color-mix(in srgb, var(--accent) 42%, var(--surface-sunken)); } +.cp-lv3 { background: color-mix(in srgb, var(--accent) 65%, var(--surface-sunken)); } +.cp-lv4 { background: var(--accent); color: var(--on-accent); } +@media (max-width: 640px) { .cp-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } } diff --git a/internal/server/web/campaigns.js b/internal/server/web/campaigns.js new file mode 100644 index 0000000..755322e --- /dev/null +++ b/internal/server/web/campaigns.js @@ -0,0 +1,263 @@ +/* Urutau - CAMPAIGNS page: sets of addresses doing the same thing. List (cards, activity + Gantt, similarity matrix) at #/campaigns and detail at #/campaigns/. + Data: /api/v1/campaigns and /api/v1/campaigns/{id}. Hostile data: textContent only. */ +(function () { + 'use strict'; + var NS = 'http://www.w3.org/2000/svg'; + var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned']; + var ICON = ''; + var ID_OK = /^[A-Za-z0-9_-]{1,64}$/; + + function boot() { + var U = window.Urutau; + if (!U || !U.registerPage) return false; + var t = U.t, nf = U.fmt.num; + function h(tag, a) { if (typeof a === 'string') a = { class: a }; return U.el.apply(null, [tag, a].concat([].slice.call(arguments, 2))); } + U.registerI18n({ + en: { + 'cp.title': 'Campaigns', + 'cp.lead.one': '{n} campaign groups {k} IPs', + 'cp.lead.other': '{n} campaigns group {k} IPs', + 'cp.lead.body': 'Addresses that asked for the same things {range}.', + 'cp.lead.empty': 'No campaign in this slice', + 'cp.lead.emptyBody': 'No set of at least three addresses behaved alike {range}.', + 'cp.detail.lead': 'Campaign {id} groups {k} IPs', + 'cp.cards': 'Campaigns', + 'cp.ips': 'IPs', + 'cp.asns': 'ASNs', + 'cp.ccs': 'Countries', + 'cp.sessions': 'Sessions', + 'cp.window': 'Window', + 'cp.techs': 'Techniques', + 'cp.sig': 'Signature', + 'cp.tool': 'Tool', + 'cp.open': 'Open', + 'cp.gantt': 'Activity', + 'cp.gantt.hint': 'When each campaign was active.', + 'cp.matrix': 'Similarity', + 'cp.matrix.hint': 'Share of addresses two campaigns have in common.', + 'cp.members': 'Members', + 'cp.timeline': 'Timeline', + 'cp.timeline.hint': 'Sessions of each member.', + 'cp.replay': 'Replay campaign', + 'cp.back': 'All campaigns', + 'cp.c.ip': 'Address', + 'cp.c.first': 'First seen', + 'cp.c.last': 'Last seen', + 'cp.c.stage': 'Stage', + 'cp.c.sessions': 'Sessions', + 'cp.truncated': 'The study was cut short; the list may be incomplete.', + 'cp.err': 'Could not load the campaigns.', + 'cp.retry': 'Try again', + 'cp.unknown': 'Campaign not found', + 'cp.unknownBody': 'It is not in this slice. Widen the period or go back to the list.', + 'cp.stage.recon': 'Recon', + 'cp.stage.probe': 'Probe', + 'cp.stage.exploit': 'Exploit', + 'cp.stage.access': 'Access', + 'cp.stage.banned': 'Banned', + 'cp.more': '+{n} more' + }, + 'pt-BR': { + 'cp.title': 'Campanhas', + 'cp.lead.one': '{n} campanha agrupa {k} IPs', + 'cp.lead.other': '{n} campanhas agrupam {k} IPs', + 'cp.lead.body': 'Endereços que pediram as mesmas coisas {range}.', + 'cp.lead.empty': 'Nenhuma campanha neste recorte', + 'cp.lead.emptyBody': 'Nenhum conjunto de três ou mais endereços agiu igual {range}.', + 'cp.detail.lead': 'A campanha {id} agrupa {k} IPs', + 'cp.cards': 'Campanhas', + 'cp.ips': 'IPs', + 'cp.asns': 'ASNs', + 'cp.ccs': 'Países', + 'cp.sessions': 'Sessões', + 'cp.window': 'Janela', + 'cp.techs': 'Técnicas', + 'cp.sig': 'Assinatura', + 'cp.tool': 'Ferramenta', + 'cp.open': 'Abrir', + 'cp.gantt': 'Atividade', + 'cp.gantt.hint': 'Quando cada campanha esteve ativa.', + 'cp.matrix': 'Semelhança', + 'cp.matrix.hint': 'Fração de endereços que duas campanhas têm em comum.', + 'cp.members': 'Membros', + 'cp.timeline': 'Linha do tempo', + 'cp.timeline.hint': 'Sessões de cada membro.', + 'cp.replay': 'Reproduzir campanha', + 'cp.back': 'Todas as campanhas', + 'cp.c.ip': 'Endereço', + 'cp.c.first': 'Primeira vez', + 'cp.c.last': 'Última vez', + 'cp.c.stage': 'Estágio', + 'cp.c.sessions': 'Sessões', + 'cp.truncated': 'O estudo foi interrompido; a lista pode estar incompleta.', + 'cp.err': 'Não foi possível carregar as campanhas.', + 'cp.retry': 'Tentar de novo', + 'cp.unknown': 'Campanha não encontrada', + 'cp.unknownBody': 'Ela não está neste recorte. Amplie o período ou volte à lista.', + 'cp.stage.recon': 'Reconhecimento', + 'cp.stage.probe': 'Sondagem', + 'cp.stage.exploit': 'Exploração', + 'cp.stage.access': 'Acesso', + 'cp.stage.banned': 'Banido', + 'cp.more': '+{n} mais' + } + }); + function sec(v) { var n = Date.parse(v); return isFinite(n) ? Math.floor(n / 1000) : 0; } + function iso(s) { return new Date(s * 1000).toISOString(); } + function stg(s) { return STAGES.indexOf(s) >= 0 ? s : 'recon'; } + function short(id) { return String(id).slice(0, 12); } + function replayHref(c) { + return '#/replay?campaign=' + encodeURIComponent(c.id) + '&from=' + encodeURIComponent(iso(sec(c.first) - 300)) + '&to=' + encodeURIComponent(iso(sec(c.last) + 300)); + } + function ipLink(ip) { return h('a', { class: 'mono cp-ip', href: '#/ip/' + encodeURIComponent(ip), text: ip }); } + function chips(list, max) { + var box = h('span', 'cp-chips'); + (list || []).slice(0, max).forEach(function (x) { box.appendChild(h('span', { class: 'cp-chip', text: x })); }); + if ((list || []).length > max) box.appendChild(h('span', { class: 'cp-chip cp-more', text: t('cp.more', { n: list.length - max }) })); + return box; + } + function svg(tag, a) { var n = document.createElementNS(NS, tag); Object.keys(a || {}).forEach(function (k) { n.setAttribute(k, String(a[k])); }); return n; } + // rows: [{label, segs: [{a, b, cls}]}], span: [min, max]; one SVG, rows 22 px high + function gantt(rows, a, b, aria) { + var W = 720, L = 130, R = 8, RH = 22, H = rows.length * RH + 22, span = Math.max(1, b - a); + var s = svg('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': aria, class: 'cp-gantt' }); + rows.forEach(function (r, i) { + var y = i * RH; + s.appendChild(svg('line', { x1: L, x2: W - R, y1: y + RH - 1, y2: y + RH - 1, class: 'cp-gl' })); + var lab = svg('text', { x: 0, y: y + 15, class: 'cp-gt' }); lab.textContent = r.label.length > 18 ? r.label.slice(0, 17) + '…' : r.label; s.appendChild(lab); + r.segs.forEach(function (g) { + var x = L + (g.a - a) / span * (W - L - R), w = Math.max(3, (g.b - g.a) / span * (W - L - R)); + var rc = svg('rect', { x: x, y: y + 4, width: w, height: RH - 9, rx: 3, class: g.cls || 'cp-bar' }); + var ti = svg('title'); ti.textContent = U.fmt.date(g.a) + ' → ' + U.fmt.date(g.b); rc.appendChild(ti); + s.appendChild(rc); + }); + }); + [0, 1].forEach(function (k) { + var x = svg('text', { x: k ? W - R : L, y: H - 6, 'text-anchor': k ? 'end' : 'start', class: 'cp-gt' }); x.textContent = U.fmt.date(k ? b : a); s.appendChild(x); + }); + return h('div', 'cp-gwrap', s); + } + function jaccard(x, y) { + var m = {}, i = 0; x.forEach(function (v) { m[v] = 1; }); + y.forEach(function (v) { if (m[v]) i++; }); + var u = x.length + y.length - i; return u ? i / u : 0; + } + function matrix(cs) { + var list = cs.slice(0, 10), box = h('div', 'cp-matrix'); + box.style.setProperty('--n', String(list.length)); + box.appendChild(h('span', 'cp-mc')); + list.forEach(function (c) { box.appendChild(h('span', { class: 'cp-mh', text: short(c.id) })); }); + list.forEach(function (a) { + box.appendChild(h('span', { class: 'cp-mh', text: short(a.id) })); + list.forEach(function (b) { + var j = jaccard(a.ips || [], b.ips || []), lv = j >= .8 ? 4 : j >= .5 ? 3 : j >= .25 ? 2 : j > 0 ? 1 : 0; + box.appendChild(h('span', { class: 'cp-mc cp-lv' + lv, title: short(a.id) + ' / ' + short(b.id) + ': ' + Math.round(j * 100) + '%', text: j > 0 ? String(Math.round(j * 100)) : '' })); + }); + }); + return box; + } + function stat(k, v) { return h('div', 'cp-st', h('span', { class: 'cp-sk', text: k }), h('b', { class: 'num', text: v })); } + + var inst = null; + function Page(root, ctx) { + var self = this, seq = 0, alive = true, data = null, key = ''; + this.ctx = ctx; + var wrap = h('div', 'cp'); + root.appendChild(wrap); + function id() { var s = self.ctx.params && self.ctx.params.segments || []; return s[0] || ''; } + function load() { + var my = ++seq, cid = id(), path = cid ? '/api/v1/campaigns/' + encodeURIComponent(cid) : '/api/v1/campaigns'; + if (cid && !ID_OK.test(cid)) { data = { missing: true }; paint(); return; } + U.api(path, Object.assign({ host: self.ctx.host }, U.rangeParams())).then(function (d) { + if (!alive || my !== seq) return; data = d; key = cid; paint(); + }).catch(function (e) { + if (!alive || my !== seq) return; + if (e && e.status === 404 && cid) { data = { missing: true }; key = cid; paint(); return; } + if (data) return; + var b = h('button', { type: 'button', class: 'btn', text: t('cp.retry') }); + b.addEventListener('click', load); + wrap.textContent = ''; + wrap.appendChild(h('div', 'state-error', h('strong', { text: t('cp.err') }), b)); + }); + } + function paint() { + wrap.textContent = ''; + if (!data) return; + if (id()) return detail(); + var cs = data.campaigns || [], range = U.rangeLabel({ inline: true }); + wrap.appendChild(cs.length ? U.ui.lead(U.pl('cp.lead', cs.length, { n: nf(data.total || cs.length), k: nf(data.ips_n || 0) }), t('cp.lead.body', { range: range }), 'danger') + : U.ui.lead(t('cp.lead.empty'), t('cp.lead.emptyBody', { range: range }), 'neutral')); + if (data.truncated) wrap.appendChild(h('p', { class: 'note', text: t('cp.truncated') })); + if (!cs.length) return; + var grid = h('div', 'cp-cards'); + cs.slice(0, 60).forEach(function (c) { + var sg = c.signature || {}; + grid.appendChild(h('article', 'cp-card', + h('header', null, h('a', { class: 'cp-id mono', href: '#/campaigns/' + encodeURIComponent(c.id), text: short(c.id) }), + h('span', { class: 'cp-win', text: U.fmt.date(sec(c.first)) + ' → ' + U.fmt.date(sec(c.last)) })), + h('div', 'cp-stats', stat(t('cp.ips'), nf(c.ips_n || 0)), stat(t('cp.asns'), nf((c.asns || []).length)), stat(t('cp.ccs'), nf((c.ccs || []).length)), stat(t('cp.sessions'), nf(c.sessions_n || 0))), + h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.sig') }), chips(sg.paths, 3)), + sg.tool ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.tool') }), h('span', { class: 'cp-chip', text: sg.tool })) : null, + (c.techs || []).length ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.techs') }), chips(c.techs, 4)) : null, + (c.ccs || []).length ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.ccs') }), chips((c.ccs || []).map(function (x) { return (U.fmt.flag(x) + ' ' + x).trim(); }), 6)) : null, + h('footer', null, h('a', { class: 'btn', href: '#/campaigns/' + encodeURIComponent(c.id), text: t('cp.open') }), + h('a', { class: 'btn', href: replayHref(c), text: t('cp.replay') })))); + }); + wrap.appendChild(U.ui.panel({ title: t('cp.cards'), help: 'term.campaign' }, grid)); + var top = cs.slice(0, 15), mn = Infinity, mx = 0; + top.forEach(function (c) { mn = Math.min(mn, sec(c.first)); mx = Math.max(mx, sec(c.last)); }); + wrap.appendChild(U.ui.panel({ title: t('cp.gantt'), hint: t('cp.gantt.hint') }, + gantt(top.map(function (c) { return { label: short(c.id), segs: [{ a: sec(c.first), b: sec(c.last) }] }; }), mn, Math.max(mx, mn + 1), t('cp.gantt')))); + if (cs.length > 1) wrap.appendChild(U.ui.panel({ title: t('cp.matrix'), help: 'term.campaign', hint: t('cp.matrix.hint') }, matrix(cs))); + } + function detail() { + wrap.appendChild(h('a', { class: 'btn cp-back', href: U.href('campaigns'), text: '← ' + t('cp.back') })); + if (data.missing || !data.campaign) { wrap.appendChild(U.ui.empty(t('cp.unknown'), t('cp.unknownBody'))); return; } + var c = data.campaign, sg = c.signature || {}; + wrap.appendChild(U.ui.lead(t('cp.detail.lead', { id: short(c.id), k: nf(c.ips_n || 0) }), U.fmt.date(sec(c.first)) + ' → ' + U.fmt.date(sec(c.last)), 'danger')); + var head = h('div', 'cp-card cp-wide', + h('div', 'cp-stats', stat(t('cp.ips'), nf(c.ips_n || 0)), stat(t('cp.asns'), nf((c.asns || []).length)), stat(t('cp.ccs'), nf((c.ccs || []).length)), stat(t('cp.sessions'), nf(c.sessions_n || 0))), + h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.sig') }), chips(sg.paths, 5)), + sg.tool ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.tool') }), h('span', { class: 'cp-chip', text: sg.tool })) : null, + (c.techs || []).length ? h('p', 'cp-sig', h('span', { class: 'cp-sk', text: t('cp.techs') }), chips(c.techs, 8)) : null, + h('footer', null, h('a', { class: 'btn primary', href: replayHref(c), text: t('cp.replay') }))); + wrap.appendChild(head); + var ms = data.members || [], tb = h('tbody'); + ms.forEach(function (m) { + function td(l, k) { return h('td', { 'data-label': l }, k); } + tb.appendChild(h('tr', 'row', td(t('cp.c.ip'), ipLink(m.ip)), + td(t('cp.c.first'), h('span', { text: m.first ? U.fmt.date(m.first) : '' })), td(t('cp.c.last'), h('span', { text: m.last ? U.fmt.date(m.last) : '' })), + td(t('cp.c.stage'), m.stage ? h('span', { class: 'cp-badge cp-s-' + stg(m.stage), text: t('cp.stage.' + stg(m.stage)) }) : h('span')), + td(t('cp.c.sessions'), h('span', { class: 'num', text: (m.sessions || []).length ? nf(m.sessions.length) : '\u2013' })))); + }); + var th = h('tr'); ['ip', 'first', 'last', 'stage', 'sessions'].forEach(function (k) { th.appendChild(h('th', { text: t('cp.c.' + k) })); }); + wrap.appendChild(U.ui.panel({ title: t('cp.members') + ' (' + nf(ms.length) + ')' }, h('table', 'stack', h('thead', null, th), tb))); + var rows = [], mn = Infinity, mx = 0; + ms.slice(0, 40).forEach(function (m) { + var segs = (m.sessions || []).map(function (s) { var a = sec(s.start), b = sec(s.end); mn = Math.min(mn, a); mx = Math.max(mx, b); return { a: a, b: b, cls: 'cp-bar cp-b-' + stg(s.stage) }; }); + if (segs.length) rows.push({ label: m.ip, segs: segs }); + }); + if (rows.length) wrap.appendChild(U.ui.panel({ title: t('cp.timeline'), hint: t('cp.timeline.hint') }, gantt(rows, mn, Math.max(mx, mn + 1), t('cp.timeline')))); + } + this.update = function (c) { + var lang = self.ctx.lang, prev = key; self.ctx = c; + if (lang !== c.lang && data) paint(); + if (id() !== prev) data = null; + load(); + }; + this.refresh = function () { load(); }; + this.destroy = function () { alive = false; seq++; root.textContent = ''; }; + load(); + } + U.registerPage({ + id: 'campaigns', group: 'investigate', icon: ICON, titleKey: 'cp.title', + mount: function (el, ctx) { if (inst) inst.destroy(); inst = new Page(el, ctx); }, + update: function (ctx) { if (inst) inst.update(ctx); }, + refresh: function () { if (inst) inst.refresh(); }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); + return true; + } + if (!boot()) document.addEventListener('DOMContentLoaded', boot); +})(); diff --git a/internal/server/web/concentration.css b/internal/server/web/concentration.css new file mode 100644 index 0000000..ba29295 --- /dev/null +++ b/internal/server/web/concentration.css @@ -0,0 +1,20 @@ +/* Concentration page */ +.an-chart { min-width: 0; } +.an-svg { display: block; width: 100%; height: auto; max-width: 100%; overflow: visible; } +.an-svg .an-grid { stroke: var(--line); stroke-width: 1; } +.an-svg .an-guide { stroke: var(--warn); stroke-width: 1; stroke-dasharray: 4 4; } +.an-svg .an-line { fill: none; stroke: var(--accent); stroke-width: 2.25; stroke-linejoin: round; stroke-linecap: round; } +.an-svg .an-fill { fill: var(--accent); fill-opacity: .14; stroke: none; } +.an-svg .an-dot { fill: var(--accent); stroke: var(--surface-panel); stroke-width: 1.5; } +.an-svg .an-tick { fill: var(--ink-muted); font-size: 11px; } +.an-svg .an-strong { fill: var(--ink); font-weight: 600; } +.an-kpis { display: flex; flex-wrap: wrap; gap: var(--s-5); margin: 0 0 var(--s-3); } +.an-kpi { display: grid; } +.an-kpi-v { font: 600 1.5rem var(--font-display); font-variant-numeric: tabular-nums; color: var(--heading); } +.an-kpi-l { color: var(--ink-muted); font-size: .8125rem; } +.an-scroll { max-height: 420px; overflow: auto; } +.an-table { width: 100%; border-collapse: collapse; font-size: .875rem; } +.an-table th, .an-table td { padding: 5px var(--s-3); border-bottom: 1px solid var(--line); text-align: left; } +.an-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); } +.an-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; } +.an-table .an-key { overflow-wrap: anywhere; word-break: break-all; } diff --git a/internal/server/web/concentration.js b/internal/server/web/concentration.js new file mode 100644 index 0000000..c06272e --- /dev/null +++ b/internal/server/web/concentration.js @@ -0,0 +1,208 @@ +/* Urutau - CONCENTRACAO page: do a few sources generate most of the attacks? + Pareto curve with a dimension selector (IP, ASN, country, path, domain), + Gini coefficient, top 10 share and a donut of the top 5 against the rest. + Data: /api/v1/concentration. Log data is hostile: textContent only. */ +(function () { + 'use strict'; + var U = window.Urutau; + if (!U || !U.registerPage) return; + var el = U.el, t = U.t; + var DIMS = ['ip', 'asn', 'country', 'path', 'domain']; + + U.registerI18n({ + en: { + 'an.co.title': 'Concentration', + 'an.co.lead': 'The top 10 {dim} generate {pct} of the attacks', + 'an.co.lead.body': 'Gini {gini} across {distinct} distinct values, {n} malicious events {range}.', + 'an.co.lead.empty': 'No malicious events to measure', + 'an.co.lead.empty.body': 'Nothing was recorded {range}.', + 'an.co.dim': 'Group by', + 'an.co.dim.ip': 'IP', + 'an.co.dim.asn': 'ASN', + 'an.co.dim.country': 'country', + 'an.co.dim.path': 'path', + 'an.co.dim.domain': 'domain', + 'an.co.curve': 'Pareto curve', + 'an.co.curve.hint': 'Share of all events held by the top N, ranked from the heaviest.', + 'an.co.x': 'Rank', + 'an.co.y': 'Cumulative share', + 'an.co.gini': 'Gini', + 'an.co.top10': 'Top 10', + 'an.co.donut': 'Top 5 and the rest', + 'an.co.donut.hint': 'How the five heaviest compare with everything else.', + 'an.co.rest': 'others', + 'an.co.list': 'Ranking', + 'an.co.list.hint': 'Up to the 200 heaviest, with the cumulative share.', + 'an.co.total': 'events', + 'an.co.off': 'The event registry is off', + 'an.co.off.d': 'This analysis reads the event registry, which is not enabled on this instance.', + 'an.co.err': 'Could not load this analysis.', + 'an.co.retry': 'Try again' + }, + 'pt-BR': { + 'an.co.title': 'Concentração', + 'an.co.lead': 'Os 10 maiores por {dim} geram {pct} dos ataques', + 'an.co.lead.body': 'Gini {gini} em {distinct} valores distintos, {n} eventos maliciosos {range}.', + 'an.co.lead.empty': 'Sem eventos maliciosos para medir', + 'an.co.lead.empty.body': 'Nada foi registrado {range}.', + 'an.co.dim': 'Agrupar por', + 'an.co.dim.ip': 'IP', + 'an.co.dim.asn': 'ASN', + 'an.co.dim.country': 'país', + 'an.co.dim.path': 'caminho', + 'an.co.dim.domain': 'domínio', + 'an.co.curve': 'Curva de Pareto', + 'an.co.curve.hint': 'Parcela de todos os eventos nas N primeiras posições, do mais pesado ao mais leve.', + 'an.co.x': 'Posição', + 'an.co.y': 'Parcela acumulada', + 'an.co.gini': 'Gini', + 'an.co.top10': 'Top 10', + 'an.co.donut': 'Top 5 e o resto', + 'an.co.donut.hint': 'Como os cinco mais pesados se comparam com todo o resto.', + 'an.co.rest': 'outros', + 'an.co.list': 'Ranking', + 'an.co.list.hint': 'Até os 200 mais pesados, com a parcela acumulada.', + 'an.co.total': 'eventos', + 'an.co.off': 'O registro de eventos está desligado', + 'an.co.off.d': 'Esta análise lê o registro de eventos, que não está ativo nesta instância.', + 'an.co.err': 'Não foi possível carregar esta análise.', + 'an.co.retry': 'Tentar de novo' + } + }); + + function tip(p, key) { var h2 = p.querySelector('.panel-h h2'); if (h2 && U.help) U.help(h2, key); return p; } + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + function s(tag, attrs, kids) { var n = el(tag, attrs); (kids || []).forEach(function (k) { n.appendChild(k); }); return n; } + function itemLabel(dim, it) { + if (dim === 'country') return it.key ? U.fmt.flag(it.key) + ' ' + U.fmt.country(it.key) : it.key; + if (dim === 'asn' && it.label) return it.key + ' ' + it.label; + return it.key; + } + + // Pareto line: x is the rank, y the cumulative share (0..100) + function pareto(items) { + var W = 640, H = 280, L = 44, R = 12, T = 12, B = 34, w = W - L - R, h = H - T - B, n = items.length; + var svg = s('svg', { viewBox: '0 0 ' + W + ' ' + H, class: 'an-svg', role: 'img', 'aria-label': t('an.co.curve'), preserveAspectRatio: 'xMidYMid meet' }); + function X(i) { return L + (n <= 1 ? 0 : i / (n - 1)) * w; } + function Y(v) { return T + (1 - v / 100) * h; } + [0, 25, 50, 75, 100].forEach(function (v) { + svg.appendChild(el('line', { class: 'an-grid', x1: L, x2: W - R, y1: Y(v), y2: Y(v) })); + svg.appendChild(el('text', { class: 'an-tick', x: L - 6, y: Y(v) + 4, 'text-anchor': 'end' }, v + '%')); + }); + [0, 0.5, 1].forEach(function (f) { + var i = Math.round(f * (n - 1)); + svg.appendChild(el('text', { class: 'an-tick', x: X(i), y: H - 16, 'text-anchor': f === 0 ? 'start' : f === 1 ? 'end' : 'middle' }, String(i + 1))); + }); + svg.appendChild(el('text', { class: 'an-tick', x: L + w / 2, y: H - 2, 'text-anchor': 'middle' }, t('an.co.x'))); + svg.appendChild(el('line', { class: 'an-guide', x1: L, x2: W - R, y1: Y(80), y2: Y(80) })); + var pts = items.map(function (it, i) { return X(i).toFixed(1) + ',' + Y(it.cum_pct).toFixed(1); }); + if (n > 0) { + svg.appendChild(el('polygon', { class: 'an-fill', points: X(0).toFixed(1) + ',' + Y(0) + ' ' + pts.join(' ') + ' ' + X(n - 1).toFixed(1) + ',' + Y(0) })); + svg.appendChild(el('polyline', { class: 'an-line', points: pts.join(' ') })); + items.forEach(function (it, i) { + if (n > 40 && i % Math.ceil(n / 40) && i !== n - 1) return; + svg.appendChild(el('circle', { class: 'an-dot', cx: X(i), cy: Y(it.cum_pct), r: 3 }, el('title', null, '#' + (i + 1) + ' ' + it.key + ': ' + it.cum_pct + '%'))); + }); + } + return el('div', { class: 'an-chart' }, svg); + } + + var inst = null, dimSaved = 'ip'; + function create(root, ctx) { + var seq = 0, alive = true, data = null, c = ctx, dim = dimSaved; + var grid = el('div', { class: 'grid-12 an-page' }); + var lead = el('div', { class: 'span-12' }); + var chips = el('div', { class: 'chip-group', role: 'group', 'aria-label': t('an.co.dim') }); + var btns = {}; + DIMS.forEach(function (d) { + var b = el('button', { type: 'button', class: 'chip-btn', 'aria-pressed': d === dim ? 'true' : 'false' }, t('an.co.dim.' + d)); + b.addEventListener('click', function () { + if (dim === d) return; + dim = dimSaved = d; data = null; + DIMS.forEach(function (x) { btns[x].setAttribute('aria-pressed', x === d ? 'true' : 'false'); }); + load(); + }); + btns[d] = b; chips.appendChild(b); + }); + var curve = U.ui.panel({ title: t('an.co.curve'), hint: t('an.co.curve.hint'), variant: 'chart', loading: true, actions: chips }); + tip(curve, 'term.pareto'); + var donut = U.ui.panel({ title: t('an.co.donut'), hint: t('an.co.donut.hint'), loading: true }); + var list = U.ui.panel({ title: t('an.co.list'), hint: t('an.co.list.hint'), loading: true }); + var kpis = el('div', { class: 'an-kpis' }); + grid.appendChild(lead); + grid.appendChild(curve); curve.classList.add('span-8'); + grid.appendChild(donut); donut.classList.add('span-4'); + grid.appendChild(list); list.classList.add('span-12'); + root.appendChild(grid); + + function paint() { + clear(lead); [curve, donut, list].forEach(function (p) { clear(p.body); }); + if (!data) return; + if (!data.enabled) { lead.appendChild(U.ui.empty(t('an.co.off'), t('an.co.off.d'))); return; } + var d = data, range = U.rangeLabel({ inline: true }), dname = t('an.co.dim.' + d.dim); + if (!d.total) { + lead.appendChild(U.ui.lead(t('an.co.lead.empty'), t('an.co.lead.empty.body', { range: range }), 'neutral')); + curve.body.appendChild(U.ui.empty(t('charts.empty'))); + donut.body.appendChild(U.ui.empty(t('charts.empty'))); + list.body.appendChild(U.ui.empty(t('charts.empty'))); + return; + } + lead.appendChild(U.ui.lead(t('an.co.lead', { dim: dname, pct: U.fmt.pct(d.top10_pct / 100) }), + t('an.co.lead.body', { gini: d.gini.toFixed(2), distinct: U.fmt.num(d.distinct), n: U.fmt.num(d.total), range: range }), 'neutral')); + kpis = el('div', { class: 'an-kpis' }, + el('div', { class: 'an-kpi' }, el('span', { class: 'an-kpi-v' }, d.gini.toFixed(2)), el('span', { class: 'an-kpi-l' }, t('an.co.gini'), ' ', (function () { var w = el('span'); U.help && U.help(w, 'term.gini'); return w; })())), + el('div', { class: 'an-kpi' }, el('span', { class: 'an-kpi-v' }, U.fmt.pct(d.top10_pct / 100)), el('span', { class: 'an-kpi-l' }, t('an.co.top10')))); + curve.body.appendChild(kpis); + curve.body.appendChild(pareto(d.items)); + var top5 = d.items.slice(0, 5), used = 0; + var rows = top5.map(function (it) { used += it.n; return { key: it.key, label: itemLabel(d.dim, it), value: it.n }; }); + if (d.total > used) rows.push({ key: '_rest', label: t('an.co.rest'), value: d.total - used }); + donut.body.appendChild(U.charts.donut(rows, { title: t('an.co.donut'), centerLabel: t('an.co.total'), colors: ['--viz-1', '--viz-2', '--viz-3', '--viz-4', '--viz-5', '--viz-8'] })); + var tbl = el('table', { class: 'an-table' }); + tbl.appendChild(el('thead', null, el('tr', null, el('th', null, '#'), el('th', null, t('an.co.dim.' + d.dim)), el('th', { class: 'num' }, t('an.co.total')), el('th', { class: 'num' }, t('an.co.y'))))); + var tb = el('tbody'); + d.items.forEach(function (it, i) { + var cell = el('td', { class: 'an-key mono' }); + if (d.dim === 'ip') { + var a = el('a', { href: '#/ip/' + encodeURIComponent(it.key) }, it.key); + cell.appendChild(a); + } else cell.textContent = itemLabel(d.dim, it); + tb.appendChild(el('tr', null, el('td', { class: 'num' }, String(i + 1)), cell, el('td', { class: 'num' }, U.fmt.num(it.n)), el('td', { class: 'num' }, it.cum_pct.toFixed(1) + '%'))); + }); + tbl.appendChild(tb); + list.body.appendChild(el('div', { class: 'an-scroll' }, tbl)); + } + function load() { + var my = ++seq; + var p = Object.assign({ dim: dim }, U.rangeParams()); + if (c.host && c.host !== 'all') p.host = c.host; + U.api('/api/v1/concentration', p).then(function (r) { + if (!alive || my !== seq) return; + data = r; paint(); + }, function () { + if (!alive || my !== seq || data) return; + clear(lead); + var b = el('button', { type: 'button', class: 'btn' }, t('an.co.retry')); + b.addEventListener('click', load); + lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('an.co.err')), b)); + }); + } + load(); + return { + root: root, lang: ctx.lang, + update: function (cx) { c = cx; load(); }, + destroy: function () { alive = false; seq++; clear(root); } + }; + } + + U.registerPage({ + id: 'concentration', group: 'analyze', titleKey: 'an.co.title', + icon: '', + mount: function (el, ctx) { if (inst) inst.destroy(); inst = create(el, ctx || {}); }, + update: function (ctx) { + ctx = ctx || {}; + if (inst && ctx.lang !== inst.lang) { var r = inst.root; inst.destroy(); inst = create(r, ctx); } else if (inst) inst.update(ctx); + }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); +})(); diff --git a/internal/server/web/defense.css b/internal/server/web/defense.css new file mode 100644 index 0000000..6a59f91 --- /dev/null +++ b/internal/server/web/defense.css @@ -0,0 +1,5 @@ +/* Defense page */ +.df-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; } +.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; } diff --git a/internal/server/web/defense.js b/internal/server/web/defense.js new file mode 100644 index 0000000..6a0d6a4 --- /dev/null +++ b/internal/server/web/defense.js @@ -0,0 +1,201 @@ +/* Urutau - DEFENSE page: is fail2ban acting? Bans over time per jail, time to + ban, blocklist coverage, leak and the SSH users tried. Data: + /api/v1/defense. Log data is hostile: dynamic text goes through textContent + only. */ +(function () { + 'use strict'; + + var MAX_BUCKETS = 400; + + function boot() { + var U = window.Urutau; + if (!U || !U.registerPage) return false; + U.registerI18n({ + en: { + 'df.title': 'Defense', + 'df.lead.some': 'fail2ban applied {n} bans {range}', + 'df.lead.sub.ok': '{a} bans are active. Few attackers kept arriving after being banned.', + 'df.lead.sub.leak': '{a} bans are active, but {l} attackers kept arriving after a ban or listing.', + 'df.lead.none': 'fail2ban did not ban anyone {range}', + 'df.lead.none.sub': 'No ban events in this window. If attacks were seen, check that the fail2ban log is being read.', + 'df.kpi.active': 'Active bans', + 'df.kpi.active.sub': '{n} bans in the window', + 'df.kpi.ttb': 'Time to ban', + 'df.kpi.ttb.sub': 'median per attack episode; 90% within {p}', + 'df.kpi.ttb.none': 'no data', + 'df.kpi.cov': 'Blocklist coverage', + 'df.kpi.cov.sub': '{n} addresses listed', + 'df.kpi.leak': 'Leak', + 'df.kpi.leak.sub': '{n} events after the ban', + 'df.bans': 'Bans per jail over time', + 'df.jails': 'Bans by jail', + 'df.jails.center': 'bans', + 'df.users': 'SSH users tried', + 'df.users.hint': 'Names attackers tried to log in with. Red: a real account of yours.', + 'df.users.none': 'No SSH failures in this window.', + 'df.ssh.sum': '{f} failures from {s} sources; {o} successful logins after failures.', + 'df.cov': 'Blocklist coverage', + 'df.cov.hint': 'Share of the attackers of the window that are in the blocklist.', + 'df.cov.label': 'of attackers listed', + 'df.bl.size': '{n} addresses ({v4} IPv4, {v6} IPv6 /64)', + 'df.bl.updated': 'last change {t}', + 'df.bl.download': 'Download blocklist', + 'df.error': 'Could not load the defense data.', + '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' + }, + 'pt-BR': { + 'df.title': 'Defesa', + 'df.lead.some': 'O fail2ban aplicou {n} bans {range}', + 'df.lead.sub.ok': '{a} bans estão ativos. Poucos atacantes continuaram chegando depois do ban.', + 'df.lead.sub.leak': '{a} bans estão ativos, mas {l} atacantes continuaram chegando depois de um ban ou da listagem.', + 'df.lead.none': 'O fail2ban não baniu ninguém {range}', + 'df.lead.none.sub': 'Nenhum evento de ban nesta janela. Se houve ataques, confira se o log do fail2ban está sendo lido.', + 'df.kpi.active': 'Bans ativos', + 'df.kpi.active.sub': '{n} bans na janela', + 'df.kpi.ttb': 'Tempo até o ban', + 'df.kpi.ttb.sub': 'mediana por episódio de ataque; 90% em até {p}', + 'df.kpi.ttb.none': 'sem dados', + 'df.kpi.cov': 'Cobertura da blocklist', + 'df.kpi.cov.sub': '{n} endereços listados', + 'df.kpi.leak': 'Vazamento', + 'df.kpi.leak.sub': '{n} eventos depois do ban', + 'df.bans': 'Bans por jail ao longo do tempo', + 'df.jails': 'Bans por jail', + 'df.jails.center': 'bans', + 'df.users': 'Usuários SSH tentados', + 'df.users.hint': 'Nomes com que os atacantes tentaram entrar. Vermelho: uma conta real sua.', + 'df.users.none': 'Nenhuma falha de SSH nesta janela.', + 'df.ssh.sum': '{f} falhas de {s} origens; {o} logins bem-sucedidos depois de falhas.', + 'df.cov': 'Cobertura da blocklist', + 'df.cov.hint': 'Parcela dos atacantes da janela que está na blocklist.', + 'df.cov.label': 'dos atacantes listados', + 'df.bl.size': '{n} endereços ({v4} IPv4, {v6} IPv6 /64)', + 'df.bl.updated': 'última alteração {t}', + 'df.bl.download': 'Baixar a blocklist', + 'df.error': 'Não foi possível carregar os dados de defesa.', + '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' + } + }); + + var el = U.el, t = U.t, nf = U.fmt.num; + var root = null, seq = 0, alive = false, ctx = null, data = null; + + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + function dur(s) { + s = Math.round(s); + if (s < 60) return s + ' s'; + if (s < 3600) return Math.round(s / 60) + ' min'; + if (s < 86400) return (s / 3600).toFixed(s < 36000 ? 1 : 0).replace(/\.0$/, '') + ' h'; + return (s / 86400).toFixed(1).replace(/\.0$/, '') + ' d'; + } + function pctTxt(v) { return (v > 0 && v < 10 ? v.toFixed(1) : Math.round(v)) + '%'; } + + function series(d) { + var step = d.step || 3600, from = d.from || 0; + var end = Math.max(ctx && ctx.to ? ctx.to : Math.floor(Date.now() / 1000), 0); + (d.bans || []).forEach(function (b) { if (b.t > end) end = b.t; }); + var n = Math.min(MAX_BUCKETS, Math.floor((end - from) / step) + 1); + if (n < 2) n = 2; + var start = from; + if (Math.floor((end - from) / step) + 1 > MAX_BUCKETS) start = Math.floor(end / step) * step - (MAX_BUCKETS - 1) * step; + var jails = {}, order = []; + (d.by_jail || []).forEach(function (j) { jails[j.jail] = new Array(n).fill(0); order.push(j.jail); }); + (d.bans || []).forEach(function (b) { + var i = Math.round((b.t - start) / step); + if (i < 0 || i >= n) return; + if (!jails[b.jail]) { jails[b.jail] = new Array(n).fill(0); order.push(b.jail); } + jails[b.jail][i] += b.n; + }); + return { step: step, start: start, list: order.map(function (j) { return { key: j, label: j, values: jails[j] }; }) }; + } + + 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('df.disabled'), t('df.disabled.sub'))); return; } + var d = data, range = U.rangeLabel({ inline: true }), leak = d.leak || { ips: 0, events: 0 }; + var bl = d.blocklist || {}, ssh = d.ssh || { users: [] }, ttb = d.ttb || {}; + if (d.bans_total > 0) { + var bad = leak.ips > 0 && leak.ips * 4 > d.bans_total; + root.appendChild(U.ui.lead(t('df.lead.some', { n: nf(d.bans_total), range: range }), + leak.ips > 0 ? t('df.lead.sub.leak', { a: nf(d.bans_active), l: nf(leak.ips) }) : t('df.lead.sub.ok', { a: nf(d.bans_active) }), bad ? 'danger' : 'ok')); + } else { + root.appendChild(U.ui.lead(t('df.lead.none', { range: range }), t('df.lead.none.sub'), 'danger')); + } + if (d.truncated) root.appendChild(el('p', { class: 'hint' }, t('df.partial'))); + + 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.kpi.active'), nf(d.bans_active), { sub: t('df.kpi.active.sub', { n: nf(d.bans_total) }) })); + k(U.ui.metric(t('df.kpi.ttb'), ttb.n ? dur(ttb.median_s) : t('df.kpi.ttb.none'), ttb.n ? { sub: t('df.kpi.ttb.sub', { p: dur(ttb.p90_s) }) } : {})); + var cov = bl.coverage_pct || 0; + k(U.ui.metric(t('df.kpi.cov'), pctTxt(cov), { sub: t('df.kpi.cov.sub', { n: nf(bl.size || 0) }), tone: cov >= 70 ? 'ok' : cov >= 40 ? 'warn' : 'danger' })); + k(U.ui.metric(t('df.kpi.leak'), nf(leak.ips), { sub: t('df.kpi.leak.sub', { n: nf(leak.events) }), tone: leak.ips ? 'warn' : 'ok' })); + root.appendChild(kp); + + var grid = el('div', { class: 'grid-12' }); + var sr = series(d); + var ap = U.ui.panel({ title: t('df.bans'), cls: 'span-8' }); + if (U.charts && U.charts.stackedArea && sr.list.length) ap.body.appendChild(U.charts.stackedArea(sr.list, sr.step, { start: sr.start, title: t('df.bans') })); + else ap.body.appendChild(U.ui.empty(t('df.lead.none', { range: range }))); + grid.appendChild(ap); + var jp = U.ui.panel({ title: t('df.jails'), cls: 'span-4' }); + var jd = (d.by_jail || []).filter(function (j) { return j.total > 0; }).map(function (j) { return { key: j.jail, label: j.jail, value: j.total }; }); + if (U.charts && U.charts.donut) jp.body.appendChild(U.charts.donut(jd, { title: t('df.jails'), centerLabel: t('df.jails.center'), format: nf })); + grid.appendChild(jp); + + var up = U.ui.panel({ title: t('df.users'), hint: t('df.users.hint'), cls: 'span-8' }); + var users = ssh.users || []; + if (!users.length) up.body.appendChild(U.ui.empty(t('df.users.none'))); + else { + up.body.appendChild(el('p', { class: 'hint df-sum' }, t('df.ssh.sum', { f: nf(ssh.fails), s: nf(ssh.sources), o: nf(ssh.ok_after_fail) }))); + var rows = users.slice(0, 15).map(function (u) { + var lit = u.user === 'admin' || u.user === 'root'; + return { key: u.user, label: u.admin ? u.user + ' (' + t('df.admin') + ')' : u.user, value: u.n, color: u.admin ? '--danger' : lit ? '--warn' : '--viz-1' }; + }); + if (U.charts && U.charts.bars) up.body.appendChild(U.charts.bars(rows, { title: t('df.users'), format: nf })); + } + grid.appendChild(up); + + var gp = U.ui.panel({ title: t('df.cov'), hint: t('df.cov.hint'), cls: 'span-4' }); + if (U.charts && U.charts.gauge) gp.body.appendChild(U.charts.gauge(Math.round(cov), 100, [{ at: 0, tone: 'danger' }, { at: 40, tone: 'warn' }, { at: 70, tone: 'ok' }], { label: t('df.cov.label'), format: function (v) { return v + '%'; } })); + gp.body.appendChild(el('p', { class: 'df-bl' }, t('df.bl.size', { n: nf(bl.size || 0), v4: nf(bl.v4 || 0), v6: nf(bl.v6 || 0) }) + (bl.updated ? ' · ' + t('df.bl.updated', { t: U.fmt.ago(bl.updated) }) : ''))); + gp.body.appendChild(el('a', { class: 'btn', href: '/api/v1/blocklist.txt?download=1&range=7d', download: 'urutau-blocklist.txt' }, t('df.bl.download'))); + grid.appendChild(gp); + root.appendChild(grid); + } + + function load() { + 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; + data = d; paint(); + }).catch(function () { + if (!alive || my !== seq || data) return; + clear(root); + root.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.error')))); + }); + } + + U.registerPage({ + id: 'defense', group: 'operate', titleKey: 'df.title', + icon: '', + mount: function (node, cx) { root = el('div', { class: 'df-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); + } +})(); diff --git a/internal/server/web/errors.css b/internal/server/web/errors.css new file mode 100644 index 0000000..0ad41f0 --- /dev/null +++ b/internal/server/web/errors.css @@ -0,0 +1,10 @@ +/* Errors page */ +.hl-scroll { max-height: 420px; overflow: auto; } +.hl-table { width: 100%; border-collapse: collapse; font-size: .875rem; } +.hl-table th, .hl-table td { padding: 5px var(--s-3); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; } +.hl-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); } +.hl-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; } +.hl-page .panel { min-width: 0; } +@media (max-width: 900px) { .hl-page .span-6, { grid-column: 1 / -1; } } +.hl-helps { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: var(--s-3, 10px); font-size: .8125rem; color: var(--ink-muted); } +.hl-help { display: inline-flex; align-items: center; gap: 4px; } diff --git a/internal/server/web/errors.js b/internal/server/web/errors.js new file mode 100644 index 0000000..a1a5df7 --- /dev/null +++ b/internal/server/web/errors.js @@ -0,0 +1,146 @@ +/* Urutau - page ERRORS ("where do the errors come from"): splits every 4xx/5xx into + frustrated attacks, proxy trouble, real application errors, bots and client mistakes. + Data: /api/v1/errors. Log data is hostile: textContent only. */ +(function () { + 'use strict'; + var U = window.Urutau; + if (!U || !U.registerPage) return; + var el = U.el, t = U.t; + var ORDER = ['app', 'proxy', 'blocked', 'attack', 'bot', 'client_broken', 'client_auth', 'client_other']; + var COLOR = { app: '--danger', proxy: '--warn', blocked: '--info', attack: '--cat-exploit', bot: '--viz-6', client_broken: '--viz-2', client_auth: '--viz-4', client_other: '--ink-muted' }; + + U.registerI18n({ + en: { + 'hl.er.title': 'Where errors come from', + 'hl.er.lead': '{n} errors; {atk} frustrated attacks, {app} real application errors', + 'hl.er.lead.body': 'Of {req} requests {range}, {proxy} of the errors are proxy trouble and {bot} come from crawlers. Server error rate (application + proxy over legitimate requests, client cancellations excluded): {rate}. Data from this instance ({inst}) only.', + 'hl.er.lead.empty': 'No errors recorded', + 'hl.er.lead.empty.body': 'No 4xx or 5xx answers {range}, or the log has no origin fields yet.', + 'hl.cls.app': 'Application', 'hl.cls.proxy': 'Proxy / network', 'hl.cls.blocked': 'Blocked by rule', 'hl.cls.attack': 'Attack', + 'hl.cls.bot': 'Crawlers', 'hl.cls.client_broken': 'Broken links', 'hl.cls.client_auth': 'Authentication', 'hl.cls.client_other': 'Other client errors', + 'hl.er.donut': 'Error classes', 'hl.er.donut.hint': 'Application and proxy errors are yours to fix; attacks and blocks mean the defences worked.', + 'hl.er.total': 'errors', + 'hl.er.time': 'Errors over time', 'hl.er.time.hint': 'Hourly, stacked by class.', + 'hl.er.heat': 'Application errors by service and hour', 'hl.er.heat.hint': 'Only answers the backend itself failed (5xx from the origin).', + 'hl.er.broken': 'Broken links', 'hl.er.broken.hint': 'Pages that answered 404 to a visitor who clicked a link. Fix the link or add a redirect.', + 'hl.er.routes': 'Routes with the most errors', 'hl.er.routes.hint': 'Method and path (ids folded), by service and class.', + 'hl.er.col.path': 'Missing path', 'hl.er.col.ref': 'Came from', 'hl.er.col.n': 'Hits', 'hl.er.col.last': 'Last', + 'hl.er.col.svc': 'Service', 'hl.er.col.route': 'Route', 'hl.er.col.class': 'Class', + 'hl.er.err': 'Could not load the error breakdown.', 'hl.er.retry': 'Try again', + 'hl.er.empty': 'Nothing to show for this range.' + }, + 'pt-BR': { + 'hl.er.title': 'De onde vêm os erros', + 'hl.er.lead': '{n} erros; {atk} ataques frustrados, {app} erros reais de aplicação', + 'hl.er.lead.body': 'De {req} requisições {range}, {proxy} dos erros são problema de proxy e {bot} vêm de rastreadores. Taxa de erro do servidor (aplicação + proxy sobre as requisições legítimas, sem cancelamentos do cliente): {rate}. Dados só desta instância ({inst}).', + 'hl.er.lead.empty': 'Nenhum erro registrado', + 'hl.er.lead.empty.body': 'Nenhuma resposta 4xx ou 5xx {range}, ou o log ainda não tem os campos de origem.', + 'hl.cls.app': 'Aplicação', 'hl.cls.proxy': 'Proxy / rede', 'hl.cls.blocked': 'Bloqueado por regra', 'hl.cls.attack': 'Ataque', + 'hl.cls.bot': 'Rastreadores', 'hl.cls.client_broken': 'Links quebrados', 'hl.cls.client_auth': 'Autenticação', 'hl.cls.client_other': 'Outros erros do cliente', + 'hl.er.donut': 'Classes de erro', 'hl.er.donut.hint': 'Erros de aplicação e de proxy são seus para corrigir; ataques e bloqueios mostram que a defesa funcionou.', + 'hl.er.total': 'erros', + 'hl.er.time': 'Erros no tempo', 'hl.er.time.hint': 'Por hora, empilhados por classe.', + 'hl.er.heat': 'Erros de aplicação por serviço e hora', 'hl.er.heat.hint': 'Só respostas em que o próprio backend falhou (5xx da origem).', + 'hl.er.broken': 'Links quebrados', 'hl.er.broken.hint': 'Páginas que deram 404 para quem clicou num link. Corrija o link ou crie um redirecionamento.', + 'hl.er.routes': 'Rotas com mais erros', 'hl.er.routes.hint': 'Método e caminho (ids agrupados), por serviço e classe.', + 'hl.er.col.path': 'Caminho ausente', 'hl.er.col.ref': 'Veio de', 'hl.er.col.n': 'Acessos', 'hl.er.col.last': 'Último', + 'hl.er.col.svc': 'Serviço', 'hl.er.col.route': 'Rota', 'hl.er.col.class': 'Classe', + 'hl.er.err': 'Não foi possível carregar o detalhamento dos erros.', 'hl.er.retry': 'Tentar de novo', + 'hl.er.empty': 'Nada para mostrar neste período.' + } + }); + + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + function pctOf(a, b) { return b > 0 ? U.fmt.pct(a / b) : '0%'; } + function table(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: 'hl-scroll' }, el('table', { class: 'hl-table' }, + el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb)); + } + function clock(ts) { return U.fmt.clock ? U.fmt.clock(ts) : String(ts); } + + var inst = null; + function create(root, ctx) { + var seq = 0, alive = true, data = null, c = ctx; + var grid = el('div', { class: 'grid-12 hl-page' }); + var lead = el('div', { class: 'span-12' }); + var pd = U.ui.panel({ title: t('hl.er.donut'), hint: t('hl.er.donut.hint'), loading: true, cls: 'span-4' }); + var pt = U.ui.panel({ title: t('hl.er.time'), hint: t('hl.er.time.hint'), variant: 'chart', loading: true, cls: 'span-8' }); + var ph = U.ui.panel({ title: t('hl.er.heat'), hint: t('hl.er.heat.hint'), variant: 'chart', loading: true, cls: 'span-12' }); + var pb = U.ui.panel({ title: t('hl.er.broken'), hint: t('hl.er.broken.hint'), variant: 'list', loading: true, cls: 'span-6' }); + var pr = U.ui.panel({ title: t('hl.er.routes'), hint: t('hl.er.routes.hint'), variant: 'list', loading: true, cls: 'span-6' }); + [lead, pd, pt, ph, pb, pr].forEach(function (n) { grid.appendChild(n); }); + root.appendChild(grid); + + function chart(fn, args, host) { + if (U.charts && U.charts[fn]) host.appendChild(U.charts[fn].apply(null, args)); + else host.appendChild(U.ui.empty(t('hl.er.empty'))); + } + function paint() { + clear(lead); [pd, pt, ph, pb, pr].forEach(function (p) { clear(p.body); }); + if (!data) return; + var d = data, cl = d.classes || {}, range = U.rangeLabel({ inline: true }); + if (!d.errors) { + lead.appendChild(U.ui.lead(t('hl.er.lead.empty'), t('hl.er.lead.empty.body', { range: range }), 'neutral')); + [pd, pt, ph, pb, pr].forEach(function (p) { p.body.appendChild(U.ui.empty(t('hl.er.empty'))); }); + return; + } + lead.appendChild(U.ui.lead(t('hl.er.lead', { n: U.fmt.num(d.errors), atk: pctOf(cl.attack, d.errors), app: pctOf(cl.app, d.errors) }), + t('hl.er.lead.body', { req: U.fmt.num(d.requests), range: range, proxy: pctOf(cl.proxy, d.errors), bot: pctOf(cl.bot, d.errors), rate: U.fmt.pct(d.app_error_rate || 0), inst: d.instance || '' }), + (cl.app || 0) > (cl.attack || 0) ? 'warn' : 'neutral')); + var main = ['app', 'proxy', 'blocked', 'attack', 'bot'].map(function (k) { return { key: k, label: t('hl.cls.' + k), value: cl[k] || 0 }; }); + main.push({ key: 'client', label: t('hl.cls.client_other'), value: cl.client || 0 }); + chart('donut', [main, { title: t('hl.er.donut'), centerLabel: t('hl.er.total') }], pd.body); + if (U.help && U.glossary) { + var lis = pd.body.querySelectorAll('.vz-legend li'); + ['app', 'proxy', 'blocked', 'attack', 'bot', 'client'].forEach(function (k, i) { + if (lis[i] && U.glossary.has('term.error_class.' + k)) U.help(lis[i], 'term.error_class.' + k); + }); + } + var series = ORDER.map(function (k) { return { key: k, label: t('hl.cls.' + k), values: (d.timeline.series[k] || []) }; }); + chart('stackedArea', [series, d.timeline.step, { start: d.timeline.start, title: t('hl.er.time') }], pt.body); + var hm = d.heatmap || {}; + if ((hm.svcs || []).length && (hm.hours || []).length) { + var xl = hm.hours.map(function (h) { return new Date(h * 1000).getHours() + 'h'; }); + var seen = {}, yl = hm.svcs.map(function (n) { + var b = String(n).split('.')[0].slice(0, 8) || n; seen[b] = (seen[b] || 0) + 1; + return seen[b] > 1 ? b + seen[b] : b; + }); + chart('heatmap', [hm.err, xl, yl, { title: t('hl.er.heat') }], ph.body); + } else ph.body.appendChild(U.ui.empty(t('hl.er.empty'))); + var br = d.broken || []; + if (U.help && U.glossary && U.glossary.has('term.broken_link')) U.help(pb.querySelector('h2'), 'term.broken_link'); + if (br.length) pb.body.appendChild(table([{ label: t('hl.er.col.path'), cls: 'mono' }, { label: t('hl.er.col.ref'), cls: 'mono' }, { label: t('hl.er.col.n'), cls: 'num' }, { label: t('hl.er.col.last') }], + br.map(function (b) { return [b.path, b.ref, U.fmt.num(b.n), b.last ? U.fmt.ago(b.last) : '']; }))); + else pb.body.appendChild(U.ui.empty(t('hl.er.empty'))); + var tr = d.top_routes || []; + if (tr.length) pr.body.appendChild(table([{ label: t('hl.er.col.svc') }, { label: t('hl.er.col.route'), cls: 'mono' }, { label: t('hl.er.col.class') }, { label: t('hl.er.col.n'), cls: 'num' }], + tr.map(function (r) { return [r.svc, r.route, (/^(app|proxy|blocked|attack|bot)$/.test(r.class) ? t('hl.cls.' + r.class) : t('hl.cls.client_other')), U.fmt.num(r.n)]; }))); + else pr.body.appendChild(U.ui.empty(t('hl.er.empty'))); + } + function load() { + var my = ++seq; + var p = Object.assign({}, U.rangeParams()); + if (c.host && c.host !== 'all') p.host = c.host; + if (c.domain && c.domain !== 'all') p.host = c.domain; + U.api('/api/v1/errors', p).then(function (r) { if (alive && my === seq) { data = r; paint(); } }, function () { + if (!alive || my !== seq || data) return; + clear(lead); + var b = el('button', { type: 'button', class: 'btn' }, t('hl.er.retry')); + b.addEventListener('click', load); + lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('hl.er.err')), b)); + }); + } + load(); + return { update: function (cx) { c = cx; load(); }, destroy: function () { alive = false; seq++; clear(root); } }; + } + + U.registerPage({ + id: 'errors', group: 'analyze', titleKey: 'hl.er.title', + icon: '', + mount: function (node, ctx) { if (inst) inst.destroy(); inst = create(node, ctx || {}); }, + update: function (ctx) { if (inst) inst.update(ctx); }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); +})(); diff --git a/internal/server/web/evolution.css b/internal/server/web/evolution.css new file mode 100644 index 0000000..9e9c342 --- /dev/null +++ b/internal/server/web/evolution.css @@ -0,0 +1,9 @@ +/* Evolution page (shared helpers .an-* live here: this file loads with the page set) */ +.an-page .an-muted { color: var(--ink-muted); margin: 0; } +.an-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; } +.an-list li { display: flex; justify-content: space-between; align-items: baseline; gap: var(--s-3); padding: 4px 0; border-bottom: 1px solid var(--line); min-width: 0; } +.an-list li:last-child { border-bottom: 0; } +.an-list .an-k, .an-list a { overflow-wrap: anywhere; min-width: 0; } +.an-list .an-n { font-variant-numeric: tabular-nums; color: var(--ink-muted); white-space: nowrap; } +.an-list .an-bad { color: var(--danger); } +.an-list .an-good { color: var(--ok); } diff --git a/internal/server/web/evolution.js b/internal/server/web/evolution.js new file mode 100644 index 0000000..5e3841b --- /dev/null +++ b/internal/server/web/evolution.js @@ -0,0 +1,158 @@ +/* Urutau - EVOLUCAO page: are we getting better or worse? Daily stacked area by + attack family, weekday x hour heatmap, families that appeared or vanished and + the change against the previous period. Data: /api/v1/evolution. Log data is + hostile: every string goes through textContent (Urutau.el). */ +(function () { + 'use strict'; + var U = window.Urutau; + if (!U || !U.registerPage) return; + var el = U.el, t = U.t; + + U.registerI18n({ + en: { + 'an.ev.title': 'Evolution', + 'an.ev.lead.better': 'Getting better: {pct} fewer attacks', + 'an.ev.lead.worse': 'Getting worse: {pct} more attacks', + 'an.ev.lead.same': 'Holding steady against the previous period', + 'an.ev.lead.none': 'No previous period to compare', + 'an.ev.lead.body': '{n} malicious events {range}, against {prev} in the period before.', + 'an.ev.area': 'Attacks per day, by family', + 'an.ev.area.hint': 'The seven busiest families; the rest are grouped as "other".', + 'an.ev.heat': 'When do they come? (UTC)', + 'an.ev.heat.hint': 'Malicious events by weekday and hour of the day.', + 'an.ev.new': 'Appeared', + 'an.ev.new.hint': 'Families seen now that did not exist in the previous period.', + 'an.ev.gone': 'Vanished', + 'an.ev.gone.hint': 'Families of the previous period that did not come back.', + 'an.ev.none': 'None', + 'an.ev.nocmp': 'There is no previous period with events to compare against.', + 'an.ev.other': 'other', + 'an.ev.off': 'The event registry is off', + 'an.ev.off.d': 'This analysis reads the event registry, which is not enabled on this instance.', + 'an.ev.err': 'Could not load this analysis.', + 'an.ev.retry': 'Try again' + }, + 'pt-BR': { + 'an.ev.title': 'Evolução', + 'an.ev.lead.better': 'Melhorando: {pct} menos ataques', + 'an.ev.lead.worse': 'Piorando: {pct} mais ataques', + 'an.ev.lead.same': 'Estável em relação ao período anterior', + 'an.ev.lead.none': 'Sem período anterior para comparar', + 'an.ev.lead.body': '{n} eventos maliciosos {range}, contra {prev} no período anterior.', + 'an.ev.area': 'Ataques por dia, por família', + 'an.ev.area.hint': 'As sete famílias mais ativas; as demais ficam em "outras".', + 'an.ev.heat': 'Quando eles vêm? (UTC)', + 'an.ev.heat.hint': 'Eventos maliciosos por dia da semana e hora do dia.', + 'an.ev.new': 'Surgiram', + 'an.ev.new.hint': 'Famílias vistas agora que não existiam no período anterior.', + 'an.ev.gone': 'Sumiram', + 'an.ev.gone.hint': 'Famílias do período anterior que não voltaram.', + 'an.ev.none': 'Nenhuma', + 'an.ev.nocmp': 'Não há período anterior com eventos para comparar.', + 'an.ev.other': 'outras', + 'an.ev.off': 'O registro de eventos está desligado', + 'an.ev.off.d': 'Esta análise lê o registro de eventos, que não está ativo nesta instância.', + 'an.ev.err': 'Não foi possível carregar esta análise.', + 'an.ev.retry': 'Tentar de novo' + } + }); + + function tip(p, key) { var h2 = p.querySelector('.panel-h h2'); if (h2 && U.help) U.help(h2, key); return p; } + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + function params(ctx) { + var p = Object.assign({}, U.rangeParams()); + if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host; + return p; + } + function famList(rows, tone) { + if (!rows || !rows.length) return el('p', { class: 'an-muted' }, t('an.ev.none')); + var ul = el('ul', { class: 'an-list' }); + rows.slice(0, 10).forEach(function (r) { + ul.appendChild(el('li', null, el('span', { class: 'an-k mono' }, r.fam), el('span', { class: 'an-n an-' + tone }, U.fmt.num(r.n)))); + }); + return ul; + } + + var inst = null; + function create(root, ctx) { + var seq = 0, alive = true, data = null, lang = ctx.lang, c = ctx; + var grid = el('div', { class: 'grid-12 an-page' }); + var lead = el('div', { class: 'span-12' }); + var area = U.ui.panel({ title: t('an.ev.area'), hint: t('an.ev.area.hint'), variant: 'chart', loading: true }); + var heat = U.ui.panel({ title: t('an.ev.heat'), hint: t('an.ev.heat.hint'), loading: true }); + var nw = U.ui.panel({ title: t('an.ev.new'), hint: t('an.ev.new.hint'), loading: true }); + var gone = U.ui.panel({ title: t('an.ev.gone'), hint: t('an.ev.gone.hint'), loading: true }); + tip(area, 'metric.attacks_per_hour_24h'); + [lead, area, heat, nw, gone].forEach(function (n, i) { grid.appendChild(n); if (i) n.classList.add(i === 1 ? 'span-12' : i === 2 ? 'span-12' : 'span-6'); }); + root.appendChild(grid); + + function paint() { + clear(lead); [area, heat, nw, gone].forEach(function (p) { clear(p.body); }); + if (!data.enabled) { lead.appendChild(U.ui.empty(t('an.ev.off'), t('an.ev.off.d'))); return; } + var d = data, pct = d.delta_pct, title, tone = 'neutral'; + if (pct === null || pct === undefined) title = t('an.ev.lead.none'); + else if (Math.abs(pct) < 5) title = t('an.ev.lead.same'); + else if (pct < 0) { title = t('an.ev.lead.better', { pct: Math.abs(Math.round(pct)) + '%' }); tone = 'ok'; } + else { title = t('an.ev.lead.worse', { pct: Math.round(pct) + '%' }); tone = 'danger'; } + lead.appendChild(U.ui.lead(title, t('an.ev.lead.body', { n: U.fmt.num(d.total), range: U.rangeLabel({ inline: true }), prev: U.fmt.num(d.prev) }), tone)); + + // area: top 7 families + other + var tot = {}; + d.days.forEach(function (x) { Object.keys(x.by_fam || {}).forEach(function (f) { tot[f] = (tot[f] || 0) + x.by_fam[f]; }); }); + var top = Object.keys(tot).filter(function (f) { return f !== 'other'; }).sort(function (a, b) { return tot[b] - tot[a]; }).slice(0, 7); + var series = top.map(function (f) { return { key: f, label: f, values: d.days.map(function (x) { return (x.by_fam || {})[f] || 0; }) }; }); + var rest = d.days.map(function (x) { + var s = 0; Object.keys(x.by_fam || {}).forEach(function (f) { if (top.indexOf(f) < 0) s += x.by_fam[f]; }); return s; + }); + if (rest.some(function (v) { return v > 0; })) series.push({ key: 'other', label: t('an.ev.other'), values: rest }); + var start = d.days.length ? Date.parse(d.days[0].d + 'T00:00:00Z') / 1000 : 0; + if (series.length && d.days.length >= 3) area.body.appendChild(U.charts.stackedArea(series, 86400, { start: start, title: t('an.ev.area') })); + else area.body.appendChild(U.ui.empty(t('charts.empty'))); + + // heatmap, Monday first + var order = [1, 2, 3, 4, 5, 6, 0], fmt = new Intl.DateTimeFormat(c.lang || undefined, { weekday: 'short', timeZone: 'UTC' }); + var labels = order.map(function (w) { return fmt.format(new Date(Date.UTC(2023, 0, 1 + w))); }); + var hours = []; for (var h = 0; h < 24; h++) hours.push(h % 3 === 0 ? String(h) : ''); + heat.body.appendChild(U.charts.heatmap(order.map(function (w) { return d.hour_dow[w] || []; }), hours, labels, { title: t('an.ev.heat') })); + + if (pct === null || pct === undefined) { + nw.body.appendChild(el('p', { class: 'an-muted' }, t('an.ev.nocmp'))); + gone.body.appendChild(el('p', { class: 'an-muted' }, t('an.ev.nocmp'))); + } else { + nw.body.appendChild(famList(d.new_families, 'bad')); + gone.body.appendChild(famList(d.gone_families, 'good')); + } + } + function load() { + var my = ++seq; + U.api('/api/v1/evolution', params(c)).then(function (r) { + if (!alive || my !== seq) return; + data = r; paint(); + }, function () { + if (!alive || my !== seq || data) return; + clear(lead); + var b = el('button', { type: 'button', class: 'btn' }, t('an.ev.retry')); + b.addEventListener('click', load); + lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('an.ev.err')), b)); + }); + } + load(); + return { + root: root, + lang: lang, + update: function (cx) { c = cx; load(); }, + destroy: function () { alive = false; seq++; clear(root); } + }; + } + + U.registerPage({ + id: 'evolution', group: 'analyze', titleKey: 'an.ev.title', + icon: '', + mount: function (el, ctx) { if (inst) inst.destroy(); inst = create(el, ctx || {}); }, + update: function (ctx) { + ctx = ctx || {}; + if (inst && ctx.lang !== inst.lang) { var r = inst.root; inst.destroy(); inst = create(r, ctx); } else if (inst) inst.update(ctx); + }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); +})(); diff --git a/internal/server/web/i18n.js b/internal/server/web/i18n.js index aa8aa3b..76f41cb 100644 --- a/internal/server/web/i18n.js +++ b/internal/server/web/i18n.js @@ -240,14 +240,14 @@ window.URUTAU_I18N = { 'state.error': 'error', 'state.disabled': 'disabled', 'cat.ok': 'ok', - 'cat.notfound': 'not found', - 'cat.scanner': 'scanner', - 'cat.exploit': 'exploit', - 'cat.bruteforce': 'brute force', - 'cat.ssh-fail': 'ssh fail', - 'cat.ssh-probe': 'ssh probe', - 'cat.ssh-ok': 'ssh login', - 'cat.ban': 'ban', + 'cat.notfound': 'Nonexistent page (404)', + 'cat.scanner': 'Vulnerability scan', + 'cat.exploit': 'Exploit attempt', + 'cat.bruteforce': 'Brute force (login)', + 'cat.ssh-fail': 'Failed SSH login', + 'cat.ssh-probe': 'SSH probe', + 'cat.ssh-ok': 'Successful SSH login', + 'cat.ban': 'Banned (fail2ban)', 'feed.unban': 'unban', 'ago.now': 'now', 'ago.s': '{n}s ago', @@ -269,7 +269,6 @@ window.URUTAU_I18N = { 'traffic.domain': 'Domain', 'traffic.allDomains': 'All domains', 'traffic.timeline': 'Requests and page views', - 'traffic.timeline.hint': 'Requests answered per time bucket; the darker bar is the share counted as page views.', 'traffic.requests': 'Requests', 'traffic.pages': 'Page views', 'traffic.visitors': 'Visitors', @@ -281,7 +280,6 @@ window.URUTAU_I18N = { 'traffic.cities': 'Cities', 'traffic.browsers': 'Browsers', 'traffic.oses': 'Operating systems', - 'traffic.devices': 'Devices', 'traffic.status': 'Status codes', 'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.', 'traffic.sub.visitors': 'distinct, hash per day', @@ -299,6 +297,188 @@ window.URUTAU_I18N = { 'device.bot': 'bot', 'device.tool': 'tool', 'device.unknown': 'unknown', + 'charts.empty': 'Nothing to chart in this slice.', + 'charts.total': 'Total', + 'charts.item': 'Item', + 'charts.value': 'Value', + 'nav.group.monitor': 'Monitor', + 'nav.group.investigate': 'Investigate', + 'nav.group.analyze': 'Analyze', + 'nav.group.operate': 'Operate', + 'nav.group.reports': 'Reports', + 'traffic.client': 'Client type', + 'traffic.client.hint': 'Share of visitors by kind of client, from the user agent.', + 'traffic.otherReq': 'Other requests', + 'traffic.status.2xx': '2xx success', + 'traffic.status.3xx': '3xx redirect', + 'traffic.status.4xx': '4xx client error', + 'traffic.status.5xx': '5xx server error', + 'traffic.browsers.hint': 'Browser family of the visitors.', + 'traffic.oses.hint': 'Operating system of the visitors.', + 'traffic.status.hint': 'Answers by HTTP status class.', + 'traffic.area.hint': 'Requests per time bucket, split into page views and other requests (assets, APIs, bots).', + 'device.misc': 'other', + 'ov.radar': 'Attack profile', + 'ov.radar.hint': 'Share of each attack category among the attacks of each host.', + 'help.label': 'Explain', + 'help.do': 'What to do', + 'cat.short.ok': 'ok', + 'cat.short.notfound': '404', + 'cat.short.scanner': 'scan', + 'cat.short.exploit': 'exploit', + 'cat.short.bruteforce': 'brute force', + 'cat.short.ssh-fail': 'SSH fail', + 'cat.short.ssh-probe': 'SSH probe', + 'cat.short.ssh-ok': 'SSH login', + 'cat.short.ban': 'ban', + 'help.cat.ok': 'A normal request that was answered successfully (2xx/3xx).', + 'help.cat.ok.do': 'Nothing to do. These are your regular visitors.', + 'help.cat.notfound': 'The visitor asked for an address that does not exist on the site. Almost always a robot guessing paths such as /.env or /wp-admin; it got nothing. Many 404s from one IP means scanning.', + 'help.cat.notfound.do': 'Ignore isolated cases. If one IP keeps doing it, check whether it is already banned or listed on the blocklist.', + 'help.cat.scanner': 'Automated probing for known weak spots (admin panels, backup files, old plugins). It looks for doors, it does not break them.', + 'help.cat.scanner.do': 'Make sure the probed software is not exposed or outdated. Block repeat offenders.', + 'help.cat.exploit': 'A request carrying an attack payload (path traversal, injection, known CVE). It tries to break in.', + 'help.cat.exploit.do': 'Check whether the answer was refused (4xx/5xx). If it was answered 2xx, treat it as an incident and review the application.', + 'help.cat.bruteforce': 'Repeated login attempts guessing passwords on a web form.', + 'help.cat.bruteforce.do': 'Enforce strong passwords and rate limits; block the IP.', + 'help.cat.ssh-fail': 'A failed SSH login: wrong user, wrong password or wrong key.', + 'help.cat.ssh-fail.do': 'Disable password login, keep fail2ban active and review accounts with many failures.', + 'help.cat.ssh-probe': 'A connection to the SSH port that never tried to log in (banner grab, protocol or key exchange scan).', + 'help.cat.ssh-probe.do': 'Usually harmless alone; look for the same IP also failing logins.', + 'help.cat.ssh-ok': 'A successful SSH login.', + 'help.cat.ssh-ok.do': 'If the user or the origin is unexpected, check the account at once.', + 'help.cat.ban': 'fail2ban banned the address after repeated abuse (or lifted a ban).', + 'help.cat.ban.do': 'Nothing to do; the ban is automatic. Check the blocklist if the same IP returns.', + 'help.metric.requests': 'All requests answered by the monitored servers in the slice, including assets and bots.', + 'help.metric.requests.do': 'Compare with malicious events to see how much of the traffic is hostile.', + 'help.metric.malicious': 'Events classified as an attack: scanning, exploits, brute force, SSH failures and probes.', + 'help.metric.malicious.do': 'A sudden rise means a campaign; open Threats to see which category.', + 'help.metric.unique_ips': 'Different IP addresses seen in the slice.', + 'help.metric.unique_ips.do': 'Many new addresses with the same behavior suggest a distributed campaign.', + 'help.metric.attacks_per_hour_24h': 'Average number of attack events per hour over the last 24 hours, with the change against the 24 hours before.', + 'help.metric.attacks_per_hour_24h.do': 'Above your normal baseline? Check Threats for the dominant category.', + 'help.metric.moving_avg_7d_per_hour': 'Attacks per hour averaged over 7 days: your usual background noise.', + 'help.metric.moving_avg_7d_per_hour.do': 'Use it as the baseline; only deviations from it deserve attention.', + 'help.metric.trend': 'How the attack rate moves compared with the previous period (rising, steady, falling).', + 'help.metric.trend.do': 'A rising trend with new attackers is the pattern of a fresh campaign.', + 'help.metric.active_attackers_24h': 'Distinct attacking IPs active in the last 24 hours.', + 'help.metric.active_attackers_24h.do': 'If it keeps growing, review the blocklist coverage.', + 'help.metric.active_attackers_1h': 'Distinct attacking IPs active in the last hour.', + 'help.metric.active_attackers_1h.do': 'A spike here is the earliest sign of a new wave.', + 'help.metric.new_attackers': 'Attacking IPs seen for the first time in this period.', + 'help.metric.new_attackers.do': 'Many new IPs in a short time point to rotating infrastructure.', + 'help.metric.returning_rate': 'Share of attackers that had already been seen before.', + 'help.metric.returning_rate.do': 'High values mean persistent attackers: banning them pays off.', + 'help.metric.sessions_per_day': 'Average attack sessions per day. A session groups one IP’s requests separated by short pauses.', + 'help.metric.sessions_per_day.do': 'Compare with active attackers to see whether each one is persistent.', + 'help.metric.exposure_rate': 'Share of attacks answered with success (2xx) on a sensitive path. This is the only number that shows real exposure.', + 'help.metric.exposure_rate.do': 'Anything above 0% needs a look: open the IP page and the exposure section.', + 'help.metric.exploits_refused_pct': 'Share of exploit attempts that the server refused (4xx/5xx).', + 'help.metric.exploits_refused_pct.do': 'Close to 100% is healthy. Lower means some payloads got through.', + 'help.metric.ban_coverage': 'Share of attacking IPs that fail2ban has banned.', + 'help.metric.ban_coverage.do': 'Low coverage means attackers are not being stopped: check jails and thresholds.', + 'help.metric.blocklist_coverage': 'Share of hostile IPs that are present on the exported blocklist.', + 'help.metric.blocklist_coverage.do': 'Import the blocklist into your firewall to close the gap.', + 'help.metric.blocklist_leak': 'Hostile IPs that were on the blocklist and still got through.', + 'help.metric.blocklist_leak.do': 'Check that the firewall really applies the list.', + 'help.metric.mttb': 'Mean time to ban: how long an attacker acts before fail2ban bans it (median).', + 'help.metric.mttb.do': 'High values mean the ban rules are too slow.', + 'help.metric.visitors': 'Distinct visitors, counted with a daily rotating hash. No IP is stored.', + 'help.metric.visitors.do': 'Compare with page views to estimate engagement.', + 'help.metric.pages': 'Page views: successful answers to real page requests, without assets, bots or tools.', + 'help.metric.pages.do': 'A big gap to requests is normal: images, scripts and APIs are not pages.', + 'help.metric.bytes': 'Total data sent to clients.', + 'help.metric.bytes.do': 'A jump without more page views can mean downloads or scraping.', + 'help.metric.latency': 'Response time: p50 is the typical request, p95 is the slowest 5%.', + 'help.metric.latency.do': 'A high p95 with a normal p50 points to a few slow endpoints.', + 'help.metric.bots': 'Requests made by search and AI crawlers.', + 'help.metric.bots.do': 'Unwanted crawlers can be limited in robots.txt or at the proxy.', + 'help.term.session': 'A burst of requests from one IP separated from the next by a long pause. It turns a flood of log lines into a few readable episodes.', + 'help.term.session.do': 'Open an IP to see its sessions in order.', + 'help.term.stage.recon': 'Reconnaissance: the attacker maps what exists (404s, probing).', + 'help.term.stage.recon.do': 'Low risk by itself.', + 'help.term.stage.probe': 'Probing: it tests specific weak points.', + 'help.term.stage.probe.do': 'Watch whether it moves on to exploitation.', + 'help.term.stage.exploit': 'Exploitation: it sends attack payloads.', + 'help.term.stage.exploit.do': 'Check whether they were refused.', + 'help.term.stage.access': 'Access: it got a successful answer or logged in.', + 'help.term.stage.access.do': 'Treat as an incident and review the system.', + 'help.term.stage.banned': 'Banned: fail2ban stopped it.', + 'help.term.stage.banned.do': 'Confirm it does not come back from another address.', + 'help.term.campaign': 'Several IPs acting alike (same tools, same targets, same time): probably one operator.', + 'help.term.campaign.do': 'Block the whole network range, not just one IP.', + 'help.term.family': 'A group of similar requests, such as WordPress, version control files or SQL injection.', + 'help.term.family.do': 'Use it to see what the attackers are after.', + 'help.term.mitre': 'A standard name for an attack technique, from the MITRE ATT&CK catalogue (for example T1110 Brute Force).', + 'help.term.mitre.do': 'Use the code to search for mitigations.', + 'help.term.net_type': 'The kind of network that owns the address: hosting, residential, mobile, university, VPN.', + 'help.term.net_type.do': 'Hosting and VPN origins are rarely real customers.', + 'help.term.cadence': 'How regular the time between requests is. Machines are regular; people are not.', + 'help.term.cadence.do': 'Very regular cadence confirms automation.', + 'help.term.score': 'A number from 0 to 1000 that adds up the evidence against an IP. Suspicious from 10, hostile from 50 (a strong rule can also make it hostile).', + 'help.term.score.do': 'Sort by score to decide what to block first.', + 'help.term.level': 'The verdict derived from the score: low, suspicious or hostile.', + 'help.term.level.do': 'Hostile IPs are the candidates for the blocklist.', + 'help.term.fcrdns': 'Forward-confirmed reverse DNS: the IP’s name resolves back to the same IP. Real search engines pass; impostors do not.', + 'help.term.fcrdns.do': 'A bot claiming to be Google without FCrDNS is fake.', + 'help.term.exposure': 'A sensitive path (such as /.env) that answered successfully to an attacker. Real exposure, not just an attempt.', + 'help.term.exposure.do': 'Remove or protect the resource and rotate any secret in it.', + 'help.term.blocklist': 'The list of hostile IPs ready to import into a firewall. Only addresses with strong evidence are included.', + 'help.term.blocklist.do': 'Export it as text or JSON and load it into your firewall or fail2ban.', + 'help.term.peer': 'Another Urutau instance that shares its data with this one.', + 'help.term.peer.do': 'If a peer is offline, its numbers are missing from the totals.', + 'help.term.hub': 'The instance that gathers the data of its peers into one view.', + 'help.term.hub.do': 'Open the hub to see all servers together.', + 'help.term.client_type': 'The kind of client behind each request: desktop, mobile, tablet, bot, tool or unknown, from its user agent.', + 'help.term.client_type.do': 'A large share of tools or unknown clients is worth checking.', + 'help.term.status_class': 'HTTP answers grouped by first digit: 2xx success, 3xx redirect, 4xx client error, 5xx server error.', + 'help.term.status_class.do': '5xx means a problem on your side; many 4xx is usually scanning.', + 'help.term.attack_profile': 'The share of each attack category among all attacks of a host. Different shapes mean different kinds of pressure.', + 'help.term.attack_profile.do': 'A host with a very different shape is being targeted differently.', + 'help.term.categories': 'Attack categories: 404 = a page that does not exist (usually a robot guessing paths); scan = automated search for weak spots; brute force = password guessing on a login form; exploit = a request carrying an attack payload; SSH fail = a wrong SSH login; SSH probe = a connection to the SSH port with no login attempt; ban = fail2ban blocked the address.', + 'help.term.categories.do': 'Hover or focus the category names in the legend for the detail of each one.', + 'help.term.apdex': 'Apdex: a 0 to 1 satisfaction score from response times. Fast answers count fully, tolerable ones count half, slow ones count zero.', + 'help.term.apdex.do': 'Below 0.85 means users feel slowness: look at the slowest endpoints.', + 'help.term.slo': 'Service level objective: the target you promise, for example 99.9% of requests answered without a server error.', + '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.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).', + 'help.term.error_class.proxy.do': 'Check whether the backend is up and the proxy limits are right.', + 'help.term.error_class.blocked': 'Requests refused on purpose by a rule (403, firewall or ban).', + 'help.term.error_class.blocked.do': 'Usually healthy. Check only if real users are being blocked.', + 'help.term.error_class.attack': 'Errors caused by attack traffic (probing for pages that do not exist, exploit attempts).', + 'help.term.error_class.attack.do': 'Not a service problem. Do not count it against the SLO.', + 'help.term.error_class.bot': 'Errors triggered by crawlers and automated clients that are not attacks.', + 'help.term.error_class.bot.do': 'Fix broken links they find or limit them in robots.txt.', + 'help.term.error_class.client': 'Errors caused by real visitors (a mistyped address, an expired link).', + 'help.term.error_class.client.do': 'If frequent for one page, there may be a broken link.', + 'help.term.error_class.unknown': 'Errors that could not be assigned to a cause.', + 'help.term.error_class.unknown.do': 'Look at the examples to decide where they belong.', + 'help.term.broken_link': 'An address that real visitors request and that answers 404. Usually a link that points to a page that was moved or removed.', + 'help.term.broken_link.do': 'Fix the link or add a redirect to the new address.', + 'help.term.gini': 'Gini index: how concentrated the attacks are, from 0 (spread evenly) to 1 (a few sources do almost everything).', + 'help.term.gini.do': 'A high value means blocking a few addresses removes most of the noise.', + 'help.term.pareto': 'Pareto curve: the share of all attacks produced by the top sources (the 80/20 view).', + 'help.term.pareto.do': 'See how few IPs explain most of the attacks and block those first.', + 'help.term.kaplan_meier': 'Survival curve (Kaplan-Meier): the share of attackers still active after a given time. It shows how long they persist.', + 'help.term.kaplan_meier.do': 'A curve that stays high means persistent attackers: tighten the ban rules.', + 'help.term.recidivism': 'The share of banned addresses that came back after the ban ended.', + 'help.term.recidivism.do': 'High recidivism suggests longer bans or a permanent blocklist.', + 'help.term.mitre_tactic': 'A tactic is the goal of an attacker in the MITRE ATT&CK catalogue (reconnaissance, initial access, credential access...). Techniques are the ways to reach it.', + 'help.term.mitre_tactic.do': 'Use tactics to see which stage of an attack you are mostly seeing.', + 'help.term.ttb': 'Time to ban: how long an attacker acted before being banned.', + 'help.term.ttb.do': 'Long times mean the ban rules react too late.', + 'help.term.leak': 'A leak is a request from an address that was already banned or blocklisted and still got an answer.', + 'help.term.leak.do': 'Check that the firewall applies the blocklist at the right place.', + 'help.term.integrity_gap': 'A period where the logs have a hole: no lines were read, so events may be missing.', + 'help.term.integrity_gap.do': 'Check the log source and whether the file was rotated or the service stopped.', + 'help.term.nonhuman': 'Non-human clients: bots, crawlers, tools and scripts, recognised by their user agent or behavior.', + 'help.term.nonhuman.do': 'Not counted as visitors. Limit unwanted ones in robots.txt or at the proxy.', + 'help.term.visit': 'A legitimate visit, shown anonymously on the live map: a real visitor, with no IP or identity stored.', + 'help.term.visit.do': 'Nothing to do; it only shows where your audience comes from.', 'login.token': 'Access token', 'login.submit': 'Sign in', 'login.err.bad': 'Invalid token.', @@ -532,14 +712,14 @@ window.URUTAU_I18N = { 'state.error': 'erro', 'state.disabled': 'desativada', 'cat.ok': 'ok', - 'cat.notfound': 'não encontrado', - 'cat.scanner': 'scanner', - 'cat.exploit': 'exploit', - 'cat.bruteforce': 'força bruta', - 'cat.ssh-fail': 'falha ssh', - 'cat.ssh-probe': 'sondagem ssh', - 'cat.ssh-ok': 'login ssh', - 'cat.ban': 'ban', + 'cat.notfound': 'Página inexistente (404)', + 'cat.scanner': 'Varredura de vulnerabilidades', + 'cat.exploit': 'Tentativa de exploração', + 'cat.bruteforce': 'Força bruta (login)', + 'cat.ssh-fail': 'Login SSH falho', + 'cat.ssh-probe': 'Sondagem SSH', + 'cat.ssh-ok': 'Login SSH bem-sucedido', + 'cat.ban': 'Banido (fail2ban)', 'feed.unban': 'desbanido', 'ago.now': 'agora', 'ago.s': 'há {n}s', @@ -561,7 +741,6 @@ window.URUTAU_I18N = { 'traffic.domain': 'Domínio', 'traffic.allDomains': 'Todos os domínios', 'traffic.timeline': 'Requisições e páginas vistas', - 'traffic.timeline.hint': 'Requisições atendidas por intervalo; a barra mais escura é a parcela contada como página vista.', 'traffic.requests': 'Requisições', 'traffic.pages': 'Páginas vistas', 'traffic.visitors': 'Visitantes', @@ -573,7 +752,6 @@ window.URUTAU_I18N = { 'traffic.cities': 'Cidades', 'traffic.browsers': 'Navegadores', 'traffic.oses': 'Sistemas operacionais', - 'traffic.devices': 'Dispositivos', 'traffic.status': 'Códigos de status', 'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.', 'traffic.sub.visitors': 'distintos, hash diário', @@ -591,6 +769,188 @@ window.URUTAU_I18N = { 'device.bot': 'bot', 'device.tool': 'ferramenta', 'device.unknown': 'desconhecido', + 'charts.empty': 'Nada a exibir neste recorte.', + 'charts.total': 'Total', + 'charts.item': 'Item', + 'charts.value': 'Valor', + 'nav.group.monitor': 'Monitorar', + 'nav.group.investigate': 'Investigar', + 'nav.group.analyze': 'Analisar', + 'nav.group.operate': 'Operar', + 'nav.group.reports': 'Relatórios', + 'traffic.client': 'Tipo de cliente', + 'traffic.client.hint': 'Parcela dos visitantes por tipo de cliente, a partir do user-agent.', + 'traffic.otherReq': 'Outras requisições', + 'traffic.status.2xx': '2xx sucesso', + 'traffic.status.3xx': '3xx redirecionamento', + 'traffic.status.4xx': '4xx erro do cliente', + 'traffic.status.5xx': '5xx erro do servidor', + 'traffic.browsers.hint': 'Família de navegador dos visitantes.', + 'traffic.oses.hint': 'Sistema operacional dos visitantes.', + 'traffic.status.hint': 'Respostas por classe de status HTTP.', + 'traffic.area.hint': 'Requisições por intervalo, divididas em páginas vistas e outras requisições (arquivos, APIs, robôs).', + 'device.misc': 'outros', + 'ov.radar': 'Perfil de ataque', + 'ov.radar.hint': 'Parcela de cada categoria de ataque entre os ataques de cada host.', + 'help.label': 'Explicar', + 'help.do': 'O que fazer', + 'cat.short.ok': 'ok', + 'cat.short.notfound': '404', + 'cat.short.scanner': 'varredura', + 'cat.short.exploit': 'exploração', + 'cat.short.bruteforce': 'força bruta', + 'cat.short.ssh-fail': 'SSH falho', + 'cat.short.ssh-probe': 'sondagem SSH', + 'cat.short.ssh-ok': 'login SSH', + 'cat.short.ban': 'ban', + 'help.cat.ok': 'Um acesso normal que foi atendido com sucesso (2xx/3xx).', + 'help.cat.ok.do': 'Nada a fazer. São os seus visitantes comuns.', + 'help.cat.notfound': 'O visitante pediu um endereço que não existe no site. Quase sempre é um robô chutando caminhos como /.env ou /wp-admin; ele não obteve nada. Muitos 404 de um mesmo IP = varredura.', + 'help.cat.notfound.do': 'Ignore casos isolados. Se um IP insiste, confira se já está banido ou na lista de bloqueio.', + 'help.cat.scanner': 'Sondagem automática atrás de pontos fracos conhecidos (painéis, backups, plugins antigos). Procura portas, não as arromba.', + 'help.cat.scanner.do': 'Confirme que o software sondado não está exposto nem desatualizado. Bloqueie reincidentes.', + 'help.cat.exploit': 'Requisição com carga de ataque (travessia de caminho, injeção, CVE conhecida). Tenta invadir.', + 'help.cat.exploit.do': 'Veja se a resposta foi recusada (4xx/5xx). Se foi 2xx, trate como incidente e revise a aplicação.', + 'help.cat.bruteforce': 'Tentativas repetidas de login adivinhando senhas em um formulário web.', + 'help.cat.bruteforce.do': 'Exija senhas fortes e limite de tentativas; bloqueie o IP.', + 'help.cat.ssh-fail': 'Um login SSH que falhou: usuário, senha ou chave errados.', + 'help.cat.ssh-fail.do': 'Desative login por senha, mantenha o fail2ban ativo e revise contas com muitas falhas.', + 'help.cat.ssh-probe': 'Uma conexão à porta SSH que nunca tentou entrar (leitura de banner, varredura de protocolo ou troca de chaves).', + 'help.cat.ssh-probe.do': 'Sozinha costuma ser inofensiva; veja se o mesmo IP também falha logins.', + 'help.cat.ssh-ok': 'Um login SSH bem-sucedido.', + 'help.cat.ssh-ok.do': 'Se o usuário ou a origem forem inesperados, verifique a conta imediatamente.', + 'help.cat.ban': 'O fail2ban baniu o endereço após abusos repetidos (ou retirou o ban).', + 'help.cat.ban.do': 'Nada a fazer; o ban é automático. Veja a lista de bloqueio se o mesmo IP voltar.', + 'help.metric.requests': 'Todas as requisições atendidas pelos servidores monitorados no recorte, incluindo arquivos estáticos e robôs.', + 'help.metric.requests.do': 'Compare com os eventos maliciosos para ver quanto do tráfego é hostil.', + 'help.metric.malicious': 'Eventos classificados como ataque: varredura, exploração, força bruta, falhas e sondagens SSH.', + 'help.metric.malicious.do': 'Uma alta repentina indica campanha; abra Ameaças para ver a categoria.', + 'help.metric.unique_ips': 'Endereços IP diferentes vistos no recorte.', + 'help.metric.unique_ips.do': 'Muitos endereços novos com o mesmo comportamento sugerem campanha distribuída.', + 'help.metric.attacks_per_hour_24h': 'Média de eventos de ataque por hora nas últimas 24 horas, com a variação frente às 24 horas anteriores.', + 'help.metric.attacks_per_hour_24h.do': 'Acima do seu normal? Veja em Ameaças qual categoria domina.', + 'help.metric.moving_avg_7d_per_hour': 'Ataques por hora médios em 7 dias: o seu ruído de fundo habitual.', + 'help.metric.moving_avg_7d_per_hour.do': 'Use como linha de base; só desvios dela merecem atenção.', + 'help.metric.trend': 'Como a taxa de ataques se move frente ao período anterior (subindo, estável, caindo).', + 'help.metric.trend.do': 'Tendência de alta com atacantes novos é o padrão de uma campanha recente.', + 'help.metric.active_attackers_24h': 'IPs atacantes distintos ativos nas últimas 24 horas.', + 'help.metric.active_attackers_24h.do': 'Se continuar crescendo, revise a cobertura da lista de bloqueio.', + 'help.metric.active_attackers_1h': 'IPs atacantes distintos ativos na última hora.', + 'help.metric.active_attackers_1h.do': 'Um pico aqui é o primeiro sinal de uma nova onda.', + 'help.metric.new_attackers': 'IPs atacantes vistos pela primeira vez neste período.', + 'help.metric.new_attackers.do': 'Muitos IPs novos em pouco tempo apontam para infraestrutura rotativa.', + 'help.metric.returning_rate': 'Parcela dos atacantes que já tinham sido vistos antes.', + 'help.metric.returning_rate.do': 'Valores altos indicam atacantes persistentes: banir compensa.', + 'help.metric.sessions_per_day': 'Média de sessões de ataque por dia. Uma sessão agrupa as requisições de um IP separadas por pausas curtas.', + 'help.metric.sessions_per_day.do': 'Compare com os atacantes ativos para ver se cada um é persistente.', + 'help.metric.exposure_rate': 'Parcela dos ataques respondidos com sucesso (2xx) em um caminho sensível. É o único número que mostra exposição real.', + 'help.metric.exposure_rate.do': 'Qualquer valor acima de 0% merece análise: abra a página do IP e a seção de exposição.', + 'help.metric.exploits_refused_pct': 'Parcela das tentativas de exploração que o servidor recusou (4xx/5xx).', + 'help.metric.exploits_refused_pct.do': 'Perto de 100% é saudável. Menos indica que alguma carga passou.', + 'help.metric.ban_coverage': 'Parcela dos IPs atacantes que o fail2ban baniu.', + 'help.metric.ban_coverage.do': 'Cobertura baixa significa atacantes não contidos: revise as jails e os limites.', + 'help.metric.blocklist_coverage': 'Parcela dos IPs hostis que estão na lista de bloqueio exportada.', + 'help.metric.blocklist_coverage.do': 'Importe a lista no firewall para fechar a diferença.', + 'help.metric.blocklist_leak': 'IPs hostis que estavam na lista de bloqueio e ainda assim passaram.', + 'help.metric.blocklist_leak.do': 'Verifique se o firewall realmente aplica a lista.', + 'help.metric.mttb': 'Tempo médio até o ban: quanto o atacante age antes de ser banido (mediana).', + 'help.metric.mttb.do': 'Valores altos indicam regras de ban lentas demais.', + 'help.metric.visitors': 'Visitantes distintos, contados com um hash diário rotativo. Nenhum IP é guardado.', + 'help.metric.visitors.do': 'Compare com as páginas vistas para estimar o engajamento.', + 'help.metric.pages': 'Páginas vistas: respostas bem-sucedidas a pedidos de página reais, sem arquivos estáticos, robôs ou ferramentas.', + 'help.metric.pages.do': 'Uma grande diferença para as requisições é normal: imagens, scripts e APIs não são páginas.', + 'help.metric.bytes': 'Total de dados enviados aos clientes.', + 'help.metric.bytes.do': 'Um salto sem mais páginas vistas pode indicar downloads ou raspagem.', + 'help.metric.latency': 'Tempo de resposta: p50 é o pedido típico, p95 é o dos 5% mais lentos.', + 'help.metric.latency.do': 'p95 alto com p50 normal aponta para poucos endpoints lentos.', + 'help.metric.bots': 'Requisições feitas por robôs de busca e de IA.', + 'help.metric.bots.do': 'Robôs indesejados podem ser limitados no robots.txt ou no proxy.', + 'help.term.session': 'Uma rajada de requisições de um IP separada da próxima por uma pausa longa. Transforma milhares de linhas em poucos episódios legíveis.', + 'help.term.session.do': 'Abra um IP para ver as sessões em ordem.', + 'help.term.stage.recon': 'Reconhecimento: o atacante mapeia o que existe (404, sondagem).', + 'help.term.stage.recon.do': 'Risco baixo isoladamente.', + 'help.term.stage.probe': 'Sondagem: testa pontos fracos específicos.', + 'help.term.stage.probe.do': 'Acompanhe se avança para a exploração.', + 'help.term.stage.exploit': 'Exploração: envia cargas de ataque.', + 'help.term.stage.exploit.do': 'Verifique se foram recusadas.', + 'help.term.stage.access': 'Acesso: obteve resposta de sucesso ou entrou.', + 'help.term.stage.access.do': 'Trate como incidente e revise o sistema.', + 'help.term.stage.banned': 'Banido: o fail2ban o conteve.', + 'help.term.stage.banned.do': 'Confirme que não volta por outro endereço.', + 'help.term.campaign': 'Vários IPs agindo de forma parecida (mesmas ferramentas, alvos e horários): provavelmente um único operador.', + 'help.term.campaign.do': 'Bloqueie a faixa de rede inteira, não só um IP.', + 'help.term.family': 'Um grupo de requisições parecidas, como WordPress, arquivos de controle de versão ou injeção de SQL.', + 'help.term.family.do': 'Use para ver o que os atacantes procuram.', + 'help.term.mitre': 'Nome padronizado de uma técnica de ataque, do catálogo MITRE ATT&CK (por exemplo T1110 Força bruta).', + 'help.term.mitre.do': 'Use o código para buscar mitigações.', + 'help.term.net_type': 'O tipo de rede dona do endereço: hospedagem, residencial, móvel, universidade, VPN.', + 'help.term.net_type.do': 'Origens de hospedagem e VPN raramente são clientes reais.', + 'help.term.cadence': 'Quão regular é o intervalo entre as requisições. Máquinas são regulares; pessoas não.', + 'help.term.cadence.do': 'Cadência muito regular confirma automação.', + 'help.term.score': 'Número de 0 a 1000 que soma as evidências contra um IP. Suspeito a partir de 10, hostil a partir de 50 (uma regra forte também pode torná-lo hostil).', + 'help.term.score.do': 'Ordene por pontuação para decidir o que bloquear primeiro.', + 'help.term.level': 'O veredito derivado da pontuação: baixo, suspeito ou hostil.', + 'help.term.level.do': 'IPs hostis são os candidatos à lista de bloqueio.', + 'help.term.fcrdns': 'DNS reverso confirmado: o nome do IP resolve de volta para o mesmo IP. Buscadores reais passam; impostores não.', + 'help.term.fcrdns.do': 'Um robô que diz ser Google sem FCrDNS é falso.', + 'help.term.exposure': 'Um caminho sensível (como /.env) que respondeu com sucesso a um atacante. Exposição real, não apenas tentativa.', + 'help.term.exposure.do': 'Remova ou proteja o recurso e troque qualquer segredo contido nele.', + 'help.term.blocklist': 'A lista de IPs hostis pronta para importar em um firewall. Só entram endereços com evidência forte.', + 'help.term.blocklist.do': 'Exporte em texto ou JSON e carregue no firewall ou no fail2ban.', + 'help.term.peer': 'Outra instância do Urutau que compartilha seus dados com esta.', + 'help.term.peer.do': 'Se um par está offline, os números dele faltam nos totais.', + 'help.term.hub': 'A instância que reúne os dados dos pares em uma só visão.', + 'help.term.hub.do': 'Abra o hub para ver todos os servidores juntos.', + 'help.term.client_type': 'O tipo de cliente por trás de cada requisição: computador, celular, tablet, robô, ferramenta ou desconhecido, pelo user-agent.', + 'help.term.client_type.do': 'Uma parcela grande de ferramentas ou desconhecidos merece verificação.', + 'help.term.status_class': 'Respostas HTTP agrupadas pelo primeiro dígito: 2xx sucesso, 3xx redirecionamento, 4xx erro do cliente, 5xx erro do servidor.', + 'help.term.status_class.do': '5xx indica problema do seu lado; muitos 4xx costumam ser varredura.', + 'help.term.attack_profile': 'A parcela de cada categoria de ataque entre todos os ataques de um host. Formas diferentes indicam pressões diferentes.', + 'help.term.attack_profile.do': 'Um host com forma muito diferente está sendo alvo de outro tipo de ataque.', + 'help.term.categories': 'Categorias de ataque: 404 = página que não existe (em geral um robô chutando caminhos); varredura = busca automática por pontos fracos; força bruta = adivinhar senha em um login; exploração = requisição com carga de ataque; SSH falho = login SSH errado; sondagem SSH = conexão à porta SSH sem tentar entrar; ban = o fail2ban bloqueou o endereço.', + 'help.term.categories.do': 'Passe o mouse ou o foco nos nomes da legenda para ver o detalhe de cada uma.', + 'help.term.apdex': 'Apdex: nota de satisfação de 0 a 1 a partir dos tempos de resposta. Respostas rápidas valem tudo, toleráveis valem metade, lentas valem zero.', + 'help.term.apdex.do': 'Abaixo de 0,85 os usuários sentem lentidão: veja os endpoints mais lentos.', + 'help.term.slo': 'Objetivo de nível de serviço: a meta prometida, por exemplo 99,9% das requisições atendidas sem erro do servidor.', + '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.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).', + 'help.term.error_class.proxy.do': 'Veja se o backend está no ar e se os limites do proxy estão certos.', + 'help.term.error_class.blocked': 'Requisições recusadas de propósito por uma regra (403, firewall ou ban).', + 'help.term.error_class.blocked.do': 'Em geral é saudável. Verifique só se usuários reais estão sendo bloqueados.', + 'help.term.error_class.attack': 'Erros causados por tráfego de ataque (sondagem de páginas inexistentes, tentativas de exploração).', + 'help.term.error_class.attack.do': 'Não é problema do serviço. Não conte contra o SLO.', + 'help.term.error_class.bot': 'Erros provocados por rastreadores e clientes automáticos que não são ataques.', + 'help.term.error_class.bot.do': 'Corrija os links quebrados que eles acham ou limite-os no robots.txt.', + 'help.term.error_class.client': 'Erros causados por visitantes reais (endereço digitado errado, link expirado).', + 'help.term.error_class.client.do': 'Se forem frequentes em uma página, pode haver um link quebrado.', + 'help.term.error_class.unknown': 'Erros que não puderam ser atribuídos a uma causa.', + 'help.term.error_class.unknown.do': 'Veja os exemplos para decidir a que causa pertencem.', + 'help.term.broken_link': 'Um endereço que visitantes reais pedem e que responde 404. Em geral um link apontando para uma página movida ou removida.', + 'help.term.broken_link.do': 'Corrija o link ou crie um redirecionamento para o novo endereço.', + 'help.term.gini': 'Índice de Gini: quanto os ataques estão concentrados, de 0 (bem espalhados) a 1 (poucas fontes fazem quase tudo).', + 'help.term.gini.do': 'Valor alto significa que bloquear poucos endereços elimina a maior parte do ruído.', + 'help.term.pareto': 'Curva de Pareto: a parcela de todos os ataques produzida pelas maiores fontes (visão 80/20).', + 'help.term.pareto.do': 'Veja quantos poucos IPs explicam a maioria dos ataques e bloqueie esses primeiro.', + 'help.term.kaplan_meier': 'Curva de sobrevivência (Kaplan-Meier): a parcela de atacantes ainda ativos após certo tempo. Mostra quanto tempo persistem.', + 'help.term.kaplan_meier.do': 'Curva que se mantém alta indica atacantes persistentes: endureça as regras de ban.', + 'help.term.recidivism': 'A parcela dos endereços banidos que voltaram depois do fim do ban.', + 'help.term.recidivism.do': 'Reincidência alta sugere bans mais longos ou lista de bloqueio permanente.', + 'help.term.mitre_tactic': 'Uma tática é o objetivo do atacante no catálogo MITRE ATT&CK (reconhecimento, acesso inicial, acesso a credenciais...). As técnicas são os jeitos de alcançá-lo.', + 'help.term.mitre_tactic.do': 'Use as táticas para ver em qual estágio de ataque você mais está.', + 'help.term.ttb': 'Tempo até o ban: quanto tempo o atacante agiu antes de ser banido.', + 'help.term.ttb.do': 'Tempos longos indicam regras de ban que reagem tarde.', + 'help.term.leak': 'Vazamento é uma requisição de um endereço já banido ou na lista de bloqueio que ainda assim foi atendida.', + 'help.term.leak.do': 'Verifique se o firewall aplica a lista de bloqueio no lugar certo.', + 'help.term.integrity_gap': 'Um período em que os logs têm um buraco: nenhuma linha foi lida, então podem faltar eventos.', + 'help.term.integrity_gap.do': 'Veja a fonte de log e se o arquivo foi rotacionado ou o serviço parou.', + 'help.term.nonhuman': 'Clientes não humanos: robôs, rastreadores, ferramentas e scripts, reconhecidos pelo user-agent ou pelo comportamento.', + 'help.term.nonhuman.do': 'Não contam como visitantes. Limite os indesejados no robots.txt ou no proxy.', + 'help.term.visit': 'Uma visita legítima, mostrada de forma anônima no mapa ao vivo: um visitante real, sem IP nem identidade guardados.', + 'help.term.visit.do': 'Nada a fazer; apenas mostra de onde vem o seu público.', 'login.token': 'Token de acesso', 'login.submit': 'Entrar', 'login.err.bad': 'Token inválido.', diff --git a/internal/server/web/index.html b/internal/server/web/index.html index b96dc74..3f24e54 100644 --- a/internal/server/web/index.html +++ b/internal/server/web/index.html @@ -7,10 +7,6 @@ Urutau - - - - @@ -65,9 +61,5 @@ - - - - diff --git a/internal/server/web/integrity.css b/internal/server/web/integrity.css new file mode 100644 index 0000000..cf24273 --- /dev/null +++ b/internal/server/web/integrity.css @@ -0,0 +1,24 @@ +/* Urutau - INTEGRITY page. Selectors prefixed ig-. */ +.ig { display: flex; flex-direction: column; gap: var(--grid-gap, 16px); min-width: 0; } +.ig-box { display: flex; flex-direction: column; gap: var(--grid-gap, 16px); min-width: 0; } +.ig-stats > * { grid-column: span 12; } +@media (min-width: 700px) { .ig-stats > .span-3 { grid-column: span 6; } } +@media (min-width: 1100px) { .ig-stats > .span-3 { grid-column: span 3; } } +@media (min-width: 1100px) { + .ig .grid-12 > .span-6 { grid-column: span 6; } + .ig .grid-12 > .span-8 { grid-column: span 8; } + .ig .grid-12 > .span-4 { grid-column: span 4; } +} +.ig-scroll { overflow-x: auto; max-width: 100%; } +.ig-table { width: 100%; border-collapse: collapse; font-size: .8125rem; } +.ig-table th { text-align: left; font-weight: 600; color: var(--ink-muted); padding: 6px 10px; border-bottom: 1px solid var(--line); white-space: nowrap; } +.ig-table td { padding: 6px 10px; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; } +.ig-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; font-size: .875rem; overflow-wrap: anywhere; } +.ig-muted { color: var(--ink-muted); font-size: .8125rem; } +.ig-kv { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 8px 0 0; font-size: .875rem; } +.ig-kv dt { color: var(--ink-muted); } +.ig-kv dd { margin: 0; text-align: right; overflow-wrap: anywhere; } +.ig .vz-heat { width: 100%; max-width: 100%; min-width: 0; overflow: hidden; } +.ig .vz-heat svg { max-width: 100%; height: auto; display: block; } +.ig .panel, .ig .panel-b { min-width: 0; max-width: 100%; } +.ig-heatbox { position: relative; overflow: hidden; max-width: 100%; } diff --git a/internal/server/web/integrity.js b/internal/server/web/integrity.js new file mode 100644 index 0000000..280ff7b --- /dev/null +++ b/internal/server/web/integrity.js @@ -0,0 +1,279 @@ +/* Urutau - INTEGRITY page ("Is the data complete?"): volume ingested per host and + hour (holes show as empty cells), state of every source and peer, share of + malformed lines, event log and geolocation base. Log data is hostile: every + dynamic string goes through textContent (the shell's el/h helpers). */ +(function () { + 'use strict'; + + var STATES = { following: 1, waiting: 1, backfill: 1, error: 1, disabled: 1 }; + var ICON = ''; + + function boot() { + var U = window.Urutau; + if (!U || !U.registerPage) return false; + U.registerI18n({ + en: { + 'ig.title': 'Integrity', + 'ig.lead.ok': 'The data is complete', + 'ig.lead.okBody': 'No gaps of {n} hours or more, every source answers and few lines were rejected.', + 'ig.lead.bad.one': '{n} hole in the data', + 'ig.lead.bad.other': '{n} holes in the data', + 'ig.lead.badBody': 'Silences of two hours or more in sources that normally report, offline peers or sources in error. Check the panels below.', + 'ig.lead.loading': 'Checking the data...', + 'ig.stat.hosts': 'Hosts reporting', + 'ig.stat.gaps': 'Gaps found', + 'ig.stat.parse': 'Invalid lines', + 'ig.stat.log': 'Event log', + 'ig.stat.logSub': '{days} days, {size}', + 'ig.stat.logOff': 'off', + 'ig.heat.title': 'Events ingested per hour', + 'ig.heat.hint': 'One row per host, one column per hour. Empty cells are hours with no event at all.', + 'ig.heat.empty': 'No events in this period.', + 'ig.gaps.title': 'Gaps', + 'ig.gaps.none': 'No silence of two hours or more.', + 'ig.gaps.line': '{host}: {from} to {to} ({h} h)', + 'ig.src.title': 'Sources', + 'ig.src.host': 'Host', + 'ig.src.name': 'Source', + 'ig.src.state': 'State', + 'ig.src.lines': 'Lines', + 'ig.src.bad': 'Invalid', + 'ig.src.last': 'Last event', + 'ig.src.none': 'No sources reported.', + 'ig.state.following': 'following', + 'ig.state.waiting': 'waiting', + 'ig.state.backfill': 'catching up', + 'ig.state.error': 'error', + 'ig.state.disabled': 'disabled', + 'ig.peers.title': 'Peers', + 'ig.peers.none': 'No peers configured.', + 'ig.peers.online': 'online', + 'ig.peers.offline': 'offline', + 'ig.peers.live': 'live', + 'ig.peers.sync': 'synced {t}', + 'ig.peers.never': 'never synced', + 'ig.log.title': 'Event log and geolocation', + 'ig.log.off': 'The event log is off: periods, sessions and replay have no data.', + 'ig.log.days': 'Days kept', + 'ig.log.size': 'Size on disk', + 'ig.log.dropped': 'Events dropped', + 'ig.geo.state': 'Geolocation base', + 'ig.geo.city': 'City base build', + 'ig.geo.asn': 'ASN base build', + 'ig.geo.unknown': 'unknown', + 'ig.lag': 'Delay', + 'ig.host.lagLine': '{host}: last event {t}' + }, + 'pt-BR': { + 'ig.title': 'Integridade', + 'ig.lead.ok': 'Os dados estão completos', + 'ig.lead.okBody': 'Nenhum buraco de {n} horas ou mais, todas as fontes respondem e poucas linhas foram rejeitadas.', + 'ig.lead.bad.one': '{n} buraco nos dados', + 'ig.lead.bad.other': '{n} buracos nos dados', + 'ig.lead.badBody': 'Silêncios de duas horas ou mais em fontes que costumam registrar, peers fora do ar ou fontes com erro. Veja os painéis abaixo.', + 'ig.lead.loading': 'Conferindo os dados...', + 'ig.stat.hosts': 'Hosts reportando', + 'ig.stat.gaps': 'Buracos encontrados', + 'ig.stat.parse': 'Linhas inválidas', + 'ig.stat.log': 'Registro de eventos', + 'ig.stat.logSub': '{days} dias, {size}', + 'ig.stat.logOff': 'desligado', + 'ig.heat.title': 'Eventos ingeridos por hora', + 'ig.heat.hint': 'Uma linha por host, uma coluna por hora. Células vazias são horas sem nenhum evento.', + 'ig.heat.empty': 'Nenhum evento neste período.', + 'ig.gaps.title': 'Buracos', + 'ig.gaps.none': 'Nenhum silêncio de duas horas ou mais.', + 'ig.gaps.line': '{host}: de {from} a {to} ({h} h)', + 'ig.src.title': 'Fontes', + 'ig.src.host': 'Host', + 'ig.src.name': 'Fonte', + 'ig.src.state': 'Estado', + 'ig.src.lines': 'Linhas', + 'ig.src.bad': 'Inválidas', + 'ig.src.last': 'Último evento', + 'ig.src.none': 'Nenhuma fonte informada.', + 'ig.state.following': 'acompanhando', + 'ig.state.waiting': 'aguardando', + 'ig.state.backfill': 'recuperando', + 'ig.state.error': 'erro', + 'ig.state.disabled': 'desativada', + 'ig.peers.title': 'Peers', + 'ig.peers.none': 'Nenhum peer configurado.', + 'ig.peers.online': 'no ar', + 'ig.peers.offline': 'fora do ar', + 'ig.peers.live': 'ao vivo', + 'ig.peers.sync': 'sincronizado {t}', + 'ig.peers.never': 'nunca sincronizou', + 'ig.log.title': 'Registro de eventos e geolocalização', + 'ig.log.off': 'O registro de eventos está desligado: períodos, sessões e replay ficam sem dados.', + 'ig.log.days': 'Dias guardados', + 'ig.log.size': 'Tamanho em disco', + 'ig.log.dropped': 'Eventos descartados', + 'ig.geo.state': 'Base de geolocalização', + 'ig.geo.city': 'Build da base de cidades', + 'ig.geo.asn': 'Build da base de ASN', + 'ig.geo.unknown': 'desconhecida', + 'ig.lag': 'Atraso', + 'ig.host.lagLine': '{host}: último evento {t}' + } + }); + var t = U.t, nf = U.fmt.num; + var h = function (tag, cls) { return U.el.apply(null, [tag, cls ? { class: cls } : null].concat([].slice.call(arguments, 2))); }; + + function when(ts) { return ts ? U.fmt.date(ts) : '-'; } + + var root = null, box = null, ctx0 = null, seq = 0, alive = false, data = null, timer = null; + + function params(c) { + var p = U.rangeParams(); + if (c && c.host && c.host !== 'all') p.host = c.host; + return p; + } + + function load(c) { + var my = ++seq; + U.api('/api/v1/integrity', params(c || ctx0)).then(function (d) { + if (!alive || my !== seq) return; + data = d; paint(); + }).catch(function () { + if (!alive || my !== seq || data) return; + while (box.firstChild) box.removeChild(box.firstChild); + box.appendChild(U.ui.empty(t('error.load'))); + }); + } + + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + + function hourLabel(hn) { + var d = new Date(hn * 3600000); + return ('0' + d.getDate()).slice(-2) + '/' + ('0' + d.getHours()).slice(-2); + } + + function table(headers, rows) { + var tb = h('table', 'ig-table'); + var tr = h('tr'); + headers.forEach(function (x) { tr.appendChild(h('th', null, x)); }); + tb.appendChild(h('thead', null, tr)); + var body = h('tbody'); + rows.forEach(function (r) { + var row = h('tr'); + r.forEach(function (c) { row.appendChild(h('td', null, c)); }); + body.appendChild(row); + }); + tb.appendChild(body); + return h('div', 'ig-scroll', tb); + } + + function paint() { + if (!data) return; + clear(box); + var hosts = data.hosts || [], peers = data.peers || []; + var gaps = 0, lines = 0, bad = 0, errors = 0, onlineN = 0; + hosts.forEach(function (x) { + gaps += (x.gaps || []).length; + if (x.online) onlineN++; + (x.sources || []).forEach(function (s) { lines += s.lines; bad += s.malformed; if (s.state === 'error') errors++; }); + }); + var offline = peers.filter(function (p) { return !p.online; }).length; + var rate = lines + bad > 0 ? bad / (lines + bad) : 0; + var holes = gaps + offline + errors; + var ok = holes === 0 && rate < 0.01; + var title = ok ? t('ig.lead.ok') : U.pl('ig.lead.bad', holes || 1); + box.appendChild(U.ui.lead(title, ok ? t('ig.lead.okBody', { n: 2 }) : t('ig.lead.badBody'), ok ? 'ok' : 'danger')); + + var stats = h('div', 'grid-12 ig-stats'); + function sp(node) { node.classList.add('span-3'); stats.appendChild(node); } + sp(U.ui.stat(t('ig.stat.hosts'), nf(onlineN) + ' / ' + nf(hosts.length), null, onlineN === hosts.length ? 'ok' : 'danger')); + sp(U.ui.stat(t('ig.stat.gaps'), nf(gaps), null, gaps ? 'danger' : 'ok', null, 'term.integrity_gap')); + sp(U.ui.stat(t('ig.stat.parse'), (rate * 100).toFixed(rate < 0.1 ? 2 : 1) + '%', nf(bad) + ' / ' + nf(lines + bad), rate >= 0.01 ? 'danger' : 'ok')); + var lg = data.eventlog || {}; + sp(U.ui.stat(t('ig.stat.log'), lg.enabled ? nf(lg.days) : t('ig.stat.logOff'), lg.enabled ? t('ig.stat.logSub', { days: nf(lg.days), size: U.fmt.bytes(lg.bytes) }) : null, lg.enabled ? 'ok' : 'neutral')); + box.appendChild(stats); + + // heatmap + var hp = U.ui.panel({ title: t('ig.heat.title'), hint: t('ig.heat.hint'), variant: 'chart' }); + var n = hosts.length ? (hosts[0].hourly || []).length : 0; + if (!n || !hosts.some(function (x) { return (x.hourly || []).some(function (v) { return v > 0; }); })) { + hp.body.appendChild(U.ui.empty(t('ig.heat.empty'))); + } else { + var xl = []; + for (var i = 0; i < n; i++) xl.push(hourLabel(data.from_hour + i)); + hp.body.appendChild(h('div', 'ig-heatbox', U.charts.heatmap(hosts.map(function (x) { return x.hourly; }), xl, hosts.map(function (x) { return x.name; }), { title: t('ig.heat.title') }))); } + box.appendChild(hp); + + var grid = h('div', 'grid-12'); + // gaps + var gp = U.ui.panel({ title: t('ig.gaps.title') }); + gp.classList.add('span-6'); + var gl = h('ul', 'ig-list'); + hosts.forEach(function (x) { + (x.gaps || []).forEach(function (g) { + gl.appendChild(h('li', null, t('ig.gaps.line', { host: x.name, from: when(g.from), to: when(g.to), h: nf(Math.round((g.to - g.from) / 3600)) }))); + }); + }); + gp.body.appendChild(gl.children.length ? gl : U.ui.empty(t('ig.gaps.none'))); + grid.appendChild(gp); + // peers + var pp = U.ui.panel({ title: t('ig.peers.title') }); + pp.classList.add('span-6'); + if (!peers.length) pp.body.appendChild(U.ui.empty(t('ig.peers.none'))); + else { + var pl = h('ul', 'ig-list'); + peers.forEach(function (p) { + pl.appendChild(h('li', null, h('strong', null, p.name), ' ', U.ui.badge(t(p.online ? 'ig.peers.online' : 'ig.peers.offline'), p.online ? 'ok' : 'danger'), + p.live ? ' ' : null, p.live ? U.ui.badge(t('ig.peers.live'), 'neutral') : null, ' ', + h('span', 'ig-muted', p.last_sync ? t('ig.peers.sync', { t: U.fmt.ago(p.last_sync) }) : t('ig.peers.never')))); + }); + pp.body.appendChild(pl); + } + grid.appendChild(pp); + // sources + var sp2 = U.ui.panel({ title: t('ig.src.title') }); + sp2.classList.add('span-8'); + var rows = []; + hosts.forEach(function (x) { + (x.sources || []).forEach(function (s) { + var tone = s.state === 'error' ? 'danger' : s.state === 'following' ? 'ok' : 'neutral'; + rows.push([x.name, s.name, U.ui.badge(STATES[s.state] ? t('ig.state.' + s.state) : String(s.state || ''), tone), nf(s.lines), nf(s.malformed), s.last ? U.fmt.ago(s.last) : '-']); + }); + }); + sp2.body.appendChild(rows.length ? table([t('ig.src.host'), t('ig.src.name'), t('ig.src.state'), t('ig.src.lines'), t('ig.src.bad'), t('ig.src.last')], rows) : U.ui.empty(t('ig.src.none'))); + grid.appendChild(sp2); + // log + geo + var lp = U.ui.panel({ title: t('ig.log.title') }); + lp.classList.add('span-4'); + if (!lg.enabled) lp.body.appendChild(h('p', 'ig-muted', t('ig.log.off'))); + var kv = h('dl', 'ig-kv'); + function row(k, v) { kv.appendChild(h('dt', null, k)); kv.appendChild(h('dd', null, v)); } + if (lg.enabled) { row(t('ig.log.days'), nf(lg.days)); row(t('ig.log.size'), U.fmt.bytes(lg.bytes)); row(t('ig.log.dropped'), nf(lg.dropped)); } + var g = data.geo || {}; + row(t('ig.geo.state'), g.state ? (STATES[g.state] ? t('ig.state.' + g.state) : String(g.state)) : t('ig.geo.unknown')); + row(t('ig.geo.city'), g.city_build ? U.fmt.date(g.city_build) : t('ig.geo.unknown')); + row(t('ig.geo.asn'), g.asn_build ? U.fmt.date(g.asn_build) : t('ig.geo.unknown')); + lp.body.appendChild(kv); + grid.appendChild(lp); + box.appendChild(grid); + } + + U.registerPage({ + id: 'integrity', group: 'operate', icon: ICON, titleKey: 'ig.title', + mount: function (el, c) { + ctx0 = c; alive = true; data = null; + root = h('div', 'ig'); + box = h('div', 'ig-box'); + root.appendChild(box); + box.appendChild(U.ui.lead(t('ig.lead.loading'), null, 'neutral')); + el.appendChild(root); + load(c); + }, + update: function (c) { ctx0 = c; load(c); if (data) paint(); }, + refresh: function () { load(ctx0); }, + unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = box = data = null; } + }); + return true; + } + + if (!boot()) { + var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100); + } +})(); diff --git a/internal/server/web/live.css b/internal/server/web/live.css index e3a89e0..02075b6 100644 --- a/internal/server/web/live.css +++ b/internal/server/web/live.css @@ -164,3 +164,19 @@ button.lv-row[aria-pressed="false"] .lv-row-l { text-decoration: line-through; } .lv-bar { gap: 6px; } .lv-notes { margin-left: 0; width: 100%; } } + +/* legitimate traffic (anonymous visits) */ +.lv-vis { gap: 8px; } +.lv-vis-dot { width: 10px; height: 10px; border-radius: 50%; border: 2px solid var(--lv-muted); flex: none; } +.lv-vis[aria-pressed="true"] { border-color: var(--accent); } +.lv-vis[aria-pressed="true"] .lv-vis-dot { background: var(--lv-muted); border-color: var(--lv-muted); } +.lv-devs, .lv-m-visit { display: none; } +.lv-vis-on .lv-devs { display: flex; } +.lv-vis-on .lv-m-visit { display: flex; } +.lv-k-visit { --k: var(--ink-muted, #9db3bd); } +.lv-ev-visit .lv-vtxt { grid-column: span 1; color: var(--lv-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.lv-ev-visit { grid-template-columns: auto auto minmax(0, 1fr); } +.lv-left .lv-ev-visit { grid-template-columns: auto auto minmax(0, 1fr); } +.lv-leg { display: none; align-items: center; gap: 6px; } +.lv-vis-on .lv-leg { display: inline-flex; } +.lv-leg-sw { width: 16px; height: 2px; background: var(--ink-muted, #9db3bd); } diff --git a/internal/server/web/live.js b/internal/server/web/live.js index 0c299c6..59f8a2c 100644 --- a/internal/server/web/live.js +++ b/internal/server/web/live.js @@ -15,7 +15,7 @@ var CAT_OK = {}; CATS.forEach(function (c) { CAT_OK[c] = 1; }); - var MAX_ARCS = 300, MAX_PENDING = 400, RING_MAX = 800, RING_TRIM = 300; + var MAX_VARCS = 150, MAX_VPENDING = 150, MAX_ARCS = 300, MAX_PENDING = 400, RING_MAX = 800, RING_TRIM = 300; var WORLD_W = 2000, WORLD_H = 789, LAT_TOP = 84, LAT_BOT = -58; var DEFAULT_DST = { lat: -23.55, lon: -46.63 }; var RAD = Math.PI / 180, TAU = Math.PI * 2; @@ -138,7 +138,7 @@ this.paused = false; this.hidden = document.hidden; this.reduced = !!(window.matchMedia && matchMedia('(prefers-reduced-motion: reduce)').matches); this.T = 0; this.last = 0; this.raf = 0; this.dirty = true; - this.arcs = []; this.free = []; this.pending = []; this.frameKey = {}; + this.arcs = []; this.varcs = []; this.vpending = []; this.free = []; this.pending = []; this.frameKey = {}; this.dests = {}; this.destList = []; this.dots = []; this.more = []; this.frameAvg = 16; this.quality = 1; this.W = 0; this.H = 0; this.dpr = 1; this.reserve = 0; @@ -189,7 +189,7 @@ this.listeners.forEach(function (l) { try { l[0].removeEventListener(l[1], l[2], l[3]); } catch (x) { /* ignore */ } }); this.listeners = []; if (this.ro) { this.ro.disconnect(); this.ro = null; } - this.arcs = []; this.free = []; this.pending = []; this.dots = []; this.flatCache = null; this.pickCbs = []; + this.arcs = []; this.varcs = []; this.vpending = []; this.free = []; this.pending = []; this.dots = []; this.flatCache = null; this.pickCbs = []; if (this.cv.parentNode) this.cv.parentNode.removeChild(this.cv); }; @@ -202,6 +202,8 @@ var rgb = parseColor(css(TOKEN[c]), FALLBACK[c]); cols[c] = { rgb: rgb, c0: rgba(rgb, 0), c1: rgba(rgb, 1), css: rgba(rgb, 1) }; }); + var vrgb = parseColor(tok('--ink-muted', '--muted'), '#9db3bd'); + cols.visit = { rgb: vrgb, c0: rgba(vrgb, 0), c1: rgba(vrgb, 1), css: rgba(vrgb, 1) }; this.colors = cols; this.dark = (bg[0] * 299 + bg[1] * 587 + bg[2] * 114) / 1000 < 128; this.pal = { text: text, bg: bg, accent: parseColor(css('--accent'), '#38bdf8') }; @@ -211,8 +213,8 @@ M.setTheme = function () { this.readTheme(); this.kick(); }; M.setMode = function (m) { this.mode = m === 'globe' ? 'globe' : 'flat'; this.target = this.mode === 'globe' ? 1 : 0; this.cv.classList.toggle('lv-globe', this.mode === 'globe'); this.dirty = true; this.kick(); }; - M.pause = function (p) { this.paused = !!p; if (p) this.pending.length = 0; this.last = 0; this.dirty = true; this.kick(); }; - M.clear = function () { this.arcs = []; this.pending.length = 0; this.dots = []; this.more = []; this.dirty = true; this.kick(); }; + M.pause = function (p) { this.paused = !!p; if (p) { this.pending.length = 0; this.vpending.length = 0; } this.last = 0; this.dirty = true; this.kick(); }; + M.clear = function () { this.arcs = []; this.varcs = []; this.vpending.length = 0; this.pending.length = 0; this.dots = []; this.more = []; this.dirty = true; this.kick(); }; M.setDest = function (host, d, est) { var cur = this.dests[host]; @@ -260,13 +262,21 @@ // ev: an event as sent by the server ({cat, host, src, dst, cc}); returns whether it can be drawn M.spawnEvent = function (ev, o) { - if (!this.alive || !ev || !CAT_OK[ev.cat]) return false; + var vis = !!(o && o.visit); + if (!this.alive || !ev || (!vis && !CAT_OK[ev.cat])) return false; var org = this.originOf(ev); if (!org) return false; var host = str(ev.host, 64) || 'local'; var d = this.destFor(host, ev.dst && typeof ev.dst === 'object' ? ev.dst : null); - var hl = !!(o && o.highlight) || !!HOSTILE[ev.cat]; + var hl = !vis && (!!(o && o.highlight) || !!HOSTILE[ev.cat]); if (this.paused || this.hidden) return true; + if (vis) { + if (this.reduced) return true; + if (this.vpending.length >= MAX_VPENDING) this.vpending.shift(); + this.vpending.push({ o: org, d: d, cat: 'visit', hl: false, v: true }); + this.kick(); + return true; + } if (this.reduced) { this.dots.push({ lat: org.lat, lon: org.lon, v: vec(org.lat, org.lon), cat: ev.cat }); if (this.dots.length > 160) this.dots.shift(); @@ -353,7 +363,7 @@ M.onVisibility = function () { this.hidden = document.hidden; - if (this.hidden) { if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.pending.length = 0; } + if (this.hidden) { if (this.raf) cancelAnimationFrame(this.raf); this.raf = 0; this.pending.length = 0; this.vpending.length = 0; } else { this.last = 0; this.dirty = true; this.kick(); } }; @@ -473,7 +483,7 @@ }; M.drawFlatLayer = function (g, layerAlpha, add) { - var ox = this.ox, oy = this.oy, mw = this.mw, mh = this.mh, T = this.T, arcs = this.arcs, i; + var ox = this.ox, oy = this.oy, mw = this.mw, mh = this.mh, T = this.T, arcs = this.ordered(), i; g.globalCompositeOperation = 'source-over'; for (i = 0; i < this.dots.length; i++) { // reduced motion: static dots instead of arcs var dd = this.dots[i]; @@ -485,12 +495,12 @@ for (i = 0; i < arcs.length; i++) { var a = arcs[i], age = T - a.born; if (age < 0) continue; - var col = this.colors[a.cat]; + var col = a.visit ? this.colors.visit : this.colors[a.cat]; var x0 = ox + a.u0 * mw, y0 = oy + a.v0 * mh, x1 = ox + a.dest.u0 * mw, y1 = oy + a.dest.v0 * mh; var dx = x1 - x0, dy = y1 - y0, dist = Math.sqrt(dx * dx + dy * dy); var cx = (x0 + x1) / 2, cy = (y0 + y1) / 2 - Math.min(dist * 0.42, mh * 0.5) - 4; var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1)); - var fade = layerAlpha * (1 - 0.75 * tail); + var fade = layerAlpha * (1 - 0.75 * tail) * (a.visit ? 0.8 : 1); if (tail < 1 && head > tail) { // exact sub-curve of the quadratic Bezier between parameters tail..head var ut = 1 - tail, uh = 1 - head; @@ -503,18 +513,18 @@ g.strokeStyle = gr; g.beginPath(); g.moveTo(ax, ay); g.quadraticCurveTo(kx, ky, bx, by); if (a.hostile) { g.globalAlpha = fade * 0.25; g.lineWidth = 5; g.stroke(); } - g.globalAlpha = fade; g.lineWidth = (a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0); + g.globalAlpha = fade; g.lineWidth = (a.visit ? 0.9 : a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0); g.stroke(); if (head < 1) { g.fillStyle = col.css; g.beginPath(); g.arc(bx, by, a.hostile ? 2.8 : 2, 0, TAU); g.fill(); } } - if (age < 0.7) { + if (age < 0.7 && !a.visit) { g.globalAlpha = layerAlpha * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1; g.beginPath(); g.arc(x0, y0, 2 + age * 9, 0, TAU); g.stroke(); } - this.drawPulse(g, x1, y1, a, age, col, null, 1, layerAlpha); + if (!a.visit) this.drawPulse(g, x1, y1, a, age, col, null, 1, layerAlpha); } g.globalCompositeOperation = 'source-over'; for (i = 0; i < this.destList.length; i++) { @@ -660,7 +670,7 @@ }; M.drawGlobeLayer = function (g, m, add) { - var cx = this.cx, cy = this.cy, R = this.gR, T = this.T, arcs = this.arcs, i, k; + var cx = this.cx, cy = this.cy, R = this.gR, T = this.T, arcs = this.ordered(), i, k; g.globalCompositeOperation = 'source-over'; for (i = 0; i < this.dots.length; i++) { var dd = this.dots[i]; @@ -674,9 +684,9 @@ for (i = 0; i < arcs.length; i++) { var a = arcs[i], age = T - a.born; if (age < 0) continue; - var col = this.colors[a.cat]; + var col = a.visit ? this.colors.visit : this.colors[a.cat]; var head = ease(clamp(age / a.D, 0, 1)), tail = ease(clamp((age - a.hold) / a.D, 0, 1)); - var fade = m * (1 - 0.75 * tail); + var fade = m * (1 - 0.75 * tail) * (a.visit ? 0.8 : 1); var A = a.a, B = a.b, w = a.w, sw = Math.sin(w); if (tail < 1 && head > tail) { var lift = 0.05 + 0.22 * w / Math.PI; @@ -700,16 +710,16 @@ gr.addColorStop(0, col.c0); gr.addColorStop(1, col.c1); g.strokeStyle = gr; if (a.hostile) { g.globalAlpha = fade * 0.25; g.lineWidth = 5; g.stroke(); } - g.globalAlpha = fade; g.lineWidth = (a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0); + g.globalAlpha = fade; g.lineWidth = (a.visit ? 0.9 : a.hostile ? 2.2 : 1.3) + (a.n > 1 ? Math.min(2, Math.log(a.n)) : 0); g.stroke(); if (head < 1) { g.fillStyle = col.css; g.beginPath(); g.arc(lx, ly, a.hostile ? 2.8 : 2, 0, TAU); g.fill(); } } } - if (age >= a.D) { + if (age >= a.D && !a.visit) { this.rot(B[0], B[1], B[2]); if (this.rz > 0.02) this.drawPulse(g, cx + this.rx * R, cy - this.ry * R, a, age, col, Math.atan2(-this.ry, this.rx), this.rz, m); } - if (age < 0.7) { + if (age < 0.7 && !a.visit) { this.rot(A[0], A[1], A[2]); if (this.rz > 0.02) { g.globalAlpha = m * (1 - age / 0.7) * 0.8; g.strokeStyle = col.css; g.lineWidth = 1; @@ -753,7 +763,7 @@ M.spawn = function (it) { var a = this.free.pop() || {}; var o = it.o, d = it.d, hostile = !!it.hl; - a.cat = it.cat; a.hostile = hostile; a.n = 1; a.dest = d; + a.cat = it.cat; a.hostile = hostile; a.n = 1; a.dest = d; a.visit = !!it.v; a.born = this.T; a.u0 = (o.lon + 180) / 360; a.v0 = (LAT_TOP - clamp(o.lat, LAT_BOT, LAT_TOP)) / (LAT_TOP - LAT_BOT); a.a = vec(o.lat, o.lon); a.b = d.v; @@ -761,8 +771,9 @@ a.D = hostile ? 1.35 : 1.0; a.hold = hostile ? 1.4 : 0.2; a.pl = hostile ? 1.9 : 1.1; + if (a.visit) { a.D = 0.75; a.hold = 0; a.pl = 0.1; } a.life = Math.max(a.D + a.pl, a.D + a.hold + a.D); - this.arcs.push(a); + (a.visit ? this.varcs : this.arcs).push(a); return a; }; @@ -782,6 +793,19 @@ if (merged) this.addMore(merged); }; + // legitimate visits: their own queue and cap, always drawn under the attacks + M.stepVisits = function () { + var q = this.vpending, n = 0, budget = q.length > 60 ? 30 : 8; + while (q.length && n < budget && this.varcs.length < Math.round(MAX_VARCS * this.quality)) { this.spawn(q.shift()); n++; } + }; + M.ordered = function () { + var o = this.order || (this.order = []), i, j = 0; + for (i = 0; i < this.varcs.length; i++) o[j++] = this.varcs[i]; + for (i = 0; i < this.arcs.length; i++) o[j++] = this.arcs[i]; + o.length = j; + return o; + }; + M.addMore = function (n) { var s = Math.floor(Date.now() / 1000), m = this.more; if (m.length && m[m.length - 1][0] === s) m[m.length - 1][1] += n; else m.push([s, n]); @@ -811,7 +835,7 @@ if (this.frameAvg > 26) this.quality = Math.max(0.35, this.quality - 0.02); else if (this.frameAvg < 20) this.quality = Math.min(1, this.quality + 0.01); } - this.stepSpawn(); + this.stepSpawn(); this.stepVisits(); } var df = this.target - this.m, morph = false; if (Math.abs(df) > 0.003) { this.m += df * (this.reduced ? 1 : Math.min(1, dt * 6.5)); morph = true; } else this.m = this.target; @@ -826,11 +850,14 @@ if (still && !wasDirty && !morph) return; // nothing changed: leave the loop idle this.dirty = false; this.draw(); - var arcs = this.arcs; - for (var i = arcs.length - 1; i >= 0; i--) { - if (this.T - arcs[i].born > arcs[i].life) { - this.free.push(arcs[i]); - arcs[i] = arcs[arcs.length - 1]; arcs.pop(); + var lists = [this.arcs, this.varcs]; + for (var li = 0; li < 2; li++) { + var arcs = lists[li]; + for (var i = arcs.length - 1; i >= 0; i--) { + if (this.T - arcs[i].born > arcs[i].life) { + this.free.push(arcs[i]); + arcs[i] = arcs[arcs.length - 1]; arcs.pop(); + } } } if (!still || morph || this.dirty) this.kick(); @@ -845,6 +872,14 @@ U.registerI18n({ en: { 'live.title': 'Live', + 'live.visits': 'Legitimate traffic', + 'live.visit': 'visit', + 'live.legend.visits': 'visits', + 'live.m.vis': 'Visits, 15 min', + 'live.m.pages': 'Pages, 15 min', + 'live.unit.pages': 'distinct pages', + 'live.devices': 'Devices', + 'live.vis.empty': 'anonymous', 'live.mode': 'View', 'live.mode.flat': 'Flat map', 'live.mode.globe': 'Globe', @@ -886,6 +921,14 @@ }, 'pt-BR': { 'live.title': 'Ao vivo', + 'live.visits': 'Tráfego legítimo', + 'live.visit': 'visita', + 'live.legend.visits': 'visitas', + 'live.m.vis': 'Visitas, 15 min', + 'live.m.pages': 'Páginas, 15 min', + 'live.unit.pages': 'páginas distintas', + 'live.vis.empty': 'anônima', + 'live.devices': 'Dispositivos', 'live.mode': 'Visualização', 'live.mode.flat': 'Mapa plano', 'live.mode.globe': 'Globo', @@ -951,12 +994,15 @@ this.minute = -1; this.listDirty = true; this.hoverList = false; this.more = []; this.listeners = []; this.timers = []; this.dn = null; this.dnLang = ''; this.lastEv = null; + this.visitsOn = false; this.es = null; this.vring = []; this.vbk = {}; this.pathLast = new Map(); this.devs = {}; this.devChips = {}; this.offDev = {}; this.seen = {}; this.seenN = 0; + try { this.visitsOn = localStorage.getItem('urutau.live.visits') === '1'; } catch (x) { /* storage blocked */ } this.build(); this.map = mapApi(new AttackMap(U, this.mapBox, { mode: this.pref(), interactive: true })); this.map.onMore(function (n) { self.addMore(n); }); this.map.onPick(function (d) { self.toggleHost(d.host); }); this.syncMode(this.pref()); + this.applyVisits(); this.unsub = U.onEvent ? U.onEvent(function (e) { self.ingest(e); }) : null; this.listen(document, 'visibilitychange', function () { self.onVisibility(); }); @@ -984,6 +1030,7 @@ P.destroy = function () { this.alive = false; if (this.unsub) { try { this.unsub(); } catch (x) { /* ignore */ } this.unsub = null; } + this.closeStream(); this.timers.forEach(clearInterval); this.timers = []; this.listeners.forEach(function (l) { try { l[0].removeEventListener(l[1], l[2], l[3]); } catch (x) { /* ignore */ } }); this.listeners = []; @@ -1003,14 +1050,16 @@ // language changed: rebuild the DOM keeping the map, the filters and the paused state P.rebuild = function () { - var self = this, hosts = Object.keys(this.hostsSeen), paused = this.paused; - this.hostsSeen = {}; this.hostChips = {}; + var self = this, hosts = Object.keys(this.hostsSeen), paused = this.paused, devs = Object.keys(this.devs); + this.hostsSeen = {}; this.hostChips = {}; this.devChips = {}; this.devs = {}; var mapEl = this.map._map.cv, was = this.stage.classList.contains('lv-nopanels'); this.build(); this.mapBox.appendChild(mapEl); this.map._map.container = this.mapBox; if (this.map._map.ro) { this.map._map.ro.disconnect(); this.map._map.ro.observe(this.mapBox); } hosts.forEach(function (h) { self.noteHost(h); }); + devs.forEach(function (d) { self.noteDevice(d); }); + this.applyVisits(); this.stage.classList.toggle('lv-nopanels', was); this.syncMode(this.map.getMode()); if (paused) this.setPaused(true); @@ -1083,15 +1132,24 @@ this.bFs.setAttribute('aria-pressed', 'false'); ctl.appendChild(this.bFs); } + this.bVis = document.createElement('button'); + this.bVis.type = 'button'; this.bVis.className = 'lv-btn lv-vis'; + this.bVis.appendChild(this.el('span', 'lv-vis-dot')); + this.bVis.appendChild(this.el('span', '', t('live.visits'))); + this.bVis.addEventListener('click', function () { self.setVisits(!self.visitsOn); }); + ctl.appendChild(this.bVis); bar.appendChild(ctl); this.hostBox = el('div', 'lv-hosts'); this.hostBox.setAttribute('role', 'group'); this.hostBox.setAttribute('aria-label', t('live.hosts')); bar.appendChild(this.hostBox); + this.devBox = el('div', 'lv-hosts lv-devs'); this.devBox.setAttribute('role', 'group'); this.devBox.setAttribute('aria-label', t('live.devices')); + bar.appendChild(this.devBox); var notes = el('div', 'lv-notes'); this.nPaused = el('span', 'lv-note', t('live.paused')); this.nPaused.hidden = true; this.nFilter = el('span', 'lv-note', t('live.filtered')); this.nFilter.hidden = true; this.nMore = el('span', 'lv-note', ''); this.nMore.hidden = true; this.nEst = el('span', 'lv-note', t('live.est')); this.nEst.hidden = true; - [this.nPaused, this.nFilter, this.nMore, this.nEst].forEach(function (n) { notes.appendChild(n); }); + this.nLeg = el('span', 'lv-note lv-leg'); this.nLeg.appendChild(el('span', 'lv-leg-sw')); this.nLeg.appendChild(el('span', '', t('live.legend.visits'))); + [this.nPaused, this.nFilter, this.nMore, this.nEst, this.nLeg].forEach(function (n) { notes.appendChild(n); }); bar.appendChild(notes); stage.appendChild(bar); @@ -1105,7 +1163,7 @@ var side = el('div', 'lv-side'); this.side = side; var mets = el('div', 'lv-metrics'); this.mM = {}; - ['15m', '1h', 'avg', 'ips', 'new', 'last'].forEach(function (k) { self.mM[k] = self.metric(k); mets.appendChild(self.mM[k]); }); + ['15m', '1h', 'avg', 'ips', 'new', 'last', 'vis', 'pages'].forEach(function (k) { self.mM[k] = self.metric(k); if (k === 'vis' || k === 'pages') self.mM[k].classList.add('lv-m-visit'); mets.appendChild(self.mM[k]); }); this.spark = document.createElement('canvas'); this.spark.className = 'lv-spark'; this.spark.setAttribute('aria-hidden', 'true'); this.spark.width = 150; this.spark.height = 32; this.mM['15m'].appendChild(this.spark); @@ -1195,6 +1253,72 @@ this.map.resize(); }; + // ---- legitimate traffic (anonymous visits): its own stream, only while the option is on + P.setVisits = function (on) { + this.visitsOn = on; + try { localStorage.setItem('urutau.live.visits', on ? '1' : '0'); } catch (x) { /* storage blocked */ } + this.applyVisits(); + this.minute = -1; this.listDirty = true; this.tick(true); + }; + P.applyVisits = function () { + var on = this.visitsOn; + this.bVis.setAttribute('aria-pressed', on ? 'true' : 'false'); + this.stage.classList.toggle('lv-vis-on', on); + if (on) this.openStream(); else { this.closeStream(); this.vring = []; this.map.clear(); } + this.map._map.resize(); + }; + P.openStream = function () { + var self = this; + if (this.es || !window.EventSource) return; + var es = new EventSource('/api/v1/events/stream?visits=1'); + es.addEventListener('ev', function (m) { + var e; + try { e = JSON.parse(m.data); } catch (x) { return; } + if (!e || typeof e !== 'object') return; + if (e.kind === 'visit') self.visit(e); + else if (e.kind === 'visit_batch') self.visitBatch(e); + else self.ingest(e); + }); + this.es = es; + }; + P.closeStream = function () { if (this.es) { this.es.close(); this.es = null; } }; + + P.noteDevice = function (d) { + if (!d || this.devs[d] || Object.keys(this.devs).length >= 8) return; + var self = this; + this.devs[d] = 1; + var b = document.createElement('button'); + b.type = 'button'; b.className = 'lv-chip'; b.setAttribute('aria-pressed', this.offDev[d] ? 'false' : 'true'); + b.appendChild(this.el('span', 'lv-chip-l', d)); + b.addEventListener('click', function () { + self.offDev[d] = !self.offDev[d]; + b.setAttribute('aria-pressed', self.offDev[d] ? 'false' : 'true'); + self.listDirty = true; + }); + this.devBox.appendChild(b); this.devChips[d] = b; + }; + + P.vcount = function (n, t, dev, path) { + var m = Math.floor(t / 60), b = this.vbk[m] || (this.vbk[m] = { n: 0 }); + b.n += n; + if (path && (this.pathLast.size < 5000 || this.pathLast.has(path))) this.pathLast.set(path, m); + }; + P.visit = function (e) { + var s = e.src && typeof e.src === 'object' ? e.src : null, tsec = isNum(e.t) ? e.t : Date.now() / 1000; + var dev = str(e.device, 16), path = str(e.path, 90); + var r = { visit: true, t: tsec, host: str(e.host, 64) || 'local', city: str(s && s.city, 48), cc: cc2(s && s.cc) || cc2(e.cc), domain: str(e.domain, 60), path: path, device: dev, ev: e }; + this.noteHost(r.host); if (dev) this.noteDevice(dev); + this.vcount(1, tsec, dev, path); + this.vring.push(r); + if (this.vring.length > 200) this.vring.splice(0, 80); + this.listDirty = true; + if (this.paused || this.hidden || this.offHosts[r.host] || (dev && this.offDev[dev])) return; + var h = this.ctx && this.ctx.host; + if (h && h !== 'all' && h !== r.host) return; + this.map.spawn(e, { visit: true }); + }; + P.visitBatch = function (e) { if (isNum(e.n) && e.n > 0) this.vcount(Math.min(e.n, 1e6), isNum(e.t) ? e.t : Date.now() / 1000, '', ''); }; + P.toggleHost = function (h) { if (!this.hostChips[h]) return; this.offHosts[h] = !this.offHosts[h]; @@ -1331,6 +1455,11 @@ else if (e.source === 'fail2ban') what = 'fail2ban [' + str(e.jail, 40) + ']'; var key = tsec + '|' + ip + '|' + e.cat + '|' + what; if (have) { if (have[key]) return null; have[key] = 1; } + else if (this.es) { + if (this.seen[key]) return null; + this.seen[key] = 1; + if (++this.seenN > 3000) { this.seen = {}; this.seenN = 0; } + } var r = { t: tsec, key: key, cat: e.cat, host: host, ip: ip, what: what, cc: cc2(s && s.cc) || cc2(e.cc), city: str(s && s.city, 48), ev: e }; this.noteHost(host); this.ring.push(r); @@ -1467,6 +1596,16 @@ for (var k in this.bk) if (+k < min - 1500) delete this.bk[k]; }; + P.visitMetrics = function (min, fmtN) { + var vn = 0, pg = 0, vi, mm = this.mM, self = this; + for (vi = min - 14; vi <= min; vi++) if (this.vbk[vi]) vn += this.vbk[vi].n; + this.pathLast.forEach(function (last) { if (last >= min - 14) pg++; }); + mm.vis.val.textContent = fmtN(vn); this.setSub(mm.vis, this.t('live.legend.visits'), ''); + mm.pages.val.textContent = fmtN(pg); this.setSub(mm.pages, this.t('live.unit.pages'), ''); + this.pathLast.forEach(function (last, p) { if (last < min - 30) self.pathLast.delete(p); }); + for (var vk in this.vbk) if (+vk < min - 40) delete this.vbk[vk]; + }; + P.regionName = function (cc) { if (this.U.fmt && this.U.fmt.country) { var n = this.U.fmt.country(cc); if (n) return n; } var lang = this.ctx.lang || undefined; @@ -1482,6 +1621,7 @@ var fmtN = this.U.fmt && this.U.fmt.num ? this.U.fmt.num : String; var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; }; if (min !== this.minute) { this.minute = min; this.computeMetrics(min, fmtN); } + if (this.visitsOn) this.visitMetrics(min, fmtN); // category and server counts, origins: the 15 minute window (partial minute included) var a = this.agg(min - 14, min, true), vis = this.agg(min - 14, min, false), c; CATS.forEach(function (k) { @@ -1541,8 +1681,20 @@ var box = this.recList, ring = this.ring, n = 0, self = this, i, r; var fl = this.U.fmt && this.U.fmt.flag ? this.U.fmt.flag : function () { return ''; }; while (box.firstChild) box.removeChild(box.firstChild); - for (i = ring.length - 1; i >= 0 && n < 30; i--) { - r = ring[i]; + var merged = ring; + if (this.visitsOn && this.vring.length) merged = ring.concat(this.vring).sort(function (a, b) { return a.t - b.t; }); + for (i = merged.length - 1; i >= 0 && n < 30; i--) { + r = merged[i]; + if (r.visit) { + if (!this.hostOk(r.host) || (r.device && this.offDev[r.device])) continue; + n++; + var vl = this.el('li', 'lv-ev lv-ev-visit'); + vl.appendChild(this.el('time', 'lv-ev-t', new Date(r.t * 1000).toLocaleTimeString(this.ctx.lang || undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' }))); + vl.appendChild(this.el('span', 'lv-tag lv-k-visit', this.t('live.visit'))); + vl.appendChild(this.el('span', 'lv-vtxt', [r.city || this.t('live.vis.empty'), r.domain, r.path, r.device].filter(Boolean).join(' \u00B7 '))); + box.appendChild(vl); + continue; + } if (!this.visible(r)) continue; n++; var li = this.el('li', 'lv-ev'); diff --git a/internal/server/web/mitre.css b/internal/server/web/mitre.css new file mode 100644 index 0000000..2af6df7 --- /dev/null +++ b/internal/server/web/mitre.css @@ -0,0 +1,28 @@ +/* MITRE ATT&CK page */ +.mt-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; } +.mt-matrix { display: grid; gap: var(--s-3, 12px); grid-template-columns: repeat(auto-fit, minmax(10.5rem, 1fr)); } +.mt-col { display: flex; flex-direction: column; gap: 6px; min-width: 0; } +.mt-th { display: flex; flex-direction: column; padding: 6px 8px; border-bottom: 2px solid var(--accent); min-width: 0; } +.mt-th strong { font: 700 .875rem/1.25 var(--font-display, inherit); color: var(--heading, var(--ink)); overflow-wrap: anywhere; } +.mt-th-sub { color: var(--ink-muted); font-size: .75rem; } +.mt-cell { display: grid; grid-template-columns: 1fr auto; gap: 0 8px; text-align: left; cursor: pointer; min-width: 0; + color: var(--ink); font: inherit; padding: 7px 9px; border-radius: 6px; border: 1px solid var(--line); + background: color-mix(in srgb, var(--accent) calc(var(--i, .1) * 60%), var(--surface-panel)); } +.mt-cell:hover, .mt-cell:focus-visible { border-color: var(--accent); } +.mt-cell.on { outline: 2px solid var(--accent); outline-offset: 1px; } +.mt-id { font: 600 .75rem/1.2 var(--font-mono, monospace); color: var(--ink-muted); grid-column: 1; } +.mt-n { grid-column: 2; grid-row: 1 / span 2; align-self: center; font-weight: 700; } +.mt-name { grid-column: 1; font-size: .8125rem; line-height: 1.25; overflow-wrap: anywhere; } +.mt-table { width: 100%; border-collapse: collapse; font-size: .875rem; } +.mt-table th, .mt-table td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; } +.mt-table th.num, .mt-table td.num { text-align: right; } +.mt-tablewrap { min-width: 0; max-width: 100%; } +.mt-link { color: var(--accent); font-family: var(--font-mono, monospace); } +.mt-trend { white-space: nowrap; font-size: .8125rem; } +.mt-up { color: var(--danger); } .mt-down { color: var(--ok); } .mt-flat, .mt-new { color: var(--ink-muted); } +.mt-drill { margin-top: var(--s-4, 16px); padding-top: var(--s-3, 12px); border-top: 1px solid var(--line); } +.mt-drill-h { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } +.mt-drill-h h3 { margin-right: auto; font-size: 1rem; overflow-wrap: anywhere; } +.mt-drill h4 { margin: 12px 0 6px; font-size: .875rem; color: var(--ink-muted); } +.mt-ips { display: flex; flex-wrap: wrap; gap: 6px; } +.mt-path { font-family: var(--font-mono, monospace); } diff --git a/internal/server/web/mitre.js b/internal/server/web/mitre.js new file mode 100644 index 0000000..ef87195 --- /dev/null +++ b/internal/server/web/mitre.js @@ -0,0 +1,236 @@ +/* Urutau - MITRE ATT&CK page: tactics x techniques matrix, radar per tactic and + ranking with trend. Data: /api/v1/techniques. Drill-down reads + /api/v1/events and keeps the events that carry the technique. Log data is + hostile: dynamic text goes through textContent only. */ +(function () { + 'use strict'; + + var TECH_RE = /^T\d{4}(\.\d{3})?$/; + var DRILL_LIMIT = 5000; + + function boot() { + var U = window.Urutau; + if (!U || !U.registerPage) return false; + U.registerI18n({ + en: { + 'mt.title': 'MITRE ATT&CK', + 'mt.lead.some': '{n} techniques in {m} tactics {range}', + 'mt.lead.sub': '{n} events matched a known technique.', + 'mt.lead.none': 'No technique observed {range}', + 'mt.lead.none.sub': 'Nothing matched the ATT&CK mapping in this window.', + 'mt.matrix': 'Which tactics and techniques hit us?', + 'mt.matrix.hint': 'Columns are tactics, cells are techniques; the darker, the more events. Click a cell to see who used it.', + 'mt.radar': 'Pressure per tactic', + 'mt.rank': 'Techniques by volume', + 'mt.col.tech': 'Technique', + 'mt.col.events': 'Events', + 'mt.col.ips': 'IPs', + 'mt.col.trend': 'Trend', + 'mt.trend.new': 'new', + 'mt.trend.vs': 'against the previous period of the same length', + 'mt.cell': '{name}: {events} events, {ips} IPs', + 'mt.drill.title': 'Who used {id}', + 'mt.drill.loading': 'Loading events...', + 'mt.drill.none': 'No recent event with this technique in the loaded sample.', + 'mt.drill.note': 'Showing {n} of the most recent events ({ips} IPs).', + 'mt.drill.ips': 'IPs', + 'mt.drill.events': 'Latest events', + 'mt.drill.open': 'Open on attack.mitre.org', + 'mt.drill.close': 'Close', + 'mt.error': 'Could not load the techniques.', + 'mt.disabled': 'The event registry is off', + 'mt.disabled.sub': 'Techniques are read from the event registry; enable it to see this page.', + 'mt.empty': 'No technique in this window', + 'mt.partial': 'Partial result: the study hit its time or size limit.' + }, + 'pt-BR': { + 'mt.title': 'MITRE ATT&CK', + 'mt.lead.some': '{n} técnicas em {m} táticas {range}', + 'mt.lead.sub': '{n} eventos corresponderam a uma técnica conhecida.', + 'mt.lead.none': 'Nenhuma técnica observada {range}', + 'mt.lead.none.sub': 'Nada correspondeu ao mapeamento ATT&CK nesta janela.', + 'mt.matrix': 'Que táticas e técnicas nos atingem?', + 'mt.matrix.hint': 'As colunas são táticas e as células, técnicas; quanto mais escuro, mais eventos. Clique numa célula para ver quem a usou.', + 'mt.radar': 'Pressão por tática', + 'mt.rank': 'Técnicas por volume', + 'mt.col.tech': 'Técnica', + 'mt.col.events': 'Eventos', + 'mt.col.ips': 'IPs', + 'mt.col.trend': 'Tendência', + 'mt.trend.new': 'nova', + 'mt.trend.vs': 'em relação ao período anterior de mesma duração', + 'mt.cell': '{name}: {events} eventos, {ips} IPs', + 'mt.drill.title': 'Quem usou {id}', + 'mt.drill.loading': 'Carregando eventos...', + 'mt.drill.none': 'Nenhum evento recente com esta técnica na amostra carregada.', + 'mt.drill.note': 'Mostrando {n} dos eventos mais recentes ({ips} IPs).', + 'mt.drill.ips': 'IPs', + 'mt.drill.events': 'Últimos eventos', + 'mt.drill.open': 'Abrir em attack.mitre.org', + 'mt.drill.close': 'Fechar', + 'mt.error': 'Não foi possível carregar as técnicas.', + 'mt.disabled': 'O registro de eventos está desligado', + 'mt.disabled.sub': 'As técnicas vêm do registro de eventos; ative-o para ver esta página.', + 'mt.empty': 'Nenhuma técnica nesta janela', + 'mt.partial': 'Resultado parcial: o estudo atingiu o limite de tempo ou de tamanho.' + } + }); + + var el = U.el, t = U.t, nf = U.fmt.num; + var root = null, seq = 0, alive = false, ctx = null, data = null, errBox = null, sel = null, drillSeq = 0; + + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + function when(s) { return s ? U.fmt.ago(s) : ''; } + function techURL(id) { + if (!TECH_RE.test(id)) return 'https://attack.mitre.org/techniques/'; + return 'https://attack.mitre.org/techniques/' + id.replace('.', '/') + '/'; + } + function trendNode(row) { + if (row.trend_pct === null || row.trend_pct === undefined) return el('span', { class: 'mt-trend mt-new', title: t('mt.trend.vs') }, t('mt.trend.new')); + var v = row.trend_pct, up = v > 0.5, down = v < -0.5; + var txt = (up ? '▲ ' : down ? '▼ ' : '■ ') + Math.abs(Math.round(v)) + '%'; + return el('span', { class: 'mt-trend ' + (up ? 'mt-up' : down ? 'mt-down' : 'mt-flat'), title: t('mt.trend.vs') }, txt); + } + + function renderMatrix(tactics, max) { + var grid = el('div', { class: 'mt-matrix' }); + tactics.forEach(function (ta) { + var col = el('div', { class: 'mt-col' }); + var total = ta.techniques.reduce(function (a, x) { return a + x.events; }, 0); + col.appendChild(el('div', { class: 'mt-th' }, + el('strong', null, ta.name), + el('span', { class: 'mt-th-sub' }, (ta.id || '-') + ' · ' + nf(total)))); + ta.techniques.forEach(function (tc) { + var ratio = Math.max(0.08, Math.min(1, tc.events / max)); + var b = el('button', { + type: 'button', class: 'mt-cell' + (sel === tc.id ? ' on' : ''), style: { '--i': ratio.toFixed(3) }, + title: t('mt.cell', { name: tc.name, events: nf(tc.events), ips: nf(tc.ips) }) + }, el('span', { class: 'mt-id' }, tc.id), el('span', { class: 'mt-name' }, tc.name), el('span', { class: 'mt-n num' }, nf(tc.events))); + b.addEventListener('click', function () { sel = sel === tc.id ? null : tc.id; paint(); }); + col.appendChild(b); + }); + grid.appendChild(col); + }); + return grid; + } + + function renderRank(rows) { + var tb = el('tbody'); + rows.slice(0, 15).forEach(function (r) { + tb.appendChild(el('tr', null, + el('td', null, el('a', { class: 'mt-link', href: techURL(r.id), target: '_blank', rel: 'noopener noreferrer' }, r.id), ' ', r.name), + el('td', { class: 'num' }, nf(r.events)), + el('td', { class: 'num' }, nf(r.ips)), + el('td', null, trendNode(r)))); + }); + return el('div', { class: 'mt-tablewrap' }, el('table', { class: 'mt-table' }, + el('thead', null, el('tr', null, el('th', null, t('mt.col.tech')), el('th', { class: 'num' }, t('mt.col.events')), el('th', { class: 'num' }, t('mt.col.ips')), el('th', null, t('mt.col.trend')))), tb)); + } + + var drillBox = null; + function drill(tc) { + var my = ++drillSeq; + if (!drillBox) return; + clear(drillBox); + drillBox.appendChild(el('p', { class: 'hint' }, t('mt.drill.loading'))); + var p = ctx && ctx.from ? { from: ctx.from, to: ctx.to } : U.rangeParams(); + var q = {}; Object.keys(p).forEach(function (k) { q[k] = p[k]; }); + if (ctx && ctx.host && ctx.host !== 'all') q.host = ctx.host; + q.limit = DRILL_LIMIT; + U.api('/api/v1/events', q).then(function (d) { + if (!alive || my !== drillSeq) return; + var evs = (d.events || []).filter(function (e) { return Array.isArray(e.tech) && e.tech.indexOf(tc.id) >= 0; }); + var byIP = {}; + evs.forEach(function (e) { byIP[e.ip] = (byIP[e.ip] || 0) + 1; }); + var ips = Object.keys(byIP).sort(function (a, b) { return byIP[b] - byIP[a]; }); + clear(drillBox); + drillBox.appendChild(el('div', { class: 'mt-drill-h' }, + el('h3', null, t('mt.drill.title', { id: tc.id }) + ' · ' + tc.name), + el('a', { class: 'btn', href: techURL(tc.id), target: '_blank', rel: 'noopener noreferrer' }, t('mt.drill.open')), + (function () { var b = el('button', { type: 'button', class: 'btn' }, t('mt.drill.close')); b.addEventListener('click', function () { sel = null; paint(); }); return b; })())); + if (!evs.length) { drillBox.appendChild(el('p', { class: 'hint' }, t('mt.drill.none'))); return; } + drillBox.appendChild(el('p', { class: 'hint' }, t('mt.drill.note', { n: nf(evs.length), ips: nf(ips.length) }))); + var chips = el('div', { class: 'mt-ips' }); + ips.slice(0, 24).forEach(function (ip) { + var b = el('button', { type: 'button', class: 'chip' }, ip + ' ×' + nf(byIP[ip])); + b.addEventListener('click', function () { U.openIP(ip); }); + chips.appendChild(b); + }); + var tb = el('tbody'); + evs.slice(0, 20).forEach(function (e) { + tb.appendChild(el('tr', null, el('td', null, e.t ? U.fmt.clock(e.t) : ''), el('td', null, String(e.ip || '')), el('td', null, String(e.cat || '')), + el('td', { class: 'mt-path' }, String(e.path || e.user || e.jail || '')))); + }); + drillBox.appendChild(el('h4', null, t('mt.drill.ips'))); + drillBox.appendChild(chips); + drillBox.appendChild(el('h4', null, t('mt.drill.events'))); + drillBox.appendChild(el('div', { class: 'mt-tablewrap' }, el('table', { class: 'mt-table' }, tb))); + }).catch(function () { + if (!alive || my !== drillSeq) return; + clear(drillBox); drillBox.appendChild(el('p', { class: 'hint' }, t('mt.error'))); + }); + } + + function paint() { + if (!root) return; + clear(root); + drillBox = null; + if (!data) { root.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } })); return; } + if (!data.enabled) { root.appendChild(U.ui.empty(t('mt.disabled'), t('mt.disabled.sub'))); return; } + var tactics = data.tactics || [], all = []; + tactics.forEach(function (ta) { ta.techniques.forEach(function (x) { all.push(x); }); }); + var range = U.rangeLabel({ inline: true }); + if (!all.length) { + root.appendChild(U.ui.lead(t('mt.lead.none', { range: range }), t('mt.lead.none.sub'), 'ok')); + root.appendChild(U.ui.empty(t('mt.empty'))); + return; + } + root.appendChild(U.ui.lead(t('mt.lead.some', { n: nf(all.length), m: nf(tactics.length), range: range }), t('mt.lead.sub', { n: nf(data.total) }), 'danger')); + if (data.truncated) root.appendChild(el('p', { class: 'hint' }, t('mt.partial'))); + var max = Math.max.apply(null, all.map(function (x) { return x.events; })); + var grid = el('div', { class: 'grid-12' }); + var mp = U.ui.panel({ title: t('mt.matrix'), hint: t('mt.matrix.hint'), cls: 'span-12' }, renderMatrix(tactics, max)); + drillBox = el('div', { class: 'mt-drill' }); + if (sel) { mp.body.appendChild(drillBox); } else drillBox = null; + grid.appendChild(mp); + var axes = tactics.map(function (ta) { return { key: ta.id || 'other', label: ta.name }; }); + var vals = tactics.map(function (ta) { return ta.techniques.reduce(function (a, x) { return a + x.events; }, 0); }); + var rp = U.ui.panel({ title: t('mt.radar'), cls: 'span-4' }); + if (U.charts && U.charts.radar && axes.length >= 3) rp.body.appendChild(U.charts.radar(axes, [{ label: t('mt.col.events'), values: vals }], { title: t('mt.radar'), format: nf })); + else if (U.charts && U.charts.bars) rp.body.appendChild(U.charts.bars(tactics.map(function (ta, i) { return { key: ta.id || 'other', label: ta.name, value: vals[i] }; }), { title: t('mt.radar'), format: nf })); + grid.appendChild(rp); + grid.appendChild(U.ui.panel({ title: t('mt.rank'), cls: 'span-8' }, renderRank(all.slice().sort(function (a, b) { return b.events - a.events; })))); + root.appendChild(grid); + if (sel) { + var tc = all.filter(function (x) { return x.id === sel; })[0]; + if (tc) drill(tc); else { sel = null; } + } + } + + function load() { + var my = ++seq; + U.api('/api/v1/techniques', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) { + if (!alive || my !== seq) return; + data = d; paint(); + }).catch(function () { + if (!alive || my !== seq || data) return; + clear(root); + root.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('mt.error')))); + }); + } + + U.registerPage({ + id: 'mitre', group: 'analyze', titleKey: 'mt.title', + icon: '', + mount: function (node, cx) { root = el('div', { class: 'mt-page' }); node.appendChild(root); ctx = cx; alive = true; data = null; sel = null; paint(); load(); }, + update: function (cx) { ctx = cx; load(); }, + refresh: function () { if (!sel) load(); }, + unmount: function () { alive = false; seq++; drillSeq++; 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); + } +})(); diff --git a/internal/server/web/pages.json b/internal/server/web/pages.json new file mode 100644 index 0000000..e5023fc --- /dev/null +++ b/internal/server/web/pages.json @@ -0,0 +1,72 @@ +{ + "pages": [ + { + "name": "geo", + "css": true + }, + { + "name": "live", + "css": true + }, + { + "name": "ip", + "css": true + }, + { + "name": "replay", + "css": true + }, + { + "name": "sessions", + "css": true + }, + { + "name": "campaigns", + "css": true + }, + { + "name": "search", + "css": true + }, + { + "name": "mitre", + "css": true + }, + { + "name": "defense", + "css": true + }, + { + "name": "evolution", + "css": true + }, + { + "name": "concentration", + "css": true + }, + { + "name": "survival", + "css": true + }, + { + "name": "errors", + "css": true + }, + { + "name": "slo", + "css": true + }, + { + "name": "protocol", + "css": true + }, + { + "name": "integrity", + "css": true + }, + { + "name": "reports", + "css": true + } + ] +} \ No newline at end of file diff --git a/internal/server/web/protocol.css b/internal/server/web/protocol.css new file mode 100644 index 0000000..0ad41f0 --- /dev/null +++ b/internal/server/web/protocol.css @@ -0,0 +1,10 @@ +/* Errors page */ +.hl-scroll { max-height: 420px; overflow: auto; } +.hl-table { width: 100%; border-collapse: collapse; font-size: .875rem; } +.hl-table th, .hl-table td { padding: 5px var(--s-3); border-bottom: 1px solid var(--line); text-align: left; overflow-wrap: anywhere; } +.hl-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); } +.hl-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; } +.hl-page .panel { min-width: 0; } +@media (max-width: 900px) { .hl-page .span-6, { grid-column: 1 / -1; } } +.hl-helps { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: var(--s-3, 10px); font-size: .8125rem; color: var(--ink-muted); } +.hl-help { display: inline-flex; align-items: center; gap: 4px; } diff --git a/internal/server/web/protocol.js b/internal/server/web/protocol.js new file mode 100644 index 0000000..de62558 --- /dev/null +++ b/internal/server/web/protocol.js @@ -0,0 +1,141 @@ +/* Urutau - page PROTOCOL ("Protocols and TLS"): HTTP version and TLS version by error class, + cipher suites, unusual methods, http against https. Data: /api/v1/protocols. textContent only. */ +(function () { + 'use strict'; + var U = window.Urutau; + if (!U || !U.registerPage) return; + var el = U.el, t = U.t; + var CLS = ['ok', 'app', 'proxy', 'blocked', 'attack', 'bot', 'client']; + var COLOR = { ok: '--ok', app: '--danger', proxy: '--warn', blocked: '--info', attack: '--cat-exploit', bot: '--viz-6', client: '--viz-5' }; + var PROTO = ['http1', 'http2', 'http3', 'other']; + var TLS = ['tls13', 'tls12', 'tls_old', 'none']; + + U.registerI18n({ + en: { + 'hl.pr.title': 'Protocols and TLS', + 'hl.pr.lead': '{pct} of requests use HTTP/2 or newer over TLS 1.3', + 'hl.pr.lead.body': '{plain} arrive over plain http {range}. Attack traffic leans on {atk}.', + 'hl.pr.lead.empty': 'No protocol data yet', + 'hl.pr.lead.empty.body': 'No Traefik requests with protocol fields {range}. Older log formats do not carry them.', + 'hl.pr.proto': 'HTTP version by class', 'hl.pr.proto.hint': 'Share of each class per protocol. Scripts and scanners often speak HTTP/1.1 or 1.0.', + 'hl.pr.tls': 'TLS version by class', 'hl.pr.tls.hint': 'Plain http and old TLS versions stand out here.', + 'hl.pr.ciphers': 'Cipher suites', 'hl.pr.ciphers.hint': 'What clients negotiated.', + 'hl.pr.methods': 'Methods', 'hl.pr.methods.hint': 'Methods outside GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS are marked.', + 'hl.pr.scheme': 'http against https', 'hl.pr.scheme.hint': 'Requests that reached the proxy on each entry point.', + 'hl.pr.odd': 'unusual', 'hl.pr.col.method': 'Method', 'hl.pr.col.n': 'Requests', 'hl.pr.col.errs': 'Errors', + 'hl.pr.p.http1': 'HTTP/1.x', 'hl.pr.p.http2': 'HTTP/2', 'hl.pr.p.http3': 'HTTP/3', 'hl.pr.p.other': 'Other', + 'hl.pr.t.tls13': 'TLS 1.3', 'hl.pr.t.tls12': 'TLS 1.2', 'hl.pr.t.tls_old': 'TLS 1.1 or older', 'hl.pr.t.none': 'No TLS (http)', + 'hl.pr.s.https': 'https', 'hl.pr.s.http': 'http', + 'hl.pr.c.ok': 'Succeeded', 'hl.pr.c.app': 'Application', 'hl.pr.c.proxy': 'Proxy', 'hl.pr.c.blocked': 'Blocked', 'hl.pr.c.attack': 'Attack', 'hl.pr.c.bot': 'Crawlers', 'hl.pr.c.client': 'Client', + 'hl.pr.err': 'Could not load the protocol data.', 'hl.pr.retry': 'Try again', 'hl.pr.empty': 'Nothing to show for this range.' + }, + 'pt-BR': { + 'hl.pr.title': 'Protocolos e TLS', + 'hl.pr.lead': '{pct} das requisições usam HTTP/2 ou mais novo sobre TLS 1.3', + 'hl.pr.lead.body': '{plain} chegam por http puro {range}. O tráfego de ataque se concentra em {atk}.', + 'hl.pr.lead.empty': 'Ainda sem dados de protocolo', + 'hl.pr.lead.empty.body': 'Nenhuma requisição do Traefik com campos de protocolo {range}. Formatos de log antigos não os trazem.', + 'hl.pr.proto': 'Versão do HTTP por classe', 'hl.pr.proto.hint': 'Parcela de cada classe por protocolo. Scripts e varreduras costumam falar HTTP/1.1 ou 1.0.', + 'hl.pr.tls': 'Versão do TLS por classe', 'hl.pr.tls.hint': 'Http puro e versões antigas de TLS aparecem aqui.', + 'hl.pr.ciphers': 'Suítes de cifra', 'hl.pr.ciphers.hint': 'O que os clientes negociaram.', + 'hl.pr.methods': 'Métodos', 'hl.pr.methods.hint': 'Métodos fora de GET, HEAD, POST, PUT, PATCH, DELETE e OPTIONS ficam marcados.', + 'hl.pr.scheme': 'http contra https', 'hl.pr.scheme.hint': 'Requisições que chegaram ao proxy em cada entrada.', + 'hl.pr.odd': 'incomum', 'hl.pr.col.method': 'Método', 'hl.pr.col.n': 'Requisições', 'hl.pr.col.errs': 'Erros', + 'hl.pr.p.http1': 'HTTP/1.x', 'hl.pr.p.http2': 'HTTP/2', 'hl.pr.p.http3': 'HTTP/3', 'hl.pr.p.other': 'Outro', + 'hl.pr.t.tls13': 'TLS 1.3', 'hl.pr.t.tls12': 'TLS 1.2', 'hl.pr.t.tls_old': 'TLS 1.1 ou anterior', 'hl.pr.t.none': 'Sem TLS (http)', + 'hl.pr.s.https': 'https', 'hl.pr.s.http': 'http', + 'hl.pr.c.ok': 'Sucesso', 'hl.pr.c.app': 'Aplicação', 'hl.pr.c.proxy': 'Proxy', 'hl.pr.c.blocked': 'Bloqueado', 'hl.pr.c.attack': 'Ataque', 'hl.pr.c.bot': 'Rastreadores', 'hl.pr.c.client': 'Cliente', + 'hl.pr.err': 'Não foi possível carregar os dados de protocolo.', 'hl.pr.retry': 'Tentar de novo', 'hl.pr.empty': 'Nada para mostrar neste período.' + } + }); + + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + function sum(o) { var n = 0; Object.keys(o || {}).forEach(function (k) { n += o[k]; }); return n; } + // rows (one per protocol/version) of parts (one per class), each row scaled to 100% + function stacked(rows, label, host) { + var data = rows.map(function (r) { + var tot = sum(r.c); + return { key: r.k, label: label(r.k) + ' (' + U.fmt.num(tot) + ')', value: 100, + parts: CLS.map(function (k) { return { label: t('hl.pr.c.' + k), value: tot ? (r.c[k] || 0) / tot * 100 : 0, color: COLOR[k] }; }) }; + }); + if (U.charts && U.charts.bars) host.appendChild(U.charts.bars(data, { horizontal: true, stacked: true, format: function () { return ''; }, title: '' })); + else host.appendChild(U.ui.empty(t('hl.pr.empty'))); + var lg = el('div', { class: 'hl-legend' }); + CLS.forEach(function (k) { lg.appendChild(el('span', null, el('i', { style: { background: 'var(' + COLOR[k] + ')' } }), t('hl.pr.c.' + k))); }); + host.appendChild(lg); + } + // a client class collapses its subtypes (the API already sums them under "client") + function rowsOf(map, names) { + return names.filter(function (k) { return map && map[k]; }).map(function (k) { return { k: k, c: map[k] }; }); + } + + var inst = null; + function create(root, ctx) { + var seq = 0, alive = true, data = null, c = ctx; + var grid = el('div', { class: 'grid-12 hl-page' }); + var lead = el('div', { class: 'span-12' }); + var pp = U.ui.panel({ title: t('hl.pr.proto'), hint: t('hl.pr.proto.hint'), variant: 'chart', loading: true, cls: 'span-6' }); + var pt = U.ui.panel({ title: t('hl.pr.tls'), hint: t('hl.pr.tls.hint'), variant: 'chart', loading: true, cls: 'span-6' }); + var ps = U.ui.panel({ title: t('hl.pr.scheme'), hint: t('hl.pr.scheme.hint'), loading: true, cls: 'span-4' }); + var pc = U.ui.panel({ title: t('hl.pr.ciphers'), hint: t('hl.pr.ciphers.hint'), variant: 'chart', loading: true, cls: 'span-8' }); + var pm = U.ui.panel({ title: t('hl.pr.methods'), hint: t('hl.pr.methods.hint'), variant: 'list', loading: true, cls: 'span-12' }); + [lead, pp, pt, ps, pc, pm].forEach(function (n) { grid.appendChild(n); }); + root.appendChild(grid); + + function paint() { + clear(lead); [pp, pt, ps, pc, pm].forEach(function (p) { clear(p.body); }); + if (!data) return; + var d = data, range = U.rangeLabel({ inline: true }); + var protoTot = {}, total = 0; + PROTO.forEach(function (k) { protoTot[k] = sum((d.protocols || {})[k]); total += protoTot[k]; }); + if (!total) { + lead.appendChild(U.ui.lead(t('hl.pr.lead.empty'), t('hl.pr.lead.empty.body', { range: range }), 'neutral')); + [pp, pt, ps, pc, pm].forEach(function (p) { p.body.appendChild(U.ui.empty(t('hl.pr.empty'))); }); + return; + } + var modern = ((d.tls || {}).tls13 ? sum(d.tls.tls13) : 0), h2 = protoTot.http2 + protoTot.http3; + var plain = (d.scheme || {}).http || 0, https = (d.scheme || {}).https || 0; + var atkP = PROTO.slice().sort(function (a, b) { return ((d.protocols[b] || {}).attack || 0) - ((d.protocols[a] || {}).attack || 0); })[0]; + lead.appendChild(U.ui.lead(t('hl.pr.lead', { pct: U.fmt.pct(Math.min(modern, h2) / total) }), + t('hl.pr.lead.body', { plain: U.fmt.pct(plain / Math.max(1, plain + https)), range: range, atk: t('hl.pr.p.' + atkP) }), plain > 0 ? 'warn' : 'neutral')); + stacked(rowsOf(d.protocols, PROTO), function (k) { return t('hl.pr.p.' + k); }, pp.body); + stacked(rowsOf(d.tls, TLS), function (k) { return t('hl.pr.t.' + k); }, pt.body); + // http vs https + if (U.charts && U.charts.donut) ps.body.appendChild(U.charts.donut([{ key: 'https', label: t('hl.pr.s.https'), value: https }, { key: 'http', label: t('hl.pr.s.http'), value: plain }], + { title: t('hl.pr.scheme'), colors: ['--ok', '--warn'], centerLabel: t('hl.pr.col.n') })); + var ci = (d.ciphers || []).slice(0, 12).map(function (x) { return { key: x.name, label: x.name, value: x.n }; }); + if (ci.length && U.charts && U.charts.bars) pc.body.appendChild(U.charts.bars(ci, { horizontal: true, title: t('hl.pr.ciphers') })); + else pc.body.appendChild(U.ui.empty(t('hl.pr.empty'))); + var tb = el('tbody'); + (d.methods || []).forEach(function (m) { + var errs = sum(m.classes) - (m.classes.ok || 0); + tb.appendChild(el('tr', null, el('td', { class: 'mono' }, m.method, m.odd ? U.ui.badge(t('hl.pr.odd'), 'warn') : null), el('td', { class: 'num' }, U.fmt.num(m.n)), el('td', { class: 'num' }, U.fmt.num(errs)), + el('td', null, CLS.filter(function (k) { return m.classes[k] || (k === 'client' && false); }).map(function (k) { return t('hl.pr.c.' + k) + ' ' + U.fmt.num(m.classes[k]); }).join(' · ')))); + }); + pm.body.appendChild(el('div', { class: 'hl-scroll' }, el('table', { class: 'hl-table' }, + el('thead', null, el('tr', null, el('th', null, t('hl.pr.col.method')), el('th', { class: 'num' }, t('hl.pr.col.n')), el('th', { class: 'num' }, t('hl.pr.col.errs')), el('th', null, ''))), tb))); + } + function load() { + var my = ++seq; + var p = Object.assign({}, U.rangeParams()); + if (c.domain && c.domain !== 'all') p.host = c.domain; + U.api('/api/v1/protocols', p).then(function (r) { if (alive && my === seq) { data = r; paint(); } }, function () { + if (!alive || my !== seq || data) return; + clear(lead); + var b = el('button', { type: 'button', class: 'btn' }, t('hl.pr.retry')); + b.addEventListener('click', load); + lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('hl.pr.err')), b)); + }); + } + load(); + return { update: function (cx) { c = cx; load(); }, destroy: function () { alive = false; seq++; clear(root); } }; + } + + U.registerPage({ + id: 'protocol', group: 'analyze', titleKey: 'hl.pr.title', + icon: '', + mount: function (node, ctx) { if (inst) inst.destroy(); inst = create(node, ctx || {}); }, + update: function (ctx) { if (inst) inst.update(ctx); }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); +})(); diff --git a/internal/server/web/reports.css b/internal/server/web/reports.css new file mode 100644 index 0000000..f7c7aa6 --- /dev/null +++ b/internal/server/web/reports.css @@ -0,0 +1,78 @@ +/* Urutau - REPORTS page. Selectors prefixed rpt-. On screen the report is a sheet; with + @media print it fills A4 pages and the shell chrome disappears. */ +.rpt { min-width: 0; } +.rpt-box { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; } +.rpt-bar { display: flex; flex-wrap: wrap; gap: 8px; } +.rpt-sheet { background: var(--surface-panel); border: 1px solid var(--line); border-radius: var(--radius, 10px); padding: clamp(14px, 3vw, 32px); display: flex; flex-direction: column; gap: 22px; min-width: 0; color: var(--ink); } +.rpt-cover { border-bottom: 2px solid var(--accent); padding-bottom: 14px; } +.rpt-kicker { margin: 0; font-size: .75rem; letter-spacing: .08em; text-transform: uppercase; color: var(--ink-muted); } +.rpt-cover h1 { margin: 4px 0 10px; font: 700 1.75rem/1.15 var(--font-display); color: var(--heading); } +.rpt-meta { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 3px 14px; margin: 0; font-size: .875rem; } +.rpt-meta dt { color: var(--ink-muted); } +.rpt-meta dd { margin: 0; overflow-wrap: anywhere; } +.rpt-sec h2 { margin: 0 0 10px; font: 650 1.0625rem/1.2 var(--font-display); color: var(--heading); } +.rpt-sents p { margin: 0 0 6px; font-size: .9375rem; line-height: 1.5; max-width: 90ch; overflow-wrap: anywhere; } +.rpt-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-top: 12px; } +.rpt-kpi { display: flex; flex-direction: column; gap: 2px; padding: 10px 12px; border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); min-width: 0; } +.rpt-kl { font-size: .75rem; color: var(--ink-muted); } +.rpt-kpi strong { font-size: 1.375rem; color: var(--heading); } +.rpt-kd { font-size: .6875rem; color: var(--ink-muted); } +.rpt-warn { color: var(--warn); font-size: .8125rem; } +.rpt-charts { display: grid; grid-template-columns: minmax(0, 1fr); gap: 14px; } +@media (min-width: 900px) { .rpt-charts { grid-template-columns: repeat(2, minmax(0, 1fr)); } .rpt-wide { grid-column: 1 / -1; } } +.rpt-chart { min-width: 0; border: 1px solid var(--line); border-radius: var(--radius-sm, 7px); padding: 10px 12px; } +.rpt-chart h3 { margin: 0 0 8px; font-size: .8125rem; font-weight: 600; color: var(--ink-muted); } +.rpt-p2 { display: flex; flex-direction: column; gap: 18px; min-width: 0; } +.rpt-scroll { overflow-x: auto; max-width: 100%; } +.rpt-table { width: 100%; border-collapse: collapse; font-size: .8125rem; } +.rpt-table th { text-align: left; font-weight: 600; color: var(--ink-muted); padding: 5px 8px; border-bottom: 1px solid var(--line-strong, var(--line)); } +.rpt-table td { padding: 5px 8px; border-bottom: 1px solid var(--line); overflow-wrap: anywhere; vertical-align: top; } +.rpt-none { margin: 0; color: var(--ink-muted); font-size: .8125rem; } +.rpt-foot { margin: 0; font-size: .75rem; color: var(--ink-faint); } + +@page { size: A4; margin: 12mm; } +@media print { + :root, :root[data-theme] { + --surface-base: #fff; --surface-panel: #fff; --surface-sunken: #f4f6f8; --surface-raised: #fff; + --line: #cfd6dc; --line-strong: #8a96a0; --ink: #14202a; --ink-muted: #46545f; --ink-faint: #5d6b76; --heading: #000; + --accent: #0a78b5; --warn: #8a5a00; + color-scheme: light; + } + html, body { background: #fff !important; color: #14202a; } + .rail, .topbar, .slice, .tabbar, .more-sheet, .err-banner, .shell-foot, .toasts, .scrim, .skip, .rpt-bar, #detail { display: none !important; } + .app { display: block !important; background: none !important; min-height: 0; } + .main, main#view { display: block !important; padding: 0 !important; margin: 0 !important; overflow: visible !important; } + .rpt-sheet { border: 0; padding: 0; gap: 12px; border-radius: 0; } + .rpt-cover h1 { font-size: 1.5rem; } + .rpt-sec, .rpt-chart, .rpt-kpi { break-inside: avoid; } + .rpt-charts { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8px; } + .rpt-wide { grid-column: 1 / -1; } + .rpt-p2 { break-before: page; gap: 10px; } + .rpt-p2 .rpt-sec { break-inside: avoid; } + .rpt-scroll { overflow: visible; } + .rpt-table { font-size: 8.5pt; } + .rpt-sents p { font-size: 10pt; } + .rpt-kpi strong { font-size: 1.125rem; } +} +.rpt .vz svg, .rpt .chart-wrap svg { max-width: 100%; height: auto; } +@media print { + .rpt-sec-charts { break-inside: auto; } + .rpt-kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; } + .rpt-kpi { padding: 6px 8px; } + .rpt-chart { padding: 6px 8px; } + .rpt-chart svg { max-height: 150px; width: 100%; } + .rpt-chart .vz-legend, .rpt-chart ul { font-size: 8pt; } + .rpt-sheet { gap: 10px; } +} +@media print { + .rpt-chart svg { max-height: 120px; } + .rpt-chart .vz-donut, .rpt-chart .vz-donut svg { max-height: 120px; } + .rpt-chart .bar-row, .rpt-chart .vz-row { font-size: 8.5pt; } + .rpt-chart .vz-row { margin: 2px 0; } +} +@media print { + .rpt-noprint { display: none !important; } + .rpt-charts { grid-template-columns: repeat(3, minmax(0, 1fr)); } + .rpt-table td, .rpt-table th { padding: 3px 6px; } + .rpt-p2 .rpt-sec h2 { margin-bottom: 4px; font-size: 11pt; } +} diff --git a/internal/server/web/reports.js b/internal/server/web/reports.js new file mode 100644 index 0000000..62acf16 --- /dev/null +++ b/internal/server/web/reports.js @@ -0,0 +1,357 @@ +/* Urutau - REPORTS page: executive report of the chosen period, printable on A4 + (window.print() with @page / @media print in reports.css, no libraries) and + exportable as JSON or CSV. Data: GET /api/v1/report. Log data is hostile: + every dynamic string goes through textContent; CSV cells that start with + = + - @ get a leading apostrophe (spreadsheet formula injection). */ +(function () { + 'use strict'; + + var ICON = ''; + + function csvCell(v) { + if (v === null || v === undefined) return ''; + if (typeof v === 'number') return isFinite(v) ? String(v) : ''; + var s = String(v); + if (/^[=+\-@\t\r]/.test(s)) s = "'" + s; + if (/[",\n\r]/.test(s)) s = '"' + s.replace(/"/g, '""') + '"'; + return s; + } + + function boot() { + var U = window.Urutau; + if (!U || !U.registerPage) return false; + U.registerI18n({ + en: { + 'rpt.title': 'Reports', + 'rpt.print': 'Print', + 'rpt.json': 'Export JSON', + 'rpt.csv': 'Export CSV', + 'rpt.cover.kicker': 'Executive report', + 'rpt.cover.title': 'Security report', + 'rpt.cover.period': 'Period', + 'rpt.cover.hosts': 'Hosts', + 'rpt.cover.generated': 'Generated', + 'rpt.cover.all': 'all hosts', + 'rpt.sum.title': 'Executive summary', + 'rpt.sum.lead': 'In this period {hosts} recorded {attacks} attacks from {ips} distinct addresses; {hostile} of them were hostile and {bans} are banned.', + 'rpt.sum.up': 'Attacks rose {pct}% against the previous period.', + 'rpt.sum.down': 'Attacks fell {pct}% against the previous period.', + 'rpt.sum.flat': 'Attack volume is in line with the previous period.', + 'rpt.sum.noPrev': 'There is no previous period to compare with.', + 'rpt.sum.top': 'The most frequent attack family was {fam}, and most traffic came from {cc}.', + 'rpt.sum.ban': 'The median time to ban was {t}; {cov}% of hostile addresses are covered by a ban.', + 'rpt.sum.expo': '{n} attack requests were answered with success and deserve review.', + 'rpt.sum.noExpo': 'No attack request reached an exposed resource.', + 'rpt.k.requests': 'Requests', + 'rpt.k.attacks': 'Attacks', + 'rpt.k.unique_ips': 'Unique IPs', + 'rpt.k.hostile_ips': 'Hostile IPs', + 'rpt.k.bans': 'Bans', + 'rpt.k.visitors': 'Visitors', + 'rpt.k.nonhuman': 'Non-human clients', + 'rpt.k.page_views': 'Page views', + 'rpt.k.prev': 'before: {v}', + 'rpt.chart.timeline': 'Attacks over time', + 'rpt.chart.families': 'Attack families', + 'rpt.chart.countries': 'Origin countries', + 'rpt.chart.asns': 'Networks (ASN)', + 'rpt.chart.techniques': 'Techniques', + 'rpt.table.ips': 'Top addresses', + 'rpt.table.campaigns': 'Main campaigns', + 'rpt.table.escalations': 'Escalations', + 'rpt.table.exposure': 'Exposures', + 'rpt.table.defense': 'Defence', + 'rpt.col.ip': 'Address', + 'rpt.col.score': 'Score', + 'rpt.col.level': 'Level', + 'rpt.col.country': 'Country', + 'rpt.col.network': 'Network', + 'rpt.col.events': 'Events', + 'rpt.col.banned': 'Banned', + 'rpt.col.campaign': 'Campaign', + 'rpt.col.ips': 'IPs', + 'rpt.col.period': 'Active', + 'rpt.col.techs': 'Techniques', + 'rpt.col.stage': 'Stage', + 'rpt.col.host': 'Host', + 'rpt.col.path': 'Path', + 'rpt.col.status': 'Status', + 'rpt.col.family': 'Family', + 'rpt.col.when': 'When', + 'rpt.yes': 'yes', + 'rpt.no': 'no', + 'rpt.empty': 'Nothing to report in this period.', + 'rpt.none': 'None in this period.', + 'rpt.def.mttb': 'Median time to ban', + 'rpt.def.mttbP90': 'Time to ban (90th percentile)', + 'rpt.def.cover': 'Ban coverage', + 'rpt.def.blocklist': 'Blocklist coverage', + 'rpt.def.exposure': 'Exposure rate', + 'rpt.def.refused': 'Exploits refused', + 'rpt.def.n': 'Bans measured', + 'rpt.truncated': 'The study was cut at its limits; the figures may be partial.', + 'rpt.foot': 'Generated by Urutau. Addresses come from logs and are shown as recorded.' + }, + 'pt-BR': { + 'rpt.title': 'Relatórios', + 'rpt.print': 'Imprimir', + 'rpt.json': 'Exportar JSON', + 'rpt.csv': 'Exportar CSV', + 'rpt.cover.kicker': 'Relatório executivo', + 'rpt.cover.title': 'Relatório de segurança', + 'rpt.cover.period': 'Período', + 'rpt.cover.hosts': 'Hosts', + 'rpt.cover.generated': 'Gerado em', + 'rpt.cover.all': 'todos os hosts', + 'rpt.sum.title': 'Sumário executivo', + 'rpt.sum.lead': 'Neste período {hosts} registrou {attacks} ataques de {ips} endereços distintos; {hostile} deles foram hostis e {bans} estão banidos.', + 'rpt.sum.up': 'Os ataques subiram {pct}% em relação ao período anterior.', + 'rpt.sum.down': 'Os ataques caíram {pct}% em relação ao período anterior.', + 'rpt.sum.flat': 'O volume de ataques está em linha com o período anterior.', + 'rpt.sum.noPrev': 'Não há período anterior para comparar.', + 'rpt.sum.top': 'A família de ataque mais frequente foi {fam}, e a maior parte do tráfego veio de {cc}.', + 'rpt.sum.ban': 'O tempo mediano até o banimento foi {t}; {cov}% dos endereços hostis estão cobertos por um ban.', + 'rpt.sum.expo': '{n} requisições de ataque foram respondidas com sucesso e merecem revisão.', + 'rpt.sum.noExpo': 'Nenhuma requisição de ataque chegou a um recurso exposto.', + 'rpt.k.requests': 'Requisições', + 'rpt.k.attacks': 'Ataques', + 'rpt.k.unique_ips': 'IPs únicos', + 'rpt.k.hostile_ips': 'IPs hostis', + 'rpt.k.bans': 'Bans', + 'rpt.k.visitors': 'Visitantes', + 'rpt.k.nonhuman': 'Clientes não humanos', + 'rpt.k.page_views': 'Páginas vistas', + 'rpt.k.prev': 'antes: {v}', + 'rpt.chart.timeline': 'Ataques ao longo do tempo', + 'rpt.chart.families': 'Famílias de ataque', + 'rpt.chart.countries': 'Países de origem', + 'rpt.chart.asns': 'Redes (ASN)', + 'rpt.chart.techniques': 'Técnicas', + 'rpt.table.ips': 'Principais endereços', + 'rpt.table.campaigns': 'Principais campanhas', + 'rpt.table.escalations': 'Escaladas', + 'rpt.table.exposure': 'Exposições', + 'rpt.table.defense': 'Defesa', + 'rpt.col.ip': 'Endereço', + 'rpt.col.score': 'Pontuação', + 'rpt.col.level': 'Nível', + 'rpt.col.country': 'País', + 'rpt.col.network': 'Rede', + 'rpt.col.events': 'Eventos', + 'rpt.col.banned': 'Banido', + 'rpt.col.campaign': 'Campanha', + 'rpt.col.ips': 'IPs', + 'rpt.col.period': 'Atividade', + 'rpt.col.techs': 'Técnicas', + 'rpt.col.stage': 'Estágio', + 'rpt.col.host': 'Host', + 'rpt.col.path': 'Caminho', + 'rpt.col.status': 'Status', + 'rpt.col.family': 'Família', + 'rpt.col.when': 'Quando', + 'rpt.yes': 'sim', + 'rpt.no': 'não', + 'rpt.empty': 'Nada a relatar neste período.', + 'rpt.none': 'Nenhum neste período.', + 'rpt.def.mttb': 'Tempo mediano até o ban', + 'rpt.def.mttbP90': 'Tempo até o ban (percentil 90)', + 'rpt.def.cover': 'Cobertura de bans', + 'rpt.def.blocklist': 'Cobertura da lista de bloqueio', + 'rpt.def.exposure': 'Taxa de exposição', + 'rpt.def.refused': 'Exploits recusados', + 'rpt.def.n': 'Bans medidos', + 'rpt.truncated': 'O estudo foi cortado nos seus limites; os números podem estar parciais.', + 'rpt.foot': 'Gerado pelo Urutau. Os endereços vêm dos logs e aparecem como registrados.' + } + }); + var t = U.t, nf = U.fmt.num; + var h = function (tag, cls) { return U.el.apply(null, [tag, cls ? { class: cls } : null].concat([].slice.call(arguments, 2))); }; + + var root = null, box = null, ctx0 = null, seq = 0, alive = false, data = null; + + function dur(s) { + s = Math.round(s || 0); + if (s < 60) return t('dur.s', { n: nf(s) }); + if (s < 3600) return t('dur.m', { n: nf(Math.round(s / 60)) }); + if (s < 86400) return t('dur.h', { n: nf(Math.round(s / 3600)) }); + return t('dur.d', { n: nf(Math.round(s / 86400)) }); + } + function day(ts) { return new Date(ts * 1000).toLocaleDateString((ctx0 && ctx0.lang) || undefined, { day: 'numeric', month: 'short', year: 'numeric' }); } + function pctTxt(v) { return nf(Math.round(v * 10) / 10) + '%'; } + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + + function params(c) { + var p = U.rangeParams(); + if (c && c.host && c.host !== 'all') p.host = c.host; + p.format = 'json'; + return p; + } + function load(c) { + var my = ++seq; + U.api('/api/v1/report', params(c || ctx0)).then(function (d) { + if (!alive || my !== seq) return; + data = d; paint(); + }).catch(function () { + if (!alive || my !== seq || data) return; + clear(box); + box.appendChild(U.ui.empty(t('error.load'))); + }); + } + + function save(name, type, text) { + try { + var url = URL.createObjectURL(new Blob([text], { type: type })); + var a = document.createElement('a'); + a.href = url; a.download = name; + document.body.appendChild(a); a.click(); document.body.removeChild(a); + setTimeout(function () { URL.revokeObjectURL(url); }, 2000); + } catch (e) { console.error(e); } + } + function stamp(ext) { + var r = data && data.range ? data.range : { from: 0, to: 0 }; + var f = function (x) { return new Date(x * 1000).toISOString().slice(0, 10); }; + return 'urutau-report-' + f(r.from) + '_' + f(r.to) + '.' + ext; + } + function toCSV(d) { + var rows = [['section', 'key', 'value', 'extra']]; + function add() { rows.push([].slice.call(arguments)); } + add('range', 'from', new Date(d.range.from * 1000).toISOString()); + add('range', 'to', new Date(d.range.to * 1000).toISOString()); + add('range', 'hosts', (d.hosts || []).join(' ')); + Object.keys(d.summary || {}).forEach(function (k) { + var v = d.summary[k]; + if (typeof v === 'number') add('summary', k, v, d.summary.prev && typeof d.summary.prev[k] === 'number' ? d.summary.prev[k] : ''); + }); + ['families', 'techniques', 'countries', 'asns'].forEach(function (s) { (d[s] || []).forEach(function (r) { add(s, r.key, r.n, r.label || ''); }); }); + (d.top_ips || []).forEach(function (r) { add('top_ips', r.ip, r.score, [r.level, r.cc, r.as_org, r.events, r.banned ? 'banned' : ''].join(' ')); }); + (d.campaigns || []).forEach(function (c) { add('campaigns', c.id, c.ips_n, (c.techs || []).join(' ')); }); + (d.escalations || []).forEach(function (e) { add('escalations', e.ip, e.stage, e.host || ''); }); + ((d.exposures || {}).items || []).forEach(function (e) { add('exposures', e.ip, e.path, [e.host, e.domain, e.status, e.fam].join(' ')); }); + Object.keys(d.defense || {}).forEach(function (k) { add('defense', k, d.defense[k]); }); + return rows.map(function (r) { return r.map(csvCell).join(','); }).join('\r\n') + '\r\n'; + } + + function toolbar() { + var bar = h('div', 'rpt-bar'); + var b1 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.print')); + b1.addEventListener('click', function () { window.print(); }); + var b2 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.json')); + b2.addEventListener('click', function () { if (data) save(stamp('json'), 'application/json', JSON.stringify(data, null, 2)); }); + var b3 = U.el('button', { type: 'button', class: 'btn' }, t('rpt.csv')); + b3.addEventListener('click', function () { if (data) save(stamp('csv'), 'text/csv;charset=utf-8', '' + toCSV(data)); }); + bar.appendChild(b1); bar.appendChild(b2); bar.appendChild(b3); + return bar; + } + + function table(headers, rows) { + var tb = h('table', 'rpt-table'), tr = h('tr'); + headers.forEach(function (x) { tr.appendChild(h('th', null, x)); }); + tb.appendChild(h('thead', null, tr)); + var body = h('tbody'); + rows.forEach(function (r) { var row = h('tr'); r.forEach(function (c) { row.appendChild(h('td', null, c)); }); body.appendChild(row); }); + tb.appendChild(body); + return h('div', 'rpt-scroll', tb); + } + function section(title, body, cls) { + return h('section', 'rpt-sec' + (cls ? ' ' + cls : ''), h('h2', null, title), body); + } + function emptyNote(key) { return h('p', 'rpt-none', t(key || 'rpt.none')); } + function barRows(list) { return (list || []).map(function (r) { return { key: r.key, label: r.label ? r.key + ' ' + r.label : r.key, value: r.n }; }); } + + function paint() { + if (!data) return; + clear(box); + var d = data, s = d.summary || {}, doc = h('article', 'rpt-sheet'); + var hosts = (d.hosts && d.hosts.length) ? d.hosts.join(', ') : t('rpt.cover.all'); + + // cover + doc.appendChild(h('header', 'rpt-cover', + h('p', 'rpt-kicker', t('rpt.cover.kicker')), + h('h1', null, t('rpt.cover.title')), + h('dl', 'rpt-meta', + h('dt', null, t('rpt.cover.period')), h('dd', null, day(d.range.from) + ' - ' + day(d.range.to)), + h('dt', null, t('rpt.cover.hosts')), h('dd', null, hosts), + h('dt', null, t('rpt.cover.generated')), h('dd', null, U.fmt.date(d.generated))))); + + // executive summary + var sents = []; + sents.push(t('rpt.sum.lead', { hosts: hosts, attacks: nf(s.attacks), ips: nf(s.unique_ips), hostile: nf(s.hostile_ips), bans: nf(s.bans) })); + var dp = s.delta_pct && typeof s.delta_pct.attacks === 'number' ? s.delta_pct.attacks : null; + if (!s.has_prev || dp === null) sents.push(t('rpt.sum.noPrev')); + else if (Math.abs(dp) < 5) sents.push(t('rpt.sum.flat')); + else sents.push(t(dp > 0 ? 'rpt.sum.up' : 'rpt.sum.down', { pct: nf(Math.round(Math.abs(dp))) })); + if ((d.families || []).length && (d.countries || []).length) sents.push(t('rpt.sum.top', { fam: d.families[0].key, cc: U.fmt.country(d.countries[0].key) })); + var df = d.defense || {}; + if (df.mttb_n > 0) sents.push(t('rpt.sum.ban', { t: dur(df.mttb_median_s), cov: nf(Math.round(df.ban_coverage)) })); + var ex = d.exposures || {}; + sents.push(ex.total > 0 ? t('rpt.sum.expo', { n: nf(ex.total) }) : t('rpt.sum.noExpo')); + var kp = h('div', 'rpt-kpis'); + ['requests', 'attacks', 'unique_ips', 'hostile_ips', 'bans', 'visitors', 'nonhuman', 'page_views'].forEach(function (k) { + var delta = s.delta_pct && typeof s.delta_pct[k] === 'number' ? s.delta_pct[k] : null; + kp.appendChild(h('div', 'rpt-kpi', h('span', 'rpt-kl', t('rpt.k.' + k)), h('strong', 'num', nf(s[k] || 0)), + s.has_prev ? h('span', 'rpt-kd', (delta === null ? '' : (delta > 0 ? '▲ ' : delta < 0 ? '▼ ' : '') + nf(Math.abs(Math.round(delta))) + '% · ') + t('rpt.k.prev', { v: nf((s.prev || {})[k] || 0) })) : null)); + }); + var sumBox = h('div', null, h('div', 'rpt-sents', sents.map(function (x) { return h('p', null, x); })), kp); + if (d.truncated) sumBox.appendChild(h('p', 'rpt-warn', t('rpt.truncated'))); + doc.appendChild(section(t('rpt.sum.title'), sumBox, 'rpt-first')); + + // charts + var tl = d.timeline || {}; + var chartsBox = h('div', 'rpt-charts'); + var c1 = h('div', 'rpt-chart rpt-wide', h('h3', null, t('rpt.chart.timeline'))); + c1.appendChild(U.charts.stackedArea([{ key: 'attacks', label: t('rpt.k.attacks'), values: tl.values || [] }], tl.step, { start: tl.start, title: t('rpt.chart.timeline') })); + chartsBox.appendChild(c1); + function cbox(title, node, cls) { var c = h('div', 'rpt-chart' + (cls ? ' ' + cls : ''), h('h3', null, title)); c.appendChild(node); chartsBox.appendChild(c); } + cbox(t('rpt.chart.families'), (d.families || []).length ? U.charts.donut(d.families.slice(0, 5).map(function (r) { return { key: r.key, label: r.key, value: r.n }; }), { title: t('rpt.chart.families') }) : emptyNote()); + cbox(t('rpt.chart.countries'), (d.countries || []).length ? U.charts.bars((d.countries || []).slice(0, 5).map(function (r) { return { key: r.key, label: U.fmt.country(r.key), value: r.n }; }), { title: t('rpt.chart.countries') }) : emptyNote()); + cbox(t('rpt.chart.asns'), (d.asns || []).length ? U.charts.bars(barRows(d.asns.slice(0, 5)), { title: t('rpt.chart.asns') }) : emptyNote()); + cbox(t('rpt.chart.techniques'), (d.techniques || []).length ? U.charts.bars(barRows(d.techniques.slice(0, 5)), { title: t('rpt.chart.techniques') }) : emptyNote(), 'rpt-noprint'); + doc.appendChild(section(t('rpt.chart.timeline'), chartsBox, 'rpt-sec-charts')); + + // tables (page 2) + var p2 = h('div', 'rpt-p2'); + p2.appendChild(section(t('rpt.table.ips'), (d.top_ips || []).length ? table([t('rpt.col.ip'), t('rpt.col.score'), t('rpt.col.level'), t('rpt.col.country'), t('rpt.col.network'), t('rpt.col.events'), t('rpt.col.banned')], + d.top_ips.map(function (r) { return [r.ip, nf(r.score), r.level, r.cc ? U.fmt.country(r.cc) : '-', r.as_org || '-', nf(r.events), t(r.banned ? 'rpt.yes' : 'rpt.no')]; })) : emptyNote())); + p2.appendChild(section(t('rpt.table.campaigns'), (d.campaigns || []).length ? table([t('rpt.col.campaign'), t('rpt.col.ips'), t('rpt.col.period'), t('rpt.col.techs')], + d.campaigns.map(function (c) { return [c.id, nf(c.ips_n), day(Date.parse(c.first) / 1000) + ' - ' + day(Date.parse(c.last) / 1000), (c.techs || []).slice(0, 4).join(', ')]; })) : emptyNote())); + p2.appendChild(section(t('rpt.table.escalations'), (d.escalations || []).length ? table([t('rpt.col.ip'), t('rpt.col.stage'), t('rpt.col.host')], + d.escalations.map(function (e) { return [e.ip, e.stage, e.host || '-']; })) : emptyNote())); + p2.appendChild(section(t('rpt.table.exposure'), (ex.items || []).length ? table([t('rpt.col.when'), t('rpt.col.ip'), t('rpt.col.host'), t('rpt.col.path'), t('rpt.col.status'), t('rpt.col.family')], + ex.items.map(function (e) { return [U.fmt.date(e.t), e.ip, e.domain || e.host || '-', e.path, String(e.status), e.fam || '-']; })) : emptyNote('rpt.sum.noExpo'))); + p2.appendChild(section(t('rpt.table.defense'), table(['', ''], [ + [t('rpt.def.mttb'), df.mttb_n > 0 ? dur(df.mttb_median_s) : '-'], + [t('rpt.def.mttbP90'), df.mttb_n > 0 ? dur(df.mttb_p90_s) : '-'], + [t('rpt.def.n'), nf(df.mttb_n || 0)], + [t('rpt.def.cover'), pctTxt(df.ban_coverage || 0)], + [t('rpt.def.blocklist'), pctTxt(df.blocklist_coverage || 0)], + [t('rpt.def.exposure'), pctTxt(df.exposure_rate || 0)], + [t('rpt.def.refused'), pctTxt(df.exploits_refused_pct || 0)] + ]))); + p2.appendChild(h('p', 'rpt-foot', t('rpt.foot'))); + doc.appendChild(p2); + + box.appendChild(toolbar()); + box.appendChild(doc); + } + + U.registerPage({ + id: 'reports', group: 'reports', icon: ICON, titleKey: 'rpt.title', + mount: function (el, c) { + ctx0 = c; alive = true; data = null; + root = h('div', 'rpt'); + box = h('div', 'rpt-box'); + root.appendChild(box); + box.appendChild(h('div', 'skeleton')); + el.appendChild(root); + load(c); + }, + update: function (c) { ctx0 = c; load(c); }, + unmount: function () { alive = false; seq++; if (root && root.parentNode) root.parentNode.removeChild(root); root = box = data = null; } + }); + return true; + } + + if (!boot()) { + var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100); + } +})(); diff --git a/internal/server/web/search.css b/internal/server/web/search.css new file mode 100644 index 0000000..35da622 --- /dev/null +++ b/internal/server/web/search.css @@ -0,0 +1,25 @@ +/* Urutau - SEARCH page. Selectors prefixed sr-. */ +.sr { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; } +.sr-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 150px), 1fr)); gap: 10px; align-items: end; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius, 10px); background: var(--surface-panel); } +.sr-fld { display: flex; flex-direction: column; gap: 4px; min-width: 0; font-size: .75rem; color: var(--ink-muted); } +.sr-fld input, .sr-fld select { width: 100%; min-width: 0; } +.sr-period { font-size: .875rem; color: var(--ink); min-height: 36px; display: flex; align-items: center; } +.sr-act { display: flex; gap: 8px; } +.sr-ip { color: var(--accent); text-decoration: none; overflow-wrap: anywhere; } +.sr-path { overflow-wrap: anywhere; word-break: break-all; } +.sr-table td { vertical-align: top; } +.sr-cat { display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: .75rem; font-weight: 600; color: #04121c; background: var(--ink-faint); } +.sr-c-notfound { background: var(--info); } .sr-c-scanner { background: var(--warn); } .sr-c-bruteforce { background: #fb923c; } +.sr-c-exploit { background: var(--danger); } .sr-c-ssh-fail { background: #fb923c; } .sr-c-ssh-probe { background: var(--warn); } +.sr-c-ssh-ok { background: #c026d3; } .sr-c-ban { background: var(--ink-muted); } +.sr-more { align-self: center; } + +/* Wide table: stack into cards up to 1023px (the shared rule starts at 767px). */ +@media (max-width: 1023px) { + table.sr-table thead { display: none; } + table.sr-table, table.sr-table tbody, table.sr-table tr, table.sr-table td { display: block; width: 100%; } + table.sr-table tr { border-top: 1px solid var(--line); padding: 8px 0; } + table.sr-table tr:first-child { border-top: 0; } + table.sr-table td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; text-align: right; min-width: 0; overflow-wrap: anywhere; } + table.sr-table td::before { content: attr(data-label); color: var(--ink-muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; text-align: left; flex: none; } +} diff --git a/internal/server/web/search.js b/internal/server/web/search.js new file mode 100644 index 0000000..466fc2b --- /dev/null +++ b/internal/server/web/search.js @@ -0,0 +1,220 @@ +/* Urutau - SEARCH page: event search over /api/v1/events with cursor paging, CSV export + in the browser. Hostile data: textContent only; CSV cells starting with = + - @ get a ' prefix. */ +(function () { + 'use strict'; + var CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban']; + var CAT_OK = {}; CATS.concat(['ok']).forEach(function (c) { CAT_OK[c] = 1; }); + var ICON = ''; + var PAGE = 100, MAXROWS = 5000; + + function boot() { + var U = window.Urutau; + if (!U || !U.registerPage) return false; + var t = U.t, nf = U.fmt.num; + function h(tag, a) { if (typeof a === 'string') a = { class: a }; return U.el.apply(null, [tag, a].concat([].slice.call(arguments, 2))); } + U.registerI18n({ + en: { + 'sr.title': 'Event search', + 'sr.lead.one': '{n} event found', + 'sr.lead.other': '{n} events found', + 'sr.lead.more': 'More events match; load more to continue.', + 'sr.lead.body': 'Events {range}, newest first.', + 'sr.lead.empty': 'No event matches', + 'sr.lead.emptyBody': 'Nothing {range} fits these filters, or the event registry is off.', + 'sr.f.ip': 'IP or prefix', + 'sr.f.q': 'Path contains', + 'sr.f.fam': 'Family', + 'sr.f.cat': 'Category', + 'sr.f.status': 'Status', + 'sr.f.host': 'Host', + 'sr.f.period': 'Period', + 'sr.f.all': 'All', + 'sr.f.s2': '2xx', + 'sr.f.s3': '3xx', + 'sr.f.s4': '4xx', + 'sr.f.s5': '5xx', + 'sr.search': 'Search', + 'sr.clear': 'Clear', + 'sr.more': 'Load more', + 'sr.csv': 'Export CSV', + 'sr.csv.done': 'CSV saved', + 'sr.c.time': 'Time', + 'sr.c.ip': 'Address', + 'sr.c.cat': 'Category', + 'sr.c.host': 'Host', + 'sr.c.path': 'Request', + 'sr.c.status': 'Status', + 'sr.c.fam': 'Family', + 'sr.statusnote': 'The status filter applies to the rows already loaded.', + 'sr.cap': 'Row limit reached ({n}); narrow the search.', + 'sr.err': 'Search failed.', + 'sr.retry': 'Try again', + 'sr.busy': 'The server is busy; try again in a few seconds.', + 'sr.badq': 'The server rejected these filters.' + }, + 'pt-BR': { + 'sr.title': 'Busca de eventos', + 'sr.lead.one': '{n} evento encontrado', + 'sr.lead.other': '{n} eventos encontrados', + 'sr.lead.more': 'Há mais eventos; carregue mais para continuar.', + 'sr.lead.body': 'Eventos {range}, do mais novo ao mais antigo.', + 'sr.lead.empty': 'Nenhum evento encontrado', + 'sr.lead.emptyBody': 'Nada {range} combina com estes filtros, ou o registro de eventos está desligado.', + 'sr.f.ip': 'IP ou prefixo', + 'sr.f.q': 'Caminho contém', + 'sr.f.fam': 'Família', + 'sr.f.cat': 'Categoria', + 'sr.f.status': 'Status', + 'sr.f.host': 'Servidor', + 'sr.f.period': 'Período', + 'sr.f.all': 'Todos', + 'sr.f.s2': '2xx', + 'sr.f.s3': '3xx', + 'sr.f.s4': '4xx', + 'sr.f.s5': '5xx', + 'sr.search': 'Buscar', + 'sr.clear': 'Limpar', + 'sr.more': 'Carregar mais', + 'sr.csv': 'Exportar CSV', + 'sr.csv.done': 'CSV salvo', + 'sr.c.time': 'Hora', + 'sr.c.ip': 'Endereço', + 'sr.c.cat': 'Categoria', + 'sr.c.host': 'Servidor', + 'sr.c.path': 'Requisição', + 'sr.c.status': 'Status', + 'sr.c.fam': 'Família', + 'sr.statusnote': 'O filtro de status vale para as linhas já carregadas.', + 'sr.cap': 'Limite de linhas atingido ({n}); restrinja a busca.', + 'sr.err': 'A busca falhou.', + 'sr.retry': 'Tentar de novo', + 'sr.busy': 'O servidor está ocupado; tente de novo em alguns segundos.', + 'sr.badq': 'O servidor recusou estes filtros.' + } + }); + function catKey(c) { return CAT_OK[c] ? c : 'ok'; } + function csvCell(v) { + var s = v === null || v === undefined ? '' : String(v); + if (/^[=+\-@\t\r]/.test(s)) s = "'" + s; + return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; + } + function statusOk(f, st) { return !f || String(Math.floor((st || 0) / 100)) === f; } + function iso(sec) { return new Date(sec * 1000).toISOString(); } + + var inst = null; + function Page(root, ctx) { + var self = this, alive = true, seq = 0, rows = [], next = '', total = 0, loaded = false, busy = false, err = '', capped = false; + this.ctx = ctx; + var q0 = (ctx.params && ctx.params.query) || {}; + var F = { ip: q0.ip || '', q: q0.q || '', fam: q0.fam || '', cat: CATS.indexOf(q0.cat) >= 0 ? q0.cat : '', status: '', host: '' }; + var wrap = h('div', 'sr'), leadBox = h('div'), form = h('form', { class: 'sr-form', novalidate: true }), out = h('div'); + root.appendChild(wrap); wrap.appendChild(leadBox); wrap.appendChild(form); wrap.appendChild(out); + var inputs = {}; + function field(key, label, el) { inputs[key] = el; return h('label', 'sr-fld', h('span', { text: label }), el); } + function buildForm() { + form.textContent = ''; inputs = {}; + function text(key, label, ph, max) { var i = h('input', { type: 'text', maxlength: max, autocomplete: 'off', spellcheck: 'false', placeholder: ph || '' }); i.value = F[key]; return field(key, label, i); } + form.appendChild(text('ip', t('sr.f.ip'), '198.51.100.7', 64)); + form.appendChild(text('q', t('sr.f.q'), '/.env', 200)); + form.appendChild(text('fam', t('sr.f.fam'), '', 40)); + var cat = h('select'); cat.appendChild(h('option', { value: '', text: t('sr.f.all') })); + CATS.forEach(function (c) { cat.appendChild(h('option', { value: c, text: t('cat.short.' + c) })); }); cat.value = F.cat; + form.appendChild(field('cat', t('sr.f.cat'), cat)); + var stt = h('select'); [['', t('sr.f.all')], ['2', t('sr.f.s2')], ['3', t('sr.f.s3')], ['4', t('sr.f.s4')], ['5', t('sr.f.s5')]].forEach(function (o) { stt.appendChild(h('option', { value: o[0], text: o[1] })); }); + stt.value = F.status; stt.title = t('sr.statusnote'); + form.appendChild(field('status', t('sr.f.status'), stt)); + form.appendChild(text('host', t('sr.f.host'), '', 64)); + form.appendChild(h('div', 'sr-fld', h('span', { text: t('sr.f.period') }), h('b', { class: 'sr-period', text: U.rangeLabel() }))); + var go = h('button', { type: 'submit', class: 'btn primary', text: t('sr.search') }); + var clr = h('button', { type: 'button', class: 'btn', text: t('sr.clear') }); + clr.addEventListener('click', function () { F = { ip: '', q: '', fam: '', cat: '', status: '', host: '' }; buildForm(); run(); }); + form.appendChild(h('div', 'sr-act', go, clr)); + } + form.addEventListener('submit', function (e) { e.preventDefault(); readForm(); run(); }); + inputs = {}; + function readForm() { Object.keys(F).forEach(function (k) { if (inputs[k]) F[k] = String(inputs[k].value || '').trim(); }); } + function params(cursor) { + var p = Object.assign({ limit: PAGE }, U.rangeParams()); + var host = F.host || (self.ctx.host && self.ctx.host !== 'all' ? self.ctx.host : ''); + if (host) p.host = host; + ['ip', 'q', 'fam', 'cat'].forEach(function (k) { if (F[k]) p[k] = F[k]; }); + if (cursor) p.cursor = cursor; + return p; + } + function run() { rows = []; next = ''; total = 0; loaded = false; err = ''; capped = false; fetchPage(''); } + function fetchPage(cursor) { + var my = ++seq; busy = true; paint(); + U.api('/api/v1/events', params(cursor)).then(function (d) { + if (!alive || my !== seq) return; + busy = false; loaded = true; err = ''; + rows = rows.concat(d.events || []); total = d.total_estimate || rows.length; next = d.next || ''; + if (rows.length >= MAXROWS) { capped = true; next = ''; } + paint(); + }).catch(function (e) { + if (!alive || my !== seq) return; + busy = false; loaded = true; err = e && e.status === 503 ? 'sr.busy' : e && e.status === 400 ? 'sr.badq' : 'sr.err'; paint(); + }); + } + function visible() { return rows.filter(function (r) { return statusOk(F.status, r.status); }); } + function exportCsv() { + var cols = ['t', 'ip', 'cat', 'host', 'domain', 'method', 'path', 'status', 'fam', 'cc']; + var lines = [cols.join(',')]; + visible().forEach(function (r) { lines.push(cols.map(function (c) { return csvCell(c === 't' ? iso(r.t) : r[c]); }).join(',')); }); + var url = URL.createObjectURL(new Blob([lines.join('\r\n') + '\r\n'], { type: 'text/csv;charset=utf-8' })); + var a = document.createElement('a'); a.href = url; a.download = 'urutau-events.csv'; document.body.appendChild(a); a.click(); + setTimeout(function () { URL.revokeObjectURL(url); if (a.parentNode) a.parentNode.removeChild(a); }, 500); + U.toast(t('sr.csv.done')); + } + function paint() { + leadBox.textContent = ''; out.textContent = ''; + var vis = visible(), range = U.rangeLabel({ inline: true }); + if (err) { + var rb = h('button', { type: 'button', class: 'btn', text: t('sr.retry') }); rb.addEventListener('click', run); + out.appendChild(h('div', 'state-error', h('strong', { text: t(err) }), rb)); return; + } + if (!loaded) { out.appendChild(h('div', 'skeleton')); return; } + leadBox.appendChild(vis.length ? U.ui.lead(U.pl('sr.lead', vis.length, { n: nf(vis.length) + (next ? '+' : '') }), t('sr.lead.body', { range: range }) + (next ? ' ' + t('sr.lead.more') : ''), 'ok') + : U.ui.lead(t('sr.lead.empty'), t('sr.lead.emptyBody', { range: range }), 'neutral')); + if (!vis.length) { if (next) out.appendChild(moreBtn()); return; } + var tb = h('tbody'); + vis.forEach(function (r) { + function td(l, k, c) { return h('td', { 'data-label': l, class: c || null }, k); } + var c = catKey(r.cat), st = r.status ? String(r.status) : ''; + tb.appendChild(h('tr', 'row', + td(t('sr.c.time'), h('span', { text: U.fmt.date(r.t) }), 'nw'), + td(t('sr.c.ip'), h('a', { class: 'mono sr-ip', href: '#/ip/' + encodeURIComponent(r.ip || ''), text: r.ip || '' })), + td(t('sr.c.cat'), h('span', { class: 'sr-cat sr-c-' + c, text: t('cat.short.' + c) })), + td(t('sr.c.host'), h('span', { text: r.domain || r.host || '' })), + td(t('sr.c.path'), h('span', { class: 'mono sr-path', text: ((r.method || '') + ' ' + (r.path || r.user || r.jail || '')).trim() })), + td(t('sr.c.status'), h('span', { class: 'num', text: st })), + td(t('sr.c.fam'), h('span', { text: r.fam || '' })))); + }); + var th = h('tr'); ['time', 'ip', 'cat', 'host', 'path', 'status', 'fam'].forEach(function (k) { th.appendChild(h('th', { text: t('sr.c.' + k) })); }); + var csv = h('button', { type: 'button', class: 'btn', text: t('sr.csv') }); csv.addEventListener('click', exportCsv); + out.appendChild(U.ui.panel({ title: t('sr.title'), help: 'cat.scanner', actions: [csv] }, h('table', 'stack sr-table', h('thead', null, th), tb))); + if (capped) out.appendChild(h('p', { class: 'note', text: t('sr.cap', { n: nf(MAXROWS) }) })); + if (next) out.appendChild(moreBtn()); + } + function moreBtn() { var b = h('button', { type: 'button', class: 'btn sr-more', text: t('sr.more') }); b.disabled = busy; b.addEventListener('click', function () { fetchPage(next); }); return b; } + buildForm(); + this.update = function (c) { + var lang = self.ctx.lang; self.ctx = c; + if (lang !== c.lang) { readForm(); buildForm(); } + else { var p = form.querySelector('.sr-period'); if (p) p.textContent = U.rangeLabel(); } + var key = JSON.stringify(U.rangeParams()) + c.host; + if (key !== self.lastKey) { self.lastKey = key; run(); } + }; + this.destroy = function () { alive = false; seq++; root.textContent = ''; }; + this.lastKey = JSON.stringify(U.rangeParams()) + ctx.host; + run(); + } + U.registerPage({ + id: 'search', group: 'investigate', icon: ICON, titleKey: 'sr.title', + mount: function (el, ctx) { if (inst) inst.destroy(); inst = new Page(el, ctx); }, + update: function (ctx) { if (inst) inst.update(ctx); }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); + return true; + } + if (!boot()) document.addEventListener('DOMContentLoaded', boot); +})(); diff --git a/internal/server/web/sessions.css b/internal/server/web/sessions.css new file mode 100644 index 0000000..b773be9 --- /dev/null +++ b/internal/server/web/sessions.css @@ -0,0 +1,34 @@ +/* Urutau - SESSIONS page. Selectors prefixed ss-. */ +.ss { display: flex; flex-direction: column; gap: var(--s-3, 12px); min-width: 0; } +.ss-funnel { display: flex; flex-direction: column; gap: 6px; } +.ss-fr { display: grid; grid-template-columns: 110px minmax(0, 1fr) 64px; gap: 10px; align-items: center; min-height: 36px; padding: 2px 8px; border: 1px solid transparent; border-radius: var(--radius-sm, 7px); background: none; color: var(--ink); font: inherit; cursor: pointer; text-align: left; } +.ss-fr:hover, .ss-fr.on { background: var(--surface-raised); border-color: var(--line-strong); } +.ss-fl { font-size: .875rem; color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; } +.ss-fbar { display: block; height: 14px; border-radius: 7px; background: var(--surface-sunken); overflow: hidden; } +.ss-fbar i { display: block; height: 100%; border-radius: 7px; } +.ss-fn { text-align: right; font-weight: 600; } +.ss-s-recon { background: var(--info); } +.ss-s-probe { background: var(--warn); } +.ss-s-exploit { background: var(--danger); } +.ss-s-access { background: #c026d3; } +.ss-s-banned { background: var(--ink-faint); } +.ss-badge, .ss-step { display: inline-block; padding: 1px 9px; border-radius: 999px; font-size: .75rem; font-weight: 600; color: #04121c; } +.ss-filters { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; } +.ss-filters select { max-width: 100%; min-width: 0; } +.ss-table td { vertical-align: middle; } +.ss-ip { color: var(--accent); text-decoration: none; overflow-wrap: anywhere; } +.ss-rp { min-height: 32px; padding: 2px 10px; font-size: .8125rem; } +.ss-chains { display: flex; flex-direction: column; gap: 8px; } +.ss-chain { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 14px; } +.ss-steps { display: flex; flex-wrap: wrap; gap: 4px; } +@media (max-width: 640px) { .ss-fr { grid-template-columns: 84px minmax(0, 1fr) 48px; gap: 6px; } } + +/* Wide table: stack into cards up to 1023px (the shared rule starts at 767px). */ +@media (max-width: 1023px) { + table.ss-table thead { display: none; } + table.ss-table, table.ss-table tbody, table.ss-table tr, table.ss-table td { display: block; width: 100%; } + table.ss-table tr { border-top: 1px solid var(--line); padding: 8px 0; } + table.ss-table tr:first-child { border-top: 0; } + table.ss-table td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; text-align: right; min-width: 0; overflow-wrap: anywhere; } + table.ss-table td::before { content: attr(data-label); color: var(--ink-muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; text-align: left; flex: none; } +} diff --git a/internal/server/web/sessions.js b/internal/server/web/sessions.js new file mode 100644 index 0000000..d907f53 --- /dev/null +++ b/internal/server/web/sessions.js @@ -0,0 +1,216 @@ +/* Urutau - SESSIONS page: funnel by escalation stage and the sessions that escalated. + Data: /api/v1/sessions/funnel. Log data is hostile: textContent only, classes from whitelists. */ +(function () { + 'use strict'; + var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned']; + var ICON = ''; + var SHOW = 100; + + function boot() { + var U = window.Urutau; + if (!U || !U.registerPage) return false; + var t = U.t, nf = U.fmt.num; + function h(tag, a) { if (typeof a === 'string') a = { class: a }; return U.el.apply(null, [tag, a].concat([].slice.call(arguments, 2))); } + U.registerI18n({ + en: { + 'ss.title': 'Sessions', + 'ss.lead.one': '{n} session; {k} reached exploitation', + 'ss.lead.other': '{n} sessions; {k} reached exploitation', + 'ss.lead.body': 'Sessions {range}, grouped by the furthest stage each one reached.', + 'ss.lead.empty': 'No sessions in this slice', + 'ss.lead.emptyBody': 'Nothing was recorded {range}, or the event registry is off.', + 'ss.sampled': 'Showing the {n} most severe of {m} sessions.', + 'ss.funnel': 'Escalation funnel', + 'ss.funnel.hint': 'Sessions that reached each stage or went beyond it. Click a stage to filter the list.', + 'ss.stage.recon': 'Recon', + 'ss.stage.probe': 'Probe', + 'ss.stage.exploit': 'Exploit', + 'ss.stage.access': 'Access', + 'ss.stage.banned': 'Banned', + 'ss.f.stage': 'Stage', + 'ss.f.host': 'Host', + 'ss.f.fam': 'Family', + 'ss.f.all': 'All', + 'ss.list': 'Sessions', + 'ss.c.ip': 'Address', + 'ss.c.stage': 'Stage', + 'ss.c.start': 'Start', + 'ss.c.dur': 'Duration', + 'ss.c.events': 'Events', + 'ss.c.hosts': 'Hosts', + 'ss.c.fam': 'Family', + 'ss.c.replay': 'Replay', + 'ss.replay': 'Replay', + 'ss.more': 'Show more', + 'ss.none': 'No session matches these filters', + 'ss.esc': 'Escalation chains', + 'ss.esc.hint': 'The steps of the most serious sessions.', + 'ss.err': 'Could not load the sessions.', + 'ss.retry': 'Try again', + 'ss.dur.s': '{n} s', + 'ss.dur.m': '{n} min', + 'ss.dur.h': '{n} h' + }, + 'pt-BR': { + 'ss.title': 'Sessões', + 'ss.lead.one': '{n} sessão; {k} chegaram a exploração', + 'ss.lead.other': '{n} sessões; {k} chegaram a exploração', + 'ss.lead.body': 'Sessões {range}, agrupadas pelo estágio mais avançado de cada uma.', + 'ss.lead.empty': 'Nenhuma sessão neste recorte', + 'ss.lead.emptyBody': 'Nada foi registrado {range}, ou o registro de eventos está desligado.', + 'ss.sampled': 'Mostrando as {n} mais graves de {m} sessões.', + 'ss.funnel': 'Funil de escalada', + 'ss.funnel.hint': 'Sessões que chegaram a cada estágio ou foram além. Clique num estágio para filtrar a lista.', + 'ss.stage.recon': 'Reconhecimento', + 'ss.stage.probe': 'Sondagem', + 'ss.stage.exploit': 'Exploração', + 'ss.stage.access': 'Acesso', + 'ss.stage.banned': 'Banido', + 'ss.f.stage': 'Estágio', + 'ss.f.host': 'Servidor', + 'ss.f.fam': 'Família', + 'ss.f.all': 'Todos', + 'ss.list': 'Sessões', + 'ss.c.ip': 'Endereço', + 'ss.c.stage': 'Estágio', + 'ss.c.start': 'Início', + 'ss.c.dur': 'Duração', + 'ss.c.events': 'Eventos', + 'ss.c.hosts': 'Servidores', + 'ss.c.fam': 'Família', + 'ss.c.replay': 'Reprodução', + 'ss.replay': 'Reproduzir', + 'ss.more': 'Mostrar mais', + 'ss.none': 'Nenhuma sessão combina com estes filtros', + 'ss.esc': 'Cadeias de escalada', + 'ss.esc.hint': 'Os passos das sessões mais graves.', + 'ss.err': 'Não foi possível carregar as sessões.', + 'ss.retry': 'Tentar de novo', + 'ss.dur.s': '{n} s', + 'ss.dur.m': '{n} min', + 'ss.dur.h': '{n} h' + } + }); + function stg(s) { return STAGES.indexOf(s) >= 0 ? s : 'recon'; } + function dur(s) { return s < 90 ? t('ss.dur.s', s) : s < 5400 ? t('ss.dur.m', Math.round(s / 60)) : t('ss.dur.h', Math.round(s / 360) / 10); } + function iso(sec) { return new Date(sec * 1000).toISOString(); } + function topFam(s) { var b = '', n = 0; Object.keys(s.fams || {}).forEach(function (k) { if (s.fams[k] > n) { n = s.fams[k]; b = k; } }); return b; } + function link(ip) { return h('a', { class: 'mono ss-ip', href: '#/ip/' + encodeURIComponent(ip), text: ip }); } + function opt(sel, v, label) { sel.appendChild(h('option', { value: v, text: label })); } + + var inst = null; + function Page(root, ctx) { + var self = this, data = null, seq = 0, alive = true, st = { stage: '', host: '', fam: '', shown: SHOW }; + this.ctx = ctx; + var wrap = h('div', 'ss'); + root.appendChild(wrap); + function load() { + var my = ++seq; + U.api('/api/v1/sessions/funnel', Object.assign({ host: self.ctx.host }, U.rangeParams())).then(function (d) { + if (!alive || my !== seq) return; data = d; paint(); + }).catch(function () { + if (!alive || my !== seq || data) return; + var b = h('button', { type: 'button', class: 'btn', text: t('ss.retry') }); + b.addEventListener('click', load); + wrap.textContent = ''; + wrap.appendChild(h('div', 'state-error', h('strong', { text: t('ss.err') }), b)); + }); + } + function paint() { + wrap.textContent = ''; + var d = data, n = d.sessions_n || 0, k = d.exploited || 0, range = U.rangeLabel({ inline: true }); + wrap.appendChild(n ? U.ui.lead(U.pl('ss.lead', n, { n: nf(n), k: nf(k) }), t('ss.lead.body', { range: range }), k > 0 ? 'danger' : 'ok') + : U.ui.lead(t('ss.lead.empty'), t('ss.lead.emptyBody', { range: range }), 'neutral')); + if (!n) return; + // funnel + var max = Math.max(1, d.reached.recon || 1), fb = h('div', 'ss-funnel'); + STAGES.forEach(function (g) { + var v = d.reached[g] || 0, b = h('button', { type: 'button', class: 'ss-fr' + (st.stage === g ? ' on' : '') }); + b.appendChild(h('span', { class: 'ss-fl', text: t('ss.stage.' + g) })); + var bar = h('span', 'ss-fbar'), i = h('i', 'ss-s-' + g); + i.style.width = Math.max(v ? 2 : 0, v / max * 100) + '%'; + bar.appendChild(i); + b.appendChild(bar); + b.appendChild(h('span', { class: 'ss-fn num', text: nf(v) })); + b.addEventListener('click', function () { st.stage = st.stage === g ? '' : g; st.shown = SHOW; paint(); }); + fb.appendChild(b); + }); + wrap.appendChild(U.ui.panel({ title: t('ss.funnel'), help: 'term.session', hint: t('ss.funnel.hint') }, fb)); + // filters + var hosts = {}, fams = {}; + d.sessions.forEach(function (s) { (s.hosts || []).forEach(function (x) { hosts[x] = 1; }); Object.keys(s.fams || {}).forEach(function (x) { fams[x] = 1; }); }); + var f = h('div', 'ss-filters'); + function sel(label, key, values, labeler) { + var s = h('select', { 'aria-label': label }); + opt(s, '', label + ': ' + t('ss.f.all')); + values.forEach(function (v) { opt(s, v, labeler ? labeler(v) : v); }); + s.value = values.indexOf(st[key]) >= 0 ? st[key] : ''; + s.addEventListener('change', function () { st[key] = s.value; st.shown = SHOW; paint(); }); + f.appendChild(s); + } + sel(t('ss.f.stage'), 'stage', STAGES, function (g) { return t('ss.stage.' + g); }); + sel(t('ss.f.host'), 'host', Object.keys(hosts).sort()); + sel(t('ss.f.fam'), 'fam', Object.keys(fams).sort()); + // list + var rows = d.sessions.filter(function (s) { + return (!st.stage || stg(s.stage) === st.stage) && (!st.host || (s.hosts || []).indexOf(st.host) >= 0) && (!st.fam || (s.fams || {})[st.fam]); + }); + var body = h('div'); + if (d.sampled) body.appendChild(h('p', { class: 'note', text: t('ss.sampled', { n: nf(d.sessions.length), m: nf(n) }) })); + body.appendChild(f); + if (!rows.length) body.appendChild(U.ui.empty(t('ss.none'))); + else { + var tb = h('tbody'); + rows.slice(0, st.shown).forEach(function (s) { + var a = Math.floor(Date.parse(s.start) / 1000), b = Math.floor(Date.parse(s.end) / 1000); + var rp = h('a', { class: 'btn ss-rp', href: '#/replay?ip=' + encodeURIComponent(s.ip) + '&from=' + encodeURIComponent(iso(a - 60)) + '&to=' + encodeURIComponent(iso(b + 60)), text: t('ss.replay') }); + function td(label, kid, cls) { return h('td', { 'data-label': label, class: cls || null }, kid); } + tb.appendChild(h('tr', 'row', + td(t('ss.c.ip'), link(s.ip)), + td(t('ss.c.stage'), h('span', { class: 'ss-badge ss-s-' + stg(s.stage), text: t('ss.stage.' + stg(s.stage)) })), + td(t('ss.c.start'), h('span', { text: U.fmt.date(a) }), 'nw'), + td(t('ss.c.dur'), h('span', { text: dur(s.dur_s || 0) })), + td(t('ss.c.events'), h('span', { class: 'num', text: nf(s.n || 0) })), + td(t('ss.c.hosts'), h('span', { text: (s.hosts || []).slice(0, 3).join(', ') })), + td(t('ss.c.fam'), h('span', { text: topFam(s) })), + td(t('ss.c.replay'), rp))); + }); + var th = h('tr'); + ['ip', 'stage', 'start', 'dur', 'events', 'hosts', 'fam', 'replay'].forEach(function (c) { th.appendChild(h('th', { text: t('ss.c.' + c) })); }); + body.appendChild(h('table', 'stack ss-table', h('thead', null, th), tb)); + if (rows.length > st.shown) { + var more = h('button', { type: 'button', class: 'btn', text: t('ss.more') }); + more.addEventListener('click', function () { st.shown += SHOW; paint(); }); + body.appendChild(more); + } + } + wrap.appendChild(U.ui.panel({ title: t('ss.list') }, body)); + // escalation chains + if (d.escalations && d.escalations.length) { + var ul = h('div', 'ss-chains'); + d.escalations.slice(0, 20).forEach(function (e) { + var steps = h('div', 'ss-steps'); + (e.steps || []).slice(0, 12).forEach(function (p) { + steps.appendChild(h('span', { class: 'ss-step ss-s-' + stg(p.stage), title: String(p.evidence || ''), text: t('ss.stage.' + stg(p.stage)) })); + }); + ul.appendChild(h('div', 'ss-chain', link(e.ip), steps)); + }); + wrap.appendChild(U.ui.panel({ title: t('ss.esc'), help: 'term.stage.exploit', hint: t('ss.esc.hint') }, ul)); + } + } + this.update = function (c) { var lang = self.ctx.lang; self.ctx = c; if (lang !== c.lang && data) paint(); data = null; load(); }; + this.refresh = function () { load(); }; + this.destroy = function () { alive = false; seq++; root.textContent = ''; }; + load(); + } + U.registerPage({ + id: 'sessions', group: 'investigate', icon: ICON, titleKey: 'ss.title', + mount: function (el, ctx) { if (inst) inst.destroy(); inst = new Page(el, ctx); }, + update: function (ctx) { if (inst) inst.update(ctx); }, + refresh: function () { if (inst) inst.refresh(); }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); + return true; + } + if (!boot()) document.addEventListener('DOMContentLoaded', boot); +})(); diff --git a/internal/server/web/slo.css b/internal/server/web/slo.css new file mode 100644 index 0000000..b41df57 --- /dev/null +++ b/internal/server/web/slo.css @@ -0,0 +1,31 @@ +/* Services (SLO) page */ +.hl-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--grid-gap, 16px); } +.hl-card { border: 1px solid var(--line); border-radius: var(--radius); padding: var(--s-4, 14px); background: var(--surface-raised); display: grid; gap: 8px; min-width: 0; border-top: 3px solid var(--ok); } +.hl-card.tone-warn { border-top-color: var(--warn); } +.hl-card.tone-danger { border-top-color: var(--danger); } +.hl-card header { display: grid; gap: 2px; min-width: 0; } +.hl-name { margin: 0; font-size: 1rem; overflow-wrap: anywhere; color: var(--heading); } +.hl-svc { color: var(--ink-faint); font-size: .75rem; overflow-wrap: anywhere; } +.hl-big { font: 600 1.75rem var(--font-display); color: var(--heading); display: flex; align-items: baseline; gap: 8px; } +.hl-big small { font: 500 .75rem var(--font-sans); color: var(--ink-muted); } +.hl-bar { height: 6px; border-radius: 3px; background: var(--surface-sunken); overflow: hidden; } +.hl-bar i { display: block; height: 100%; background: var(--ok); } +.tone-warn .hl-bar i { background: var(--warn); } .tone-danger .hl-bar i { background: var(--danger); } +.hl-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; } +.hl-st { display: grid; min-width: 0; } +.hl-sv { font-weight: 600; font-size: .9375rem; color: var(--ink); } +.hl-sl { font-size: .6875rem; color: var(--ink-muted); } +.hl-spark { height: 28px; color: var(--accent); } +.hl-spark svg { width: 100%; height: 100%; fill: none; stroke: currentColor; stroke-width: 1.5; } +.hl-card footer { font-size: .75rem; color: var(--ink-muted); } +.hl-bands { display: grid; gap: var(--s-4, 14px); } +.hl-bgrp h4 { margin: 0 0 4px; font-size: .875rem; color: var(--heading); overflow-wrap: anywhere; } +.hl-brow { display: grid; grid-template-columns: 34px repeat(3, minmax(0, 1fr)); gap: 8px; align-items: center; margin: 2px 0; } +.hl-bq { font-size: .75rem; color: var(--ink-muted); } +.hl-btrack { position: relative; display: block; height: 16px; background: var(--surface-sunken); border-radius: 3px; overflow: hidden; } +.hl-btrack i { display: block; height: 100%; opacity: .85; } +.hl-btrack b { position: absolute; left: 6px; top: 0; font-weight: 500; font-size: .6875rem; line-height: 16px; color: var(--ink); } +.hl-legend { display: flex; gap: 14px; font-size: .75rem; color: var(--ink-muted); } +.hl-legend i { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 5px; } +.hl-page .panel { min-width: 0; } +@media (max-width: 900px) { .hl-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } } diff --git a/internal/server/web/slo.js b/internal/server/web/slo.js new file mode 100644 index 0000000..2ba1f4b --- /dev/null +++ b/internal/server/web/slo.js @@ -0,0 +1,157 @@ +/* Urutau - page SLO ("Services"): one card per backend service with its SLI, error budget, + Apdex, p95 latency and traffic; latency bands (total, origin, proxy) and a profile radar. + Data: /api/v1/services. Log data is hostile: textContent only. */ +(function () { + 'use strict'; + var U = window.Urutau; + if (!U || !U.registerPage) return; + var el = U.el, t = U.t; + + U.registerI18n({ + en: { + 'hl.sl.title': 'Services', + 'hl.sl.lead': '{n} services, {ok} within their objective', + 'hl.sl.lead.body': 'Objective: 99.5% of legitimate requests without an application or proxy error. {worst} has the least budget left ({budget}) {range}.', + 'hl.sl.lead.body.all': 'Objective: 99.5% of legitimate requests without an application or proxy error, {range}.', + 'hl.sl.lead.empty': 'No services seen yet', + 'hl.sl.lead.empty.body': 'No Traefik requests with service data {range}.', + 'hl.sl.cards': 'Service health', 'hl.sl.cards.hint': 'SLI is the share of legitimate requests answered without an application or proxy error.', + 'hl.sl.sli': 'SLI', 'hl.sl.budget': 'Budget left', 'hl.sl.apdex': 'Apdex', 'hl.sl.p95': 'p95', 'hl.sl.rps': 'peak req/s', 'hl.sl.burn': 'Burn 1h', + 'hl.sl.req': '{n} requests', + 'hl.sl.bands': 'Latency bands', 'hl.sl.bands.hint': 'p50, p95 and p99 of the total time, the backend time and the proxy overhead (ms), for the busiest services.', + 'hl.sl.band.total': 'Total', 'hl.sl.band.origin': 'Backend', 'hl.sl.band.overhead': 'Proxy', + 'hl.sl.radar': 'Profile', 'hl.sl.radar.hint': 'Each axis is scaled to the best service: availability, Apdex, speed (p95), retries and traffic.', + 'hl.sl.ax.avail': 'Availability', 'hl.sl.ax.apdex': 'Apdex', 'hl.sl.ax.speed': 'Speed', 'hl.sl.ax.retry': 'No retries', 'hl.sl.ax.traffic': 'Traffic', + 'hl.sl.err': 'Could not load the services.', 'hl.sl.retry': 'Try again', 'hl.sl.empty': 'Nothing to show for this range.' + }, + 'pt-BR': { + 'hl.sl.title': 'Serviços', + 'hl.sl.lead': '{n} serviços, {ok} dentro do objetivo', + 'hl.sl.lead.body': 'Objetivo: 99,5% das requisições legítimas sem erro de aplicação ou de proxy. {worst} tem o menor orçamento restante ({budget}) {range}.', + 'hl.sl.lead.body.all': 'Objetivo: 99,5% das requisições legítimas sem erro de aplicação ou de proxy, {range}.', + 'hl.sl.lead.empty': 'Nenhum serviço visto ainda', + 'hl.sl.lead.empty.body': 'Nenhuma requisição do Traefik com dados de serviço {range}.', + 'hl.sl.cards': 'Saúde dos serviços', 'hl.sl.cards.hint': 'O SLI é a parcela das requisições legítimas respondidas sem erro de aplicação ou de proxy.', + 'hl.sl.sli': 'SLI', 'hl.sl.budget': 'Orçamento restante', 'hl.sl.apdex': 'Apdex', 'hl.sl.p95': 'p95', 'hl.sl.rps': 'pico req/s', 'hl.sl.burn': 'Consumo 1h', + 'hl.sl.req': '{n} requisições', + 'hl.sl.bands': 'Faixas de latência', 'hl.sl.bands.hint': 'p50, p95 e p99 do tempo total, do tempo no backend e da sobrecarga do proxy (ms), nos serviços mais ocupados.', + 'hl.sl.band.total': 'Total', 'hl.sl.band.origin': 'Backend', 'hl.sl.band.overhead': 'Proxy', + 'hl.sl.radar': 'Perfil', 'hl.sl.radar.hint': 'Cada eixo é relativo ao melhor serviço: disponibilidade, Apdex, rapidez (p95), retentativas e tráfego.', + 'hl.sl.ax.avail': 'Disponibilidade', 'hl.sl.ax.apdex': 'Apdex', 'hl.sl.ax.speed': 'Rapidez', 'hl.sl.ax.retry': 'Sem retentativas', 'hl.sl.ax.traffic': 'Tráfego', + 'hl.sl.err': 'Não foi possível carregar os serviços.', 'hl.sl.retry': 'Tentar de novo', 'hl.sl.empty': 'Nada para mostrar neste período.' + } + }); + + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + function ms(v) { return v >= 1000 ? (v / 1000).toFixed(v >= 10000 ? 0 : 1) + ' s' : (v >= 10 ? Math.round(v) : v.toFixed(1)) + ' ms'; } + function pct1(v) { return (v * 100).toFixed(v >= 0.9995 ? 2 : 1) + '%'; } + function tone(s) { return s.budget_left <= 0.1 || s.burn_1h >= 6 ? 'danger' : s.budget_left <= 0.5 || s.burn_1h >= 2 ? 'warn' : 'ok'; } + + function card(s) { + var tn = tone(s); + var spark = U.charts && U.charts.sparkline && s.spark && s.spark.length > 1 ? U.charts.sparkline(s.spark) : null; + var stat = function (label, value, key) { + var l = el('span', { class: 'hl-sl' }, label); + if (key && U.help && U.glossary && U.glossary.has(key)) U.help(l, key); + return el('div', { class: 'hl-st' }, el('span', { class: 'hl-sv num' }, value), l); + }; + return el('article', { class: 'hl-card tone-' + tn }, + el('header', null, el('h3', { class: 'hl-name' }, s.alias), el('span', { class: 'hl-svc mono' }, s.svc)), + el('div', { class: 'hl-big num' }, pct1(s.sli), el('small', null, t('hl.sl.sli'))), + el('div', { class: 'hl-bar', role: 'img', 'aria-label': t('hl.sl.budget') + ' ' + U.fmt.pct(s.budget_left) }, el('i', { style: { width: Math.round(s.budget_left * 100) + '%' } })), + el('div', { class: 'hl-stats' }, stat(t('hl.sl.budget'), U.fmt.pct(s.budget_left), 'term.error_budget'), stat(t('hl.sl.apdex'), s.apdex.toFixed(2), 'term.apdex'), stat(t('hl.sl.p95'), ms(s.p95.total)), stat(t('hl.sl.rps'), s.rps_peak.toFixed(2))), + spark ? el('div', { class: 'hl-spark' }, spark) : null, + el('footer', null, t('hl.sl.req', { n: U.fmt.num(s.req) }))); + } + + var inst = null; + function create(root, ctx) { + var seq = 0, alive = true, data = null, c = ctx; + var grid = el('div', { class: 'grid-12 hl-page' }); + var lead = el('div', { class: 'span-12' }); + var pc = U.ui.panel({ title: t('hl.sl.cards'), hint: t('hl.sl.cards.hint'), loading: true, cls: 'span-12' }); + var pb = U.ui.panel({ title: t('hl.sl.bands'), hint: t('hl.sl.bands.hint'), variant: 'chart', loading: true, cls: 'span-8' }); + var pr = U.ui.panel({ title: t('hl.sl.radar'), hint: t('hl.sl.radar.hint'), variant: 'chart', loading: true, cls: 'span-4' }); + [lead, pc, pb, pr].forEach(function (n) { grid.appendChild(n); }); + root.appendChild(grid); + + function bands(list) { + var box = el('div', { class: 'hl-bands' }); + var mx = 0; list.slice(0, 8).forEach(function (s) { ['p50', 'p95', 'p99'].forEach(function (q) { ['total', 'origin', 'overhead'].forEach(function (k) { if (s[q][k] > mx) mx = s[q][k]; }); }); }); + list.slice(0, 8).forEach(function (s) { + var g = el('div', { class: 'hl-bgrp' }, el('h4', null, s.alias)); + ['p50', 'p95', 'p99'].forEach(function (q) { + var v = s[q]; + var line = el('div', { class: 'hl-brow' }, el('span', { class: 'hl-bq' }, q)); + [['total', 'hl.sl.band.total', '--viz-1'], ['origin', 'hl.sl.band.origin', '--viz-3'], ['overhead', 'hl.sl.band.overhead', '--viz-5']].forEach(function (p) { + var w = mx ? Math.max(v[p[0]] > 0 ? 1.5 : 0, v[p[0]] / mx * 100) : 0; + var i = el('i', { style: { width: w + '%', background: 'var(' + p[2] + ')' } }); + i.title = t(p[1]) + ' ' + ms(v[p[0]]); + line.appendChild(el('span', { class: 'hl-btrack' }, i, el('b', { class: 'num' }, ms(v[p[0]])))); + }); + g.appendChild(line); + }); + box.appendChild(g); + }); + var lg = el('div', { class: 'hl-legend' }); + [['hl.sl.band.total', '--viz-1'], ['hl.sl.band.origin', '--viz-3'], ['hl.sl.band.overhead', '--viz-5']].forEach(function (p) { + lg.appendChild(el('span', null, el('i', { style: { background: 'var(' + p[1] + ')' } }), t(p[0]))); + }); + box.appendChild(lg); + return box; + } + function radar(list) { + var top = list.slice(0, 5); + if (!(U.charts && U.charts.radar) || top.length < 1) return U.ui.empty(t('hl.sl.empty')); + var maxReq = 0, minP = Infinity; + top.forEach(function (s) { if (s.req > maxReq) maxReq = s.req; if (s.p95.total > 0 && s.p95.total < minP) minP = s.p95.total; }); + var axes = [{ key: 'avail', label: t('hl.sl.ax.avail') }, { key: 'apdex', label: t('hl.sl.ax.apdex') }, { key: 'speed', label: t('hl.sl.ax.speed') }, { key: 'retry', label: t('hl.sl.ax.retry') }, { key: 'traffic', label: t('hl.sl.ax.traffic') }]; + var series = top.map(function (s) { + return { label: s.alias, values: [s.sli * 100, s.apdex * 100, s.p95.total > 0 ? Math.min(100, minP / s.p95.total * 100) : 100, Math.max(0, 100 - s.retries_pct * 10), maxReq ? s.req / maxReq * 100 : 0] }; + }); + return U.charts.radar(axes, series, { max: 100, title: t('hl.sl.radar'), format: function (v) { return Math.round(v) + ''; } }); + } + function paint() { + clear(lead); [pc, pb, pr].forEach(function (p) { clear(p.body); }); + if (!data) return; + var range = U.rangeLabel({ inline: true }); + if (!data.length) { + lead.appendChild(U.ui.lead(t('hl.sl.lead.empty'), t('hl.sl.lead.empty.body', { range: range }), 'neutral')); + [pc, pb, pr].forEach(function (p) { p.body.appendChild(U.ui.empty(t('hl.sl.empty'))); }); + return; + } + var ok = data.filter(function (s) { return s.budget_left > 0; }).length; + var worst = data.slice().sort(function (a, b) { return a.budget_left - b.budget_left; })[0]; + lead.appendChild(U.ui.lead(t('hl.sl.lead', { n: data.length, ok: ok }), + worst.budget_left >= 1 ? t('hl.sl.lead.body.all', { range: range }) : t('hl.sl.lead.body', { worst: worst.alias, budget: U.fmt.pct(worst.budget_left), range: range }), + ok === data.length ? 'ok' : 'warn')); + var cards = el('div', { class: 'hl-cards' }); + data.forEach(function (s) { cards.appendChild(card(s)); }); + pc.body.appendChild(cards); + pb.body.appendChild(bands(data)); + pr.body.appendChild(radar(data)); + } + function load() { + var my = ++seq; + var p = Object.assign({}, U.rangeParams()); + if (c.domain && c.domain !== 'all') p.host = c.domain; + U.api('/api/v1/services', p).then(function (r) { if (alive && my === seq) { data = r || []; paint(); } }, function () { + if (!alive || my !== seq || data) return; + clear(lead); + var b = el('button', { type: 'button', class: 'btn' }, t('hl.sl.retry')); + b.addEventListener('click', load); + lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('hl.sl.err')), b)); + }); + } + load(); + return { update: function (cx) { c = cx; load(); }, destroy: function () { alive = false; seq++; clear(root); } }; + } + + U.registerPage({ + id: 'slo', group: 'monitor', titleKey: 'hl.sl.title', + icon: '', + mount: function (node, ctx) { if (inst) inst.destroy(); inst = create(node, ctx || {}); }, + update: function (ctx) { if (inst) inst.update(ctx); }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); +})(); diff --git a/internal/server/web/style.css b/internal/server/web/style.css index 154e6d3..ff40f17 100644 --- a/internal/server/web/style.css +++ b/internal/server/web/style.css @@ -585,3 +585,63 @@ input[type="datetime-local"] { background: var(--surface-raised); border: 1px so .iv-cuts { font-size: .75rem; } .mini-days span { white-space: nowrap; } .mini-days { font-size: 10px; } + +/* ================================================================ charts and help */ +.sr-only { position: absolute !important; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; padding: 0; margin: -1px; } +.vz { min-width: 0; } +.vz-donut-wrap { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-3) var(--s-4); } +.vz-donut-svg { flex: 0 1 190px; min-width: 140px; } +.vz-donut { width: 100%; height: auto; display: block; } +.vz-seg { transition: opacity .15s, stroke-width .15s; cursor: pointer; outline: none; } +.vz-seg:hover, .vz-seg:focus { stroke-width: 31; } +.vz-seg:focus-visible { stroke: var(--ink) !important; } +.vz-seg.dim { opacity: .35; } +.vz-c-v { font: 800 26px var(--font-display); fill: var(--heading); font-variant-numeric: tabular-nums; } +.vz-c-l { font: 500 12px var(--font-sans); fill: var(--ink-muted); } +.vz-gauge-wrap .vz-c-l { text-align: center; } +.vz-legend { list-style: none; padding: 0; display: grid; gap: 4px; flex: 1 1 140px; min-width: 0; } +.vz-legend li { display: flex; align-items: center; gap: 8px; min-width: 0; font-size: .875rem; } +.vz-legend .vz-l { flex: 1; min-width: 0; overflow-wrap: anywhere; } +.vz-legend .vz-v { color: var(--ink-muted); white-space: nowrap; } +.vz-area + .legend, .vz > .vz-legend { margin-top: var(--s-2); display: flex; flex-wrap: wrap; gap: 4px 14px; } +.vz-area-s { stroke: var(--surface-panel); stroke-width: 1; fill-opacity: .9; } +.vz-guide { stroke: var(--ink-muted); stroke-width: 1; stroke-dasharray: 3 3; pointer-events: none; } +.vz-radar-wrap svg { width: 100%; height: auto; display: block; } +.vz-ring { fill: none; stroke: var(--line); stroke-width: 1; } +.vz-rs { fill-opacity: .18; stroke-width: 2; } +.vz-dot { stroke: var(--surface-panel); stroke-width: 1; outline: none; } +.vz-dot:focus-visible { stroke: var(--ink); stroke-width: 2; } +.vz-axl { font: 500 11px var(--font-sans); fill: var(--ink-muted); } +.vz-bars { display: grid; gap: 8px; } +.vz-row { display: grid; grid-template-columns: minmax(70px, 38%) minmax(0, 1fr) auto; gap: 8px; align-items: center; font-size: .875rem; } +.vz-row .vz-l { overflow-wrap: anywhere; min-width: 0; } +.vz-row .vz-v { color: var(--ink-muted); } +.vz-track { display: flex; height: 12px; background: var(--surface-raised); border-radius: 6px; overflow: hidden; } +.vz-track i { display: block; height: 100%; } +.vz-cols { display: flex; align-items: flex-end; gap: 8px; height: 180px; } +.vz-cols .vz-row { display: flex; flex-direction: column-reverse; align-items: center; height: 100%; flex: 1; min-width: 0; } +.vz-cols .vz-track { flex-direction: column-reverse; width: 100%; height: 100%; } +.vz-cols .vz-track i { width: 100%; } +.vz-heat svg { width: 100%; height: auto; display: block; } +.vz-cell { fill: var(--surface-raised); } +.vz-cell.s1 { fill: var(--seq-1); } .vz-cell.s2 { fill: var(--seq-2); } .vz-cell.s3 { fill: var(--seq-3); } .vz-cell.s4 { fill: var(--seq-4); } .vz-cell.s5 { fill: var(--seq-5); } +.vz-cell:focus-visible { stroke: var(--ink); stroke-width: 2; outline: none; } +.vz-gauge { width: 100%; max-width: 220px; height: auto; display: block; margin: 0 auto; } +.vz-g-bg, .vz-g-fg { fill: none; stroke-width: 14; stroke-linecap: round; } +.vz-g-bg { stroke: var(--surface-raised); } +.vz-g-fg { stroke: var(--ok); } .vz-g-fg.tone-warn { stroke: var(--warn); } .vz-g-fg.tone-danger { stroke: var(--danger); } .vz-g-fg.tone-info { stroke: var(--info); } +.card-chart .vz-area { min-height: var(--h-chart); } + +.help-btn { display: inline-flex; align-items: center; justify-content: center; width: 18px; height: 18px; margin-left: 6px; padding: 0; border-radius: 50%; border: 1px solid var(--line-strong); background: var(--surface-raised); color: var(--ink-muted); font: 700 11px/1 var(--font-sans); cursor: help; vertical-align: middle; text-transform: none; letter-spacing: 0; flex: none; } +.help-btn:hover, .help-btn:focus-visible { color: var(--on-accent); background: var(--accent); border-color: transparent; } +.cm-label, .panel-h h2, .legend { } +.cm-label { display: block; } +.panel-h h2 { display: inline-flex; align-items: center; } +.help-pop { position: fixed; z-index: 95; width: min(320px, calc(100vw - 16px)); background: var(--surface-overlay); color: var(--ink); border: 1px solid var(--line-strong); border-radius: var(--radius-sm); box-shadow: var(--shadow); padding: 10px 12px; font-size: .875rem; line-height: 1.45; text-transform: none; letter-spacing: 0; font-weight: 400; } +.help-pop[hidden] { display: none; } +.help-pop .help-do { margin-top: 6px; color: var(--ink-muted); } +.nav-group { margin: 10px 0 2px; padding: 0 var(--s-3); color: var(--rail-ink-muted); font: 600 11px var(--font-sans); text-transform: uppercase; letter-spacing: .1em; } +.nav-group:first-child { margin-top: 0; } +.more-sheet .nav-group { color: var(--ink-muted); padding: 6px var(--s-3) 0; } +@media (max-width: 1199px) { .nav-group { font-size: 0; height: 1px; background: var(--rail-line); margin: 8px 6px; padding: 0; } } +@media (max-width: 767px) { .more-sheet .nav-group { font-size: 11px; height: auto; background: none; margin: 6px 0 0; padding: 6px var(--s-3) 0; } } diff --git a/internal/server/web/survival.css b/internal/server/web/survival.css new file mode 100644 index 0000000..f2b82f9 --- /dev/null +++ b/internal/server/web/survival.css @@ -0,0 +1,26 @@ +/* Survival page (shared .an-* rules are repeated so each page file stands alone) */ +.an-boxes { display: grid; gap: var(--s-3); } +.an-boxrow { display: grid; grid-template-columns: minmax(70px, 28%) minmax(0, 1fr) auto; align-items: center; gap: var(--s-3); min-width: 0; } +.an-boxrow .an-fam { overflow-wrap: anywhere; font-size: .8125rem; } +.an-boxrow .an-val { font-variant-numeric: tabular-nums; color: var(--ink-muted); font-size: .8125rem; white-space: nowrap; } +.an-track { position: relative; height: 18px; border-radius: 4px; background: var(--surface-sunken); border: 1px solid var(--line); } +.an-box { position: absolute; top: 2px; bottom: 2px; border-radius: 3px; background: color-mix(in srgb, var(--accent) 45%, transparent); border: 1px solid var(--accent); } +.an-med { position: absolute; top: -2px; bottom: -2px; width: 3px; margin-left: -1px; border-radius: 2px; background: var(--heading); } +.an-rec { grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 0 var(--s-6); } +.an-chart { min-width: 0; } +.an-svg { display: block; width: 100%; height: auto; max-width: 100%; overflow: visible; } +.an-svg .an-grid { stroke: var(--line); stroke-width: 1; } +.an-svg .an-guide { stroke: var(--warn); stroke-width: 1; stroke-dasharray: 4 4; } +.an-svg .an-line { fill: none; stroke: var(--accent); stroke-width: 2.25; stroke-linejoin: round; stroke-linecap: round; } +.an-svg .an-fill { fill: var(--accent); fill-opacity: .14; stroke: none; } +.an-svg .an-dot { fill: var(--accent); stroke: var(--surface-panel); stroke-width: 1.5; } +.an-svg .an-tick { fill: var(--ink-muted); font-size: 11px; } +.an-svg .an-strong { fill: var(--ink); font-weight: 600; } +.an-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 2px; } +.an-list li { display: flex; justify-content: space-between; align-items: baseline; gap: var(--s-3); padding: 4px 0; border-bottom: 1px solid var(--line); min-width: 0; } +.an-list li:last-child { border-bottom: 0; } +.an-list .an-k, .an-list a { overflow-wrap: anywhere; min-width: 0; } +.an-list .an-n { font-variant-numeric: tabular-nums; color: var(--ink-muted); white-space: nowrap; } +.an-list .an-bad { color: var(--danger); } +.an-list .an-good { color: var(--ok); } +.an-rec li { margin-right: var(--s-5); } diff --git a/internal/server/web/survival.js b/internal/server/web/survival.js new file mode 100644 index 0000000..c173007 --- /dev/null +++ b/internal/server/web/survival.js @@ -0,0 +1,218 @@ +/* Urutau - SOBREVIVENCIA page: how long until the ban, and who comes back? + Kaplan-Meier curve (attackers never banned are censored), time-to-ban range + per family (p25-p75 bar with the median) and the list of repeat offenders. + Data: /api/v1/survival. Log data is hostile: textContent only. */ +(function () { + 'use strict'; + var U = window.Urutau; + if (!U || !U.registerPage) return; + var el = U.el, t = U.t; + + U.registerI18n({ + en: { + 'an.sv.title': 'Survival', + 'an.sv.lead': 'Half of the attack episodes end in a ban within {dur}', + 'an.sv.lead.unknown': 'Fewer than half of the attack episodes ended in a ban', + 'an.sv.lead.empty': 'No attackers to follow', + 'an.sv.lead.body': '{banned} of {n} attackers banned {range}; {rec} of the banned came back and were banned again. 90% banned within {p90}.', + 'an.sv.lead.body.nop90': '{banned} of {n} attackers banned {range}; {rec} of the banned came back and were banned again.', + 'an.sv.lead.empty.body': 'Nothing was recorded {range}.', + 'an.sv.km': 'Share still unbanned over time', + 'an.sv.km.hint': 'Kaplan-Meier curve per attack episode, from its first malicious event. Episodes that ended without a ban only count as time observed.', + 'an.sv.x': 'Time since the start of the episode', + 'an.sv.y': 'Not banned yet', + 'an.sv.median': 'median {dur}', + 'an.sv.fam': 'Time to ban by family', + 'an.sv.fam.hint': 'The bar spans the 25th to the 75th percentile; the mark is the median.', + 'an.sv.fam.row': '{fam}: median {p50}, from {p25} to {p75} ({n} banned)', + 'an.sv.rec': 'Repeat offenders', + 'an.sv.rec.hint': 'Addresses banned more than once. Open one to see its history.', + 'an.sv.rec.none': 'Nobody was banned twice in this slice.', + 'an.sv.rec.row': '{bans} bans, last {ago}', + 'an.sv.recpct': 'Recidivism', + 'an.sv.none': 'No banned attackers with a known family in this slice.', + 'an.sv.dur.s': '{n} s', + 'an.sv.dur.m': '{n} min', + 'an.sv.dur.h': '{n} h', + 'an.sv.dur.d': '{n} d', + 'an.sv.off': 'The event registry is off', + 'an.sv.off.d': 'This analysis reads the event registry, which is not enabled on this instance.', + 'an.sv.err': 'Could not load this analysis.', + 'an.sv.retry': 'Try again' + }, + 'pt-BR': { + 'an.sv.title': 'Sobrevivência', + 'an.sv.lead': 'Metade dos episódios de ataque termina em ban em até {dur}', + 'an.sv.lead.unknown': 'Menos da metade dos episódios de ataque terminou em ban', + 'an.sv.lead.empty': 'Nenhum atacante para acompanhar', + 'an.sv.lead.body': '{banned} de {n} atacantes banidos {range}; {rec} dos banidos voltaram e foram banidos de novo. 90% banidos em até {p90}.', + 'an.sv.lead.body.nop90': '{banned} de {n} atacantes banidos {range}; {rec} dos banidos voltaram e foram banidos de novo.', + 'an.sv.lead.empty.body': 'Nada foi registrado {range}.', + 'an.sv.km': 'Parcela ainda sem ban ao longo do tempo', + 'an.sv.km.hint': 'Curva de Kaplan-Meier por episódio de ataque, desde o primeiro evento malicioso. Episódios que terminaram sem ban contam só como tempo observado.', + 'an.sv.x': 'Tempo desde o início do episódio', + 'an.sv.y': 'Ainda não banido', + 'an.sv.median': 'mediana {dur}', + 'an.sv.fam': 'Tempo até o ban por família', + 'an.sv.fam.hint': 'A barra vai do percentil 25 ao 75; a marca é a mediana.', + 'an.sv.fam.row': '{fam}: mediana {p50}, de {p25} a {p75} ({n} banidos)', + 'an.sv.rec': 'Reincidentes', + 'an.sv.rec.hint': 'Endereços banidos mais de uma vez. Abra um para ver o histórico.', + 'an.sv.rec.none': 'Ninguém foi banido duas vezes neste recorte.', + 'an.sv.rec.row': '{bans} bans, último {ago}', + 'an.sv.recpct': 'Reincidência', + 'an.sv.none': 'Nenhum atacante banido com família conhecida neste recorte.', + 'an.sv.dur.s': '{n} s', + 'an.sv.dur.m': '{n} min', + 'an.sv.dur.h': '{n} h', + 'an.sv.dur.d': '{n} d', + 'an.sv.off': 'O registro de eventos está desligado', + 'an.sv.off.d': 'Esta análise lê o registro de eventos, que não está ativo nesta instância.', + 'an.sv.err': 'Não foi possível carregar esta análise.', + 'an.sv.retry': 'Tentar de novo' + } + }); + + function tip(p, key) { var h2 = p.querySelector('.panel-h h2'); if (h2 && U.help) U.help(h2, key); return p; } + function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } + function one(x) { return U.fmt.num(Math.round(x * 10) / 10); } + function dur(sec) { + if (sec < 90) return t('an.sv.dur.s', { n: Math.round(sec) }); + if (sec < 5400) return t('an.sv.dur.m', { n: Math.round(sec / 60) }); + if (sec < 129600) return t('an.sv.dur.h', { n: one(sec / 3600) }); + return t('an.sv.dur.d', { n: one(sec / 86400) }); + } + + // step curve of the survival function; x linear in time + function km(points, median) { + var W = 640, H = 280, L = 44, R = 14, T = 12, B = 34, w = W - L - R, h = H - T - B; + var tmax = points.length ? points[points.length - 1].t_s : 0; + if (tmax <= 0) tmax = 1; + var svg = el('svg', { viewBox: '0 0 ' + W + ' ' + H, class: 'an-svg', role: 'img', 'aria-label': t('an.sv.km'), preserveAspectRatio: 'xMidYMid meet' }); + function X(v) { return L + v / tmax * w; } + function Y(v) { return T + (1 - v) * h; } + [0, 0.25, 0.5, 0.75, 1].forEach(function (v) { + svg.appendChild(el('line', { class: 'an-grid', x1: L, x2: W - R, y1: Y(v), y2: Y(v) })); + svg.appendChild(el('text', { class: 'an-tick', x: L - 6, y: Y(v) + 4, 'text-anchor': 'end' }, Math.round(v * 100) + '%')); + }); + [0, 0.5, 1].forEach(function (f) { + svg.appendChild(el('text', { class: 'an-tick', x: X(f * tmax), y: H - 16, 'text-anchor': f === 0 ? 'start' : f === 1 ? 'end' : 'middle' }, dur(f * tmax))); + }); + svg.appendChild(el('text', { class: 'an-tick', x: L + w / 2, y: H - 2, 'text-anchor': 'middle' }, t('an.sv.x'))); + var d = ''; + points.forEach(function (p, i) { + d += (i ? 'H' + X(p.t_s).toFixed(1) + 'V' : 'M' + X(p.t_s).toFixed(1) + ',') + Y(p.survival).toFixed(1); + if (!i) d += ''; + }); + if (points.length) { + svg.appendChild(el('path', { class: 'an-fill', d: d + 'V' + Y(0) + 'H' + X(0) + 'Z' })); + svg.appendChild(el('path', { class: 'an-line', d: d })); + } + if (typeof median === 'number') { + svg.appendChild(el('line', { class: 'an-guide', x1: X(median), x2: X(median), y1: T, y2: T + h })); + svg.appendChild(el('line', { class: 'an-guide', x1: L, x2: X(median), y1: Y(0.5), y2: Y(0.5) })); + svg.appendChild(el('text', { class: 'an-tick an-strong', x: Math.min(X(median) + 6, W - R), y: T + 12, 'text-anchor': X(median) > W - 120 ? 'end' : 'start' }, t('an.sv.median', { dur: dur(median) }))); + } + points.forEach(function (p) { + if (points.length > 60) return; + svg.appendChild(el('circle', { class: 'an-dot', cx: X(p.t_s), cy: Y(p.survival), r: 3 }, el('title', null, dur(p.t_s) + ': ' + Math.round(p.survival * 1000) / 10 + '%'))); + }); + return el('div', { class: 'an-chart' }, svg); + } + + function boxes(rows) { + if (!rows.length) return U.ui.empty(t('an.sv.none')); + var max = 1; + rows.forEach(function (r) { if (r.p75 > max) max = r.p75; }); + max *= 1.08; + var box = el('div', { class: 'an-boxes' }); + rows.forEach(function (r) { + var left = r.p25 / max * 100, width = Math.max((r.p75 - r.p25) / max * 100, 1.2), med = r.p50 / max * 100; + var track = el('div', { class: 'an-track' }, + el('div', { class: 'an-box', style: { left: left + '%', width: width + '%' } }), + el('div', { class: 'an-med', style: { left: med + '%' } })); + var row = el('div', { class: 'an-boxrow', role: 'img', 'aria-label': t('an.sv.fam.row', { fam: r.fam, p50: dur(r.p50), p25: dur(r.p25), p75: dur(r.p75), n: r.n }) }, + el('span', { class: 'an-fam mono' }, r.fam), track, el('span', { class: 'an-val' }, dur(r.p50))); + row.setAttribute('title', t('an.sv.fam.row', { fam: r.fam, p50: dur(r.p50), p25: dur(r.p25), p75: dur(r.p75), n: r.n })); + box.appendChild(row); + }); + return box; + } + + var inst = null; + function create(root, ctx) { + var seq = 0, alive = true, data = null, c = ctx; + var grid = el('div', { class: 'grid-12 an-page' }); + var lead = el('div', { class: 'span-12' }); + var curve = U.ui.panel({ title: t('an.sv.km'), hint: t('an.sv.km.hint'), variant: 'chart', loading: true }); + tip(curve, 'term.kaplan_meier'); + var fam = U.ui.panel({ title: t('an.sv.fam'), hint: t('an.sv.fam.hint'), loading: true }); + tip(fam, 'metric.mttb'); + var rec = U.ui.panel({ title: t('an.sv.rec'), hint: t('an.sv.rec.hint'), loading: true }); + tip(rec, 'term.recidivism'); + grid.appendChild(lead); + grid.appendChild(curve); curve.classList.add('span-8'); + grid.appendChild(fam); fam.classList.add('span-4'); + grid.appendChild(rec); rec.classList.add('span-12'); + root.appendChild(grid); + + function paint() { + clear(lead); [curve, fam, rec].forEach(function (p) { clear(p.body); }); + if (!data) return; + var d = data, range = U.rangeLabel({ inline: true }); + if (!d.enabled) { lead.appendChild(U.ui.empty(t('an.sv.off'), t('an.sv.off.d'))); return; } + if (!d.attackers) { + lead.appendChild(U.ui.lead(t('an.sv.lead.empty'), t('an.sv.lead.empty.body', { range: range }), 'neutral')); + curve.body.appendChild(U.ui.empty(t('charts.empty'))); + fam.body.appendChild(U.ui.empty(t('charts.empty'))); + rec.body.appendChild(U.ui.empty(t('charts.empty'))); + return; + } + var med = d.median_to_ban_s, p90 = d.p90_to_ban_s, recpct = U.fmt.pct(d.recidivism_pct / 100); + var vars = { banned: U.fmt.num(d.banned), n: U.fmt.num(d.attackers), range: range, rec: recpct, p90: typeof p90 === 'number' ? dur(p90) : '' }; + var title = typeof med === 'number' ? t('an.sv.lead', { dur: dur(med) }) : t('an.sv.lead.unknown'); + lead.appendChild(U.ui.lead(title, t(typeof p90 === 'number' ? 'an.sv.lead.body' : 'an.sv.lead.body.nop90', vars), typeof med === 'number' && med <= 3600 ? 'ok' : 'danger')); + curve.body.appendChild(km(d.km || [], typeof med === 'number' ? med : null)); + fam.body.appendChild(boxes(d.by_family || [])); + if (!d.recidivists || !d.recidivists.length) { rec.body.appendChild(U.ui.empty(t('an.sv.rec.none'))); return; } + var ul = el('ul', { class: 'an-list an-rec' }); + d.recidivists.forEach(function (r) { + var a = el('a', { class: 'mono', href: '#/ip/' + encodeURIComponent(r.ip) }, r.ip); + ul.appendChild(el('li', null, a, el('span', { class: 'an-n' }, t('an.sv.rec.row', { bans: r.bans, ago: U.fmt.ago(r.last) })))); + }); + rec.body.appendChild(ul); + } + function load() { + var my = ++seq; + var p = Object.assign({}, U.rangeParams()); + if (c.host && c.host !== 'all') p.host = c.host; + U.api('/api/v1/survival', p).then(function (r) { + if (!alive || my !== seq) return; + data = r; paint(); + }, function () { + if (!alive || my !== seq || data) return; + clear(lead); + var b = el('button', { type: 'button', class: 'btn' }, t('an.sv.retry')); + b.addEventListener('click', load); + lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('an.sv.err')), b)); + }); + } + load(); + return { + root: root, lang: ctx.lang, + update: function (cx) { c = cx; load(); }, + destroy: function () { alive = false; seq++; clear(root); } + }; + } + + U.registerPage({ + id: 'survival', group: 'analyze', titleKey: 'an.sv.title', + icon: '', + mount: function (el, ctx) { if (inst) inst.destroy(); inst = create(el, ctx || {}); }, + update: function (ctx) { + ctx = ctx || {}; + if (inst && ctx.lang !== inst.lang) { var r = inst.root; inst.destroy(); inst = create(r, ctx); } else if (inst) inst.update(ctx); + }, + unmount: function () { if (inst) { inst.destroy(); inst = null; } } + }); +})(); diff --git a/internal/store/analytics.go b/internal/store/analytics.go new file mode 100644 index 0000000..bee0e18 --- /dev/null +++ b/internal/store/analytics.go @@ -0,0 +1,589 @@ +package store + +import ( + "math" + "sort" + "strconv" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" +) + +// Temporal analytics (evolution, concentration, survival), all derived from +// the event registry in one bounded scan (study budget and deadline, 30 s cache). + +const ( + anMaxKeys = 200000 // distinct keys held by a concentration scan + anMaxItems = 200 + anMaxIPs = 300000 // distinct addresses held by a survival scan + anKMPoints = 200 + anMaxRecid = 50 + anMaxFamilies = 12 + anMaxDays = 62 +) + +// AnDay is one UTC day of the evolution chart. +type AnDay struct { + D string `json:"d"` + Total uint32 `json:"total"` + ByCat map[string]uint32 `json:"by_cat"` + ByFam map[string]uint32 `json:"by_fam"` +} + +// AnFam is a family with its event count. +type AnFam struct { + Fam string `json:"fam"` + N uint32 `json:"n"` +} + +// EvolutionOut answers "are we getting better or worse". +type EvolutionOut struct { + Enabled bool `json:"enabled"` + Truncated bool `json:"truncated"` + Days []AnDay `json:"days"` + HourDow [7][24]uint32 `json:"hour_dow"` + NewFamilies []AnFam `json:"new_families"` + GoneFamilies []AnFam `json:"gone_families"` + Total uint64 `json:"total"` + Prev uint64 `json:"prev"` + DeltaPct *float64 `json:"delta_pct"` +} + +// AnItem is one row of a concentration curve. +type AnItem struct { + Key string `json:"key"` + Label string `json:"label,omitempty"` + N uint32 `json:"n"` + CumPct float64 `json:"cum_pct"` +} + +// ConcentrationOut answers "do a few generate most of it". +type ConcentrationOut struct { + Enabled bool `json:"enabled"` + Truncated bool `json:"truncated"` + Dim string `json:"dim"` + Total uint64 `json:"total"` + Distinct int `json:"distinct"` + Gini float64 `json:"gini"` + Top10Pct float64 `json:"top10_pct"` + Items []AnItem `json:"items"` +} + +// KMPoint is one step of a Kaplan-Meier curve. +type KMPoint struct { + T int64 `json:"t_s"` + Survival float64 `json:"survival"` +} + +// FamTTB is the time-to-ban quartiles of one family. +type FamTTB struct { + Fam string `json:"fam"` + P25 int64 `json:"p25"` + P50 int64 `json:"p50"` + P75 int64 `json:"p75"` + N int `json:"n"` +} + +// Recidivist is an address banned more than once. +type Recidivist struct { + IP string `json:"ip"` + Bans int `json:"bans"` + Last int64 `json:"last"` +} + +// SurvivalOut answers "how long until the ban, and who comes back". +type SurvivalOut struct { + Enabled bool `json:"enabled"` + Truncated bool `json:"truncated"` + Attackers int `json:"attackers"` + Banned int `json:"banned"` + Episodes int `json:"episodes"` + MedianToBanS *int64 `json:"median_to_ban_s"` + P90ToBanS *int64 `json:"p90_to_ban_s"` + KM []KMPoint `json:"km"` + ByFamily []FamTTB `json:"by_family"` + Recidivists []Recidivist `json:"recidivists"` + RecidivismPct float64 `json:"recidivism_pct"` +} + +// ---- pure math ---- + +// anGini is the Gini coefficient (0 equal .. 1 concentrated) of non-negative counts. +func anGini(v []float64) float64 { + n := len(v) + if n == 0 { + return 0 + } + x := append([]float64(nil), v...) + sort.Float64s(x) + var sum, w float64 + for i, f := range x { + sum += f + w += float64(i+1) * f + } + if sum == 0 { + return 0 + } + g := 2*w/(float64(n)*sum) - float64(n+1)/float64(n) + if g < 0 { + g = 0 + } + return math.Round(g*1000) / 1000 +} + +// anPareto turns descending-sorted counts into rows with the cumulative percentage. +func anPareto(sorted []AnItem, total uint64) []AnItem { + var cum uint64 + for i := range sorted { + cum += uint64(sorted[i].N) + if total > 0 { + sorted[i].CumPct = math.Round(float64(cum)/float64(total)*1000) / 10 + } + } + return sorted +} + +// anSubject is one observed address for Kaplan-Meier: time to the event, and +// whether the event (a ban) happened (false: censored at T). +type anSubject struct { + T int64 + Event bool +} + +// anKaplanMeier returns the survival curve (starting at t=0, S=1) with one +// point per distinct event time, plus the first times S drops to <= 0.5 and <= 0.1. +func anKaplanMeier(subs []anSubject) (curve []KMPoint, median, p90 *int64) { + curve = []KMPoint{{0, 1}} + if len(subs) == 0 { + return + } + s := append([]anSubject(nil), subs...) + sort.Slice(s, func(i, j int) bool { + if s[i].T != s[j].T { + return s[i].T < s[j].T + } + return s[i].Event && !s[j].Event // events before censors at a tie + }) + atRisk := len(s) + surv := 1.0 + for i := 0; i < len(s); { + t := s[i].T + d, c := 0, 0 + for i < len(s) && s[i].T == t { + if s[i].Event { + d++ + } else { + c++ + } + i++ + } + if d > 0 && atRisk > 0 { + surv *= 1 - float64(d)/float64(atRisk) + curve = append(curve, KMPoint{t, math.Round(surv*10000) / 10000}) + if median == nil && surv <= 0.5 { + v := t + median = &v + } + if p90 == nil && surv <= 0.1 { + v := t + p90 = &v + } + } + atRisk -= d + c + } + if len(curve) > anKMPoints { + step := float64(len(curve)-1) / float64(anKMPoints-1) + out := make([]KMPoint, 0, anKMPoints) + for k := 0; k < anKMPoints; k++ { + out = append(out, curve[int(math.Round(float64(k)*step))]) + } + curve = out + } + return +} + +// anQuant is the q-quantile of ascending values (nearest rank). +func anQuant(v []int64, q float64) int64 { + if len(v) == 0 { + return 0 + } + i := int(math.Ceil(q*float64(len(v)))) - 1 + if i < 0 { + i = 0 + } + if i >= len(v) { + i = len(v) - 1 + } + return v[i] +} + +// ---- scans ---- + +func (s *Store) anScan(from, to int64, host string, fn func(evlog.Rec) bool) (truncated bool) { + deadline := time.Now().Add(studyDead) + n := 0 + info := s.elog.Scan(evlog.Filter{From: from, To: to, Host: host}, studyBudget, false, func(r evlog.Rec, _ []byte) bool { + if n++; n%4096 == 0 && time.Now().After(deadline) { + truncated = true + return false + } + return fn(r) + }) + return truncated || info.Truncated +} + +func anHostKey(h string) string { + if h == "all" { + return "" + } + return h +} + +// Evolution compares [from, to] with the period of equal length before it. +func (s *Store) Evolution(from, to int64, host string) EvolutionOut { + host = anHostKey(host) + k := studyKey{kind: "an-evolution", from: from, to: to, host: host} + return s.cached(k, func() any { return s.evolution(from, to, host) }).(EvolutionOut) +} + +func (s *Store) evolution(from, to int64, host string) EvolutionOut { + out := EvolutionOut{Days: []AnDay{}, NewFamilies: []AnFam{}, GoneFamilies: []AnFam{}} + if s.elog == nil || to <= from { + return out + } + out.Enabled = true + span := to - from + 1 + prevFrom := from - span + days := map[int64]*AnDay{} + cur, prev := map[string]uint32{}, map[string]uint32{} + out.Truncated = s.anScan(prevFrom, to, host, func(r evlog.Rec) bool { + if !core.Category(r.Cat).IsMalicious() { + return true + } + fam := r.Fam + if fam == "" { + fam = "other" + } + if r.T < from { + out.Prev++ + prev[fam]++ + return true + } + out.Total++ + cur[fam]++ + d := r.T / 86400 + a := days[d] + if a == nil { + a = &AnDay{D: time.Unix(d*86400, 0).UTC().Format("2006-01-02"), ByCat: map[string]uint32{}, ByFam: map[string]uint32{}} + days[d] = a + } + a.Total++ + a.ByCat[r.Cat]++ + a.ByFam[fam]++ + t := time.Unix(r.T, 0).UTC() + out.HourDow[int(t.Weekday())][t.Hour()]++ + return true + }) + first, last := from/86400, to/86400 + if last-first >= anMaxDays { + first = last - anMaxDays + 1 + } + for d := first; d <= last; d++ { + a := days[d] + if a == nil { + a = &AnDay{D: time.Unix(d*86400, 0).UTC().Format("2006-01-02"), ByCat: map[string]uint32{}, ByFam: map[string]uint32{}} + } + out.Days = append(out.Days, *a) + } + if out.Prev > 0 { + v := math.Round((float64(out.Total)-float64(out.Prev))/float64(out.Prev)*1000) / 10 + out.DeltaPct = &v + for f, n := range cur { + if prev[f] == 0 { + out.NewFamilies = append(out.NewFamilies, AnFam{f, n}) + } + } + for f, n := range prev { + if cur[f] == 0 { + out.GoneFamilies = append(out.GoneFamilies, AnFam{f, n}) + } + } + for _, l := range []*[]AnFam{&out.NewFamilies, &out.GoneFamilies} { + sort.Slice(*l, func(i, j int) bool { + if (*l)[i].N != (*l)[j].N { + return (*l)[i].N > (*l)[j].N + } + return (*l)[i].Fam < (*l)[j].Fam + }) + if len(*l) > 20 { + *l = (*l)[:20] + } + } + } + return out +} + +// ConcentrationDims are the accepted dimensions. +var ConcentrationDims = map[string]bool{"ip": true, "asn": true, "country": true, "path": true, "domain": true} + +// Concentration measures how unevenly malicious events spread over a dimension. +func (s *Store) Concentration(from, to int64, host, dim string) ConcentrationOut { + host = anHostKey(host) + k := studyKey{kind: "an-conc", from: from, to: to, host: host, cat: dim} + return s.cached(k, func() any { return s.concentration(from, to, host, dim) }).(ConcentrationOut) +} + +func (s *Store) concentration(from, to int64, host, dim string) ConcentrationOut { + out := ConcentrationOut{Dim: dim, Items: []AnItem{}} + if s.elog == nil || to <= from || !ConcentrationDims[dim] { + return out + } + out.Enabled = true + counts := map[string]uint32{} + labels := map[string]string{} + geo := map[string]core.GeoInfo{} + out.Truncated = s.anScan(from, to, host, func(r evlog.Rec) bool { + if !core.Category(r.Cat).IsMalicious() { + return true + } + key, label := "", "" + switch dim { + case "ip": + key = r.IP + case "path": + if r.Source != "traefik" { + return true + } + key = r.Path + if len(key) > 200 { + key = key[:200] + } + case "domain": + key = r.Domain + case "country": + key = r.CC + if key == "" { + g, ok := geo[r.IP] + if !ok { + g = s.GeoOf(r.IP) + if len(geo) < 50000 { + geo[r.IP] = g + } + } + key = g.CC + } + case "asn": + g, ok := geo[r.IP] + if !ok { + g = s.GeoOf(r.IP) + if len(geo) < 50000 { + geo[r.IP] = g + } + } + if g.ASN != 0 { + key, label = "AS"+strconv.Itoa(int(g.ASN)), g.ASOrg + } + } + if key == "" { + return true + } + if _, seen := counts[key]; !seen && len(counts) >= anMaxKeys { + out.Truncated = true + return true + } + counts[key]++ + if label != "" { + labels[key] = label + } + return true + }) + all := make([]AnItem, 0, len(counts)) + vals := make([]float64, 0, len(counts)) + for k, n := range counts { + all = append(all, AnItem{Key: k, Label: labels[k], N: n}) + vals = append(vals, float64(n)) + out.Total += uint64(n) + } + sort.Slice(all, func(i, j int) bool { + if all[i].N != all[j].N { + return all[i].N > all[j].N + } + return all[i].Key < all[j].Key + }) + out.Distinct = len(all) + out.Gini = anGini(vals) + if len(all) > anMaxItems { + all = all[:anMaxItems] + } + out.Items = anPareto(all, out.Total) + if len(out.Items) > 0 { + i := 9 + if len(out.Items) <= i { + i = len(out.Items) - 1 + } + out.Top10Pct = out.Items[i].CumPct + } + return out +} + +// Survival studies the time from an attacker's first malicious event to its +// ban (Kaplan-Meier, censoring the ones never banned) and the ones banned again. +func (s *Store) Survival(from, to int64, host string) SurvivalOut { + host = anHostKey(host) + k := studyKey{kind: "an-survival", from: from, to: to, host: host} + return s.cached(k, func() any { return s.survival(from, to, host) }).(SurvivalOut) +} + +type anIPState struct { + mal []int64 + bans []int64 + fam string +} + +// anEpisodes splits the activity of one address into attack episodes. An +// episode starts at the first malicious event after the previous ban, runs +// through events with gaps of at most episodeGap, and ends at the ban (event +// observed, T = ban - start) or, with no ban, at its last event + episodeGap +// (censored, capped at end). +func anEpisodes(mal, bans []int64, end int64) []anSubject { + sort.Slice(mal, func(i, j int) bool { return mal[i] < mal[j] }) + sort.Slice(bans, func(i, j int) bool { return bans[i] < bans[j] }) + var out []anSubject + prev := int64(-1) + bi := 0 + for i := 0; i < len(mal); { + if mal[i] <= prev { + i++ + continue + } + start, last := mal[i], mal[i] + for bi < len(bans) && bans[bi] < start { + bi++ + } + next := int64(-1) + if bi < len(bans) { + next = bans[bi] + } + j := i + 1 + for j < len(mal) && mal[j]-last <= episodeGap && (next < 0 || mal[j] <= next) { + last = mal[j] + j++ + } + i = j + if next >= 0 && next-last <= episodeGap { + out = append(out, anSubject{next - start, true}) + prev = next + bi++ + continue + } + stop := last + episodeGap + if stop > end { + stop = end + } + d := stop - start + if d < 0 { + d = 0 + } + out = append(out, anSubject{d, false}) + prev = last + } + return out +} + +func (s *Store) survival(from, to int64, host string) SurvivalOut { + out := SurvivalOut{KM: []KMPoint{{0, 1}}, ByFamily: []FamTTB{}, Recidivists: []Recidivist{}} + if s.elog == nil || to <= from { + return out + } + out.Enabled = true + ips := map[string]*anIPState{} + out.Truncated = s.anScan(from, to, host, func(r evlog.Rec) bool { + c := core.Category(r.Cat) + isBan := c == core.Ban && !r.Unban + if !isBan && !c.IsMalicious() { + return true + } + st := ips[r.IP] + if st == nil { + if len(ips) >= anMaxIPs { + return true + } + st = &anIPState{} + ips[r.IP] = st + } + if isBan { + st.bans = append(st.bans, r.T) + return true + } + if len(st.mal) < 5000 { + st.mal = append(st.mal, r.T) + } + if st.fam == "" && r.Fam != "" { + st.fam = r.Fam + } + return true + }) + end := to + if now := s.now().Unix(); now < end { + end = now + } + var subs []anSubject + famT := map[string][]int64{} + var banned, recid, attackers int + var rec []Recidivist + for ip, st := range ips { + if len(st.mal) == 0 { + continue + } + attackers++ + eps := anEpisodes(st.mal, st.bans, end) + subs = append(subs, eps...) + for _, e := range eps { + if e.Event && st.fam != "" { + famT[st.fam] = append(famT[st.fam], e.T) + } + } + if n := len(st.bans); n > 0 { + banned++ + if n >= 2 { + recid++ + rec = append(rec, Recidivist{ip, n, st.bans[len(st.bans)-1]}) + } + } + } + out.Attackers, out.Banned, out.Episodes = attackers, banned, len(subs) + out.KM, out.MedianToBanS, out.P90ToBanS = anKaplanMeier(subs) + if banned > 0 { + out.RecidivismPct = math.Round(float64(recid)/float64(banned)*1000) / 10 + } + for f, v := range famT { + sort.Slice(v, func(i, j int) bool { return v[i] < v[j] }) + out.ByFamily = append(out.ByFamily, FamTTB{f, anQuant(v, .25), anQuant(v, .5), anQuant(v, .75), len(v)}) + } + sort.Slice(out.ByFamily, func(i, j int) bool { + if out.ByFamily[i].N != out.ByFamily[j].N { + return out.ByFamily[i].N > out.ByFamily[j].N + } + return out.ByFamily[i].Fam < out.ByFamily[j].Fam + }) + if len(out.ByFamily) > anMaxFamilies { + out.ByFamily = out.ByFamily[:anMaxFamilies] + } + sort.Slice(rec, func(i, j int) bool { + if rec[i].Bans != rec[j].Bans { + return rec[i].Bans > rec[j].Bans + } + if rec[i].Last != rec[j].Last { + return rec[i].Last > rec[j].Last + } + return rec[i].IP < rec[j].IP + }) + if len(rec) > anMaxRecid { + rec = rec[:anMaxRecid] + } + if rec != nil { + out.Recidivists = rec + } + return out +} diff --git a/internal/store/analytics_test.go b/internal/store/analytics_test.go new file mode 100644 index 0000000..c70b45a --- /dev/null +++ b/internal/store/analytics_test.go @@ -0,0 +1,185 @@ +package store + +import ( + "math" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +func TestGini(t *testing.T) { + if g := anGini(nil); g != 0 { + t.Fatalf("empty %v", g) + } + if g := anGini([]float64{5, 5, 5, 5}); g != 0 { + t.Fatalf("equal %v", g) + } + // one holds everything among 4: (n-1)/n = 0.75 + if g := anGini([]float64{0, 0, 0, 100}); math.Abs(g-0.75) > 1e-9 { + t.Fatalf("concentrated %v", g) + } + if g := anGini([]float64{0, 0}); g != 0 { + t.Fatalf("zeros %v", g) + } +} + +func TestPareto(t *testing.T) { + items := anPareto([]AnItem{{Key: "a", N: 60}, {Key: "b", N: 30}, {Key: "c", N: 10}}, 100) + if items[0].CumPct != 60 || items[1].CumPct != 90 || items[2].CumPct != 100 { + t.Fatalf("%+v", items) + } + if e := anPareto(nil, 0); len(e) != 0 { + t.Fatal("empty") + } +} + +func TestKaplanMeierCensoring(t *testing.T) { + // times 10(ban) 20(censored) 30(ban) 40(ban): S(10)=3/4, at 30 risk=2 -> 3/4*1/2, at 40 risk=1 -> 0 + c, med, p90 := anKaplanMeier([]anSubject{{10, true}, {20, false}, {30, true}, {40, true}}) + want := []KMPoint{{0, 1}, {10, 0.75}, {30, 0.375}, {40, 0}} + if len(c) != len(want) { + t.Fatalf("%+v", c) + } + for i := range want { + if c[i] != want[i] { + t.Fatalf("%d: %+v want %+v", i, c[i], want[i]) + } + } + if med == nil || *med != 30 || p90 == nil || *p90 != 40 { + t.Fatalf("median %v p90 %v", med, p90) + } + // everybody censored: no event, no median + c, med, p90 = anKaplanMeier([]anSubject{{5, false}, {9, false}}) + if len(c) != 1 || med != nil || p90 != nil { + t.Fatalf("censored %+v", c) + } + c, med, _ = anKaplanMeier(nil) + if len(c) != 1 || med != nil { + t.Fatal("empty") + } + var many []anSubject + for i := 1; i <= 1000; i++ { + many = append(many, anSubject{int64(i), true}) + } + if c, _, _ := anKaplanMeier(many); len(c) != anKMPoints || c[len(c)-1].Survival != 0 { + t.Fatalf("downsample %d", len(c)) + } +} + +func TestAnalyticsEmpty(t *testing.T) { + s := store30("oracle") + f, to := t0.Unix()-86400, t0.Unix() + if e := s.Evolution(f, to, ""); e.Enabled || e.Days == nil { + t.Fatalf("no registry: %+v", e) + } + s = store30("oracle") + s.SetEventLog(openLog(t)) + if e := s.Evolution(f, to, ""); !e.Enabled || e.Total != 0 || e.DeltaPct != nil || len(e.Days) < 2 { + t.Fatalf("empty evolution: %+v", e) + } + if c := s.Concentration(f, to, "", "ip"); !c.Enabled || c.Total != 0 || c.Items == nil || c.Gini != 0 { + t.Fatalf("empty concentration: %+v", c) + } + if c := s.Concentration(f, to, "", "bogus"); c.Enabled { + t.Fatal("bad dim") + } + if v := s.Survival(f, to, ""); !v.Enabled || v.MedianToBanS != nil || len(v.KM) != 1 || v.RecidivismPct != 0 { + t.Fatalf("empty survival: %+v", v) + } +} + +func TestAnalyticsData(t *testing.T) { + s := store30("oracle") + s.SetEventLog(openLog(t)) + at := func(d time.Duration) time.Time { return t0.Add(-d) } + mal := func(ip, path string, cat core.Category, d time.Duration) { + s.Ingest(core.Event{Time: at(d), IP: ip, Cat: cat, Source: "traefik", Domain: "a.example", Method: "GET", Path: path, Status: 404, UA: "curl/8"}) + } + // 1.1.1.1 is the heavy hitter now; 2.2.2.2 and 3.3.3.3 are light; 9.9.9.9 only existed the day before + for i := 0; i < 8; i++ { + mal("1.1.1.1", "/.env", core.Scanner, time.Hour+time.Duration(i)*time.Minute) + } + mal("2.2.2.2", "/wp-login.php", core.Scanner, 2*time.Hour) + mal("3.3.3.3", "/xmlrpc.php", core.Scanner, 3*time.Hour) + mal("9.9.9.9", "/.git/config", core.Exploit, 30*time.Hour) + // bans: 1.1.1.1 twice (recidivist), 2.2.2.2 once; 3.3.3.3 never (censored) + ban := func(ip string, d time.Duration) { + s.Ingest(core.Event{Time: at(d), IP: ip, Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}) + } + ban("1.1.1.1", 50*time.Minute) + ban("1.1.1.1", 20*time.Minute) + ban("2.2.2.2", 2*time.Hour-300*time.Second) + f, to := t0.Unix()-86400, t0.Unix() + + c := s.Concentration(f, to, "", "ip") + if c.Total != 10 || c.Distinct != 3 || c.Items[0].Key != "1.1.1.1" || c.Items[0].CumPct != 80 || c.Gini <= 0.3 { + t.Fatalf("concentration %+v", c) + } + if c.Top10Pct != 100 { + t.Fatalf("top10 %v", c.Top10Pct) + } + if p := s.Concentration(f, to, "", "path"); p.Items[0].Key != "/.env" || p.Items[0].N != 8 { + t.Fatalf("path %+v", p) + } + if d := s.Concentration(f, to, "", "domain"); d.Distinct != 1 || d.Gini != 0 { + t.Fatalf("domain %+v", d) + } + + v := s.Survival(f, to, "") + if v.Attackers != 3 || v.Banned != 2 || v.RecidivismPct != 50 || len(v.Recidivists) != 1 || v.Recidivists[0].IP != "1.1.1.1" || v.Recidivists[0].Bans != 2 { + t.Fatalf("survival %+v", v) + } + // 1.1.1.1: first malicious 8m before the ban...: first event at -67m, ban at -50m = 1020 s; 2.2.2.2: 300 s; 3.3.3.3 censored at 3 h + if v.MedianToBanS == nil || *v.MedianToBanS != 1020 { + t.Fatalf("median %v km %+v", v.MedianToBanS, v.KM) + } + if v.P90ToBanS != nil { + t.Fatalf("p90 must be unknown with a censored attacker: %v", *v.P90ToBanS) + } + + e := s.Evolution(f, to, "") + if e.Total != 10 || e.Prev != 1 || e.DeltaPct == nil || *e.DeltaPct != 900 { + t.Fatalf("evolution %+v", e) + } + var tot uint32 + for _, d := range e.Days { + tot += d.Total + } + if tot != 10 { + t.Fatalf("days sum %d", tot) + } + var hd uint32 + for _, r := range e.HourDow { + for _, n := range r { + hd += n + } + } + if hd != 10 { + t.Fatalf("hour_dow %d", hd) + } +} + +func TestAnEpisodes(t *testing.T) { + end := int64(100000) + // episode 1: 0..60, banned at 100 (observed 100); episode 2: 200 alone, silent until 10000 (censored 200+1800-200); + // episode 3: 10000, 10100 then end of data (censored at last+30min) + got := anEpisodes([]int64{0, 60, 200, 10000, 10100}, []int64{100}, end) + want := []anSubject{{100, true}, {1800, false}, {1900, false}} + if len(got) != len(want) { + t.Fatalf("%+v", got) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("%d: %+v want %+v", i, got[i], want[i]) + } + } + // a ban long after the last event does not end that episode; censoring is capped at the window end + got = anEpisodes([]int64{0}, []int64{5000}, 600) + if len(got) != 1 || got[0] != (anSubject{600, false}) { + t.Fatalf("%+v", got) + } + if len(anEpisodes(nil, []int64{5}, end)) != 0 { + t.Fatal("ban without events") + } +} diff --git a/internal/store/campaigns.go b/internal/store/campaigns.go new file mode 100644 index 0000000..899d9f2 --- /dev/null +++ b/internal/store/campaigns.go @@ -0,0 +1,263 @@ +package store + +import ( + "context" + "sort" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" +) + +// Caps of the campaign views. +const ( + MaxCampaignsOut = 200 + MaxMembersOut = 500 +) + +// CampaignsOut is the campaign list derived from a period study. +type CampaignsOut struct { + Range RangeInfo `json:"range"` + Enabled bool `json:"enabled"` + Truncated bool `json:"truncated,omitempty"` + Total int `json:"total"` + IPsN int `json:"ips_n"` + Campaigns []intel.Campaign `json:"campaigns"` +} + +// Member is one address of a campaign with its sessions in the period. +type Member struct { + IP string `json:"ip"` + First int64 `json:"first"` + Last int64 `json:"last"` + Stage string `json:"stage"` + Sessions []intel.Session `json:"sessions"` +} + +// CampaignDetail is one campaign with its members and ordered sessions. +type CampaignDetail struct { + Range RangeInfo `json:"range"` + Truncated bool `json:"truncated,omitempty"` + Campaign intel.Campaign `json:"campaign"` + Members []Member `json:"members"` +} + +var stageRank = map[string]int{intel.StageRecon: 1, intel.StageProbe: 2, intel.StageExploit: 3, intel.StageAccess: 4, intel.StageBanned: 5} + +// StageRank orders the escalation stages (0 for an unknown one). +func StageRank(s string) int { return stageRank[s] } + +// CampaignsOf lists the campaigns of a period study (at most MaxCampaignsOut, +// most addresses first) and the number of distinct addresses they group. +func CampaignsOf(p PeriodOut) CampaignsOut { + list := append([]intel.Campaign(nil), p.Campaigns...) + sort.SliceStable(list, func(i, j int) bool { + if list[i].IPsN != list[j].IPsN { + return list[i].IPsN > list[j].IPsN + } + return list[i].First.Before(list[j].First) + }) + out := CampaignsOut{Range: p.Range, Enabled: p.Enabled, Truncated: p.Truncated, Total: len(list)} + seen := map[string]bool{} + n := 0 + for _, c := range list { + n += c.IPsN + for _, ip := range c.IPs { + seen[ip] = true + } + } + out.IPsN = max(len(seen), 0) + if n > 0 && len(seen) == 0 { + out.IPsN = n + } + if len(list) > MaxCampaignsOut { + list = list[:MaxCampaignsOut] + } + out.Campaigns = list + if out.Campaigns == nil { + out.Campaigns = []intel.Campaign{} + } + return out +} + +// CampaignOf returns the detail of one campaign of a period study. +func CampaignOf(p PeriodOut, id string) (CampaignDetail, bool) { + for _, c := range p.Campaigns { + if c.ID != id { + continue + } + d := CampaignDetail{Range: p.Range, Truncated: p.Truncated, Campaign: c, Members: []Member{}} + by := map[string]*Member{} + for _, ip := range c.IPs { + by[ip] = &Member{IP: ip, Stage: "", Sessions: []intel.Session{}} + } + total := 0 + for _, s := range p.Sessions { + if s.CampaignID != id || total >= MaxMembersOut { + continue + } + m := by[s.IP] + if m == nil { + m = &Member{IP: s.IP, Sessions: []intel.Session{}} + by[s.IP] = m + } + total++ + st, en := s.Start.Unix(), s.End.Unix() + if m.First == 0 || st < m.First { + m.First = st + } + if en > m.Last { + m.Last = en + } + if StageRank(s.Stage) > StageRank(m.Stage) { + m.Stage = s.Stage + } + m.Sessions = append(m.Sessions, s) + } + for _, m := range by { + sort.Slice(m.Sessions, func(i, j int) bool { return m.Sessions[i].Start.Before(m.Sessions[j].Start) }) + d.Members = append(d.Members, *m) + } + sort.Slice(d.Members, func(i, j int) bool { + a, b := d.Members[i], d.Members[j] + if (a.First == 0) != (b.First == 0) { + return a.First != 0 + } + if a.First != b.First { + return a.First < b.First + } + return a.IP < b.IP + }) + if len(d.Members) > MaxMembersOut { + d.Members = d.Members[:MaxMembersOut] + } + return d, true + } + return CampaignDetail{}, false +} + +// FunnelOut is the escalation funnel of a period study. +type FunnelOut struct { + Range RangeInfo `json:"range"` + Enabled bool `json:"enabled"` + Truncated bool `json:"truncated,omitempty"` + SessionsN int `json:"sessions_n"` + Sampled bool `json:"sampled,omitempty"` + Stages map[string]int `json:"stages"` + Reached map[string]int `json:"reached"` + Exploited int `json:"exploited"` + Sessions []intel.Session `json:"sessions"` + Escalations []EscalationOut `json:"escalations"` +} + +// StageCounts is the funnel over every session of a study. +type StageCounts struct { + SessionsN int + Truncated bool + Stages map[string]int + Reached map[string]int + Exploited int +} + +func newCounts() StageCounts { + z := func() map[string]int { + return map[string]int{"recon": 0, "probe": 0, "exploit": 0, "access": 0, "banned": 0} + } + return StageCounts{Stages: z(), Reached: z()} +} + +// Add counts one session. A ban says nothing about how far the session got: +// it counts as recon and probe. +func (c *StageCounts) Add(stage string, success bool) { + if _, ok := c.Stages[stage]; !ok { + return + } + c.SessionsN++ + c.Stages[stage]++ + r := StageRank(stage) + if stage == intel.StageBanned { + c.Reached["recon"]++ + c.Reached["probe"]++ + c.Reached[intel.StageBanned]++ + } else { + for k, v := range stageRank { + if v <= r { + c.Reached[k]++ + } + } + } + if r == 3 || r == 4 || success { + c.Exploited++ + } +} + +// CountStages studies [q.From, q.To] and counts ALL its sessions by stage +// (the period study keeps only 200). Cached 30 s like the other studies. +func (s *Store) CountStages(q PeriodQuery) StageCounts { + k := studyKey{"funnel", q.From, q.To, q.Host, q.IP, q.Cat, q.Fam, q.Gap} + return s.cached(k, func() any { return s.countStages(q) }).(StageCounts) +} + +func (s *Store) countStages(q PeriodQuery) StageCounts { + out := newCounts() + if s.elog == nil { + return out + } + gap := time.Duration(q.Gap) * time.Second + if q.Gap < 60 { + gap = intel.DefaultGap + if q.Gap > 0 { + gap = 60 * time.Second + } + } + deadline := time.Now().Add(studyDead) + ctx, cancel := context.WithDeadline(context.Background(), deadline) + defer cancel() + var evs []intel.Ev + info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget, false, + func(r evlog.Rec, _ []byte) bool { + if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && ctx.Err() != nil { + out.Truncated = true + return false + } + evs = append(evs, toEv(r)) + return true + }) + out.Truncated = out.Truncated || info.Truncated + for _, ss := range intel.Sessions(evs, gap) { + out.Add(ss.Stage, ss.Success) + } + return out +} + +// FunnelOf builds the funnel: the counts cover every session when counts is +// given (nil: only the listed ones), the list holds the most severe sessions +// of the study (the study keeps at most 200). +func FunnelOf(p PeriodOut, counts *StageCounts) FunnelOut { + f := FunnelOut{Range: p.Range, Enabled: p.Enabled, Truncated: p.Truncated, SessionsN: p.SessionsN} + c := newCounts() + if counts != nil { + c = *counts + f.SessionsN = c.SessionsN + f.Truncated = f.Truncated || c.Truncated + } else { + for _, s := range p.Sessions { + c.Add(s.Stage, s.Success) + } + } + f.Stages, f.Reached, f.Exploited = c.Stages, c.Reached, c.Exploited + f.Sessions = append([]intel.Session{}, p.Sessions...) + f.Escalations = p.Escalations + if f.Escalations == nil { + f.Escalations = []EscalationOut{} + } + f.Sampled = f.SessionsN > len(f.Sessions) + sort.SliceStable(f.Sessions, func(i, j int) bool { + a, b := StageRank(f.Sessions[i].Stage), StageRank(f.Sessions[j].Stage) + if a != b { + return a > b + } + return f.Sessions[i].Start.After(f.Sessions[j].Start) + }) + return f +} diff --git a/internal/store/campaigns_test.go b/internal/store/campaigns_test.go new file mode 100644 index 0000000..def3452 --- /dev/null +++ b/internal/store/campaigns_test.go @@ -0,0 +1,34 @@ +package store + +import ( + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" +) + +func TestCampaignViewsAndFunnel(t *testing.T) { + now := time.Now() + p := PeriodOut{Enabled: true, SessionsN: 4, Campaigns: []intel.Campaign{ + {ID: "a", IPsN: 2, IPs: []string{"1.1.1.1", "1.1.1.2"}}, {ID: "b", IPsN: 3, IPs: []string{"2.2.2.1", "2.2.2.2", "1.1.1.1"}}}, + Sessions: []intel.Session{ + {ID: "s1", IP: "1.1.1.1", Start: now, End: now, Stage: "recon", CampaignID: "a"}, + {ID: "s2", IP: "1.1.1.2", Start: now, End: now, Stage: "exploit", CampaignID: "a"}, + {ID: "s3", IP: "9.9.9.9", Start: now, End: now, Stage: "access"}, + {ID: "s4", IP: "9.9.9.8", Start: now, End: now, Stage: "banned"}}} + c := CampaignsOf(p) + if c.Total != 2 || c.Campaigns[0].ID != "b" || c.IPsN != 4 { + t.Fatalf("%+v", c) + } + d, ok := CampaignOf(p, "a") + if !ok || len(d.Members) != 2 || d.Members[1].Stage != "exploit" { + t.Fatalf("%+v", d) + } + if _, ok := CampaignOf(p, "zz"); ok { + t.Fatal("unknown id") + } + f := FunnelOf(p, nil) + if f.Stages["banned"] != 1 || f.Reached["recon"] != 4 || f.Exploited != 2 || f.Sessions[0].Stage != "banned" { + t.Fatalf("%+v", f) + } +} diff --git a/internal/store/defense.go b/internal/store/defense.go new file mode 100644 index 0000000..47b56ab --- /dev/null +++ b/internal/store/defense.go @@ -0,0 +1,328 @@ +package store + +import ( + "sort" + "strings" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" +) + +// BanPoint is bans of one jail in one bucket of the series. +type BanPoint struct { + T int64 `json:"t"` + Jail string `json:"jail"` + N int `json:"n"` +} + +// JailRow counts the bans of one jail. +type JailRow struct { + Jail string `json:"jail"` + Active int `json:"active"` + Total int `json:"total"` +} + +// TTBStat is the time from the first malicious event to the first ban. +type TTBStat struct { + MedianS float64 `json:"median_s"` + P90S float64 `json:"p90_s"` + N int `json:"n"` +} + +// SSHUser is one SSH user name tried by attackers. +type SSHUser struct { + User string `json:"user"` + N int `json:"n"` + Admin bool `json:"admin"` +} + +// SSHDefense summarises the SSH failures of the window. +type SSHDefense struct { + Fails int `json:"fails"` + Users []SSHUser `json:"users"` + Sources int `json:"sources"` + OKAfterFail int `json:"ok_after_fail"` +} + +// BlocklistStat describes the blocklist the instance would publish. +type BlocklistStat struct { + Size int `json:"size"` + V4 int `json:"v4"` + V6 int `json:"v6"` + Updated int64 `json:"updated"` + CoveragePct float64 `json:"coverage_pct"` // attackers of the window that are listed +} + +// LeakStat counts attackers that kept arriving after a ban or listing. +type LeakStat struct { + IPs int `json:"ips"` + Events int `json:"events"` +} + +// DefenseOut is GET /api/v1/defense. +type DefenseOut struct { + Enabled bool `json:"enabled"` + Truncated bool `json:"truncated,omitempty"` + Step int64 `json:"step"` + From int64 `json:"from"` + BansActive int `json:"bans_active"` + BansTotal int `json:"bans_total"` + Bans []BanPoint `json:"bans"` + ByJail []JailRow `json:"by_jail"` + TTB TTBStat `json:"ttb"` + SSH SSHDefense `json:"ssh"` + Blocklist BlocklistStat `json:"blocklist"` + Leak LeakStat `json:"leak"` +} + +const maxDefenseUsers = 50 + +// defenseStep picks the bucket of the bans series for a window. +func defenseStep(span int64) int64 { + st := span / 60 + if st < 300 { + st = 300 + } + return (st + 299) / 300 * 300 +} + +type ipDef struct { + firstMal, firstBan, firstFail int64 + okAfter bool + mal, bans []int64 +} + +// Defense answers "is fail2ban acting?" for [q.From, q.To]: bans per jail, +// time to ban, SSH pressure, blocklist coverage and leak. Same caps, deadline +// and 30 s cache as Period. +func (s *Store) Defense(q PeriodQuery) DefenseOut { + k := studyKey{kind: "defense", from: q.From, to: q.To, host: q.Host} + return s.cached(k, func() any { return s.defense(q) }).(DefenseOut) +} + +func (s *Store) defense(q PeriodQuery) DefenseOut { + step := defenseStep(q.To - q.From) + out := DefenseOut{Step: step, From: q.From / step * step, Bans: []BanPoint{}, ByJail: []JailRow{}, SSH: SSHDefense{Users: []SSHUser{}}} + if s.elog == nil { + return out + } + out.Enabled = true + deadline := time.Now().Add(studyDead) + ips := map[string]*ipDef{} + get := func(ip string) *ipDef { + d := ips[ip] + if d == nil { + d = &ipDef{} + ips[ip] = d + } + return d + } + series := map[[2]any]int{} + jailTotal := map[string]int{} + users := map[string]int{} + sshSrc := map[string]struct{}{} + n, malN := 0, 0 + info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host}, studyBudget, false, + func(r evlog.Rec, _ []byte) bool { + if n++; n > maxStudyEvents || n%4096 == 0 && time.Now().After(deadline) { + out.Truncated = true + return false + } + c := core.Category(r.Cat) + key := KeyOf(r.IP) + switch { + case c == core.Ban: + if r.Unban { + return true + } + jail := r.Jail + if jail == "" { + jail = "?" + } + out.BansTotal++ + jailTotal[jail]++ + series[[2]any{(r.T / step) * step, jail}]++ + d := get(key) + d.bans = append(d.bans, r.T) + if d.firstBan == 0 || r.T < d.firstBan { + d.firstBan = r.T + } + case c == core.SSHFail: + out.SSH.Fails++ + if r.User != "" { + if len(users) < 5000 || users[r.User] > 0 { + users[r.User]++ + } + } + sshSrc[key] = struct{}{} + if d := get(key); d.firstFail == 0 || r.T < d.firstFail { + d.firstFail = r.T + } + fallthrough + case c.IsMalicious(): + d := get(key) + if d.firstMal == 0 || r.T < d.firstMal { + d.firstMal = r.T + } + if malN < maxStudyEvents { + d.mal = append(d.mal, r.T) + malN++ + } + case c == core.SSHOK: + if d := ips[key]; d != nil && d.firstFail > 0 && r.T >= d.firstFail { + d.okAfter = true + } + } + return true + }) + out.Truncated = out.Truncated || info.Truncated + out.SSH.Sources = len(sshSrc) + + // live state of the registry: active bans, jails, blocklist + active := map[string]int{} + listed := map[string]int64{} + s.mu.RLock() + for ip, r := range s.ips { + if len(r.Jails) > 0 { + out.BansActive++ + for _, j := range r.Jails { + active[j]++ + } + } + if r.ListedSince > 0 { + out.Blocklist.Size++ + if strings.Contains(ip, ":") { + out.Blocklist.V6++ + } else { + out.Blocklist.V4++ + } + if r.ListedSince > out.Blocklist.Updated { + out.Blocklist.Updated = r.ListedSince + } + if ips[ip] != nil { + listed[ip] = r.ListedSince + } + } + if d := ips[ip]; d != nil && d.firstBan > 0 && r.TTB > 0 && d.firstMal == 0 { + d.firstMal = d.firstBan - r.TTB + } + } + adminOf := map[string]bool{} + for u := range users { + adminOf[u] = s.isAdminUser(u) + } + s.mu.RUnlock() + + for j, t := range jailTotal { + out.ByJail = append(out.ByJail, JailRow{Jail: j, Active: active[j], Total: t}) + } + for j, a := range active { + if _, ok := jailTotal[j]; !ok { + out.ByJail = append(out.ByJail, JailRow{Jail: j, Active: a}) + } + } + sort.Slice(out.ByJail, func(i, j int) bool { + a, b := out.ByJail[i], out.ByJail[j] + if a.Total != b.Total { + return a.Total > b.Total + } + return a.Jail < b.Jail + }) + for k, v := range series { + out.Bans = append(out.Bans, BanPoint{T: k[0].(int64), Jail: k[1].(string), N: v}) + } + sort.Slice(out.Bans, func(i, j int) bool { + if out.Bans[i].T != out.Bans[j].T { + return out.Bans[i].T < out.Bans[j].T + } + return out.Bans[i].Jail < out.Bans[j].Jail + }) + + var ttb []float64 + attackers, covered := 0, 0 + for ip, d := range ips { + if d.firstMal == 0 { + continue + } + attackers++ + if _, ok := listed[ip]; ok { + covered++ + } + ttb = append(ttb, episodeTTB(d.mal, d.bans)...) + cut := d.firstBan + if l := listed[ip]; l > 0 && (cut == 0 || l < cut) { + cut = l + } + if cut == 0 { + continue + } + leak := 0 + for _, t := range d.mal { + if t > cut { + leak++ + } + } + if leak > 0 { + out.Leak.IPs++ + out.Leak.Events += leak + } + } + out.TTB.N = len(ttb) + if len(ttb) > 0 { + sort.Float64s(ttb) + out.TTB.MedianS = ttb[len(ttb)/2] + out.TTB.P90S = ttb[min(len(ttb)-1, len(ttb)*9/10)] + } + if attackers > 0 { + out.Blocklist.CoveragePct = float64(covered) / float64(attackers) * 100 + } + for u, c := range users { + out.SSH.Users = append(out.SSH.Users, SSHUser{User: u, N: c, Admin: adminOf[u]}) + } + sort.Slice(out.SSH.Users, func(i, j int) bool { + a, b := out.SSH.Users[i], out.SSH.Users[j] + if a.N != b.N { + return a.N > b.N + } + return a.User < b.User + }) + if len(out.SSH.Users) > maxDefenseUsers { + out.SSH.Users = out.SSH.Users[:maxDefenseUsers] + } + for _, d := range ips { + if d.okAfter { + out.SSH.OKAfterFail++ + } + } + return out +} + +// episodeGap is the silence that ends a burst of malicious events. +const episodeGap = 30 * 60 + +// episodeTTB measures, for every ban, the time from the start of the attack +// episode that led to it: the first malicious event after the previous ban of +// the address, extended back through a continuous run (gaps of at most 30 +// minutes) that ends at the ban. Bans with no earlier event are ignored. +func episodeTTB(mal, bans []int64) []float64 { + sort.Slice(mal, func(i, j int) bool { return mal[i] < mal[j] }) + sort.Slice(bans, func(i, j int) bool { return bans[i] < bans[j] }) + var out []float64 + prev := int64(-1) + for _, b := range bans { + hi := sort.Search(len(mal), func(i int) bool { return mal[i] > b }) - 1 // last event at or before the ban + start := int64(-1) + for i := hi; i >= 0 && mal[i] > prev; i-- { + if start >= 0 && start-mal[i] > episodeGap { + break + } + start = mal[i] + } + if start >= 0 { + out = append(out, float64(b-start)) + } + prev = b + } + return out +} diff --git a/internal/store/defense_test.go b/internal/store/defense_test.go new file mode 100644 index 0000000..d28828c --- /dev/null +++ b/internal/store/defense_test.go @@ -0,0 +1,32 @@ +package store + +import "testing" + +func TestTacticOfAndStep(t *testing.T) { + for id, want := range map[string]string{"T1595.002": "TA0043", "T1110.001": "TA0006", "T1190": "TA0001", "T9999": ""} { + if got := TacticOf(id); got != want { + t.Fatalf("%s: %q want %q", id, got, want) + } + } + if s := defenseStep(86400); s%300 != 0 || s < 300 { + t.Fatalf("step %d", s) + } + if defenseStep(60) != 300 { + t.Fatal("step floor") + } +} + +func TestEpisodeTTB(t *testing.T) { + day := int64(86400) + // three days: attack for 10 minutes, banned; again next days + mal := []int64{100, 400, 700, day + 50, day + 350, 3*day + 10} + bans := []int64{700 + 60, day + 350 + 120, 3*day + 10 + 30} + got := episodeTTB(mal, bans) + want := []float64{660, 420, 30} + if len(got) != 3 || got[0] != want[0] || got[1] != want[1] || got[2] != want[2] { + t.Fatalf("got %v want %v", got, want) + } + if len(episodeTTB(nil, []int64{5})) != 0 { + t.Fatal("a ban with no earlier event is ignored") + } +} diff --git a/internal/store/integrity.go b/internal/store/integrity.go new file mode 100644 index 0000000..a29178e --- /dev/null +++ b/internal/store/integrity.go @@ -0,0 +1,118 @@ +package store + +import ( + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" +) + +// Gap is a stretch of hours with no event at all from a source that usually has some. +type Gap struct { + From int64 `json:"from"` + To int64 `json:"to"` +} + +// MinGapHours is the shortest silence reported as a hole. +const MinGapHours = 2 + +// HourlyFromTimeline folds a timeline (any step up to one hour, or exactly +// one hour) into events per hour for the hours [fromHour, toHour] (hour numbers, +// unix/3600). Hours outside the timeline stay zero. +func HourlyFromTimeline(tl Timeline, fromHour, toHour int64) []uint32 { + if toHour < fromHour { + return []uint32{} + } + n := int(toHour-fromHour) + 1 + if n > 24*31 { + n = 24 * 31 + fromHour = toHour - int64(n) + 1 + } + out := make([]uint32, n) + if tl.Step <= 0 { + return out + } + for _, vals := range tl.Series { + for i, v := range vals { + if v == 0 { + continue + } + h := (tl.Start + int64(i)*tl.Step) / 3600 + if h < fromHour || h > toHour { + continue + } + out[h-fromHour] += v + } + } + return out +} + +// FindGaps lists runs of at least MinGapHours empty hours after the first +// busy hour, provided the source is a regular one (at least three busy hours). +// Gaps are returned as unix seconds [from, to). +func FindGaps(hourly []uint32, fromHour int64) []Gap { + busy, first := 0, -1 + for i, v := range hourly { + if v > 0 { + busy++ + if first < 0 { + first = i + } + } + } + gaps := []Gap{} + if busy < 3 { + return gaps + } + run := -1 + flush := func(end int) { + if run >= 0 && end-run >= MinGapHours { + gaps = append(gaps, Gap{From: (fromHour + int64(run)) * 3600, To: (fromHour + int64(end)) * 3600}) + } + run = -1 + } + for i := first; i < len(hourly); i++ { + if hourly[i] == 0 { + if run < 0 { + run = i + } + } else { + flush(i) + } + } + flush(len(hourly)) + return gaps +} + +// LogStats describes the event log on disk. +type LogStats struct { + Enabled bool `json:"enabled"` + Days int `json:"days"` + Bytes int64 `json:"bytes"` + Dropped uint64 `json:"dropped"` +} + +// LogStats counts the days with events (scan cached for five minutes), the +// size on disk and the events dropped by the writer. +func (s *Store) LogStats() LogStats { + if s.elog == nil { + return LogStats{} + } + k := studyKey{kind: "integrity-log"} + d := s.cachedTTL(k, 5*time.Minute, func() any { + days := map[int64]bool{} + now := s.now().Unix() + s.elog.Scan(evlog.Filter{From: now - int64(s.cfg.Retention/time.Second) - 86400, To: now + 86400}, studyBudget, false, func(r evlog.Rec, _ []byte) bool { + days[r.T/86400] = true + return true + }) + return len(days) + }).(int) + return LogStats{Enabled: true, Days: d, Bytes: s.elog.Size(), Dropped: s.elog.Dropped()} +} + +// GeoBuilds, when set by the application (serve.go: geo.Resolver.Status() -> +// City.Build / ASN.Build, as `urutau doctor` shows them), returns the build +// time of the city and ASN databases in unix seconds (0 when unknown). The +// source list the dashboard receives hides paths, so the server cannot open the +// geo directory itself. +var GeoBuilds func() (city, asn int64) diff --git a/internal/store/integrity_test.go b/internal/store/integrity_test.go new file mode 100644 index 0000000..6d94801 --- /dev/null +++ b/internal/store/integrity_test.go @@ -0,0 +1,27 @@ +package store + +import "testing" + +func TestHourlyFromTimelineAndGaps(t *testing.T) { + tl := Timeline{Start: 0, Step: 1800, Series: map[string][]uint32{ + "a": {1, 1, 0, 0, 0, 0, 0, 0, 2, 0}, + "b": {0, 1, 0, 0, 0, 0, 0, 0, 0, 0}, + }} + h := HourlyFromTimeline(tl, 0, 5) + want := []uint32{3, 0, 0, 0, 2, 0} + for i := range want { + if h[i] != want[i] { + t.Fatalf("hourly %v", h) + } + } + g := FindGaps([]uint32{0, 2, 1, 0, 0, 0, 4, 0, 5, 0}, 10) + if len(g) != 1 || g[0].From != 13*3600 || g[0].To != 16*3600 { + t.Fatalf("gaps %+v", g) + } + if g := FindGaps([]uint32{0, 0, 5, 0, 0, 0}, 0); len(g) != 0 { + t.Fatalf("irregular source has no gaps: %+v", g) + } + if len(HourlyFromTimeline(tl, 5, 1)) != 0 { + t.Fatal("empty window") + } +} diff --git a/internal/store/privacy_path_test.go b/internal/store/privacy_path_test.go new file mode 100644 index 0000000..712be33 --- /dev/null +++ b/internal/store/privacy_path_test.go @@ -0,0 +1,34 @@ +package store + +import ( + "strings" + "testing" +) + +// Paths and Referer paths kept in aggregates (top pages, broken links, error +// routes) and sent in live visit events must not carry e-mail addresses or +// secret tokens (reset links, invites). +func TestNormalizePathDropsPersonalSegments(t *testing.T) { + for in, want := range map[string]string{ + "/reset/secrettoken_abc-DEF.ghi/joao@mail.com": "/reset/:id/:id", + "/conta/joao.silva@mail.com/reset-tok_ab.cd": "/conta/:id/:id", + "/invite/aZ93kd02LmQp": "/invite/:id", + "/u/" + strings.Repeat("x", 30): "/u/:id", + "/blog/post-1": "/blog/post-1", + "/ciberfauna/guara/actions/runs/36/jobs/397": "/ciberfauna/guara/actions/runs/36/jobs/397", + "/sobre": "/sobre", + "/": "/", + } { + if got := normalizePath(in); got != want { + t.Errorf("normalizePath(%q) = %q, want %q", in, got, want) + } + } + if got := urlPath("https://site.example/reset/secrettoken_abc-DEF.ghi/joao@mail.com?token=SECRET"); strings.Contains(got, "@") || strings.Contains(got, "secrettoken") || strings.Contains(got, "SECRET") { + t.Fatalf("referer path kept personal data: %q", got) + } + m := VisitMsg{Kind: "visit", Path: "/conta/joao@mail.com", T: 1} + m.Sanitize(1) + if strings.Contains(m.Path, "@") { + t.Fatalf("peer visit path not normalized: %q", m.Path) + } +} diff --git a/internal/store/services.go b/internal/store/services.go new file mode 100644 index 0000000..79c7ac3 --- /dev/null +++ b/internal/store/services.go @@ -0,0 +1,510 @@ +package store + +import ( + "net/url" + "sort" + "strings" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +// Per-service health: for every backend service, per hour, the request mix, +// the error classes (see core.ErrorClass), latency histograms, Apdex and the +// protocol/TLS mix; per day the top failing routes, broken links and so on. + +const ( + svcCap = 64 + svcOther = "(other)" + svcRoutes = 200 + svcCiphers = 50 + svcLatN = latN + 1 // the existing bounds plus a 30 s bound +) + +// Class slots of svcHour.Cls. +const ( + ClsApp = iota + ClsProxy + ClsBlocked + ClsAttack + ClsBot + ClsClientBroken + ClsClientAuth + ClsClientOther + NumCls +) + +// ClsNames names the Cls slots. +var ClsNames = [NumCls]string{"app", "proxy", "blocked", "attack", "bot", "client_broken", "client_auth", "client_other"} + +// SvcBounds are the upper bounds (ms) of the latency histograms; the last +// bucket is everything above. +var SvcBounds = [svcLatN - 1]float64{5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000} + +func svcBucket(ns int64) int { + ms := float64(ns) / 1e6 + for i, b := range SvcBounds { + if ms <= b { + return i + } + } + return svcLatN - 1 +} + +type svcHour struct { + Hour int64 + Req, Legit uint32 + Cls [NumCls]uint32 + S [5]uint32 // 2xx 3xx 4xx 5xx other + Dur, Org, Ov [svcLatN]uint32 + ApSat, ApTol uint32 // Apdex satisfied / tolerating + ApN uint32 + Retries uint32 + Proto [4]uint32 // HTTP/1.x HTTP/2 HTTP/3 other + TLS [4]uint32 // 1.3 1.2 older none + BytesMax uint32 +} + +type svcDay struct { + Day int64 + ErrRoutes map[string]uint32 // "class|METHOD path" + Broken404 map[string]uint32 // "path\x00referer path" + Methods map[string]uint32 // "METHOD|class" + Ciphers map[string]uint32 + ProtoCls map[string]uint32 // "proto|class" + TLSCls map[string]uint32 // "tls|class" + Last404 map[string]int64 // broken link key -> last seen +} + +type svcData struct { + Hours [hourSlots]svcHour + Days [anDays]svcDay + Doms map[string]uint32 + Last int64 +} + +type svcState struct { + m map[string]*svcData +} + +// ServiceKey names the service of an event: the Traefik service without the +// provider suffix, else the router, else the host. +func ServiceKey(ev core.Event) string { + k := ev.Service + if k == "" || strings.HasPrefix(k, "noop@") || strings.HasPrefix(k, "api@") { + k = ev.Router + } + if i := strings.IndexByte(k, '@'); i >= 0 { + k = k[:i] + } + if k == "" { + k = normDomain(ev.Domain) + } + return clipS(k, 64) +} + +func isAPIPath(p string) bool { + return strings.HasPrefix(p, "/api") || strings.HasPrefix(p, "/v2/") || p == "/v2" || strings.HasPrefix(p, "/graphql") || strings.HasPrefix(p, "/trpc") +} + +func urlPath(ref string) string { + u, err := url.Parse(ref) + if err != nil || u.Host == "" { + return "" + } + p := u.EscapedPath() + if p == "" { + p = "/" + } + // a Referer path can carry personal data or secrets (reset links, e-mail) + return clipS(normalizePath(p), 120) +} + +func clsSlot(class, sub string) int { + switch class { + case core.ClassApp: + return ClsApp + case core.ClassProxy: + return ClsProxy + case core.ClassBlocked: + return ClsBlocked + case core.ClassAttack: + return ClsAttack + case core.ClassBot: + return ClsBot + case core.ClassClient: + switch sub { + case core.SubBrokenLink, core.SubExternalLink: + return ClsClientBroken + case core.SubAuth, core.SubAuthChallenge: + return ClsClientAuth + } + return ClsClientOther + } + return -1 +} + +func protoSlot(p string) int { + switch { + case strings.HasPrefix(p, "HTTP/1"): + return 0 + case strings.HasPrefix(p, "HTTP/2"): + return 1 + case strings.HasPrefix(p, "HTTP/3"): + return 2 + } + return 3 +} + +func protoName(i int) string { return [...]string{"http1", "http2", "http3", "other"}[i] } + +func tlsSlot(ev core.Event) int { + switch ev.TLSVer { + case "1.3": + return 0 + case "1.2": + return 1 + case "": + if ev.Scheme == "http" || ev.Scheme == "" { + return 3 + } + } + return 2 +} + +// TLSName names the TLS slots. +func TLSName(i int) string { return [...]string{"tls13", "tls12", "tls_old", "none"}[i] } + +// ObserveService records one Traefik request for the service health views. It +// takes every request (attacks too: the error classes need them) but only +// those that carry the origin fields feed the latency and protocol parts. +func (s *Store) ObserveService(ev core.Event) { + if ev.Source != "traefik" { + return + } + now := s.now() + if ev.Time.Before(now.Add(-s.cfg.Retention)) { + return + } + ts := ev.Time.Unix() + if max := now.Unix() + 300; ts > max { + ts = max + } + key := ServiceKey(ev) + dom := normDomain(ev.Domain) + s.mu.Lock() + defer s.mu.Unlock() + susp := false + if r := s.ips[ev.IP]; r != nil { + susp = r.BanSince > 0 || core.LevelOf(r.Score, r.Strong || attackKinds(r.Counts) >= 2, r.adminAt(now.Unix())) != core.LevelLow + } + if s.sv.m == nil { + s.sv.m = map[string]*svcData{} + } + d := s.sv.m[key] + if d == nil { + if len(s.sv.m) >= svcCap { + key = svcOther + d = s.sv.m[key] + } + if d == nil { + d = &svcData{} + s.sv.m[key] = d + } + } + d.Last = ts + bumpCap(&d.Doms, dom, 8) + h := ts / 3600 + hs := &d.Hours[int(h%hourSlots)] + if hs.Hour != h { + *hs = svcHour{Hour: h} + } + day := ts / 86400 + dd := &d.Days[int(day%anDays)] + if dd.Day != day { + *dd = svcDay{Day: day} + } + + hs.Req++ + switch c := ev.Status / 100; { + case c >= 2 && c <= 5: + hs.S[c-2]++ + default: + hs.S[4]++ + } + class, sub, _ := core.ErrorClassify(ev, susp) + slot := clsSlot(class, sub) + attackish := ev.Cat == core.Scanner || ev.Cat == core.Exploit || ev.Cat == core.BruteForce || susp + if slot >= 0 { + hs.Cls[slot]++ + } + if slot != ClsAttack && slot != ClsBlocked && slot != ClsBot && !(slot < 0 && attackish) { + hs.Legit++ + } + if ev.Retries > 0 { + hs.Retries += uint32(ev.Retries) + } + if ev.DurationNS > 0 { + hs.Dur[svcBucket(ev.DurationNS)]++ + } + if ev.OriginNS > 0 { + hs.Org[svcBucket(ev.OriginNS)]++ + } + if ev.OverheadNS > 0 { + hs.Ov[svcBucket(ev.OverheadNS)]++ + } + if ev.Bytes > 0 { + b := uint32(min64(ev.Bytes, 1<<32-1)) + if b > hs.BytesMax { + hs.BytesMax = b + } + } + // Apdex over the requests that count for the service + if slot != ClsAttack && slot != ClsBlocked && slot != ClsBot && ev.DurationNS > 0 { + t := int64(500e6) + if isAPIPath(ev.Path) { + t = 1000e6 + } + hs.ApN++ + switch { + case ev.Status >= 500: + case ev.DurationNS <= t: + hs.ApSat++ + case ev.DurationNS <= 4*t: + hs.ApTol++ + } + } + if ev.Proto != "" { + hs.Proto[protoSlot(ev.Proto)]++ + hs.TLS[tlsSlot(ev)]++ + if ev.TLSCiph != "" { + bumpCap(&dd.Ciphers, ev.TLSCiph, svcCiphers) + } + } + cn := class + if cn == "" { + cn = "ok" + } + if ev.Method != "" { + bumpCap(&dd.Methods, strings.ToUpper(ev.Method)+"|"+cn, svcCiphers*2) + } + if ev.Proto != "" { + bumpCap(&dd.ProtoCls, protoName(protoSlot(ev.Proto))+"|"+cn, 40) + bumpCap(&dd.TLSCls, TLSName(tlsSlot(ev))+"|"+cn, 40) + } + if class == "" { + return + } + p := ev.Path + if i := strings.IndexAny(p, "?#"); i >= 0 { + p = p[:i] + } + np := normalizePath(p) + bumpCap(&dd.ErrRoutes, class+"|"+strings.ToUpper(ev.Method)+" "+clipS(np, 120), svcRoutes) + if class == core.ClassClient && ev.Status == 404 && (sub == core.SubBrokenLink || sub == core.SubExternalLink) { + rp := urlPath(ev.Referer) + if rp == "" { + rp = "-" + } + k := clipS(np, 120) + "\x00" + rp + if sub == core.SubExternalLink { + if u, err := url.Parse(ev.Referer); err == nil { + rp = u.Hostname() + } + k = clipS(np, 120) + "\x00" + "@" + rp + } + bumpCap(&dd.Broken404, k, svcRoutes) + if dd.Last404 == nil { + dd.Last404 = map[string]int64{} + } + if _, ok := dd.Broken404[k]; ok { + dd.Last404[k] = ts + } + if len(dd.Last404) > 2*svcRoutes { + for kk := range dd.Last404 { + if _, ok := dd.Broken404[kk]; !ok { + delete(dd.Last404, kk) + } + } + } + } +} + +func min64(a, b int64) int64 { + if a < b { + return a + } + return b +} + +// SvcView is one service over a window. +type SvcView struct { + Key, Alias string + Hours []SvcHourOut // hours in the window, ascending (only those with traffic) + Tot SvcHourOut // the sum + ErrRoutes map[string]uint32 + Broken map[string]uint32 + BrokenLast map[string]int64 + Methods map[string]uint32 + Ciphers map[string]uint32 + ProtoCls map[string]uint32 + TLSCls map[string]uint32 +} + +// SvcHourOut is an exported copy of an hour (or of a sum of hours). +type SvcHourOut struct { + Hour int64 + Req, Legit uint32 + Cls [NumCls]uint32 + S [5]uint32 + Dur, Org, Ov [svcLatN]uint32 + ApSat, ApTol uint32 + ApN uint32 + Retries uint32 + Proto [4]uint32 + TLS [4]uint32 + BytesMax uint32 +} + +func (o *SvcHourOut) add(h *svcHour) { + o.Req += h.Req + o.Legit += h.Legit + o.ApSat += h.ApSat + o.ApTol += h.ApTol + o.ApN += h.ApN + o.Retries += h.Retries + if h.BytesMax > o.BytesMax { + o.BytesMax = h.BytesMax + } + for i := range h.Cls { + o.Cls[i] += h.Cls[i] + } + for i := range h.S { + o.S[i] += h.S[i] + } + for i := range h.Dur { + o.Dur[i] += h.Dur[i] + o.Org[i] += h.Org[i] + o.Ov[i] += h.Ov[i] + } + for i := range h.Proto { + o.Proto[i] += h.Proto[i] + o.TLS[i] += h.TLS[i] + } +} + +func mergeMap(dst *map[string]uint32, src map[string]uint32) { + if len(src) == 0 { + return + } + if *dst == nil { + *dst = make(map[string]uint32, len(src)) + } + for k, v := range src { + (*dst)[k] += v + } +} + +// Services returns every service with traffic in [from, to] (unix seconds), +// busiest first. svc filters by key or alias, host by served domain; both may be "". +func (s *Store) Services(from, to int64, svc, host string) []SvcView { + fh, lh := from/3600, to/3600 + fd, ld := from/86400, to/86400 + s.mu.RLock() + defer s.mu.RUnlock() + var out []SvcView + for key, d := range s.sv.m { + v := SvcView{Key: key, Alias: svcAlias(key, d)} + if svc != "" && svc != key && svc != v.Alias { + continue + } + if host != "" { + if _, ok := d.Doms[host]; !ok { + continue + } + } + for i := range d.Hours { + h := &d.Hours[i] + if h.Hour == 0 || h.Hour < fh || h.Hour > lh || h.Req == 0 { + continue + } + var o SvcHourOut + o.Hour = h.Hour + o.add(h) + v.Hours = append(v.Hours, o) + v.Tot.add(h) + } + if v.Tot.Req == 0 { + continue + } + sort.Slice(v.Hours, func(a, b int) bool { return v.Hours[a].Hour < v.Hours[b].Hour }) + for i := range d.Days { + dd := &d.Days[i] + if dd.Day == 0 || dd.Day < fd || dd.Day > ld { + continue + } + mergeMap(&v.ErrRoutes, dd.ErrRoutes) + mergeMap(&v.Broken, dd.Broken404) + mergeMap(&v.Methods, dd.Methods) + mergeMap(&v.Ciphers, dd.Ciphers) + mergeMap(&v.ProtoCls, dd.ProtoCls) + mergeMap(&v.TLSCls, dd.TLSCls) + for k, t := range dd.Last404 { + if v.BrokenLast == nil { + v.BrokenLast = map[string]int64{} + } + if t > v.BrokenLast[k] { + v.BrokenLast[k] = t + } + } + } + out = append(out, v) + } + sort.Slice(out, func(a, b int) bool { + if out[a].Tot.Req != out[b].Tot.Req { + return out[a].Tot.Req > out[b].Tot.Req + } + return out[a].Key < out[b].Key + }) + return out +} + +// svcAlias is the most frequent domain of the service, or the key itself. +func svcAlias(key string, d *svcData) string { + best, n := "", uint32(0) + for dom, c := range d.Doms { + if c > n || c == n && dom < best { + best, n = dom, c + } + } + if best == "" || best == "-" { + return key + } + return best +} + +// Quantile estimates the q-quantile (0..1) in milliseconds from a latency +// histogram laid out by SvcBounds (linear inside the bucket); 0 when empty. +func Quantile(h [svcLatN]uint32, q float64) float64 { + var tot float64 + for _, c := range h { + tot += float64(c) + } + if tot == 0 { + return 0 + } + target := q * tot + var acc float64 + lo := 0.0 + for i, c := range h { + up := SvcBounds[len(SvcBounds)-1] * 2 + if i < len(SvcBounds) { + up = SvcBounds[i] + } + if acc+float64(c) >= target && c > 0 { + return lo + (up-lo)*(target-acc)/float64(c) + } + acc += float64(c) + lo = up + } + return lo +} diff --git a/internal/store/services_test.go b/internal/store/services_test.go new file mode 100644 index 0000000..76c6e45 --- /dev/null +++ b/internal/store/services_test.go @@ -0,0 +1,95 @@ +package store + +import ( + "path/filepath" + "testing" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" +) + +func svcEv(status, origin int, path, ref string, ago time.Duration) core.Event { + return core.Event{Time: t0.Add(-ago), IP: "200.1.1.1", Cat: core.OK, Source: "traefik", Domain: "app.example.com", Method: "GET", Path: path, + UA: "Mozilla/5.0 x", Status: status, OriginStatus: origin, DurationNS: 40e6, OriginNS: 35e6, OverheadNS: 1e6, Referer: ref, + Router: "https-0-abc-app@docker", Service: "https-0-abc-app@docker", Proto: "HTTP/2.0", Scheme: "https", TLSVer: "1.3", TLSCiph: "TLS_AES_128_GCM_SHA256", + E: core.Enrich{Device: "desktop"}} +} + +func TestServicesAggregateAndSnapshot(t *testing.T) { + s := newStore("oracle", 100) + for i := 0; i < 10; i++ { + s.ObserveService(svcEv(200, 200, "/", "", time.Duration(i)*time.Minute)) + } + s.ObserveService(svcEv(500, 500, "/api/x/123456789012345678", "", time.Minute)) + s.ObserveService(svcEv(404, 404, "/old", "https://app.example.com/home", time.Minute)) + s.ObserveService(svcEv(404, 404, "/old", "https://app.example.com/home", time.Minute)) + atk := svcEv(404, 404, "/.env", "", time.Minute) + atk.Cat = core.Scanner + s.ObserveService(atk) + s.ObserveService(core.Event{Time: t0, Source: "ssh", IP: "1.1.1.1"}) // ignored + now := t0.Unix() + v := s.Services(now-86400, now, "", "") + if len(v) != 1 || v[0].Key != "https-0-abc-app" || v[0].Alias != "app.example.com" { + t.Fatalf("services %+v", v) + } + tot := v[0].Tot + if tot.Req != 14 || tot.Cls[ClsApp] != 1 || tot.Cls[ClsAttack] != 1 || tot.Cls[ClsClientBroken] != 2 || tot.Legit != 13 { + t.Fatalf("tot %+v", tot) + } + if tot.Proto[1] != 14 || tot.TLS[0] != 14 || tot.ApN == 0 { + t.Fatalf("proto/tls/apdex %+v", tot) + } + if q := Quantile(tot.Dur, 0.5); q < 25 || q > 50 { + t.Fatalf("p50 %v", q) + } + if len(v[0].Broken) != 1 || v[0].ErrRoutes["app|GET /api/x/:id"] != 1 { + t.Fatalf("maps %v %v", v[0].Broken, v[0].ErrRoutes) + } + if got := s.Services(now-86400, now, "nope", ""); len(got) != 0 { + t.Fatal("filter") + } + if got := s.Services(now-86400, now, "", "app.example.com"); len(got) != 1 { + t.Fatal("host filter") + } + path := filepath.Join(t.TempDir(), "snap") + if err := s.Save(path, nil); err != nil { + t.Fatal(err) + } + s2 := newStore("oracle", 100) + if _, err := s2.Load(path); err != nil { + t.Fatal(err) + } + if v2 := s2.Services(now-86400, now, "", ""); len(v2) != 1 || v2[0].Tot.Req != 14 { + t.Fatalf("after load %+v", v2) + } +} + +func TestServiceCap(t *testing.T) { + s := newStore("oracle", 100) + for i := 0; i < svcCap+10; i++ { + e := svcEv(200, 200, "/", "", time.Minute) + e.Service = "svc" + string(rune('a'+i%26)) + string(rune('a'+i/26)) + s.ObserveService(e) + } + if n := len(s.sv.m); n > svcCap+1 { + t.Fatalf("services %d", n) + } +} + +func TestCancelledIsNotServerError(t *testing.T) { + s := newStore("oracle", 100) + for i := 0; i < 5; i++ { + s.ObserveService(svcEv(499, 0, "/x", "", time.Minute)) + } + e := svcEv(200, 200, "/", "", time.Minute) + s.ObserveService(e) + run := svcEv(404, 404, "/api/actions/runner.v1.RunnerService/FetchTask", "", time.Minute) + run.Method, run.UA, run.Cat = "POST", "connect-go/1.16", core.Scanner + s.ObserveService(run) + now := t0.Unix() + v := s.Services(now-86400, now, "", "") + tot := v[0].Tot + if tot.Cls[ClsApp] != 0 || tot.Cls[ClsProxy] != 0 || tot.Cls[ClsAttack] != 0 || tot.Cls[ClsClientOther] != 5 || tot.Cls[ClsClientAuth] != 1 { + t.Fatalf("cls %+v", tot.Cls) + } +} diff --git a/internal/store/snapshot.go b/internal/store/snapshot.go index ffe9e59..513dedb 100644 --- a/internal/store/snapshot.go +++ b/internal/store/snapshot.go @@ -29,6 +29,8 @@ type snapshot struct { MonSt [slots]int64 MonN [slots]uint32 Dom map[string]*domData + GDays [anDays]gDay + Svc map[string]*svcData // service health (optional: older snapshots lack it) IPs map[string]*IPRec Recent []FeedEvent Rhead int @@ -71,7 +73,7 @@ func (s *Store) Save(path string, offsets map[string]Offset) error { } bw := bufio.NewWriterSize(f, 256*1024) s.mu.RLock() - snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, Dom: s.tr.dom, + snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, Dom: s.tr.dom, GDays: s.tr.gdays, Svc: s.sv.m, IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets, IDSeq: s.ids.Load()} err = gob.NewEncoder(bw).Encode(&snap) s.mu.RUnlock() @@ -122,7 +124,8 @@ func (s *Store) Load(path string) (map[string]Offset, error) { s.mu.Lock() s.stamps, s.counts, s.hours = snap.Stamps, snap.Counts, snap.Hours s.monSt, s.monN = snap.MonSt, snap.MonN - s.tr.dom = snap.Dom + s.tr.dom, s.tr.gdays = snap.Dom, snap.GDays + s.sv.m = snap.Svc for _, d := range s.tr.dom { if d != nil && d.Last == 0 { // snapshot written before Last existed: never prune on the first pass diff --git a/internal/store/store.go b/internal/store/store.go index 355ff49..cb40153 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -232,6 +232,7 @@ type Store struct { monSt [slots]int64 monN [slots]uint32 tr trafficState + sv svcState allow []string ips map[string]*IPRec recent []FeedEvent @@ -240,6 +241,7 @@ type Store struct { smu sync.Mutex subs map[chan FeedEvent]struct{} + vis visitState rdns RDNS enr core.Enricher diff --git a/internal/store/techniques.go b/internal/store/techniques.go new file mode 100644 index 0000000..78110a2 --- /dev/null +++ b/internal/store/techniques.go @@ -0,0 +1,169 @@ +package store + +import ( + "sort" + "strings" + "time" + + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog" + "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" +) + +// TechniqueRow is one MITRE ATT&CK technique seen in the window. +type TechniqueRow struct { + ID string `json:"id"` + Name string `json:"name"` + Events int `json:"events"` + IPs int `json:"ips"` + First int64 `json:"first"` + Last int64 `json:"last"` + TrendPct *float64 `json:"trend_pct"` // against the previous window of the same length; null without one +} + +// TacticRow groups the techniques of one tactic. +type TacticRow struct { + ID string `json:"id"` + Name string `json:"name"` + Techniques []TechniqueRow `json:"techniques"` +} + +// TechniquesOut is the matrix behind GET /api/v1/techniques. +type TechniquesOut struct { + Enabled bool `json:"enabled"` + Truncated bool `json:"truncated,omitempty"` + Tactics []TacticRow `json:"tactics"` + Total int `json:"total"` // events that carry at least one technique +} + +type tactic struct{ id, name string } + +// ATT&CK enterprise tactics in matrix order. +var tacticOrder = []tactic{ + {"TA0043", "Reconnaissance"}, {"TA0042", "Resource Development"}, {"TA0001", "Initial Access"}, + {"TA0002", "Execution"}, {"TA0003", "Persistence"}, {"TA0004", "Privilege Escalation"}, + {"TA0005", "Defense Evasion"}, {"TA0006", "Credential Access"}, {"TA0007", "Discovery"}, + {"TA0008", "Lateral Movement"}, {"TA0009", "Collection"}, {"TA0011", "Command and Control"}, + {"TA0010", "Exfiltration"}, {"TA0040", "Impact"}, +} + +// techTactic maps a technique id to the tactic id the matrix puts it under. +var techTactic = map[string]string{ + "T1190": "TA0001", "T1078": "TA0001", "T1133": "TA0001", "T1566": "TA0001", + "T1059": "TA0002", "T1203": "TA0002", + "T1505": "TA0003", "T1098": "TA0003", + "T1110": "TA0006", "T1552": "TA0006", "T1555": "TA0006", "T1528": "TA0006", + "T1083": "TA0007", "T1087": "TA0007", "T1082": "TA0007", "T1046": "TA0007", "T1018": "TA0007", + "T1213": "TA0009", "T1005": "TA0009", "T1530": "TA0009", + "T1595": "TA0043", "T1592": "TA0043", "T1590": "TA0043", "T1589": "TA0043", "T1593": "TA0043", + "T1105": "TA0011", "T1071": "TA0011", + "T1499": "TA0040", "T1498": "TA0040", +} + +// TacticOf returns the tactic id of a technique or sub-technique ("" when unknown). +func TacticOf(id string) string { + if t, ok := techTactic[id]; ok { + return t + } + if i := strings.IndexByte(id, '.'); i > 0 { + return techTactic[id[:i]] + } + return "" +} + +type techAcc struct { + cur, prev int + ips map[string]struct{} + first, last int64 +} + +// Techniques groups the techniques observed in [q.From, q.To] by MITRE +// tactic, with the trend against the previous window of the same length. +// Same caps, deadline and 30 s cache as Period. +func (s *Store) Techniques(q PeriodQuery) TechniquesOut { + k := studyKey{kind: "techniques", from: q.From, to: q.To, host: q.Host} + return s.cached(k, func() any { return s.techniques(q) }).(TechniquesOut) +} + +func (s *Store) techniques(q PeriodQuery) TechniquesOut { + out := TechniquesOut{Tactics: []TacticRow{}} + if s.elog == nil { + return out + } + out.Enabled = true + span := q.To - q.From + if span < 1 { + span = 1 + } + deadline := time.Now().Add(studyDead) + acc := map[string]*techAcc{} + n := 0 + info := s.elog.Scan(evlog.Filter{From: q.From - span, To: q.To, Host: q.Host}, studyBudget, false, + func(r evlog.Rec, _ []byte) bool { + if n++; n > maxStudyEvents || n%4096 == 0 && time.Now().After(deadline) { + out.Truncated = true + return false + } + if len(r.Tech) == 0 { + return true + } + inCur := r.T >= q.From + if inCur { + out.Total++ + } + for _, id := range r.Tech { + a := acc[id] + if a == nil { + a = &techAcc{ips: map[string]struct{}{}} + acc[id] = a + } + if !inCur { + a.prev++ + continue + } + a.cur++ + a.ips[KeyOf(r.IP)] = struct{}{} + if a.first == 0 || r.T < a.first { + a.first = r.T + } + if r.T > a.last { + a.last = r.T + } + } + return true + }) + out.Truncated = out.Truncated || info.Truncated + by := map[string][]TechniqueRow{} + for id, a := range acc { + if a.cur == 0 { + continue + } + name := intel.TechniqueName(id) + if name == "" { + name = id + } + row := TechniqueRow{ID: id, Name: name, Events: a.cur, IPs: len(a.ips), First: a.first, Last: a.last} + if a.prev > 0 { + v := float64(a.cur-a.prev) / float64(a.prev) * 100 + row.TrendPct = &v + } + by[TacticOf(id)] = append(by[TacticOf(id)], row) + } + add := func(t tactic) { + rows := by[t.id] + if len(rows) == 0 { + return + } + sort.Slice(rows, func(i, j int) bool { + if rows[i].Events != rows[j].Events { + return rows[i].Events > rows[j].Events + } + return rows[i].ID < rows[j].ID + }) + out.Tactics = append(out.Tactics, TacticRow{ID: t.id, Name: t.name, Techniques: rows}) + } + for _, t := range tacticOrder { + add(t) + } + add(tactic{"", "Other"}) + return out +} diff --git a/internal/store/traffic.go b/internal/store/traffic.go index 0022ff9..74b6e3e 100644 --- a/internal/store/traffic.go +++ b/internal/store/traffic.go @@ -11,10 +11,19 @@ import ( "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" ) -// Privacy: legitimate visitors are never stored. A visitor is the 64-bit -// prefix of SHA-256(salt | ip | user-agent | domain) kept in memory only while -// its UTC day lasts; the salt is random per process and per day, so hashes -// cannot be linked across days, and nothing here reaches a snapshot or the API. +// Privacy: visitors are never stored. A visitor is the 64-bit prefix of +// SHA-256(salt | ip | domain) (SHA-256(salt | ip) for the all-domains total) +// kept in memory only while its UTC day lasts; the salt is random per process +// and per day, so hashes cannot be linked across days, and nothing here +// reaches a snapshot or the API. +// +// A visitor is a person with a real browser: a GET 2xx of a document by a +// browser User-Agent (not a bot, tool or unknown client), not a prefetch and, +// when the browser says so, with Sec-Fetch-Dest "document". The key leaves the +// User-Agent out on purpose: scrapers rotate it per request from one address +// (a measured 2.7x inflation), a person's browser does not. Everything else +// that talks to a site (bots, tools, unknown or empty User-Agents) is counted +// apart as non-human clients. const ( anMinutes = 49 * 60 // minute buckets (48 h plus one hour of margin) @@ -38,7 +47,7 @@ type anHour struct { type anDay struct { Day int64 - Visitors uint32 + Visitors, NonHuman uint32 Pages, Refs, Countries, Cities, Browsers, OSes, Devices, Bots map[string]uint32 } @@ -51,13 +60,24 @@ type domData struct { Last int64 // unix time of the last request, for pruning idle domains // in memory only, never in a snapshot (unexported fields are skipped by gob) vis map[uint64]struct{} + nh map[uint64]struct{} visDay int64 } +// gDay is the all-domains daily total: one person on two sites counts once. +type gDay struct { + Day int64 + Visitors, NonHuman uint32 +} + type trafficState struct { dom map[string]*domData + gdays [anDays]gDay salt [16]byte saltDay int64 + // in memory only + gvis, gnh map[uint64]struct{} + gvisDay int64 } var assetExt = map[string]bool{ @@ -67,8 +87,33 @@ var assetExt = map[string]bool{ "zip": true, "gz": true, "wasm": true, "bmp": true, "webmanifest": true, "rss": true, "atom": true, } +// isHuman reports whether the User-Agent belongs to a real browser. +func isHuman(e core.Enrich) bool { + if e.Bot || e.Tool { + return false + } + switch e.Device { + case "desktop", "mobile", "tablet": + return true + } + return false +} + +func isAssetPath(p string) bool { + if i := strings.IndexAny(p, "?#"); i >= 0 { + p = p[:i] + } + i := strings.LastIndexByte(p, '.') + return i >= 0 && i > strings.LastIndexByte(p, '/') && assetExt[strings.ToLower(p[i+1:])] +} + func isPageView(ev core.Event) bool { - if ev.Method != "GET" || ev.Status < 200 || ev.Status > 299 { + if ev.Method != "GET" || ev.Status < 200 || ev.Status > 299 || ev.Prefetch { + return false + } + // A browser that says what it is fetching: only a navigation is a page + // (fetch/XHR is "empty", frames "iframe"). No header: cannot tell, accept. + if d := ev.FetchDest; d != "" && d != "document" { return false } p := ev.Path @@ -170,15 +215,59 @@ func (s *Store) domLocked(name string, status int) *domData { var uuidRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) +// readableSlug reports a human URL slug: lowercase words and numbers joined by +// "-" (blog-post-title-2024). Those are kept even when long. +func readableSlug(s string) bool { + for _, word := range strings.Split(s, "-") { + if word == "" || len(word) > 16 { + return false + } + for _, r := range word { + if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9') { + return false + } + } + } + return true +} + +// mixedToken reports the shape of a token or opaque identifier: letters and +// "-_." only, and either digits mixed with letters, mixed case, or "_"/".". +func mixedToken(s string) bool { + var lower, upper, digits, punct bool + for _, r := range s { + switch { + case r >= '0' && r <= '9': + digits = true + case r >= 'a' && r <= 'z': + lower = true + case r >= 'A' && r <= 'Z': + upper = true + case r == '_' || r == '.': + punct = true + case r == '-': + default: + return false + } + } + letters := lower || upper + return letters && (digits || (lower && upper) || punct) +} + // normalizePath turns token-like path segments (UUIDs, long hex or mixed // alphanumeric ids, long numbers) into ":id" so a top-pages list is not // filled by one-off URLs and a token in a URL is not kept. func normalizePath(p string) string { - if !strings.ContainsAny(p, "0123456789") { - return p - } parts := strings.Split(p, "/") for i, seg := range parts { + // personal or secret-looking segments: e-mail addresses, long opaque + // values, and mixed letter+digit tokens (reset links, invites, ids) + if strings.Contains(seg, "@") || len(seg) >= 48 || + (len(seg) >= 24 && !readableSlug(seg)) || + (len(seg) >= 12 && !readableSlug(seg) && mixedToken(seg)) { + parts[i] = ":id" + continue + } if len(seg) >= 16 && uuidRe.MatchString(seg) { parts[i] = ":id" continue @@ -233,6 +322,9 @@ func (s *Store) Traffic(ev core.Event) { return } d.Last = ts + if !isAssetPath(ev.Path) { + s.emitVisit(ts, dom, ev.Path, ev.IP, ev.Status, ev.E.Device, ev.E.Bot, ev.E.Tool) + } m := ts / 60 mi := int(m % anMinutes) @@ -259,13 +351,54 @@ func (s *Store) Traffic(ev core.Event) { if dd.Day != day { *dd = anDay{Day: day} } - if ev.E.Bot { - hs.Bots++ - name := ev.E.BotName - if name == "" { - name = "bot" + // per-day hash state (the salt changes every UTC day) + if s.tr.saltDay != day { + rand.Read(s.tr.salt[:]) + s.tr.saltDay = day + } + fresh := d.visDay == day && d.vis != nil + if !fresh { + if day < d.visDay { + fresh = false // older than the day being counted (out of order) + } else { + d.vis, d.nh, d.visDay = make(map[uint64]struct{}, 64), make(map[uint64]struct{}, 16), day + fresh = true + } + } + gfresh := s.tr.gvisDay == day && s.tr.gvis != nil + if !gfresh && day >= s.tr.gvisDay { + s.tr.gvis, s.tr.gnh, s.tr.gvisDay = make(map[uint64]struct{}, 256), make(map[uint64]struct{}, 64), day + gfresh = true + } + gd := &s.tr.gdays[int(day%anDays)] + if gd.Day != day { + *gd = gDay{Day: day} + } + kd, kg := s.visitorKey(ev.IP, dom), s.visitorKey(ev.IP, "") + + human := isHuman(ev.E) + if !human { + // bots, tools, unknown or empty User-Agents: never a visitor or a page + if ev.E.Bot { + hs.Bots++ + name := ev.E.BotName + if name == "" { + name = "bot" + } + bumpCap(&dd.Bots, name, anTop) + } + if fresh { + if _, seen := d.nh[kd]; !seen && len(d.nh) < visCap { + d.nh[kd] = struct{}{} + dd.NonHuman++ + } + } + if gfresh { + if _, seen := s.tr.gnh[kg]; !seen && len(s.tr.gnh) < visCap*4 { + s.tr.gnh[kg] = struct{}{} + gd.NonHuman++ + } } - bumpCap(&dd.Bots, name, anTop) return } if !isPageView(ev) { @@ -280,34 +413,19 @@ func (s *Store) Traffic(ev core.Event) { bumpCap(&dd.Pages, normalizePath(p), anTop) bumpCap(&dd.Refs, refHost(ev.Referer, dom), anTop) - // unique visitor, today's salt - if s.tr.saltDay != day { - rand.Read(s.tr.salt[:]) - s.tr.saltDay = day - } - if d.visDay != day || d.vis == nil { - if day < d.visDay { - return // older than the day being counted (out of order): no visitor accounting + if gfresh { + if _, seen := s.tr.gvis[kg]; !seen && len(s.tr.gvis) < visCap*4 { + s.tr.gvis[kg] = struct{}{} + gd.Visitors++ } - d.vis, d.visDay = make(map[uint64]struct{}, 64), day } - hsum := sha256.New() - hsum.Write(s.tr.salt[:]) - hsum.Write([]byte(ev.IP)) - hsum.Write([]byte{0}) - hsum.Write([]byte(ev.UA)) - hsum.Write([]byte{0}) - hsum.Write([]byte(dom)) - var sum [32]byte - hsum.Sum(sum[:0]) - var key uint64 - for i := 0; i < 8; i++ { - key = key<<8 | uint64(sum[i]) - } - if _, seen := d.vis[key]; seen || len(d.vis) >= visCap { + if !fresh { return } - d.vis[key] = struct{}{} + if _, seen := d.vis[kd]; seen || len(d.vis) >= visCap { + return + } + d.vis[kd] = struct{}{} dd.Visitors++ if ev.E.CC != "" { bumpCap(&dd.Countries, ev.E.CC, 300) @@ -324,6 +442,22 @@ func (s *Store) Traffic(ev core.Event) { bumpCap(&dd.Devices, orUnknown(ev.E.Device), 10) } +// visitorKey is the 64-bit prefix of SHA-256(salt | ip | domain) with today's salt. +func (s *Store) visitorKey(ip, dom string) uint64 { + h := sha256.New() + h.Write(s.tr.salt[:]) + h.Write([]byte(ip)) + h.Write([]byte{0}) + h.Write([]byte(dom)) + var sum [32]byte + h.Sum(sum[:0]) + var key uint64 + for i := 0; i < 8; i++ { + key = key<<8 | uint64(sum[i]) + } + return key +} + func max64(a, b int64) int64 { if a > b { return a @@ -348,6 +482,7 @@ type TrafficData struct { Requests uint64 `json:"requests"` Pages uint64 `json:"pages"` Visitors uint64 `json:"visitors"` + NonHuman uint64 `json:"nonhuman"` // distinct non-human clients (bots, tools, unknown), apart from visitors Bots uint64 `json:"bots"` Bytes uint64 `json:"bytes"` Status [4]uint64 `json:"status"` @@ -422,6 +557,7 @@ func (s *Store) TrafficFor(rg Range, domain string) TrafficData { firstDay, lastDay := from/86400, to/86400 maps := [8]map[string]uint32{{}, {}, {}, {}, {}, {}, {}, {}} domReq := map[string]uint32{} + domVis, domNH := map[int64]uint64{}, map[int64]uint64{} s.mu.RLock() for name, d := range s.tr.dom { @@ -475,7 +611,8 @@ func (s *Store) TrafficFor(rg Range, domain string) TrafficData { if dd.Day == 0 || dd.Day < firstDay || dd.Day > lastDay { continue } - out.Visitors += uint64(dd.Visitors) + domVis[dd.Day] += uint64(dd.Visitors) + domNH[dd.Day] += uint64(dd.NonHuman) for k, src := range [8]map[string]uint32{dd.Pages, dd.Refs, dd.Countries, dd.Cities, dd.Browsers, dd.OSes, dd.Devices, dd.Bots} { for key, v := range src { maps[k][key] += v @@ -483,6 +620,24 @@ func (s *Store) TrafficFor(rg Range, domain string) TrafficData { } } } + if out.Domain == "all" { + // all domains: a person (or bot) seen on two sites the same day counts once + for day := firstDay; day <= lastDay; day++ { + gd := s.tr.gdays[int(day%anDays)] + if gd.Day == day { + out.Visitors += uint64(gd.Visitors) + out.NonHuman += uint64(gd.NonHuman) + } else { // day recorded before the global total existed + out.Visitors += domVis[day] + out.NonHuman += domNH[day] + } + } + } else { + for day := firstDay; day <= lastDay; day++ { + out.Visitors += domVis[day] + out.NonHuman += domNH[day] + } + } s.mu.RUnlock() for name, n := range domReq { @@ -520,6 +675,7 @@ func MergeTraffic(host string, parts []TrafficData) TrafficData { out.Requests += p.Requests out.Pages += p.Pages out.Visitors += p.Visitors + out.NonHuman += p.NonHuman out.Bots += p.Bots out.Bytes += p.Bytes for i := range p.Status { diff --git a/internal/store/traffic_test.go b/internal/store/traffic_test.go index 8c86210..7f5e6a2 100644 --- a/internal/store/traffic_test.go +++ b/internal/store/traffic_test.go @@ -141,3 +141,151 @@ func TestToolBonusAndCountries(t *testing.T) { t.Fatalf("countries %+v", c) } } + +func browser(ip, dom, path string) core.Event { + return visit(ip, dom, path, "", 200, time.Minute) +} + +func TestVisitorsAreRealBrowsersCountedByAddress(t *testing.T) { + s := newStore("oracle", 100) + // a scraper rotating the User-Agent from one address is one visitor, not five + for i := 0; i < 5; i++ { + ev := browser("200.100.50.30", "a.example", "/p") + ev.UA = "Mozilla/5.0 rotating " + string(rune('a'+i)) + s.Traffic(ev) + } + // the same person on two sites counts once in the all-domains total + s.Traffic(browser("200.100.50.31", "a.example", "/")) + s.Traffic(browser("200.100.50.31", "b.example", "/")) + // fetch/XHR, prefetch, HEAD: not pages, not visitors + api := browser("200.100.50.32", "a.example", "/api/v1/summary") + api.FetchDest = "empty" + s.Traffic(api) + pre := browser("200.100.50.33", "a.example", "/next") + pre.Prefetch = true + s.Traffic(pre) + head := browser("200.100.50.34", "a.example", "/") + head.Method = "HEAD" + s.Traffic(head) + doc := browser("200.100.50.35", "a.example", "/doc") + doc.FetchDest = "document" + s.Traffic(doc) + // tools, unknown and empty User-Agents, and bots: non-human clients + for i, e := range []core.Enrich{ + {Device: "tool", Tool: true}, {Device: "unknown"}, {}, {Bot: true, BotName: "Googlebot", Device: "bot"}, + } { + ev := browser("66.249.66."+string(rune('1'+i)), "a.example", "/") + ev.E = e + s.Traffic(ev) + } + other := browser("66.249.66.1", "b.example", "/") // same bot on a second site + other.E = core.Enrich{Bot: true, Device: "bot"} + s.Traffic(other) + + all := s.TrafficSummary("24h", "all") + if all.Visitors != 3 { // .30, .31, .35 + t.Fatalf("all visitors = %d, want 3", all.Visitors) + } + if all.NonHuman != 4 { // four distinct addresses; the bot seen on two sites counts once + t.Fatalf("all non-human = %d, want 4", all.NonHuman) + } + if a := s.TrafficSummary("24h", "a.example"); a.Visitors != 3 || a.NonHuman != 4 || a.Pages != 7 { + t.Fatalf("a.example: visitors=%d nonhuman=%d pages=%d", a.Visitors, a.NonHuman, a.Pages) + } + if b := s.TrafficSummary("24h", "b.example"); b.Visitors != 1 || b.NonHuman != 1 { + t.Fatalf("b.example: visitors=%d nonhuman=%d", b.Visitors, b.NonHuman) + } +} + +func TestNonHumanSurvivesSnapshotAndMerge(t *testing.T) { + s := newStore("oracle", 100) + bot := browser("66.249.66.9", "a.example", "/") + bot.E = core.Enrich{Device: "tool", Tool: true} + s.Traffic(bot) + s.Traffic(browser("200.100.50.40", "a.example", "/")) + a := s.TrafficSummary("24h", "all") + m := MergeTraffic("all", []TrafficData{a, a}) + if a.NonHuman != 1 || a.Visitors != 1 || m.NonHuman != 2 || m.Visitors != 2 { + t.Fatalf("a=%+v m=%+v", a, m) + } +} + +type visGeo struct{} + +func (visGeo) Geo(ip string) core.GeoInfo { + return core.GeoInfo{CC: "BR", City: "Recife", Lat: -8.0476, Lon: -34.877} +} +func (visGeo) UA(string) core.UAInfo { return core.UAInfo{} } + +func TestVisitEventsHaveNoAddressAndAreRateLimited(t *testing.T) { + s := newStore("oracle", 100) + s.SetEnricher(visGeo{}) + // without subscribers nothing is built or kept + s.Traffic(browser("200.100.50.60", "a.example", "/x")) + ch, stop := s.SubscribeVisits() + defer stop() + ev := browser("200.100.50.61", "a.example", "/u/123e4567-e89b-12d3-a456-426614174000?token=secret") + ev.Referer = "https://ref.example/?q=1" + s.Traffic(ev) + asset := browser("200.100.50.61", "a.example", "/s.css") + s.Traffic(asset) // assets are not visits + m := <-ch + b, _ := json.Marshal(m) + for _, bad := range []string{"200.100.50", `"ip"`, "Mozilla", "ref.example", "secret", "123e4567"} { + if bytes.Contains(b, []byte(bad)) { + t.Fatalf("visit leaks %q: %s", bad, b) + } + } + if m.Kind != "visit" || m.Host != "oracle" || m.Domain != "a.example" || m.Device != "desktop" || m.Status != 200 || + m.Path != "/u/:id" || m.Src == nil || m.Src.Lat != -8.0 || m.Src.Lon != -34.9 || m.Src.CC != "BR" { + t.Fatalf("visit %s", b) + } + select { + case x := <-ch: + t.Fatalf("unexpected extra event %+v", x) + default: + } + // 50 in one second: 20 pass (the first already used 1), the rest is dropped, then a batch + for i := 0; i < 50; i++ { + s.Traffic(browser("200.100.50.62", "a.example", "/p")) + } + s.now = func() time.Time { return t0.Add(time.Hour) } + late := browser("200.100.50.63", "a.example", "/p") + late.Time = t0.Add(time.Hour) + s.Traffic(late) + visits, batch := 0, 0 + for len(ch) > 0 { + x := <-ch + bb, _ := json.Marshal(x) + if bytes.Contains(bb, []byte(`"ip"`)) { + t.Fatalf("ip in %s", bb) + } + switch x.Kind { + case "visit": + visits++ + case "visit_batch": + batch += x.N + } + } + if visits != 20 || batch != 31 { // 19 left of the first second + 1 new second; 31 dropped + t.Fatalf("visits=%d dropped=%d", visits, batch) + } +} + +func TestVisitSanitizeFromPeer(t *testing.T) { + m := VisitMsg{Kind: "visit", T: 1, Domain: "d", Path: "/a\x01b", Device: "", Src: &GeoPoint{Lat: 500}} + if !m.Sanitize(t0.Unix()) || m.Device != "unknown" || m.Src != nil || m.Path != "/ab" { + t.Fatalf("%+v", m) + } + if (&VisitMsg{Kind: "ev"}).Sanitize(1) { + t.Fatal("unknown kind accepted") + } + var raw map[string]any + json.Unmarshal([]byte(`{"kind":"visit","ip":"1.2.3.4"}`), &raw) + var v VisitMsg + json.Unmarshal([]byte(`{"kind":"visit","ip":"1.2.3.4"}`), &v) + b, _ := json.Marshal(v) + if bytes.Contains(b, []byte("1.2.3.4")) { + t.Fatal("ip survived a round trip") + } +} diff --git a/internal/store/traffic_visits.go b/internal/store/traffic_visits.go new file mode 100644 index 0000000..d24f6e4 --- /dev/null +++ b/internal/store/traffic_visits.go @@ -0,0 +1,145 @@ +package store + +import ( + "math" + "strings" + "sync" +) + +// Live legitimate visits. Privacy: a visit event carries NO address, User-Agent +// or referrer; the source is the aggregated geography of the city (coordinates +// rounded to one decimal, about 11 km). It is only broadcast to subscribers +// (SSE ?visits=1), never written to the event log, a snapshot or live/recent. + +// visitRate is the ceiling of visit events per second and instance; the excess +// is dropped and summarised by one visit_batch per second. +const visitRate = 20 + +// VisitMsg is a "visit" (one request) or a "visit_batch" (n dropped). +type VisitMsg struct { + Kind string `json:"kind"` + T int64 `json:"t"` + N int `json:"n,omitempty"` + Host string `json:"host,omitempty"` + Domain string `json:"domain,omitempty"` + Path string `json:"path,omitempty"` + Status int `json:"status,omitempty"` + Device string `json:"device,omitempty"` + Src *GeoPoint `json:"src,omitempty"` + Dst *Location `json:"dst,omitempty"` +} + +type visitState struct { + mu sync.Mutex + subs map[chan VisitMsg]struct{} + sec int64 + sent int + dropped int +} + +// SubscribeVisits returns the live visit events of this instance. +func (s *Store) SubscribeVisits() (<-chan VisitMsg, func()) { + ch := make(chan VisitMsg, 64) + s.vis.mu.Lock() + if s.vis.subs == nil { + s.vis.subs = map[chan VisitMsg]struct{}{} + } + s.vis.subs[ch] = struct{}{} + s.vis.mu.Unlock() + return ch, func() { + s.vis.mu.Lock() + delete(s.vis.subs, ch) + s.vis.mu.Unlock() + } +} + +func roundCoord(v float64) float64 { return math.Round(v*10) / 10 } + +var visitDevices = map[string]bool{"desktop": true, "mobile": true, "tablet": true, "bot": true, "tool": true} + +func visitPath(p string) string { + if i := strings.IndexAny(p, "?#"); i >= 0 { + p = p[:i] + } + return clipS(normalizePath(p), 120) +} + +// emitVisit broadcasts one legitimate request to the visit subscribers. +// Called with s.mu held; it never blocks and costs nothing without subscribers. +func (s *Store) emitVisit(ts int64, dom, path, ip string, status int, device string, bot, tool bool) { + v := &s.vis + v.mu.Lock() + defer v.mu.Unlock() + if len(v.subs) == 0 { + return + } + if ts != v.sec { + if v.dropped > 0 { + s.fanVisit(VisitMsg{Kind: "visit_batch", T: v.sec, N: v.dropped, Host: s.cfg.Name}) + } + v.sec, v.sent, v.dropped = ts, 0, 0 + } + if v.sent >= visitRate { + v.dropped++ + return + } + v.sent++ + switch { + case bot: + device = "bot" + case tool: + device = "tool" + case !visitDevices[device]: + device = "unknown" + } + m := VisitMsg{Kind: "visit", T: ts, Host: s.cfg.Name, Domain: clipS(dom, 100), Path: visitPath(path), Status: status, Device: device, Dst: s.Location()} + if g := s.GeoOf(ip); (g.Lat != 0 || g.Lon != 0) && validLatLon(g.Lat, g.Lon) { + m.Src = &GeoPoint{Lat: roundCoord(g.Lat), Lon: roundCoord(g.Lon), CC: validCC2(g.CC), City: clipS(g.City, 80)} + } + s.fanVisit(m) +} + +func (s *Store) fanVisit(m VisitMsg) { + for ch := range s.vis.subs { + select { + case ch <- m: + default: // slow client: drop + } + } +} + +// Sanitize validates a visit event received from a peer (it has no address +// field, and anything unknown is dropped); false means: discard it. +func (m *VisitMsg) Sanitize(now int64) bool { + if m.Kind != "visit" && m.Kind != "visit_batch" { + return false + } + if m.T <= 0 || m.T > now+300 || m.T < now-3600 { + m.T = now + } + if m.Kind == "visit_batch" { + if m.N < 0 || m.N > 1<<20 { + return false + } + *m = VisitMsg{Kind: m.Kind, T: m.T, N: m.N} + return true + } + m.N = 0 + // a peer's visit path is normalized again here: never trust it to have done so + m.Domain, m.Path = clipS(m.Domain, 100), clipS(normalizePath(m.Path), 120) + if m.Status < 0 || m.Status > 999 { + m.Status = 0 + } + if !visitDevices[m.Device] { + m.Device = "unknown" + } + if m.Src != nil { + if !validLatLon(m.Src.Lat, m.Src.Lon) { + m.Src = nil + } else { + m.Src = &GeoPoint{Lat: roundCoord(m.Src.Lat), Lon: roundCoord(m.Src.Lon), CC: validCC2(clipS(m.Src.CC, 2)), City: clipS(m.Src.City, 80)} + } + } + m.Dst = sanitizeLocation(m.Dst) + return true +} diff --git a/pid b/pid new file mode 100644 index 0000000..09c0b0d --- /dev/null +++ b/pid @@ -0,0 +1 @@ +892731 diff --git a/scripts/ui-overflow.mjs b/scripts/ui-overflow.mjs index 93c8410..6840e50 100644 --- a/scripts/ui-overflow.mjs +++ b/scripts/ui-overflow.mjs @@ -56,7 +56,7 @@ for (let i = 0; i < 50; i++) { try { if ((await fetch(base + '/api/health')).ok) let ip = bad[0]; try { const j = await (await fetch(base + '/api/v1/ips?per=1')).json(); if (j.items?.[0]) ip = j.items[0].ip; } catch { /* default */ } -const routes = ['overview', 'threats', 'geo', 'live', 'replay', 'traffic', 'ips', 'sources', 'ip/' + ip]; +const routes = ['overview', 'threats', 'geo', 'live', 'replay', 'traffic', 'ips', 'sources', 'ip/' + ip, 'sessions', 'campaigns', 'search', 'mitre', 'defense', 'evolution', 'concentration', 'survival', 'errors', 'slo', 'protocol', 'integrity', 'reports']; const sizes = [[1440, 900], [1024, 768], [768, 1024], [390, 844]]; const failures = []; const browser = await puppeteer.launch({ executablePath: chrome, args: ['--no-sandbox'] });