Files
urutau/internal/core/parse.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

216 lines
7.8 KiB
Go

package core
import (
"encoding/json"
"errors"
"net/netip"
"regexp"
"strings"
"time"
)
// ErrIgnored means a line is valid but carries nothing to record.
var ErrIgnored = errors.New("ignored")
const (
maxPath = 240
maxUA = 200
maxDomain = 100
)
func clip(s string, n int) string {
s = strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7f {
return -1
}
return r
}, s)
if len(s) > n {
s = strings.ToValidUTF8(s[:n], "")
}
return s
}
func cleanIP(s string) (string, bool) {
a, err := netip.ParseAddr(strings.TrimSpace(s))
if err != nil || a.Zone() != "" {
return "", false // a zone ("%eth0") never appears in a client address and is an injection vector
}
return a.Unmap().String(), true
}
type traefikLine struct {
ClientHost string `json:"ClientHost"`
Host string `json:"RequestHost"`
Method string `json:"RequestMethod"`
Path string `json:"RequestPath"`
Status int `json:"DownstreamStatus"`
StartUTC string `json:"StartUTC"`
Time string `json:"time"`
UA string `json:"request_User-Agent"`
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.
func ParseTraefik(line []byte) (Event, error) {
var l traefikLine
if err := json.Unmarshal(line, &l); err != nil {
return Event{}, err
}
ip, ok := cleanIP(l.ClientHost)
if !ok {
return Event{}, ErrIgnored
}
ts := l.StartUTC
if ts == "" {
ts = l.Time
}
t, err := time.Parse(time.RFC3339Nano, ts)
if err != nil {
return Event{}, err
}
ev := Event{
Time: t.UTC(), IP: ip, Source: "traefik", Status: l.Status,
Domain: clip(strings.ToLower(l.Host), maxDomain),
Method: clip(l.Method, 12),
Path: clip(l.Path, maxPath),
UA: clip(l.UA, maxUA),
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
}
var subresourceDest = map[string]bool{
"image": true, "script": true, "style": true, "font": true, "iframe": true, "frame": true, "embed": true,
"object": true, "audio": true, "video": true, "track": true, "worker": true, "sharedworker": true,
"serviceworker": true, "manifest": true, "report": true, "xslt": true, "paintworklet": true, "audioworklet": true,
}
// Framed reports whether the Sec-Fetch-* headers say a browser sent the request
// on behalf of another site or as a subresource (an <img src=.../etc/passwd> on
// a third party page). Attack tools do not send these headers.
func Framed(site, dest string) bool {
site, dest = strings.ToLower(strings.TrimSpace(site)), strings.ToLower(strings.TrimSpace(dest))
return site == "cross-site" || site == "same-site" || subresourceDest[dest]
}
const sshTail = `(?: ssh2(?:: .*)?)?(?: \[preauth\])?$`
// The user name is attacker controlled ("ssh 'a from 1.2.3.4 port 1 x'@host"),
// so every rule that carries a user is anchored at the END of the message and
// takes the user greedily: the address is always the last "from IP port N".
var sshRules = []struct {
re *regexp.Regexp
cat Category
user int // capture group of the user, 0 if none
ip int
}{
{regexp.MustCompile(`^Invalid user (.*) from (\S+) port \d+` + sshTail), SSHFail, 1, 2},
{regexp.MustCompile(`^Connection closed by invalid user (.*) (\S+) port \d+` + sshTail), SSHFail, 1, 2},
{regexp.MustCompile(`^Connection closed by authenticating user (.+) (\S+) port \d+` + sshTail), SSHFail, 1, 2},
{regexp.MustCompile(`^Failed (?:password|publickey|keyboard-interactive/pam) for (?:invalid user )?(.+) from (\S+) port \d+` + sshTail), SSHFail, 1, 2},
{regexp.MustCompile(`^Disconnected from (?:authenticating|invalid) user (.*) (\S+) port \d+` + sshTail), SSHFail, 1, 2},
{regexp.MustCompile(`^Accepted (?:publickey|password|keyboard-interactive/pam) for (.+) from (\S+) port \d+` + sshTail), SSHOK, 1, 2},
// no user field: the address sits at a fixed position right after fixed text
{regexp.MustCompile(`^Unable to negotiate with (\S+) port \d+`), SSHProbe, 0, 1},
{regexp.MustCompile(`^banner exchange: Connection from (\S+) port \d+`), SSHProbe, 0, 1},
{regexp.MustCompile(`^Protocol major versions differ for (\S+) port \d+`), SSHProbe, 0, 1},
{regexp.MustCompile(`^Connection (?:closed|reset) by (\S+) port \d+(?: \[preauth\])?$`), SSHProbe, 0, 1},
}
var sshProg = regexp.MustCompile(`^sshd(?:-session)?(?:\[\d+\])?:$`)
// ParseAuth parses one /var/log/auth.log line (ISO timestamps) written by sshd.
// The line must be exactly "<iso time> <host> sshd[pid]: <message>": text that
// merely mentions sshd (logger, sudo COMMAND=...) is ignored.
func ParseAuth(line string) (Event, error) {
f := strings.SplitN(line, " ", 4)
if len(f) < 4 || !sshProg.MatchString(f[2]) {
return Event{}, ErrIgnored
}
msg := strings.TrimSpace(f[3])
msg = strings.TrimPrefix(msg, "error: ")
if strings.HasPrefix(msg, "kex_exchange_identification") {
// "kex_exchange_identification: Connection closed by remote host" has no
// IP; the line that follows ("Connection closed by IP port N") records it.
return Event{}, ErrIgnored
}
for _, r := range sshRules {
m := r.re.FindStringSubmatch(msg)
if m == nil {
continue
}
if r.user > 0 && strings.Contains(m[r.user], " from ") {
return Event{}, ErrIgnored // an injection attempt in the user name
}
ip, ok := cleanIP(m[r.ip])
if !ok {
continue
}
t, err := time.Parse(time.RFC3339Nano, f[0])
if err != nil {
return Event{}, err
}
ev := Event{Time: t.UTC(), IP: ip, Cat: r.cat, Source: "ssh"}
if r.user > 0 {
ev.User = clip(m[r.user], 64)
}
return ev, nil
}
return Event{}, ErrIgnored
}
var f2bRe = regexp.MustCompile(`^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)(?:,\d+)? fail2ban\.actions\s+\[\d+\]: NOTICE\s+\[([^\]]+)\] (Restore Ban|Ban|Unban) (\S+)`)
// ParseFail2ban parses one fail2ban.log line. Timestamps use the host local
// time zone (UTC in containers unless TZ is set).
func ParseFail2ban(line string) (Event, error) {
m := f2bRe.FindStringSubmatch(line)
if m == nil {
return Event{}, ErrIgnored
}
ip, ok := cleanIP(m[4])
if !ok {
return Event{}, ErrIgnored
}
t, err := time.ParseInLocation("2006-01-02 15:04:05", m[1], time.Local)
if err != nil {
return Event{}, err
}
return Event{
Time: t.UTC(), IP: ip, Cat: Ban, Source: "fail2ban", Jail: clip(m[2], 40),
Unban: m[3] == "Unban", Restore: m[3] == "Restore Ban",
}, nil
}