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

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

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

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

199 lines
6.4 KiB
Go

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
}