// Package core holds the event model, the classifier and the log parsers. package core import ( "net/netip" "strings" "time" ) // Category is the kind of activity an event represents. type Category string const ( OK Category = "ok" NotFound Category = "notfound" Scanner Category = "scanner" Exploit Category = "exploit" BruteForce Category = "bruteforce" SSHFail Category = "ssh-fail" SSHProbe Category = "ssh-probe" SSHOK Category = "ssh-ok" Ban Category = "ban" ) // Categories lists every category in a stable order; the position is the index // used by the counters. var Categories = []Category{OK, NotFound, Scanner, Exploit, BruteForce, SSHFail, SSHProbe, SSHOK, Ban} // NumCats is the number of categories. const NumCats = 9 // Index returns the counter index of the category, or -1. func (c Category) Index() int { for i, x := range Categories { if x == c { return i } } return -1 } // Weight is how much one event of the category adds to an IP score. func (c Category) Weight() float64 { switch c { case NotFound: return 0.2 case Scanner: return 3 case Exploit: return 8 case BruteForce: return 2 case SSHFail: return 2 case SSHProbe: return 1 case Ban: return 10 } return 0 } // IsHTTP reports whether the category counts as a web request. func (c Category) IsHTTP() bool { switch c { case OK, NotFound, Scanner, Exploit, BruteForce: return true } return false } // IsMalicious reports whether the category counts as malicious activity. func (c Category) IsMalicious() bool { switch c { case Scanner, Exploit, BruteForce, SSHFail, SSHProbe: return true } return false } // Level is the threat level derived from an IP score. type Level string const ( LevelLow Level = "low" LevelSuspicious Level = "suspicious" LevelHostile Level = "hostile" ) // Score thresholds. const ( HostileScore = 50 SuspiciousScore = 10 ) // LevelOf is the threat level of an IP: hostile needs the score AND a strong // signal (attack-tool User-Agent, two distinct attack categories, a fail2ban // ban, or a high confidence exploit), and never applies to an address that // recently logged in over SSH (admin). func LevelOf(score float64, strong, admin bool) Level { l := LevelFor(score) if admin { return LevelLow } if l == LevelHostile && !strong { return LevelSuspicious } return l } // LevelFor maps a score to a level (score only). func LevelFor(score float64) Level { switch { case score >= HostileScore: return LevelHostile case score >= SuspiciousScore: return LevelSuspicious } return LevelLow } // Event is one classified observation from a log source. type Event struct { Time time.Time IP string Cat Category Source string // traefik, ssh, fail2ban Domain string Method string Path string UA string User string Jail string Status int // Port is the destination port probed (Source "probe"); Proto holds tcp/udp. Port uint16 // Unban marks a fail2ban unban (Cat is Ban). Restore marks a ban replayed // by fail2ban after a restart: it updates the ban state but is not scored. Unban bool Restore bool // Forged marks an attack request whose User-Agent claims to be a monitor. Forged bool // Classification detail (Traefik): Soft = the server answered 2xx/3xx so the // probe probably found nothing; Strong = a high confidence signal; Weak = a // pattern that is only meaningful together with an attack-tool User-Agent. Soft, Strong, Weak bool // Framed: the Sec-Fetch-* headers say a browser sent it cross-site or as a // subresource. It counts in the timeline but never scores an IP. Framed bool // Traffic details (Traefik only). DurationNS int64 Bytes int64 Referer string // 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 // filled by the runner before the event reaches the store. type Enrich struct { CC string // ISO 3166-1 alpha-2, "" unknown City string Browser string OS string Device string // desktop, mobile, tablet, bot, tool, unknown Bot bool BotName string Tool bool } // GeoInfo is the location and network of an address. type GeoInfo struct { CC, Country, CountryPT, Continent, Region, City string Lat, Lon float64 ASN uint32 ASOrg string } // UAInfo is a parsed User-Agent. type UAInfo struct { Browser, BrowserMajor, OS, Device, BotName, Tool string Bot bool } // Enricher resolves addresses and User-Agents. Implementations must be safe // for concurrent use and fast (it runs for every log line). type Enricher interface { Geo(ip string) GeoInfo UA(raw string) UAInfo } // ToolBonus is added to the score of every non-benign request sent by an // attack tool (sqlmap, nuclei, zgrab, masscan...). const ToolBonus = 2.0 // ParseCIDRs parses a comma separated list of CIDRs or bare IPs. func ParseCIDRs(list string) ([]netip.Prefix, error) { var out []netip.Prefix for _, part := range strings.Split(list, ",") { part = strings.TrimSpace(part) if part == "" { continue } if p, err := netip.ParsePrefix(part); err == nil { out = append(out, p.Masked()) continue } a, err := netip.ParseAddr(part) if err != nil { return nil, err } out = append(out, netip.PrefixFrom(a, a.BitLen())) } return out, nil } // Ignored reports whether ip falls in any of the prefixes. Anything that is not // a plain address (garbage, a zone like "::1%x") counts as ignored. func Ignored(prefixes []netip.Prefix, ip string) bool { a, err := netip.ParseAddr(ip) if err != nil || a.Zone() != "" { return true } a = a.Unmap() for _, p := range prefixes { if p.Contains(a) { return true } } return false } var nonGlobal = func() []netip.Prefix { var out []netip.Prefix for _, c := range []string{ "0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "224.0.0.0/4", "240.0.0.0/4", "::/128", "::1/128", "fc00::/7", "fe80::/10", "ff00::/8", "2001:db8::/32", "64:ff9b::/96", "100::/64", } { out = append(out, netip.MustParsePrefix(c)) } return out }() // IsGlobal reports whether a is a routable public unicast address: what a // blocklist may contain. Private, loopback, link-local, multicast, CGNAT, // documentation and reserved ranges are not. func IsGlobal(a netip.Addr) bool { a = a.Unmap() if !a.IsValid() || a.Zone() != "" { return false } for _, p := range nonGlobal { if p.Contains(a) { return false } } return true }