Release / Publish tags (push) Successful in 16s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m46s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 23s
CI / Format and vet (push) Successful in 24s
CI / Tests (Linux, race detector) (push) Successful in 1m22s
CI / Dependency audit (push) Successful in 27s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
337 lines
11 KiB
Go
337 lines
11 KiB
Go
package core
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/netip"
|
|
"regexp"
|
|
"strconv"
|
|
"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) {
|
|
if t := bytes.TrimLeft(line, " \t"); len(t) > 0 && t[0] != '{' {
|
|
return parseTraefikText(string(t))
|
|
}
|
|
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
|
|
}
|
|
|
|
// textFields splits a Traefik text (extended CLF) access log line into its
|
|
// fields. Quoted fields may carry backslash escapes, the [time] field is read
|
|
// up to the closing bracket.
|
|
func textFields(s string) ([]string, bool) {
|
|
var out []string
|
|
i := 0
|
|
for i < len(s) {
|
|
switch c := s[i]; {
|
|
case c == ' ' || c == '\t':
|
|
i++
|
|
case c == '"':
|
|
var b strings.Builder
|
|
i++
|
|
closed := false
|
|
for i < len(s) {
|
|
if s[i] == '\\' && i+1 < len(s) {
|
|
b.WriteByte(s[i+1])
|
|
i += 2
|
|
continue
|
|
}
|
|
if s[i] == '"' {
|
|
closed = true
|
|
i++
|
|
break
|
|
}
|
|
b.WriteByte(s[i])
|
|
i++
|
|
}
|
|
if !closed {
|
|
return nil, false
|
|
}
|
|
out = append(out, b.String())
|
|
case c == '[':
|
|
j := strings.IndexByte(s[i:], ']')
|
|
if j < 0 {
|
|
return nil, false
|
|
}
|
|
out = append(out, s[i+1:i+j])
|
|
i += j + 1
|
|
default:
|
|
j := i
|
|
for j < len(s) && s[j] != ' ' && s[j] != '\t' {
|
|
j++
|
|
}
|
|
out = append(out, s[i:j])
|
|
i = j
|
|
}
|
|
}
|
|
return out, true
|
|
}
|
|
|
|
func dash(s string) string {
|
|
if s == "-" {
|
|
return ""
|
|
}
|
|
return s
|
|
}
|
|
|
|
// parseTraefikText parses the default Traefik access log format:
|
|
// host ident user [time] "METHOD path PROTO" status size "referer" "ua" count "router" "backend" Nms
|
|
// The format carries no Host header, so Domain stays empty.
|
|
func parseTraefikText(line string) (Event, error) {
|
|
f, ok := textFields(line)
|
|
if !ok || len(f) < 9 {
|
|
return Event{}, errors.New("not a traefik text line")
|
|
}
|
|
ip, ok := cleanIP(f[0])
|
|
if !ok {
|
|
if _, err := netip.ParseAddr(strings.TrimSpace(f[0])); err != nil {
|
|
return Event{}, errors.New("bad client address")
|
|
}
|
|
return Event{}, ErrIgnored
|
|
}
|
|
t, err := time.Parse("02/Jan/2006:15:04:05 -0700", f[3])
|
|
if err != nil {
|
|
return Event{}, err
|
|
}
|
|
rl := strings.Fields(f[4])
|
|
if len(rl) < 2 {
|
|
return Event{}, errors.New("bad request line")
|
|
}
|
|
method, path, proto := rl[0], rl[1], ""
|
|
if len(rl) >= 3 {
|
|
proto = rl[len(rl)-1]
|
|
}
|
|
status, err := strconv.Atoi(f[5])
|
|
if err != nil || status < 100 || status > 999 {
|
|
return Event{}, errors.New("bad status")
|
|
}
|
|
var size int64
|
|
if f[6] != "-" {
|
|
if size, err = strconv.ParseInt(f[6], 10, 64); err != nil {
|
|
return Event{}, err
|
|
}
|
|
}
|
|
ev := Event{
|
|
Time: t.UTC(), IP: ip, Source: "traefik", Status: status,
|
|
Method: clip(method, 12), Path: clip(path, maxPath), Proto: clip(proto, 12),
|
|
Bytes: size, Referer: clip(dash(f[7]), 300), UA: clip(dash(f[8]), maxUA),
|
|
}
|
|
if len(f) > 10 {
|
|
ev.Router = clip(dash(f[10]), 64)
|
|
}
|
|
if len(f) > 11 && dash(f[11]) != "" {
|
|
ev.OriginStatus = status
|
|
}
|
|
if len(f) > 12 {
|
|
if d, err := time.ParseDuration(strings.TrimSpace(f[12])); err == nil {
|
|
ev.DurationNS = d.Nanoseconds()
|
|
}
|
|
}
|
|
c := Classify(method, path, status)
|
|
ev.Cat, ev.Soft, ev.Strong, ev.Weak = c.Cat, c.Soft, c.Strong, c.Weak
|
|
return ev, nil
|
|
}
|