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"` Duration int64 `json:"Duration"` Size int64 `json:"DownstreamContentSize"` } // 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) 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 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 " sshd[pid]: ": 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 }