feat: 1.2.0 attack intelligence, replay, 30-day history and new interface
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.
Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.
Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.
Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8f1ac462d1
commit
b7462c14fa
325 files changed
+19117
-1307
No files matched your search
@@ -0,0 +1,599 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/netip"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
)
|
||||
|
||||
// SetEventLog attaches the on-disk event registry (nil detaches it).
|
||||
func (s *Store) SetEventLog(l *evlog.Log) {
|
||||
s.elog = l
|
||||
if l != nil {
|
||||
for {
|
||||
cur := s.ids.Load()
|
||||
if l.LastID() <= cur || s.ids.CompareAndSwap(cur, l.LastID()) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// EventLog returns the registry, nil when disabled.
|
||||
func (s *Store) EventLog() *evlog.Log { return s.elog }
|
||||
|
||||
// logEvent writes a local event, in the same JSON format as the live stream.
|
||||
func (s *Store) logEvent(fe FeedEvent) {
|
||||
if s.elog == nil {
|
||||
return
|
||||
}
|
||||
b, err := json.Marshal(s.Live(fe))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.elog.Append(fe.T, b)
|
||||
}
|
||||
|
||||
// RecordPeerEvent gives a relayed peer event a local id and registers it. The
|
||||
// event must already be sanitized and carry the peer name as its host.
|
||||
func (s *Store) RecordPeerEvent(e *LiveEvent) {
|
||||
e.ID = s.ids.Add(1)
|
||||
if s.elog == nil {
|
||||
return
|
||||
}
|
||||
if b, err := json.Marshal(e); err == nil {
|
||||
s.elog.Append(e.T, b)
|
||||
}
|
||||
}
|
||||
|
||||
// EventsQuery selects events of the registry.
|
||||
type EventsQuery struct {
|
||||
From, To int64
|
||||
Host, IP, Cat, Q, Fam string
|
||||
Limit int
|
||||
Cursor string
|
||||
Desc bool
|
||||
}
|
||||
|
||||
// EventsPage is one page of events.
|
||||
type EventsPage struct {
|
||||
Events []json.RawMessage `json:"events"`
|
||||
Next string `json:"next"`
|
||||
TotalEstimate int64 `json:"total_estimate"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
func catSet(list string) map[string]bool {
|
||||
if list == "" {
|
||||
return nil
|
||||
}
|
||||
m := map[string]bool{}
|
||||
start := 0
|
||||
for i := 0; i <= len(list); i++ {
|
||||
if i == len(list) || list[i] == ',' {
|
||||
if c := list[start:i]; c != "" {
|
||||
m[c] = true
|
||||
}
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// QueryEvents reads a page from the registry.
|
||||
func (s *Store) QueryEvents(q EventsQuery) (EventsPage, error) {
|
||||
if s.elog == nil {
|
||||
return EventsPage{Events: []json.RawMessage{}}, nil
|
||||
}
|
||||
r, err := s.elog.Query(evlog.Query{Filter: evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Q: q.Q, Fam: q.Fam, Cats: catSet(q.Cat)},
|
||||
Limit: q.Limit, Cursor: q.Cursor, Desc: q.Desc})
|
||||
if err != nil {
|
||||
return EventsPage{}, err
|
||||
}
|
||||
out := EventsPage{Events: make([]json.RawMessage, 0, len(r.Items)), Next: r.Next, TotalEstimate: r.TotalEstimate, Truncated: r.Truncated, Enabled: true}
|
||||
for _, it := range r.Items {
|
||||
out.Events = append(out.Events, json.RawMessage(it.Raw))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Session is a burst of activity of one address with no gap longer than the
|
||||
// requested inactivity window.
|
||||
type Session struct {
|
||||
IP string `json:"ip"`
|
||||
Start int64 `json:"start"`
|
||||
End int64 `json:"end"`
|
||||
Events int `json:"events"`
|
||||
Cats map[string]int `json:"cats"`
|
||||
Hosts []string `json:"hosts"`
|
||||
Domains []string `json:"domains"`
|
||||
CC string `json:"cc,omitempty"`
|
||||
ASN uint32 `json:"asn,omitempty"`
|
||||
ASOrg string `json:"as_org,omitempty"`
|
||||
Score float64 `json:"score"`
|
||||
}
|
||||
|
||||
const (
|
||||
maxSessionEvents = 2_000_000
|
||||
maxSessions = 2000
|
||||
sessionScanBytes = 256 << 20
|
||||
)
|
||||
|
||||
type sev struct {
|
||||
t int64
|
||||
cat string
|
||||
host string
|
||||
domain string
|
||||
cc string
|
||||
}
|
||||
|
||||
// Sessions groups the registry events of [from, to] by address (IPv6 by /64)
|
||||
// with an inactivity gap in seconds. truncated reports a cut scan or cap.
|
||||
func (s *Store) Sessions(from, to int64, host, ip string, gap int64) (out []Session, truncated bool) {
|
||||
out = []Session{}
|
||||
if s.elog == nil {
|
||||
return
|
||||
}
|
||||
if gap < 30 {
|
||||
gap = 30
|
||||
}
|
||||
if gap > 86400 {
|
||||
gap = 86400
|
||||
}
|
||||
by := map[string][]sev{}
|
||||
n := 0
|
||||
info := s.elog.Scan(evlog.Filter{From: from, To: to, Host: host, IP: ip}, sessionScanBytes, false, func(r evlog.Rec, _ []byte) bool {
|
||||
if n >= maxSessionEvents {
|
||||
truncated = true
|
||||
return false
|
||||
}
|
||||
n++
|
||||
k := KeyOf(r.IP)
|
||||
by[k] = append(by[k], sev{r.T, r.Cat, r.Host, r.Domain, r.CC})
|
||||
return true
|
||||
})
|
||||
truncated = truncated || info.Truncated
|
||||
for k, evs := range by {
|
||||
sort.Slice(evs, func(i, j int) bool { return evs[i].t < evs[j].t })
|
||||
var cur *Session
|
||||
for _, e := range evs {
|
||||
if cur == nil || e.t-cur.End > gap {
|
||||
out = append(out, Session{IP: k, Start: e.t, Cats: map[string]int{}})
|
||||
cur = &out[len(out)-1]
|
||||
}
|
||||
cur.End = e.t
|
||||
cur.Events++
|
||||
cur.Cats[e.cat]++
|
||||
cur.Score += core.Category(e.cat).Weight()
|
||||
cur.Hosts = addUnique(cur.Hosts, e.host, 8)
|
||||
cur.Domains = addUnique(cur.Domains, e.domain, 8)
|
||||
if cur.CC == "" {
|
||||
cur.CC = e.cc
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Start != out[j].Start {
|
||||
return out[i].Start < out[j].Start
|
||||
}
|
||||
return out[i].IP < out[j].IP
|
||||
})
|
||||
if len(out) > maxSessions { // keep the heaviest, then restore the time order
|
||||
truncated = true
|
||||
sort.SliceStable(out, func(i, j int) bool { return out[i].Events > out[j].Events })
|
||||
out = out[:maxSessions]
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Start != out[j].Start {
|
||||
return out[i].Start < out[j].Start
|
||||
}
|
||||
return out[i].IP < out[j].IP
|
||||
})
|
||||
}
|
||||
for i := range out {
|
||||
g := s.GeoOf(out[i].IP)
|
||||
out[i].ASN, out[i].ASOrg = g.ASN, g.ASOrg
|
||||
if out[i].CC == "" {
|
||||
out[i].CC = g.CC
|
||||
}
|
||||
out[i].Score = round1(out[i].Score)
|
||||
if out[i].Hosts == nil {
|
||||
out[i].Hosts = []string{}
|
||||
}
|
||||
if out[i].Domains == nil {
|
||||
out[i].Domains = []string{}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ---- per-IP detail from the registry ----
|
||||
|
||||
type ipxEntry struct {
|
||||
at time.Time
|
||||
v *IPLog
|
||||
}
|
||||
|
||||
type ipxCache struct {
|
||||
mu sync.Mutex
|
||||
m map[string]ipxEntry
|
||||
}
|
||||
|
||||
// BanEvent is one ban or unban of an address.
|
||||
type BanEvent struct {
|
||||
T int64 `json:"t"`
|
||||
Jail string `json:"jail"`
|
||||
Host string `json:"host,omitempty"`
|
||||
Unban bool `json:"unban"`
|
||||
// Active: this ban is in force now (also set for a ban that began before the window)
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
// IPTimeline holds events per hour and category.
|
||||
type IPTimeline struct {
|
||||
Start int64 `json:"start"`
|
||||
Step int64 `json:"step"`
|
||||
Cats []string `json:"cats"`
|
||||
Series map[string][]uint32 `json:"series"`
|
||||
// Estimated: the daily counters were spread from totals (old record)
|
||||
Estimated bool `json:"estimated,omitempty"`
|
||||
}
|
||||
|
||||
// IPLog is what the registry says about one address.
|
||||
type IPLog struct {
|
||||
Available bool `json:"available"`
|
||||
Events int `json:"events"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
Timeline *IPTimeline `json:"timeline"`
|
||||
Source string `json:"timeline_source"` // "events" (hourly, from the registry) or "counters" (daily, from the record)
|
||||
Hosts []Count `json:"hosts"`
|
||||
Domains []Count `json:"domains"`
|
||||
Statuses []Count `json:"statuses"`
|
||||
Methods []Count `json:"methods"`
|
||||
Paths []Count `json:"paths"`
|
||||
UAs []Count `json:"uas"`
|
||||
Users []Count `json:"users"`
|
||||
Bans []BanEvent `json:"ban_history"`
|
||||
Sessions []intel.Session `json:"sessions"`
|
||||
Escalation []intel.Step `json:"escalation"`
|
||||
Cadence intel.Cadence `json:"cadence"`
|
||||
Forged bool `json:"forged"`
|
||||
SessionsN int `json:"sessions_n"` // all sessions, the list keeps the latest 50
|
||||
SessionsEv int `json:"sessions_events"` // events in all sessions
|
||||
Evs []intel.Ev `json:"-"` // for further analysis by the caller
|
||||
}
|
||||
|
||||
const (
|
||||
ipScanBytes = 256 << 20
|
||||
ipxTTL = 30 * time.Second
|
||||
maxDistinct = 5000
|
||||
)
|
||||
|
||||
func bumpMap(m map[string]uint32, k string) {
|
||||
if k == "" {
|
||||
return
|
||||
}
|
||||
if _, ok := m[k]; ok || len(m) < maxDistinct {
|
||||
m[k]++
|
||||
}
|
||||
}
|
||||
|
||||
// IPLogOf derives the detail of one address from the registry on demand
|
||||
// (cached for 30 s, at most 256 MB read per call).
|
||||
func (s *Store) IPLogOf(ip string, from, to int64) *IPLog {
|
||||
if s.elog == nil {
|
||||
return &IPLog{}
|
||||
}
|
||||
key := KeyOf(ip)
|
||||
ck := key + "|" + time.Unix(from, 0).Format("20060102150405") + "|" + time.Unix(to, 0).Format("20060102150405")
|
||||
s.ipx.mu.Lock()
|
||||
if e, ok := s.ipx.m[ck]; ok && time.Since(e.at) < ipxTTL {
|
||||
s.ipx.mu.Unlock()
|
||||
return e.v
|
||||
}
|
||||
s.ipx.mu.Unlock()
|
||||
|
||||
start := from / 3600 * 3600
|
||||
nb := int((to-start)/3600) + 1
|
||||
if nb < 1 {
|
||||
nb = 1
|
||||
}
|
||||
if nb > 722 {
|
||||
nb = 722
|
||||
}
|
||||
cats := catStrings()
|
||||
tl := &IPTimeline{Start: start, Step: 3600, Cats: cats, Series: map[string][]uint32{}}
|
||||
for _, c := range cats {
|
||||
tl.Series[c] = make([]uint32, nb)
|
||||
}
|
||||
hosts, doms, sts, meths, paths, uas, users := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
|
||||
out := &IPLog{Available: true, Timeline: tl, Bans: []BanEvent{}}
|
||||
info := s.elog.Scan(evlog.Filter{From: from, To: to, IP: key}, ipScanBytes, false, func(r evlog.Rec, _ []byte) bool {
|
||||
out.Events++
|
||||
if strings.Contains(r.Flags, "G") {
|
||||
out.Forged = true
|
||||
}
|
||||
if b := int((r.T - start) / 3600); b >= 0 && b < nb {
|
||||
if sr, ok := tl.Series[r.Cat]; ok {
|
||||
sr[b]++
|
||||
}
|
||||
}
|
||||
bumpMap(hosts, r.Host)
|
||||
bumpMap(doms, r.Domain)
|
||||
if r.Status != 0 {
|
||||
bumpMap(sts, itoa(r.Status))
|
||||
}
|
||||
bumpMap(meths, r.Method)
|
||||
if r.Source == "traefik" && r.Cat != "ok" {
|
||||
bumpMap(paths, r.Path)
|
||||
}
|
||||
bumpMap(uas, r.UA)
|
||||
if r.Cat == string(core.SSHFail) {
|
||||
bumpMap(users, r.User)
|
||||
}
|
||||
if r.Cat == string(core.Ban) && len(out.Bans) < 200 {
|
||||
out.Bans = append(out.Bans, BanEvent{T: r.T, Jail: r.Jail, Host: r.Host, Unban: r.Unban})
|
||||
}
|
||||
if len(out.Evs) < 200000 {
|
||||
out.Evs = append(out.Evs, toEv(r))
|
||||
}
|
||||
return true
|
||||
})
|
||||
out.Truncated = info.Truncated
|
||||
out.Source = "events"
|
||||
if out.Events == 0 {
|
||||
if tl2 := s.counterTimeline(key, from, to); tl2 != nil {
|
||||
out.Timeline, out.Source = tl2, "counters"
|
||||
}
|
||||
}
|
||||
out.Hosts, out.Domains, out.Statuses = topN(hosts, 16), topN(doms, 20), topN(sts, 20)
|
||||
out.Methods, out.Paths, out.UAs, out.Users = topN(meths, 12), topN(paths, 50), topN(uas, 20), topN(users, 20)
|
||||
for i := range out.UAs {
|
||||
out.UAs[i].Label = s.UALabel(out.UAs[i].Key)
|
||||
}
|
||||
sort.Slice(out.Bans, func(i, j int) bool { return out.Bans[i].T < out.Bans[j].T })
|
||||
for i := range out.Evs {
|
||||
out.Evs[i].IP = key
|
||||
}
|
||||
out.Sessions = intel.Sessions(out.Evs, intel.DefaultGap)
|
||||
if out.Sessions == nil {
|
||||
out.Sessions = []intel.Session{}
|
||||
}
|
||||
if len(out.Sessions) > 0 {
|
||||
best := 0
|
||||
for i, ss := range out.Sessions {
|
||||
if intel.StageRank(ss.Stage) > intel.StageRank(out.Sessions[best].Stage) {
|
||||
best = i
|
||||
}
|
||||
}
|
||||
out.Escalation = intel.Escalation(out.Sessions[best], out.Evs)
|
||||
}
|
||||
if out.Escalation == nil {
|
||||
out.Escalation = []intel.Step{}
|
||||
}
|
||||
var ts []time.Time
|
||||
for _, e := range out.Evs {
|
||||
if core.Category(e.Cat).IsMalicious() {
|
||||
ts = append(ts, e.T)
|
||||
}
|
||||
}
|
||||
out.Cadence = intel.CadenceFrom(ts)
|
||||
out.SessionsN = len(out.Sessions)
|
||||
for _, ss := range out.Sessions {
|
||||
out.SessionsEv += ss.N
|
||||
}
|
||||
if len(out.Sessions) > 50 {
|
||||
out.Sessions = out.Sessions[len(out.Sessions)-50:]
|
||||
}
|
||||
s.ipx.mu.Lock()
|
||||
if s.ipx.m == nil || len(s.ipx.m) >= 64 {
|
||||
s.ipx.m = map[string]ipxEntry{}
|
||||
}
|
||||
s.ipx.m[ck] = ipxEntry{time.Now(), out}
|
||||
s.ipx.mu.Unlock()
|
||||
return out
|
||||
}
|
||||
|
||||
func itoa(n int) string {
|
||||
b, _ := json.Marshal(n)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
// Neighbor is another active address near an investigated one.
|
||||
type Neighbor struct {
|
||||
IP string `json:"ip"`
|
||||
Score float64 `json:"score"`
|
||||
Level core.Level `json:"level"`
|
||||
Last int64 `json:"last"`
|
||||
N uint32 `json:"n"`
|
||||
}
|
||||
|
||||
// Neighbors lists the other active addresses of the same /24 (IPv4) or /48
|
||||
// (IPv6) and of the same ASN inside the window, top 20 each by score.
|
||||
func (s *Store) Neighbors(key string, from, to int64) (subnet, asn []Neighbor, asnN int) {
|
||||
subnet, asn = []Neighbor{}, []Neighbor{}
|
||||
var pfx netip.Prefix
|
||||
if a, err := netip.ParseAddr(key); err == nil {
|
||||
bits := 24
|
||||
if !a.Is4() {
|
||||
bits = 48
|
||||
}
|
||||
pfx, _ = a.Prefix(bits)
|
||||
} else if p, err := netip.ParsePrefix(key); err == nil {
|
||||
pfx, _ = p.Addr().Prefix(48)
|
||||
}
|
||||
myASN := s.GeoOf(key).ASN
|
||||
now := s.now().Unix()
|
||||
s.mu.RLock()
|
||||
var sub, same []Neighbor
|
||||
for k, r := range s.ips {
|
||||
if k == key || r.Last < from || r.First > to || !isAttacker(r) {
|
||||
continue
|
||||
}
|
||||
strong := r.Strong || attackKinds(r.Counts) >= 2
|
||||
nb := Neighbor{IP: k, Score: round1(r.Score), Level: core.LevelOf(r.Score, strong, r.adminAt(now)), Last: r.Last, N: uint32(malOf(r.Counts))}
|
||||
var a netip.Addr
|
||||
if x, err := netip.ParseAddr(k); err == nil {
|
||||
a = x
|
||||
} else if p, err := netip.ParsePrefix(k); err == nil {
|
||||
a = p.Addr()
|
||||
}
|
||||
if pfx.IsValid() && pfx.Contains(a) {
|
||||
sub = append(sub, nb)
|
||||
continue
|
||||
}
|
||||
if myASN != 0 && s.GeoOf(k).ASN == myASN {
|
||||
same = append(same, nb)
|
||||
}
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
byScore := func(l []Neighbor) []Neighbor {
|
||||
sort.Slice(l, func(i, j int) bool {
|
||||
if l[i].Score != l[j].Score {
|
||||
return l[i].Score > l[j].Score
|
||||
}
|
||||
return l[i].IP < l[j].IP
|
||||
})
|
||||
if len(l) > 20 {
|
||||
l = l[:20]
|
||||
}
|
||||
return l
|
||||
}
|
||||
asnN = len(same)
|
||||
subnet = append(subnet, byScore(sub)...)
|
||||
asn = append(asn, byScore(same)...)
|
||||
return
|
||||
}
|
||||
|
||||
// ScoreBreakdown is the score of an address split by category.
|
||||
func (r *IPRec) scoreBreakdown() map[string]float64 {
|
||||
out := map[string]float64{}
|
||||
var sum float64
|
||||
for i, v := range r.ScoreBy {
|
||||
sum += float64(v)
|
||||
if v > 0 {
|
||||
out[string(core.Categories[i])] = round1(float64(v))
|
||||
}
|
||||
}
|
||||
if sum == 0 { // record from before the breakdown existed: estimate from the counts
|
||||
for i, n := range r.Counts {
|
||||
if w := core.Categories[i].Weight(); n > 0 && w > 0 {
|
||||
out[string(core.Categories[i])] = round1(float64(n) * w)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func strongReasons(r *IPRec) []string {
|
||||
out := []string{}
|
||||
if r.StrongWhy&whyTool != 0 {
|
||||
out = append(out, "attack_tool_user_agent")
|
||||
}
|
||||
if r.StrongWhy&whySignal != 0 {
|
||||
out = append(out, "high_confidence_signal")
|
||||
}
|
||||
if r.StrongWhy&whyBan != 0 {
|
||||
out = append(out, "fail2ban_ban")
|
||||
}
|
||||
if attackKinds(r.Counts) >= 2 {
|
||||
out = append(out, "multiple_attack_categories")
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// IPInfo carries the per-record parts of the detail view that need the table.
|
||||
type IPInfo struct {
|
||||
ScoreBreakdown map[string]float64
|
||||
StrongReasons []string
|
||||
TTB int64
|
||||
FirstMal int64
|
||||
ActiveDays int
|
||||
Users []UserN
|
||||
Status [6]uint32
|
||||
Fams []FamN
|
||||
Techs []TechN
|
||||
Expo []Expo
|
||||
Banned bool
|
||||
ListedSince int64
|
||||
Samples []string
|
||||
Domains []string
|
||||
Jails []string
|
||||
BanSince int64
|
||||
First, Last int64
|
||||
Counts [core.NumCats]uint32
|
||||
Estimated bool
|
||||
DayBase int64
|
||||
DayCats [][core.NumCats]uint16
|
||||
}
|
||||
|
||||
// IPInfoOf returns the capped per-record detail of an address.
|
||||
func (s *Store) IPInfoOf(ip string) (IPInfo, bool) {
|
||||
key := KeyOf(ip)
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
r := s.ips[key]
|
||||
if r == nil {
|
||||
return IPInfo{}, false
|
||||
}
|
||||
days := 0
|
||||
for b := r.Days; b != 0; b &= b - 1 {
|
||||
days++
|
||||
}
|
||||
return IPInfo{ScoreBreakdown: r.scoreBreakdown(), StrongReasons: strongReasons(r), TTB: r.TTB, FirstMal: r.FirstMal, ActiveDays: days,
|
||||
Users: append([]UserN(nil), r.Users...), Status: r.Status, Fams: append([]FamN(nil), r.Fams...), Techs: append([]TechN(nil), r.Techs...),
|
||||
Expo: append([]Expo(nil), r.Expo...), Banned: len(r.Jails) > 0, ListedSince: r.ListedSince,
|
||||
Samples: append([]string(nil), r.Samples...), Domains: append([]string(nil), r.Domains...), Jails: append([]string(nil), r.Jails...),
|
||||
BanSince: r.BanSince, First: r.First, Last: r.Last, Counts: r.Counts, Estimated: r.DayEst, DayBase: r.DayBase, DayCats: append([][core.NumCats]uint16(nil), r.DayCats...)}, true
|
||||
}
|
||||
|
||||
func toEv(r evlog.Rec) intel.Ev {
|
||||
return intel.Ev{T: time.Unix(r.T, 0), IP: KeyOf(r.IP), Host: r.Host, Domain: r.Domain, Cat: r.Cat, Fam: r.Fam, Path: r.Path,
|
||||
User: r.User, Jail: r.Jail, Status: r.Status, Strong: strings.Contains(r.Flags, "S"), Unban: r.Unban}
|
||||
}
|
||||
|
||||
// counterTimeline builds a daily timeline from the per-day counters of the IP
|
||||
// record, for the days the event registry does not cover.
|
||||
func (s *Store) counterTimeline(key string, from, to int64) *IPTimeline {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
r := s.ips[key]
|
||||
if r == nil || len(r.DayCats) == 0 {
|
||||
return nil
|
||||
}
|
||||
cats := catStrings()
|
||||
start := from / 86400 * 86400
|
||||
nb := int((to-start)/86400) + 1
|
||||
if nb < 1 || nb > 32 {
|
||||
nb = max(1, min(nb, 32))
|
||||
}
|
||||
tl := &IPTimeline{Start: start, Step: 86400, Cats: cats, Series: map[string][]uint32{}, Estimated: r.DayEst}
|
||||
for _, c := range cats {
|
||||
tl.Series[c] = make([]uint32, nb)
|
||||
}
|
||||
any := false
|
||||
for k, row := range r.DayCats {
|
||||
day := r.DayBase - int64(k)
|
||||
b := int(day - start/86400)
|
||||
if b < 0 || b >= nb {
|
||||
continue
|
||||
}
|
||||
for ci, n := range row {
|
||||
if n > 0 {
|
||||
tl.Series[cats[ci]][b] += uint32(n)
|
||||
any = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !any {
|
||||
return nil
|
||||
}
|
||||
return tl
|
||||
}
|
||||
+75
-26
@@ -5,6 +5,7 @@ import (
|
||||
"math"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
@@ -22,13 +23,15 @@ type PeerExport struct {
|
||||
Traffic map[string]TrafficData `json:"traffic"`
|
||||
}
|
||||
|
||||
// Export builds the peer document for a range.
|
||||
func (s *Store) Export(rangeName string) PeerExport {
|
||||
rg := ParseRange(rangeName)
|
||||
all := s.TrafficSummary(rg.Name, "all")
|
||||
e := PeerExport{V: ExportVersion, Summary: s.Summary(rg.Name), Traffic: map[string]TrafficData{"all": all}}
|
||||
// Export builds the peer document for a named range.
|
||||
func (s *Store) Export(rangeName string) PeerExport { return s.ExportFor(ParseRange(rangeName)) }
|
||||
|
||||
// ExportFor builds the peer document for a window.
|
||||
func (s *Store) ExportFor(rg Range) PeerExport {
|
||||
all := s.TrafficFor(rg, "all")
|
||||
e := PeerExport{V: ExportVersion, Summary: s.SummaryFor(rg), Traffic: map[string]TrafficData{"all": all}}
|
||||
for _, d := range all.Domains {
|
||||
e.Traffic[d.Key] = s.TrafficSummary(rg.Name, d.Key)
|
||||
e.Traffic[d.Key] = s.TrafficFor(rg, d.Key)
|
||||
}
|
||||
return e
|
||||
}
|
||||
@@ -84,14 +87,18 @@ func fixGrid(series map[string][]uint32, cats []string, nb int) {
|
||||
// Sanitize bounds everything that came from a peer: a compromised peer must
|
||||
// not be able to inflate the hub's memory or break its charts. It rejects
|
||||
// documents of the wrong schema version.
|
||||
func (e *PeerExport) Sanitize(rangeName string) error {
|
||||
func (e *PeerExport) Sanitize(rangeName string) error { return e.SanitizeRange(ParseRange(rangeName)) }
|
||||
|
||||
// SanitizeRange is Sanitize for any window; the grid is recomputed locally.
|
||||
func (e *PeerExport) SanitizeRange(rg Range) error {
|
||||
if e.V != ExportVersion {
|
||||
return errBadExport
|
||||
}
|
||||
rg := ParseRange(rangeName)
|
||||
nowU := time.Now().Unix()
|
||||
s := &e.Summary
|
||||
s.Version = clipS(s.Version, 32)
|
||||
s.Range, s.Attribution = rg.Name, clipS(s.Attribution, 200)
|
||||
s.Range, s.Attribution = rg.Info(nowU), clipS(s.Attribution, 200)
|
||||
s.Rates = sanitizeRates(s.Rates)
|
||||
if len(s.Hosts) > 4 {
|
||||
s.Hosts = s.Hosts[:4]
|
||||
}
|
||||
@@ -100,8 +107,9 @@ func (e *PeerExport) Sanitize(rangeName string) error {
|
||||
s.Hosts[i].Location = sanitizeLocation(s.Hosts[i].Location)
|
||||
}
|
||||
// timeline: the grid is fixed by the range
|
||||
nb := int(rg.Dur.Seconds()) / int(rg.Step)
|
||||
s.Timeline.Step, s.Timeline.Cats = rg.Step, catStrings()
|
||||
gr := rg.grid(nowU)
|
||||
nb := gr.N
|
||||
s.Timeline.Step, s.Timeline.Cats = gr.Step, catStrings()
|
||||
if s.Timeline.Series == nil {
|
||||
s.Timeline.Series = map[string][]uint32{}
|
||||
}
|
||||
@@ -171,6 +179,7 @@ func (e *PeerExport) Sanitize(rangeName string) error {
|
||||
r.IP, r.Cat, r.Source = clipS(r.IP, 45), clipS(r.Cat, 20), clipS(r.Source, 20)
|
||||
r.Domain, r.Method, r.Path = clipS(r.Domain, 100), clipS(r.Method, 12), clipS(r.Path, 240)
|
||||
r.User, r.Jail = clipS(r.User, 64), clipS(r.Jail, 40)
|
||||
sanitizeFeedDetail(r)
|
||||
}
|
||||
kept := s.Recent[:0]
|
||||
for _, r := range s.Recent {
|
||||
@@ -208,25 +217,17 @@ func (e *PeerExport) Sanitize(rangeName string) error {
|
||||
delete(e.Traffic, k)
|
||||
continue
|
||||
}
|
||||
t.sanitize(rg)
|
||||
t.sanitize(rg, nowU)
|
||||
e.Traffic[k] = t
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func trafficGrid(rg Range) (int, int64) {
|
||||
switch rg.Name {
|
||||
case "1h":
|
||||
return 60, 60
|
||||
case "24h":
|
||||
return 96, 900
|
||||
}
|
||||
return 168, 3600
|
||||
}
|
||||
|
||||
func (t *TrafficData) sanitize(rg Range) {
|
||||
nb, step := trafficGrid(rg)
|
||||
t.Range = rg.Name
|
||||
func (t *TrafficData) sanitize(rg Range, nowU int64) {
|
||||
gr := rg.grid(nowU)
|
||||
nb, step := gr.N, gr.Step
|
||||
t.Range = rg.Info(nowU)
|
||||
t.Timeline.Start = gr.Start
|
||||
t.Domain = clipS(t.Domain, 253)
|
||||
t.Timeline.Step = step
|
||||
if len(t.Timeline.Req) != nb {
|
||||
@@ -244,7 +245,55 @@ func (t *TrafficData) sanitize(rg Range) {
|
||||
}
|
||||
|
||||
// SanitizeTraffic bounds a TrafficData received from elsewhere.
|
||||
func SanitizeTraffic(t *TrafficData, rangeName string) { t.sanitize(ParseRange(rangeName)) }
|
||||
func SanitizeTraffic(t *TrafficData, rangeName string) {
|
||||
t.sanitize(ParseRange(rangeName), time.Now().Unix())
|
||||
}
|
||||
|
||||
// SanitizeTrafficRange bounds a TrafficData received for any window.
|
||||
func SanitizeTrafficRange(t *TrafficData, rg Range) { t.sanitize(rg, time.Now().Unix()) }
|
||||
|
||||
// sanitizeFeedDetail bounds the investigation fields of a feed row from a peer.
|
||||
func sanitizeFeedDetail(r *FeedEvent) {
|
||||
r.UA, r.Fam, r.Marker = clipS(r.UA, 200), clipS(r.Fam, 40), clipS(r.Marker, 80)
|
||||
r.ID = 0
|
||||
if len(r.Tech) > 8 {
|
||||
r.Tech = r.Tech[:8]
|
||||
}
|
||||
for i := range r.Tech {
|
||||
r.Tech[i] = clipS(r.Tech[i], 16)
|
||||
}
|
||||
if r.Bytes < 0 || r.Bytes > 1<<40 {
|
||||
r.Bytes = 0
|
||||
}
|
||||
if r.DurMS < 0 || r.DurMS > 1<<31 {
|
||||
r.DurMS = 0
|
||||
}
|
||||
f := ""
|
||||
for _, c := range r.Flags {
|
||||
if strings.ContainsRune("SWGFX", c) && !strings.ContainsRune(f, c) {
|
||||
f += string(c)
|
||||
}
|
||||
}
|
||||
r.Flags = f
|
||||
}
|
||||
|
||||
func sanitizeRates(r Rates) Rates {
|
||||
capU := func(v uint64) uint64 { return min(v, 1<<40) }
|
||||
r.Last15m, r.Last1h, r.Last24h, r.PrevPeriod = capU(r.Last15m), capU(r.Last1h), capU(r.Last24h), capU(r.PrevPeriod)
|
||||
for _, f := range []*float64{&r.PerHourAvg24h, &r.PerHourAvg7d} {
|
||||
if !finite(*f) || *f > 1e12 {
|
||||
*f = 0
|
||||
}
|
||||
}
|
||||
if r.ChangePct != nil && (math.IsNaN(*r.ChangePct) || math.IsInf(*r.ChangePct, 0)) {
|
||||
r.ChangePct = nil
|
||||
}
|
||||
if r.PeakHour.T < 0 {
|
||||
r.PeakHour = PeakHour{}
|
||||
}
|
||||
r.NewAttackers, r.ActiveAttackers = max(0, min(r.NewAttackers, 1<<30)), max(0, min(r.ActiveAttackers, 1<<30))
|
||||
return r
|
||||
}
|
||||
|
||||
var validStates = map[string]bool{"following": true, "waiting": true, "backfill": true, "error": true, "disabled": true}
|
||||
|
||||
|
||||
@@ -0,0 +1,660 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/netip"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
)
|
||||
|
||||
// IntelClassifier fills the family, techniques and marker of an event.
|
||||
func IntelClassifier(ev core.Event) (string, []string, string) {
|
||||
fam, marker := "", ""
|
||||
if ev.Source == "traefik" {
|
||||
fam = intel.Family(ev.Path, ev.Cat, ev.Status, ev.E.Tool)
|
||||
if fam != "" {
|
||||
marker = intel.Marker(ev.Path)
|
||||
}
|
||||
}
|
||||
tech := intel.Techniques(string(ev.Cat), fam, intel.TechCtx{Tool: ev.UA, Path: ev.Path})
|
||||
return fam, tech, marker
|
||||
}
|
||||
|
||||
const studyTTL = 30 * time.Second
|
||||
|
||||
// Variables so tests can shrink them.
|
||||
var (
|
||||
studyBudget int64 = 256 << 20
|
||||
studyDead = 10 * time.Second
|
||||
)
|
||||
|
||||
type studyKey struct {
|
||||
kind string
|
||||
from, to int64
|
||||
host, ip, cat, fam string
|
||||
gap int64
|
||||
}
|
||||
|
||||
type studyEntry struct {
|
||||
at time.Time
|
||||
v any
|
||||
}
|
||||
|
||||
type studyCache struct {
|
||||
mu sync.Mutex
|
||||
m map[studyKey]studyEntry
|
||||
flights map[studyKey]*flight
|
||||
}
|
||||
|
||||
type flight struct {
|
||||
done chan struct{}
|
||||
v any
|
||||
}
|
||||
|
||||
func (s *Store) cached(k studyKey, f func() any) any { return s.cachedTTL(k, studyTTL, f) }
|
||||
|
||||
// cachedTTL returns a fresh cached value, or computes it once: concurrent
|
||||
// callers of the same key wait for the one computation (singleflight).
|
||||
func (s *Store) cachedTTL(k studyKey, ttl time.Duration, f func() any) any {
|
||||
s.study.mu.Lock()
|
||||
if e, ok := s.study.m[k]; ok && time.Since(e.at) < ttl {
|
||||
s.study.mu.Unlock()
|
||||
return e.v
|
||||
}
|
||||
if fl, ok := s.study.flights[k]; ok {
|
||||
s.study.mu.Unlock()
|
||||
<-fl.done
|
||||
return fl.v
|
||||
}
|
||||
fl := &flight{done: make(chan struct{})}
|
||||
if s.study.flights == nil {
|
||||
s.study.flights = map[studyKey]*flight{}
|
||||
}
|
||||
s.study.flights[k] = fl
|
||||
s.study.mu.Unlock()
|
||||
defer func() {
|
||||
s.study.mu.Lock()
|
||||
delete(s.study.flights, k)
|
||||
s.study.mu.Unlock()
|
||||
close(fl.done)
|
||||
}()
|
||||
fl.v = f()
|
||||
s.study.mu.Lock()
|
||||
if s.study.m == nil || len(s.study.m) >= 32 {
|
||||
s.study.m = map[studyKey]studyEntry{}
|
||||
}
|
||||
s.study.m[k] = studyEntry{time.Now(), fl.v}
|
||||
s.study.mu.Unlock()
|
||||
return fl.v
|
||||
}
|
||||
|
||||
// HourlyMal returns malicious events per hour for the hours of [from, to].
|
||||
func (s *Store) HourlyMal(from, to int64) (counts []int, at []time.Time) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
for h := from / 3600; h <= to/3600; h++ {
|
||||
n := 0
|
||||
if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h {
|
||||
n = int(malOf(hs.C))
|
||||
}
|
||||
counts = append(counts, n)
|
||||
at = append(at, time.Unix(h*3600, 0))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// ---- period ----
|
||||
|
||||
// PeriodQuery selects what a period study covers.
|
||||
type PeriodQuery struct {
|
||||
From, To int64
|
||||
Host, IP, Cat, Fam string
|
||||
Gap int64
|
||||
}
|
||||
|
||||
// FirstTech is the first sighting of a technique in the period.
|
||||
type FirstTech struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
T int64 `json:"t"`
|
||||
IP string `json:"ip"`
|
||||
}
|
||||
|
||||
// Escalation is the stage chain of one session.
|
||||
type EscalationOut struct {
|
||||
Session string `json:"session"`
|
||||
Host string `json:"host,omitempty"`
|
||||
IP string `json:"ip"`
|
||||
Stage string `json:"stage"`
|
||||
Steps []intel.Step `json:"steps"`
|
||||
}
|
||||
|
||||
// Target is a targeted host and domain.
|
||||
type Target struct {
|
||||
Host string `json:"host"`
|
||||
Domain string `json:"domain"`
|
||||
N int `json:"n"`
|
||||
}
|
||||
|
||||
// PeriodOut is the study of a time window made from the event registry.
|
||||
type PeriodOut struct {
|
||||
Range RangeInfo `json:"range"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Events int `json:"events"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
SessionsN int `json:"sessions_n"`
|
||||
Sessions []intel.Session `json:"sessions"`
|
||||
Campaigns []intel.Campaign `json:"campaigns"`
|
||||
FirstSeenTech []FirstTech `json:"first_seen_technique"`
|
||||
Escalations []EscalationOut `json:"escalations"`
|
||||
Spikes []intel.Spike `json:"spikes"`
|
||||
NewVsReturning map[string]int `json:"new_vs_returning"`
|
||||
TopTargets []Target `json:"top_targets"`
|
||||
TopFams []Count `json:"top_fams"`
|
||||
TopTechs []Count `json:"top_techs"`
|
||||
TopUsers []Count `json:"top_users"`
|
||||
TopASNs []Count `json:"top_asns"`
|
||||
EventsCursor string `json:"events_cursor"`
|
||||
}
|
||||
|
||||
const (
|
||||
maxPeriodSessions = 200
|
||||
maxPeriodCampaigns = 50
|
||||
maxEscalations = 20
|
||||
maxStudyEvents = 1_500_000
|
||||
)
|
||||
|
||||
type evLite struct {
|
||||
t int64
|
||||
path string
|
||||
ua string
|
||||
}
|
||||
|
||||
// Period studies [From, To] from the registry: sessions with stages,
|
||||
// campaigns, first sightings, escalations, spikes and tops. At most 256 MB of
|
||||
// registry is read and 10 s spent; the result is cached for 30 s.
|
||||
func (s *Store) Period(q PeriodQuery) PeriodOut {
|
||||
k := studyKey{"period", q.From, q.To, q.Host, q.IP, q.Cat, q.Fam, q.Gap}
|
||||
return s.cached(k, func() any { return s.period(q) }).(PeriodOut)
|
||||
}
|
||||
|
||||
// PeriodSlow is Period with a longer cache (5 minutes), for views that only
|
||||
// need the campaign context of an address and must not recompute the whole
|
||||
// study on every visit.
|
||||
func (s *Store) PeriodSlow(q PeriodQuery) PeriodOut {
|
||||
k := studyKey{"period-slow", q.From, q.To, q.Host, q.IP, q.Cat, q.Fam, q.Gap}
|
||||
return s.cachedTTL(k, 5*time.Minute, func() any { return s.period(q) }).(PeriodOut)
|
||||
}
|
||||
|
||||
func (s *Store) period(q PeriodQuery) PeriodOut {
|
||||
now := s.now().Unix()
|
||||
out := PeriodOut{Range: RangeInfo{Name: "custom", From: q.From, To: q.To, Step: 3600},
|
||||
Sessions: []intel.Session{}, Campaigns: []intel.Campaign{}, FirstSeenTech: []FirstTech{}, Escalations: []EscalationOut{},
|
||||
Spikes: []intel.Spike{}, NewVsReturning: map[string]int{"new": 0, "returning": 0}, TopTargets: []Target{},
|
||||
TopFams: []Count{}, TopTechs: []Count{}, TopUsers: []Count{}, TopASNs: []Count{}, EventsCursor: evlog.StartCursor(q.From)}
|
||||
if s.elog == nil {
|
||||
return out
|
||||
}
|
||||
out.Enabled = true
|
||||
gap := time.Duration(q.Gap) * time.Second
|
||||
switch {
|
||||
case q.Gap <= 0:
|
||||
gap = intel.DefaultGap
|
||||
case q.Gap < 60:
|
||||
gap = 60 * time.Second
|
||||
}
|
||||
deadline := time.Now().Add(studyDead)
|
||||
ctx, cancel := context.WithDeadline(context.Background(), deadline)
|
||||
defer cancel()
|
||||
var evs []intel.Ev
|
||||
byIP := map[string][]evLite{}
|
||||
fams, techs, users, asns := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
|
||||
tgt := map[[2]string]int{}
|
||||
firstT := map[string]FirstTech{}
|
||||
ipSeen := map[string]bool{}
|
||||
info := s.elog.Scan(evlog.Filter{From: q.From, To: q.To, Host: q.Host, IP: q.IP, Cats: catSet(q.Cat), Fam: q.Fam}, studyBudget, false,
|
||||
func(r evlog.Rec, _ []byte) bool {
|
||||
if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && time.Now().After(deadline) {
|
||||
out.Truncated = true
|
||||
return false
|
||||
}
|
||||
e := toEv(r)
|
||||
evs = append(evs, e)
|
||||
if r.Source == "traefik" {
|
||||
byIP[e.IP] = append(byIP[e.IP], evLite{r.T, r.Path, r.UA})
|
||||
}
|
||||
bumpMap(fams, r.Fam)
|
||||
for _, t := range r.Tech {
|
||||
bumpMap(techs, t)
|
||||
if f, ok := firstT[t]; !ok || r.T < f.T {
|
||||
firstT[t] = FirstTech{ID: t, Name: intel.TechniqueName(t), T: r.T, IP: e.IP}
|
||||
}
|
||||
}
|
||||
if r.Cat == string(core.SSHFail) {
|
||||
bumpMap(users, r.User)
|
||||
}
|
||||
if r.Domain != "" && core.Category(r.Cat).IsMalicious() {
|
||||
if len(tgt) < 5000 || tgt[[2]string{r.Host, r.Domain}] > 0 {
|
||||
tgt[[2]string{r.Host, r.Domain}]++
|
||||
}
|
||||
}
|
||||
ipSeen[e.IP] = true
|
||||
return true
|
||||
})
|
||||
out.Truncated = out.Truncated || info.Truncated
|
||||
out.Events = len(evs)
|
||||
sessions := intel.Sessions(evs, gap)
|
||||
out.SessionsN = len(sessions)
|
||||
|
||||
// signatures and campaigns: events and sessions of an address are both in
|
||||
// time order, so one pass with two pointers pairs them
|
||||
sigs := map[string]intel.Signature{}
|
||||
sessByIP := map[string][]int{}
|
||||
for i, ss := range sessions {
|
||||
sessByIP[ss.IP] = append(sessByIP[ss.IP], i)
|
||||
}
|
||||
nIP := 0
|
||||
for ip, idx := range sessByIP {
|
||||
if nIP++; nIP%64 == 0 && ctx.Err() != nil {
|
||||
out.Truncated = true
|
||||
break
|
||||
}
|
||||
lite := byIP[ip]
|
||||
sort.Slice(lite, func(a, b int) bool { return lite[a].t < lite[b].t })
|
||||
j := 0
|
||||
for _, i := range idx {
|
||||
ss := sessions[i]
|
||||
st, en := ss.Start.Unix(), ss.End.Unix()
|
||||
for j < len(lite) && lite[j].t < st {
|
||||
j++
|
||||
}
|
||||
var paths []string
|
||||
tool := ""
|
||||
for k := j; k < len(lite) && lite[k].t <= en; k++ {
|
||||
paths = append(paths, lite[k].path)
|
||||
if tool == "" {
|
||||
if l := s.UALabel(lite[k].ua); strings.HasSuffix(l, "(tool)") {
|
||||
tool = l
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(paths) == 0 {
|
||||
continue
|
||||
}
|
||||
sg := intel.SignatureFrom(paths, tool)
|
||||
g := s.GeoOf(ss.IP)
|
||||
sg.ASN, sg.CC = g.ASN, g.CC
|
||||
sg.NetType, _ = intel.NetType(g.ASN, g.ASOrg, "")
|
||||
sigs[ss.ID] = sg
|
||||
if g.ASN != 0 {
|
||||
asns["AS"+strconv.Itoa(int(g.ASN))+" "+g.ASOrg]++
|
||||
}
|
||||
}
|
||||
}
|
||||
var camps []intel.Campaign
|
||||
if ctx.Err() == nil {
|
||||
camps = intel.CampaignsCtx(ctx, sessions, sigs, 0)
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
out.Truncated = true
|
||||
}
|
||||
if len(camps) > maxPeriodCampaigns {
|
||||
sort.SliceStable(camps, func(i, j int) bool { return camps[i].IPsN > camps[j].IPsN })
|
||||
camps = camps[:maxPeriodCampaigns]
|
||||
}
|
||||
if camps != nil {
|
||||
out.Campaigns = camps
|
||||
}
|
||||
// escalations (highest stages first)
|
||||
order := make([]int, len(sessions))
|
||||
for i := range order {
|
||||
order[i] = i
|
||||
}
|
||||
sort.SliceStable(order, func(a, b int) bool {
|
||||
return intel.StageRank(sessions[order[a]].Stage) > intel.StageRank(sessions[order[b]].Stage)
|
||||
})
|
||||
evByIP := map[string][]intel.Ev{}
|
||||
for _, e := range evs {
|
||||
evByIP[e.IP] = append(evByIP[e.IP], e)
|
||||
}
|
||||
for _, i := range order {
|
||||
ss := sessions[i]
|
||||
if intel.StageRank(ss.Stage) < intel.StageRank(intel.StageExploit) || len(out.Escalations) >= maxEscalations {
|
||||
break
|
||||
}
|
||||
out.Escalations = append(out.Escalations, EscalationOut{Session: ss.ID, IP: ss.IP, Stage: ss.Stage, Steps: intel.Escalation(ss, evByIP[ss.IP])})
|
||||
}
|
||||
// sessions list: the heaviest, in time order
|
||||
if len(sessions) > maxPeriodSessions {
|
||||
sort.SliceStable(sessions, func(i, j int) bool { return sessions[i].N > sessions[j].N })
|
||||
sessions = sessions[:maxPeriodSessions]
|
||||
sort.SliceStable(sessions, func(i, j int) bool { return sessions[i].Start.Before(sessions[j].Start) })
|
||||
}
|
||||
if sessions != nil {
|
||||
out.Sessions = sessions
|
||||
}
|
||||
for _, f := range firstT {
|
||||
out.FirstSeenTech = append(out.FirstSeenTech, f)
|
||||
}
|
||||
sort.Slice(out.FirstSeenTech, func(i, j int) bool { return out.FirstSeenTech[i].T < out.FirstSeenTech[j].T })
|
||||
for k, n := range tgt {
|
||||
out.TopTargets = append(out.TopTargets, Target{k[0], k[1], n})
|
||||
}
|
||||
sort.Slice(out.TopTargets, func(i, j int) bool {
|
||||
if out.TopTargets[i].N != out.TopTargets[j].N {
|
||||
return out.TopTargets[i].N > out.TopTargets[j].N
|
||||
}
|
||||
return out.TopTargets[i].Domain < out.TopTargets[j].Domain
|
||||
})
|
||||
if len(out.TopTargets) > 20 {
|
||||
out.TopTargets = out.TopTargets[:20]
|
||||
}
|
||||
out.TopFams, out.TopTechs, out.TopUsers, out.TopASNs = topN(fams, 20), topN(techs, 20), topN(users, 20), topN(asns, 20)
|
||||
for i := range out.TopTechs {
|
||||
out.TopTechs[i].Label = intel.TechniqueName(out.TopTechs[i].Key)
|
||||
}
|
||||
// new vs returning: an address first seen inside the period is new
|
||||
s.mu.RLock()
|
||||
for ip := range ipSeen {
|
||||
if r := s.ips[ip]; r != nil && r.First < q.From {
|
||||
out.NewVsReturning["returning"]++
|
||||
} else {
|
||||
out.NewVsReturning["new"]++
|
||||
}
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
// spikes: hourly malicious counts with 7 days of history before the period
|
||||
hf := q.From - 7*86400
|
||||
if cut := now - int64(s.cfg.Retention/time.Second); hf < cut {
|
||||
hf = cut
|
||||
}
|
||||
hc, at := s.HourlyMal(hf, q.To)
|
||||
for _, sp := range intel.Spikes(hc, at) {
|
||||
if sp.At.Unix() >= q.From/3600*3600 && sp.At.Unix() <= q.To {
|
||||
out.Spikes = append(out.Spikes, sp)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- metrics ----
|
||||
|
||||
// Metric is a value with the previous period and a sparkline.
|
||||
type Metric struct {
|
||||
Value float64 `json:"value"`
|
||||
Prev float64 `json:"prev"`
|
||||
DeltaPct *float64 `json:"delta_pct"`
|
||||
Spark []float64 `json:"spark"`
|
||||
}
|
||||
|
||||
func mk(v, prev float64, spark []float64) Metric {
|
||||
m := Metric{Value: round1(v), Prev: round1(prev), Spark: spark}
|
||||
if m.Spark == nil {
|
||||
m.Spark = []float64{}
|
||||
}
|
||||
if prev > 0 {
|
||||
d := round1((v - prev) / prev * 100)
|
||||
m.DeltaPct = &d
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// MetricsOut holds the stable investigation metrics (per hour or per day,
|
||||
// never per minute).
|
||||
type MetricsOut struct {
|
||||
Range RangeInfo `json:"range"`
|
||||
Generated int64 `json:"generated"`
|
||||
AttacksPerHour24h Metric `json:"attacks_per_hour_24h"`
|
||||
MovingAvg7d Metric `json:"moving_avg_7d_per_hour"`
|
||||
Trend Metric `json:"trend"` // percent change of the range against the previous one
|
||||
Active24h Metric `json:"active_attackers_24h"`
|
||||
Active1h Metric `json:"active_attackers_1h"`
|
||||
NewAttackers Metric `json:"new_attackers"`
|
||||
ReturningRate Metric `json:"returning_rate"`
|
||||
SessionsPerDay Metric `json:"sessions_per_day"`
|
||||
ExposureRate Metric `json:"exposure_rate"`
|
||||
ExploitsRefused Metric `json:"exploits_refused_pct"`
|
||||
MTTB struct {
|
||||
MedianS float64 `json:"median_s"`
|
||||
P90S float64 `json:"p90_s"`
|
||||
PrevMed float64 `json:"prev_median_s"`
|
||||
N int `json:"n"`
|
||||
} `json:"mttb"`
|
||||
BanCoverage Metric `json:"ban_coverage"`
|
||||
BlocklistCoverage Metric `json:"blocklist_coverage"`
|
||||
BlocklistLeak Metric `json:"blocklist_leak"`
|
||||
SSH struct {
|
||||
Fails24h Metric `json:"fails_24h"`
|
||||
UsersDistinct Metric `json:"users_distinct"`
|
||||
OKAfterFail Metric `json:"ok_after_fail"`
|
||||
} `json:"ssh"`
|
||||
Concentration struct {
|
||||
Top10IPs Metric `json:"top10_ips"`
|
||||
Top5ASNs Metric `json:"top5_asns"`
|
||||
} `json:"concentration"`
|
||||
Truncated bool `json:"truncated,omitempty"`
|
||||
}
|
||||
|
||||
func floats(c []int) []float64 {
|
||||
out := make([]float64, len(c))
|
||||
for i, v := range c {
|
||||
out[i] = float64(v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func downsample(c []int, n int) []float64 {
|
||||
if len(c) <= n {
|
||||
return floats(c)
|
||||
}
|
||||
out := make([]float64, n)
|
||||
for i := 0; i < n; i++ {
|
||||
lo, hi := i*len(c)/n, (i+1)*len(c)/n
|
||||
var sum int
|
||||
for _, v := range c[lo:hi] {
|
||||
sum += v
|
||||
}
|
||||
out[i] = float64(sum)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Metrics computes the metric set for a window (cached for 30 s).
|
||||
func (s *Store) Metrics(rg Range) MetricsOut {
|
||||
now := s.now().Unix()
|
||||
from, to := rg.bounds(now)
|
||||
k := studyKey{kind: "metrics", from: from / 60, to: to / 60}
|
||||
return s.cached(k, func() any { return s.metrics(rg) }).(MetricsOut)
|
||||
}
|
||||
|
||||
func (s *Store) metrics(rg Range) MetricsOut {
|
||||
now := s.now().Unix()
|
||||
from, to := rg.bounds(now)
|
||||
span := to - from
|
||||
out := MetricsOut{Range: rg.Info(now), Generated: now}
|
||||
retCut := now - int64(s.cfg.Retention/time.Second)
|
||||
|
||||
s.mu.RLock()
|
||||
last24 := s.malLocked(now-86400, now+1, now)
|
||||
prev24 := s.malLocked(now-2*86400, now-86400, now)
|
||||
last7 := s.malLocked(now-7*86400, now+1, now)
|
||||
var prev7 uint64
|
||||
if now-14*86400 >= retCut {
|
||||
prev7 = s.malLocked(now-14*86400, now-7*86400, now)
|
||||
}
|
||||
cur := s.malLocked(from, to+1, now)
|
||||
var prev uint64
|
||||
if from-span >= retCut {
|
||||
prev = s.malLocked(from-span, from, now)
|
||||
}
|
||||
var fails24, failsPrev uint64
|
||||
for h := (now - 86400) / 3600; h <= now/3600; h++ {
|
||||
if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h {
|
||||
fails24 += uint64(hs.C[core.SSHFail.Index()])
|
||||
}
|
||||
}
|
||||
for h := (now - 2*86400) / 3600; h < (now-86400)/3600; h++ {
|
||||
if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h {
|
||||
failsPrev += uint64(hs.C[core.SSHFail.Index()])
|
||||
}
|
||||
}
|
||||
users := map[string]bool{}
|
||||
for h := (now - 86400) / 3600; h <= now/3600; h++ {
|
||||
if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h {
|
||||
for u := range hs.Users {
|
||||
users[u] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
var act24, act1, newN, retN, newPrev int
|
||||
var hostile, hostileBanned, hostileListed, leak int
|
||||
var pairs, pairsPrev [][2]time.Time
|
||||
ipEv := map[string]int{}
|
||||
asnEv := map[string]int{}
|
||||
for ip, r := range s.ips {
|
||||
if !isAttacker(r) {
|
||||
continue
|
||||
}
|
||||
if r.Last >= now-86400 {
|
||||
act24++
|
||||
}
|
||||
if r.Last >= now-3600 {
|
||||
act1++
|
||||
}
|
||||
if r.Last >= from && r.First <= to {
|
||||
if r.First >= from {
|
||||
newN++
|
||||
} else {
|
||||
retN++
|
||||
}
|
||||
ipEv[ip] += int(malOf(r.Counts))
|
||||
asnEv["AS"+strconv.Itoa(int(s.GeoOf(ip).ASN))] += int(malOf(r.Counts))
|
||||
strong := r.Strong || attackKinds(r.Counts) >= 2
|
||||
if core.LevelOf(r.Score, strong, r.adminAt(now)) == core.LevelHostile {
|
||||
hostile++
|
||||
banned := len(r.Jails) > 0
|
||||
listed := false
|
||||
if a, err := netip.ParseAddr(strings.SplitN(ip, "/", 2)[0]); err == nil {
|
||||
listed = core.IsGlobal(a)
|
||||
}
|
||||
if banned {
|
||||
hostileBanned++
|
||||
}
|
||||
if listed {
|
||||
hostileListed++
|
||||
}
|
||||
if !banned && !listed {
|
||||
leak++
|
||||
}
|
||||
}
|
||||
}
|
||||
if r.First >= from-span && r.First < from {
|
||||
newPrev++
|
||||
}
|
||||
if r.TTB > 0 && r.FirstMal >= from && r.FirstMal <= to {
|
||||
pairs = append(pairs, [2]time.Time{time.Unix(0, 0), time.Unix(r.TTB, 0)})
|
||||
} else if r.TTB > 0 && r.FirstMal >= from-span && r.FirstMal < from {
|
||||
pairsPrev = append(pairsPrev, [2]time.Time{time.Unix(0, 0), time.Unix(r.TTB, 0)})
|
||||
}
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
|
||||
h24, _ := s.HourlyMal(now-86400+3600, now)
|
||||
out.AttacksPerHour24h = mk(float64(last24)/24, float64(prev24)/24, floats(h24))
|
||||
var days []float64
|
||||
for d := 6; d >= 0; d-- {
|
||||
days = append(days, round1(float64(s.malRange(now-int64(d+1)*86400, now-int64(d)*86400, now))/24))
|
||||
}
|
||||
out.MovingAvg7d = mk(float64(last7)/168, float64(prev7)/168, days)
|
||||
hr, _ := s.HourlyMal(from, to)
|
||||
tr := intel.Trend(float64(cur), float64(prev)) * 100
|
||||
out.Trend = mk(tr, 0, downsample(hr, 48))
|
||||
out.Trend.Prev, out.Trend.DeltaPct = float64(prev), nil
|
||||
out.Active24h, out.Active1h = mk(float64(act24), 0, nil), mk(float64(act1), 0, nil)
|
||||
out.NewAttackers = mk(float64(newN), float64(newPrev), nil)
|
||||
if t := newN + retN; t > 0 {
|
||||
out.ReturningRate = mk(float64(retN)/float64(t)*100, 0, nil)
|
||||
} else {
|
||||
out.ReturningRate = mk(0, 0, nil)
|
||||
}
|
||||
if hostile > 0 {
|
||||
out.BanCoverage = mk(float64(hostileBanned)/float64(hostile)*100, 0, nil)
|
||||
out.BlocklistCoverage = mk(float64(hostileListed)/float64(hostile)*100, 0, nil)
|
||||
} else {
|
||||
out.BanCoverage, out.BlocklistCoverage = mk(0, 0, nil), mk(0, 0, nil)
|
||||
}
|
||||
out.BlocklistLeak = mk(float64(leak), 0, nil)
|
||||
out.SSH.Fails24h = mk(float64(fails24), float64(failsPrev), nil)
|
||||
out.SSH.UsersDistinct = mk(float64(len(users)), 0, nil)
|
||||
med, p90 := intel.MTTB(pairs)
|
||||
pm, _ := intel.MTTB(pairsPrev)
|
||||
out.MTTB.MedianS, out.MTTB.P90S, out.MTTB.PrevMed, out.MTTB.N = med.Seconds(), p90.Seconds(), pm.Seconds(), len(pairs)
|
||||
out.Concentration.Top10IPs = mk(intel.Concentration(ipEv, 10)*100, 0, nil)
|
||||
delete(asnEv, "AS0")
|
||||
out.Concentration.Top5ASNs = mk(intel.Concentration(asnEv, 5)*100, 0, nil)
|
||||
|
||||
// from the registry: sessions, exposure, refused exploits, ssh login after brute force
|
||||
out.SessionsPerDay, out.ExposureRate, out.ExploitsRefused, out.SSH.OKAfterFail = mk(0, 0, nil), mk(0, 0, nil), mk(0, 0, nil), mk(0, 0, nil)
|
||||
if s.elog != nil {
|
||||
var evs []intel.Ev
|
||||
var expl, refused int
|
||||
deadline := time.Now().Add(studyDead)
|
||||
info := s.elog.Scan(evlog.Filter{From: from, To: to}, studyBudget, false, func(r evlog.Rec, _ []byte) bool {
|
||||
if len(evs) >= maxStudyEvents || len(evs)%4096 == 0 && time.Now().After(deadline) {
|
||||
out.Truncated = true
|
||||
return false
|
||||
}
|
||||
evs = append(evs, toEv(r))
|
||||
if r.Cat == string(core.Exploit) && r.Status > 0 {
|
||||
expl++
|
||||
if r.Status >= 400 {
|
||||
refused++
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
out.Truncated = out.Truncated || info.Truncated
|
||||
sess := intel.Sessions(evs, 0)
|
||||
perDay := map[int64]int{}
|
||||
succ, okAfter := 0, 0
|
||||
for _, ss := range sess {
|
||||
perDay[ss.Start.Unix()/86400]++
|
||||
if ss.Success {
|
||||
succ++
|
||||
}
|
||||
if ss.Cats[string(core.SSHOK)] > 0 && ss.Cats[string(core.SSHFail)] > 0 {
|
||||
okAfter++
|
||||
}
|
||||
}
|
||||
if len(sess) > 0 {
|
||||
ndays := float64(span) / 86400
|
||||
if ndays < 1 {
|
||||
ndays = 1
|
||||
}
|
||||
var spark []float64
|
||||
for d := from / 86400; d <= to/86400; d++ {
|
||||
spark = append(spark, float64(perDay[d]))
|
||||
}
|
||||
out.SessionsPerDay = mk(float64(len(sess))/ndays, 0, spark)
|
||||
out.ExposureRate = mk(float64(succ)/float64(len(sess))*100, 0, nil)
|
||||
}
|
||||
if expl > 0 {
|
||||
out.ExploitsRefused = mk(float64(refused)/float64(expl)*100, 0, nil)
|
||||
}
|
||||
out.SSH.OKAfterFail = mk(float64(okAfter), 0, nil)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Store) malRange(a, b, nowU int64) uint64 {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.malLocked(a, b, nowU)
|
||||
}
|
||||
@@ -133,6 +133,7 @@ func (e *LiveEvent) Sanitize(now int64) bool {
|
||||
e.Source = clipS(e.Source, 20)
|
||||
e.Domain, e.Method, e.Path = clipS(e.Domain, 100), clipS(e.Method, 12), clipS(e.Path, 240)
|
||||
e.User, e.Jail = clipS(e.User, 64), clipS(e.Jail, 40)
|
||||
sanitizeFeedDetail(&e.FeedEvent)
|
||||
if e.Status < 0 || e.Status > 999 {
|
||||
e.Status = 0
|
||||
}
|
||||
@@ -168,5 +169,6 @@ func SanitizeFeed(r *FeedEvent) bool {
|
||||
r.IP = a.Unmap().String()
|
||||
r.CC = validCC2(clipS(r.CC, 2))
|
||||
r.Unban, r.Forged = false, false
|
||||
sanitizeFeedDetail(r)
|
||||
return true
|
||||
}
|
||||
@@ -112,7 +112,9 @@ func Merge(host string, parts []Summary) Summary {
|
||||
var ipLists [][]IPSummary
|
||||
var paths, doms, uas, users, ctry [][]Count
|
||||
var recent []FeedEvent
|
||||
var rates []Rates
|
||||
for _, p := range parts {
|
||||
rates = append(rates, p.Rates)
|
||||
if p.Generated > out.Generated {
|
||||
out.Generated = p.Generated
|
||||
}
|
||||
@@ -170,6 +172,12 @@ func Merge(host string, parts []Summary) Summary {
|
||||
out.Totals.UniqueIPs = p.Totals.UniqueIPs
|
||||
}
|
||||
}
|
||||
out.Rates = mergeRates(rates, out.Totals.Malicious, out.Timeline, hostile)
|
||||
for i, p := range parts {
|
||||
_ = i
|
||||
out.Rates.ActiveAttackers = max(out.Rates.ActiveAttackers, p.Rates.ActiveAttackers)
|
||||
out.Rates.NewAttackers = max(out.Rates.NewAttackers, p.Rates.NewAttackers)
|
||||
}
|
||||
if len(out.IPs) > summaryIPs {
|
||||
out.IPs = out.IPs[:summaryIPs]
|
||||
}
|
||||
@@ -183,3 +191,26 @@ func Merge(host string, parts []Summary) Summary {
|
||||
out.Recent = recent
|
||||
return out
|
||||
}
|
||||
|
||||
// mergeRates adds the per-host rates up. Attacker counts cannot be added
|
||||
// exactly (the same address can hit several hosts) so the caller takes the
|
||||
// larger of the merged list and the busiest host.
|
||||
func mergeRates(parts []Rates, malicious uint64, tl Timeline, _ int) Rates {
|
||||
var out Rates
|
||||
var prevOK bool
|
||||
for _, p := range parts {
|
||||
out.Last15m += p.Last15m
|
||||
out.Last1h += p.Last1h
|
||||
out.Last24h += p.Last24h
|
||||
out.PerHourAvg7d += p.PerHourAvg7d
|
||||
out.PrevPeriod += p.PrevPeriod
|
||||
prevOK = prevOK || p.ChangePct != nil
|
||||
}
|
||||
out.PerHourAvg24h = avg1(out.Last24h, 24)
|
||||
out.PerHourAvg7d = round1(out.PerHourAvg7d)
|
||||
if prevOK {
|
||||
out.ChangePct = pct(malicious, out.PrevPeriod)
|
||||
}
|
||||
out.PeakHour = PeakOf(tl)
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MaxSpan is the longest window a request may ask for.
|
||||
const MaxSpan = 30 * 24 * time.Hour
|
||||
|
||||
// DefaultRetention is the default and the maximum --retention.
|
||||
const DefaultRetention = 30 * 24 * time.Hour
|
||||
|
||||
// minuteKeep is how far back minute buckets exist.
|
||||
const minuteKeep = 48 * time.Hour
|
||||
|
||||
// RangeOrder lists the named windows.
|
||||
var RangeOrder = []string{"1h", "2h", "3h", "6h", "12h", "24h", "2d", "3d", "5d", "7d", "15d", "30d"}
|
||||
|
||||
// BackgroundRanges are the windows a hub keeps fresh for every peer; any other
|
||||
// window is fetched on demand.
|
||||
var BackgroundRanges = []string{"1h", "24h", "7d", "30d"}
|
||||
|
||||
// Range describes a time window: a named one relative to now, or a custom one
|
||||
// (From/To in unix seconds).
|
||||
type Range struct {
|
||||
Name string
|
||||
Dur time.Duration
|
||||
Step int64 // timeline bucket size in seconds
|
||||
From int64 // custom windows only
|
||||
To int64
|
||||
Clipped bool
|
||||
}
|
||||
|
||||
// stepFor picks the timeline granularity from the window length.
|
||||
func stepFor(d time.Duration) int64 {
|
||||
switch {
|
||||
case d <= 3*time.Hour:
|
||||
return 60
|
||||
case d <= 6*time.Hour:
|
||||
return 120
|
||||
case d <= 12*time.Hour:
|
||||
return 300
|
||||
case d <= 48*time.Hour:
|
||||
return 900
|
||||
}
|
||||
return 3600
|
||||
}
|
||||
|
||||
// Ranges are the named windows.
|
||||
var Ranges = func() map[string]Range {
|
||||
m := map[string]Range{}
|
||||
for _, n := range RangeOrder {
|
||||
d, _ := time.ParseDuration(n)
|
||||
if n[len(n)-1] == 'd' {
|
||||
k, _ := strconv.Atoi(n[:len(n)-1])
|
||||
d = time.Duration(k) * 24 * time.Hour
|
||||
}
|
||||
m[n] = Range{Name: n, Dur: d, Step: stepFor(d)}
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
// ParseRange returns the named range, defaulting to 24h.
|
||||
func ParseRange(name string) Range {
|
||||
if r, ok := Ranges[name]; ok {
|
||||
return r
|
||||
}
|
||||
return Ranges["24h"]
|
||||
}
|
||||
|
||||
// ParseRangeStrict returns the named range or false.
|
||||
func ParseRangeStrict(name string) (Range, bool) {
|
||||
r, ok := Ranges[name]
|
||||
return r, ok
|
||||
}
|
||||
|
||||
// Custom reports whether the window is an absolute one.
|
||||
func (r Range) Custom() bool { return r.To != 0 }
|
||||
|
||||
// Key identifies the window (cache keys, peer requests).
|
||||
func (r Range) Key() string {
|
||||
if r.Custom() {
|
||||
return fmt.Sprintf("custom:%d-%d", r.From, r.To)
|
||||
}
|
||||
return r.Name
|
||||
}
|
||||
|
||||
func (r Range) bounds(now int64) (int64, int64) {
|
||||
if r.Custom() {
|
||||
return r.From, r.To
|
||||
}
|
||||
return now - int64(r.Dur/time.Second), now
|
||||
}
|
||||
|
||||
// Bounds returns the window as unix seconds.
|
||||
func (r Range) Bounds(now int64) (from, to int64) { return r.bounds(now) }
|
||||
|
||||
type grid struct {
|
||||
Start, Step int64
|
||||
N int
|
||||
}
|
||||
|
||||
func (g grid) minute() bool { return g.Step < 3600 }
|
||||
|
||||
func (r Range) grid(now int64) grid {
|
||||
from, to := r.bounds(now)
|
||||
if !r.Custom() {
|
||||
step := r.Step
|
||||
nb := int(int64(r.Dur/time.Second) / step)
|
||||
return grid{Start: (to/step - int64(nb) + 1) * step, Step: step, N: nb}
|
||||
}
|
||||
step := stepFor(time.Duration(to-from) * time.Second)
|
||||
if step < 3600 && from < now-int64(minuteKeep/time.Second) {
|
||||
step = 3600 // minute buckets no longer exist that far back
|
||||
}
|
||||
start := from / step * step
|
||||
nb := int((to - start + step - 1) / step)
|
||||
if nb < 1 {
|
||||
nb = 1
|
||||
}
|
||||
return grid{Start: start, Step: step, N: nb}
|
||||
}
|
||||
|
||||
// RangeInfo is the "range" object of the responses.
|
||||
type RangeInfo struct {
|
||||
Name string `json:"name"`
|
||||
From int64 `json:"from"`
|
||||
To int64 `json:"to"`
|
||||
Step int64 `json:"step"`
|
||||
Clipped bool `json:"clipped"`
|
||||
}
|
||||
|
||||
// UnmarshalJSON accepts the object and the legacy string form of old peers.
|
||||
func (ri *RangeInfo) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
if json.Unmarshal(b, &s) == nil {
|
||||
*ri = RangeInfo{Name: s}
|
||||
return nil
|
||||
}
|
||||
type plain RangeInfo
|
||||
var p plain
|
||||
if err := json.Unmarshal(b, &p); err != nil {
|
||||
return err
|
||||
}
|
||||
*ri = RangeInfo(p)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Info describes the window at time now.
|
||||
func (r Range) Info(now int64) RangeInfo {
|
||||
from, to := r.bounds(now)
|
||||
return RangeInfo{Name: r.Name, From: from, To: to, Step: r.grid(now).Step, Clipped: r.Clipped}
|
||||
}
|
||||
|
||||
// ErrRange is a bad range request (HTTP 400).
|
||||
var ErrRange = errors.New("invalid range")
|
||||
|
||||
// ResolveRange validates the range parameters of a request: a named window, or
|
||||
// from/to (unix seconds; to defaults to now; from/to win over a name). The
|
||||
// result is clipped to the retention and never longer than MaxSpan.
|
||||
func (s *Store) ResolveRange(name, fromS, toS string) (Range, error) {
|
||||
if fromS == "" && toS == "" {
|
||||
if name == "" {
|
||||
return Ranges["24h"], nil
|
||||
}
|
||||
r, ok := Ranges[name]
|
||||
if !ok {
|
||||
return Range{}, fmt.Errorf("%w: unknown range %q", ErrRange, name)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
if fromS == "" {
|
||||
return Range{}, fmt.Errorf("%w: to needs from", ErrRange)
|
||||
}
|
||||
now := s.now().Unix()
|
||||
from, err := strconv.ParseInt(fromS, 10, 64)
|
||||
if err != nil || from < 0 || from > 1<<33 {
|
||||
return Range{}, fmt.Errorf("%w: bad from", ErrRange)
|
||||
}
|
||||
to := now
|
||||
if toS != "" {
|
||||
if to, err = strconv.ParseInt(toS, 10, 64); err != nil || to < 0 || to > 1<<33 {
|
||||
return Range{}, fmt.Errorf("%w: bad to", ErrRange)
|
||||
}
|
||||
}
|
||||
if to <= from {
|
||||
return Range{}, fmt.Errorf("%w: to must be after from", ErrRange)
|
||||
}
|
||||
if to-from > int64(MaxSpan/time.Second) {
|
||||
return Range{}, fmt.Errorf("%w: at most 30 days", ErrRange)
|
||||
}
|
||||
if to > now {
|
||||
to = now
|
||||
if to <= from {
|
||||
return Range{}, fmt.Errorf("%w: from is in the future", ErrRange)
|
||||
}
|
||||
}
|
||||
rg := Range{Name: "custom", From: from, To: to}
|
||||
if cut := now - int64(s.cfg.Retention/time.Second); from < cut {
|
||||
rg.From, rg.Clipped = cut, true
|
||||
if rg.To <= rg.From {
|
||||
rg.To = rg.From + 60
|
||||
}
|
||||
}
|
||||
rg.Dur = time.Duration(rg.To-rg.From) * time.Second
|
||||
rg.Step = stepFor(rg.Dur)
|
||||
return rg, nil
|
||||
}
|
||||
|
||||
// Retention is the configured retention.
|
||||
func (s *Store) Retention() time.Duration { return s.cfg.Retention }
|
||||
|
||||
// Now is the store clock.
|
||||
func (s *Store) Now() time.Time { return s.now() }
|
||||
+165
-3
@@ -10,7 +10,7 @@ import (
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
const snapshotVersion = 1
|
||||
const snapshotVersion = 2
|
||||
|
||||
// Offset is a saved read position of a log file.
|
||||
type Offset struct {
|
||||
@@ -33,6 +33,33 @@ type snapshot struct {
|
||||
Recent []FeedEvent
|
||||
Rhead int
|
||||
Offsets map[string]Offset
|
||||
IDSeq uint64
|
||||
}
|
||||
|
||||
// Version 1 snapshots (7 days: minute buckets for the whole window, 168 hour
|
||||
// slots, 8 analytics days) are read and converted on load.
|
||||
type snapshotV1 struct {
|
||||
V int
|
||||
Saved int64
|
||||
Stamps [7 * 24 * 60]int64
|
||||
Counts [7 * 24 * 60][core.NumCats]uint32
|
||||
Hours [7 * 24]hourSlot
|
||||
MonSt [7 * 24 * 60]int64
|
||||
MonN [7 * 24 * 60]uint32
|
||||
Dom map[string]*domDataV1
|
||||
IPs map[string]*IPRec
|
||||
Recent []FeedEvent
|
||||
Rhead int
|
||||
Offsets map[string]Offset
|
||||
}
|
||||
|
||||
type domDataV1 struct {
|
||||
MinSt [24 * 60]int64
|
||||
MinReq [24 * 60]uint32
|
||||
MinPages [24 * 60]uint32
|
||||
Hours [7 * 24]anHour
|
||||
Days [8]anDay
|
||||
Last int64
|
||||
}
|
||||
|
||||
// Save writes the state atomically (tmp + rename).
|
||||
@@ -45,7 +72,7 @@ func (s *Store) Save(path string, offsets map[string]Offset) error {
|
||||
bw := bufio.NewWriterSize(f, 256*1024)
|
||||
s.mu.RLock()
|
||||
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, Dom: s.tr.dom,
|
||||
IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets}
|
||||
IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets, IDSeq: s.ids.Load()}
|
||||
err = gob.NewEncoder(bw).Encode(&snap)
|
||||
s.mu.RUnlock()
|
||||
if err == nil {
|
||||
@@ -77,7 +104,17 @@ func (s *Store) Load(path string) (map[string]Offset, error) {
|
||||
defer f.Close()
|
||||
var snap snapshot
|
||||
if err := gob.NewDecoder(bufio.NewReaderSize(f, 256*1024)).Decode(&snap); err != nil {
|
||||
return nil, err
|
||||
// not a version 2 stream: try the version 1 layout
|
||||
var v1 snapshotV1
|
||||
f1, oerr := os.Open(path)
|
||||
if oerr != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f1.Close()
|
||||
if err1 := gob.NewDecoder(bufio.NewReaderSize(f1, 256*1024)).Decode(&v1); err1 != nil || v1.V != 1 {
|
||||
return nil, err
|
||||
}
|
||||
snap = s.migrateV1(&v1)
|
||||
}
|
||||
if snap.V != snapshotVersion {
|
||||
return nil, errors.New("snapshot version mismatch")
|
||||
@@ -97,6 +134,27 @@ func (s *Store) Load(path string) (map[string]Offset, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
for ip, r := range snap.IPs {
|
||||
if r == nil {
|
||||
delete(snap.IPs, ip)
|
||||
}
|
||||
}
|
||||
nowU := s.now().Unix()
|
||||
for _, r := range snap.IPs {
|
||||
// records saved before ListedSince existed: the best estimate is the last event
|
||||
if r.ListedSince == 0 && listedRule(r, nowU) {
|
||||
r.ListedSince = r.Last
|
||||
}
|
||||
// records saved before the day counters existed: spread the totals
|
||||
// evenly over the days between the first and the last event (an
|
||||
// estimate; the registry refines it where it has data)
|
||||
if len(r.DayCats) == 0 {
|
||||
spreadDays(r)
|
||||
}
|
||||
}
|
||||
if snap.IDSeq > s.ids.Load() {
|
||||
s.ids.Store(snap.IDSeq)
|
||||
}
|
||||
s.ips = snap.IPs
|
||||
if s.ips == nil {
|
||||
s.ips = map[string]*IPRec{}
|
||||
@@ -123,3 +181,107 @@ func (s *Store) Load(path string) (map[string]Offset, error) {
|
||||
|
||||
// EnsureDir creates the directory of a snapshot path.
|
||||
func EnsureDir(path string) error { return os.MkdirAll(filepath.Dir(path), 0o700) }
|
||||
|
||||
// migrateV1 converts a version 1 snapshot without losing data: the minute
|
||||
// buckets older than the new minute window are folded into hour buckets.
|
||||
func (s *Store) migrateV1(v *snapshotV1) snapshot {
|
||||
n := snapshot{V: snapshotVersion, Saved: v.Saved, IPs: v.IPs, Recent: v.Recent, Rhead: v.Rhead, Offsets: v.Offsets}
|
||||
// hour slots: same hour numbers, now with category counts
|
||||
for _, h := range v.Hours {
|
||||
if h.Hour != 0 {
|
||||
n.Hours[int(h.Hour%hourSlots)] = h
|
||||
}
|
||||
}
|
||||
for i, m := range v.Stamps {
|
||||
if m == 0 {
|
||||
continue
|
||||
}
|
||||
hr := m / 60
|
||||
hs := &n.Hours[int(hr%hourSlots)]
|
||||
if hs.Hour != hr {
|
||||
*hs = hourSlot{Hour: hr}
|
||||
}
|
||||
for c, k := range v.Counts[i] {
|
||||
hs.C[c] += k
|
||||
}
|
||||
j := int(m % slots)
|
||||
if n.Stamps[j] < m {
|
||||
n.Stamps[j], n.Counts[j] = m, v.Counts[i]
|
||||
}
|
||||
}
|
||||
for i, m := range v.MonSt {
|
||||
if m == 0 {
|
||||
continue
|
||||
}
|
||||
hr := m / 60
|
||||
hs := &n.Hours[int(hr%hourSlots)]
|
||||
if hs.Hour != hr {
|
||||
*hs = hourSlot{Hour: hr}
|
||||
}
|
||||
hs.Mon += v.MonN[i]
|
||||
j := int(m % slots)
|
||||
if n.MonSt[j] < m {
|
||||
n.MonSt[j], n.MonN[j] = m, v.MonN[i]
|
||||
}
|
||||
}
|
||||
n.Dom = make(map[string]*domData, len(v.Dom))
|
||||
for name, d := range v.Dom {
|
||||
if d == nil {
|
||||
continue
|
||||
}
|
||||
nd := &domData{Last: d.Last}
|
||||
for i, m := range d.MinSt {
|
||||
if m == 0 {
|
||||
continue
|
||||
}
|
||||
j := int(m % anMinutes)
|
||||
nd.MinSt[j], nd.MinReq[j], nd.MinPages[j] = m, d.MinReq[i], d.MinPages[i]
|
||||
}
|
||||
for _, h := range d.Hours {
|
||||
if h.Hour != 0 {
|
||||
nd.Hours[int(h.Hour%hourSlots)] = h
|
||||
}
|
||||
}
|
||||
for _, dd := range d.Days {
|
||||
if dd.Day != 0 {
|
||||
nd.Days[int(dd.Day%anDays)] = dd
|
||||
}
|
||||
}
|
||||
n.Dom[name] = nd
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// spreadDays estimates the per-day counters of an old record from its totals.
|
||||
func spreadDays(r *IPRec) {
|
||||
var tot uint32
|
||||
for _, n := range r.Counts {
|
||||
tot += n
|
||||
}
|
||||
if tot == 0 || r.Last == 0 {
|
||||
return
|
||||
}
|
||||
last := r.Last / 86400
|
||||
nd := int(last - r.First/86400 + 1)
|
||||
nd = max(1, min(nd, 30))
|
||||
r.DayBase, r.DayEst, r.Days = last, true, 0
|
||||
r.DayCats = make([][core.NumCats]uint16, nd)
|
||||
for c, n := range r.Counts {
|
||||
base, rem := n/uint32(nd), int(n%uint32(nd))
|
||||
for k := 0; k < nd; k++ {
|
||||
v := base
|
||||
if k < rem {
|
||||
v++
|
||||
}
|
||||
r.DayCats[k][c] = uint16(min(v, 65535))
|
||||
}
|
||||
}
|
||||
for k := 0; k < nd; k++ {
|
||||
for _, v := range r.DayCats[k] {
|
||||
if v > 0 {
|
||||
r.Days |= 1 << uint(k)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+418
-14
@@ -6,15 +6,18 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
)
|
||||
|
||||
const (
|
||||
slots = 7 * 24 * 60 // minute buckets
|
||||
hourSlots = 7 * 24
|
||||
topCap = 64 // entries kept per top-list per hour
|
||||
slots = 49 * 60 // minute buckets (48 h plus one hour of margin)
|
||||
hourSlots = 30 * 24 // hour buckets, 30 days
|
||||
topCap = 64 // entries kept per top-list per hour
|
||||
maxSample = 4
|
||||
maxUAs = 2
|
||||
maxDomain = 3
|
||||
@@ -59,11 +62,79 @@ type IPRec struct {
|
||||
StrongAt int64
|
||||
// FramedScore: the part of Score that came from framed requests (bounded by framedCap).
|
||||
FramedScore float64
|
||||
|
||||
// Per-IP detail, all small and capped (about 1 KB per IP at the caps). The
|
||||
// rest of the detail view is derived from the event log on demand.
|
||||
ScoreBy [core.NumCats]float32 // score contribution per category
|
||||
StrongWhy uint8 // whyTool | whySignal | whyBan
|
||||
FirstMal int64 // first malicious event
|
||||
TTB int64 // seconds from the first malicious event to the first ban
|
||||
Users []UserN // SSH users tried (<= maxUsers)
|
||||
Status [6]uint32 // answer classes: none, 2xx, 3xx, 4xx, 5xx, other
|
||||
Fams []FamN // attack families (<= maxFams)
|
||||
Techs []TechN // techniques (<= maxTechs)
|
||||
Expo []Expo // successful answers to attack requests (<= maxExpo)
|
||||
CadAcc []float64 // reserved for the cadence accumulator (<= 16 values)
|
||||
DayBase int64 // epoch day of bit 0 of Days
|
||||
Days uint32 // active days: bit k = active on DayBase-k
|
||||
DayEst bool // DayCats was estimated from the totals (record saved before the counters existed)
|
||||
DayCats [][core.NumCats]uint16 // events per day and category, DayCats[k] = DayBase-k (<= 30 days)
|
||||
ListedSince int64 // when the address started to satisfy the blocklist rule (0: not listed)
|
||||
}
|
||||
|
||||
// Reasons an address is strong (IPRec.StrongWhy).
|
||||
const (
|
||||
whyTool = 1
|
||||
whySignal = 2
|
||||
whyBan = 4
|
||||
)
|
||||
|
||||
const (
|
||||
maxUsers = 32
|
||||
maxFams = 16
|
||||
maxTechs = 16
|
||||
maxExpo = 8
|
||||
maxExamp = 3
|
||||
)
|
||||
|
||||
// UserN is one SSH user tried by an address.
|
||||
type UserN struct {
|
||||
U string
|
||||
N uint32
|
||||
First int64
|
||||
}
|
||||
|
||||
// FamN counts one attack family of an address.
|
||||
type FamN struct {
|
||||
Fam string
|
||||
N uint32
|
||||
S [4]uint32 // 2xx 3xx 4xx 5xx
|
||||
Ex []string
|
||||
}
|
||||
|
||||
// TechN counts one technique of an address.
|
||||
type TechN struct {
|
||||
ID string
|
||||
N uint32
|
||||
First, Last int64
|
||||
}
|
||||
|
||||
// Expo is a successful answer to an attack request.
|
||||
type Expo struct {
|
||||
T int64
|
||||
Host string
|
||||
Domain string
|
||||
Path string
|
||||
Status int
|
||||
Bytes int64
|
||||
Fam string
|
||||
}
|
||||
|
||||
type hourSlot struct {
|
||||
Hour int64
|
||||
Paths, Domains, UAs, Users, Countries map[string]uint32
|
||||
C [core.NumCats]uint32 // events per category in the hour
|
||||
Mon uint32 // monitoring requests in the hour
|
||||
}
|
||||
|
||||
// FeedEvent is one entry of the live feed.
|
||||
@@ -82,6 +153,15 @@ type FeedEvent struct {
|
||||
Unban bool `json:"unban,omitempty"`
|
||||
Forged bool `json:"forged,omitempty"`
|
||||
CC string `json:"cc,omitempty"`
|
||||
UA string `json:"ua,omitempty"`
|
||||
ID uint64 `json:"id,omitempty"`
|
||||
// Detail for the replay and the investigation views.
|
||||
Fam string `json:"fam,omitempty"`
|
||||
Tech []string `json:"tech,omitempty"`
|
||||
Marker string `json:"marker,omitempty"`
|
||||
Bytes int64 `json:"bytes,omitempty"`
|
||||
DurMS int64 `json:"dur_ms,omitempty"`
|
||||
Flags string `json:"flags,omitempty"` // S strong, W weak, G forged, F framed, X soft
|
||||
}
|
||||
|
||||
// SetAttribution sets the credit line shown in the dashboard footer (geo data licence).
|
||||
@@ -93,6 +173,53 @@ func (s *Store) SetEnricher(e core.Enricher) { s.enr = e }
|
||||
// RDNS resolves addresses asynchronously; Lookup never blocks.
|
||||
type RDNS interface{ Lookup(ip string) string }
|
||||
|
||||
// FCrDNSVerifier is implemented by resolvers that can confirm a crawler.
|
||||
type FCrDNSVerifier interface {
|
||||
FCrDNS(ip string, suffixes []string) bool
|
||||
}
|
||||
|
||||
var crawlerSuffixes = []struct {
|
||||
ua string
|
||||
suffixes []string
|
||||
}{
|
||||
{"googlebot", []string{"googlebot.com", "google.com"}},
|
||||
{"bingbot", []string{"search.msn.com"}},
|
||||
}
|
||||
|
||||
// FCrDNS verifies an address that claims, through one of its User-Agents, to
|
||||
// be Googlebot or Bingbot. It returns nil when no UA makes the claim (or the
|
||||
// address cannot be checked), true or false otherwise.
|
||||
func (s *Store) FCrDNS(ip string, uas []string) *bool {
|
||||
v, ok := s.rdns.(FCrDNSVerifier)
|
||||
if !ok || s.rdns == nil {
|
||||
return nil
|
||||
}
|
||||
if a, err := netip.ParseAddr(ip); err != nil || a.Zone() != "" {
|
||||
return nil // an IPv6 /64 key is not an address
|
||||
}
|
||||
var want []string
|
||||
for _, ua := range uas {
|
||||
l := strings.ToLower(ua)
|
||||
for _, c := range crawlerSuffixes {
|
||||
if strings.Contains(l, c.ua) {
|
||||
want = append(want, c.suffixes...)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(want) == 0 {
|
||||
return nil
|
||||
}
|
||||
res := v.FCrDNS(ip, want)
|
||||
return &res
|
||||
}
|
||||
|
||||
// IsAdminUser reports whether u is listed in --admin-users.
|
||||
func (s *Store) IsAdminUser(u string) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.isAdminUser(u)
|
||||
}
|
||||
|
||||
// Store is the whole in-memory state of one instance.
|
||||
type Store struct {
|
||||
cfg Config
|
||||
@@ -121,8 +248,22 @@ type Store struct {
|
||||
|
||||
cacheMu sync.Mutex
|
||||
cache map[string]cachedSummary
|
||||
|
||||
ids atomic.Uint64 // event ids, increasing
|
||||
elog *evlog.Log
|
||||
class Classifier
|
||||
ipx ipxCache
|
||||
study studyCache
|
||||
sizes map[string]map[int64]uint32 // per domain: typical 404 / SPA body sizes
|
||||
}
|
||||
|
||||
// Classifier fills the attack family, the techniques and the marker of an
|
||||
// event (wired to internal/intel); nil or empty results are fine.
|
||||
type Classifier func(core.Event) (fam string, tech []string, marker string)
|
||||
|
||||
// SetClassifier installs the classifier.
|
||||
func (s *Store) SetClassifier(c Classifier) { s.class = c }
|
||||
|
||||
type cachedSummary struct {
|
||||
at time.Time
|
||||
s Summary
|
||||
@@ -130,14 +271,17 @@ type cachedSummary struct {
|
||||
|
||||
// New creates an empty store.
|
||||
func New(cfg Config) *Store {
|
||||
if cfg.Retention <= 0 || cfg.Retention > 7*24*time.Hour {
|
||||
cfg.Retention = 7 * 24 * time.Hour
|
||||
if cfg.Retention <= 0 {
|
||||
cfg.Retention = 7 * 24 * time.Hour // zero value; the daemon always passes --retention
|
||||
}
|
||||
if cfg.Retention > DefaultRetention {
|
||||
cfg.Retention = DefaultRetention
|
||||
}
|
||||
if cfg.MaxIPs <= 0 {
|
||||
cfg.MaxIPs = 20000
|
||||
}
|
||||
return &Store{cfg: cfg, now: time.Now, ips: make(map[string]*IPRec), subs: map[chan FeedEvent]struct{}{},
|
||||
cache: map[string]cachedSummary{}, started: time.Now()}
|
||||
cache: map[string]cachedSummary{}, started: time.Now(), class: IntelClassifier}
|
||||
}
|
||||
|
||||
// Name of this instance.
|
||||
@@ -255,6 +399,11 @@ func (s *Store) Ingest(ev core.Event) {
|
||||
}
|
||||
scored := !(ev.Cat == core.Ban && (ev.Unban || ev.Restore))
|
||||
malHTTP := ev.Source == "traefik" && (ev.Cat == core.Scanner || ev.Cat == core.Exploit || ev.Cat == core.BruteForce)
|
||||
var fam, marker string
|
||||
var tech []string
|
||||
if s.class != nil && (ev.Cat.IsMalicious() || ev.Cat == core.NotFound || ev.Cat == core.OK) {
|
||||
fam, tech, marker = s.class(ev)
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
if scored {
|
||||
@@ -272,6 +421,7 @@ func (s *Store) Ingest(ev core.Event) {
|
||||
if hs.Hour != h {
|
||||
*hs = hourSlot{Hour: h}
|
||||
}
|
||||
hs.C[ci]++
|
||||
switch {
|
||||
case malHTTP:
|
||||
bump(&hs.Paths, ev.Path)
|
||||
@@ -299,7 +449,9 @@ func (s *Store) Ingest(ev core.Event) {
|
||||
r = &IPRec{First: ts, Last: ts}
|
||||
s.ips[key] = r
|
||||
}
|
||||
suspicious := false // the address was already suspicious or hostile before this event
|
||||
if r != nil {
|
||||
suspicious = core.LevelOf(r.Score, r.Strong || attackKinds(r.Counts) >= 2, r.adminAt(now.Unix())) != core.LevelLow
|
||||
if ts < r.First {
|
||||
r.First = ts
|
||||
}
|
||||
@@ -320,20 +472,30 @@ func (s *Store) Ingest(ev core.Event) {
|
||||
r.FramedScore += w
|
||||
}
|
||||
r.Score += w
|
||||
r.ScoreBy[ci] += float32(w)
|
||||
if framed {
|
||||
// never a strong signal: the headers prove nothing either way
|
||||
} else if ev.E.Tool && ev.Cat != core.OK && ev.Cat != core.SSHOK && ev.Cat != core.Ban {
|
||||
r.Score += core.ToolBonus
|
||||
r.ScoreBy[ci] += core.ToolBonus
|
||||
r.Strong = true
|
||||
r.StrongWhy |= whyTool
|
||||
r.StrongAt = max(r.StrongAt, ts)
|
||||
}
|
||||
if (ev.Strong && !framed) || ev.Cat == core.Ban {
|
||||
r.Strong = true
|
||||
if ev.Cat == core.Ban {
|
||||
r.StrongWhy |= whyBan
|
||||
} else {
|
||||
r.StrongWhy |= whySignal
|
||||
}
|
||||
r.StrongAt = max(r.StrongAt, ts)
|
||||
}
|
||||
if ev.Cat == core.SSHOK && ts > r.SSHOK && s.isAdminUser(ev.User) {
|
||||
r.SSHOK = ts
|
||||
}
|
||||
s.detailLocked(r, ev, ts, fam, tech, suspicious)
|
||||
updateListed(r, ts, now.Unix())
|
||||
}
|
||||
if malHTTP {
|
||||
r.Domains = addUnique(r.Domains, clipS(ev.Domain, maxText), maxDomain)
|
||||
@@ -360,23 +522,259 @@ func (s *Store) Ingest(ev core.Event) {
|
||||
}
|
||||
var fe FeedEvent
|
||||
feed := ev.Cat != core.OK && ev.Cat != core.NotFound && !ev.Restore
|
||||
if feed {
|
||||
fe = FeedEvent{T: ts, IP: ev.IP, Cat: string(ev.Cat), Source: ev.Source, Host: s.cfg.Name, Domain: ev.Domain,
|
||||
Method: ev.Method, Path: ev.Path, User: ev.User, Jail: ev.Jail, Status: ev.Status, Unban: ev.Unban, Forged: ev.Forged, CC: ev.E.CC}
|
||||
if len(s.recent) < FeedSize {
|
||||
s.recent = append(s.recent, fe)
|
||||
} else {
|
||||
s.recent[s.rhead] = fe
|
||||
s.rhead = (s.rhead + 1) % FeedSize
|
||||
// The event log also keeps a 404 of an attack tool and any answer to an
|
||||
// address that is already suspicious or hostile (to show what it got);
|
||||
// never an address that looks like a visitor.
|
||||
record := feed || (!ev.Restore && (ev.Cat == core.NotFound && ev.E.Tool || suspicious && (ev.Cat == core.OK || ev.Cat == core.NotFound)))
|
||||
if record {
|
||||
fe = s.feedOf(ev, ts, fam, tech, marker)
|
||||
if feed {
|
||||
if len(s.recent) < FeedSize {
|
||||
s.recent = append(s.recent, fe)
|
||||
} else {
|
||||
s.recent[s.rhead] = fe
|
||||
s.rhead = (s.rhead + 1) % FeedSize
|
||||
}
|
||||
}
|
||||
}
|
||||
s.noteSizeLocked(ev, fam) // after the decision: an answer never defines its own "typical" size
|
||||
s.mu.Unlock()
|
||||
|
||||
if record {
|
||||
s.logEvent(fe)
|
||||
}
|
||||
if feed && now.Unix()-ts < 300 {
|
||||
s.broadcast(fe)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) feedOf(ev core.Event, ts int64, fam string, tech []string, marker string) FeedEvent {
|
||||
flags := ""
|
||||
for _, f := range []struct {
|
||||
on bool
|
||||
c string
|
||||
}{{ev.Strong, "S"}, {ev.Weak, "W"}, {ev.Forged, "G"}, {ev.Framed, "F"}, {ev.Soft, "X"}} {
|
||||
if f.on {
|
||||
flags += f.c
|
||||
}
|
||||
}
|
||||
return FeedEvent{T: ts, IP: ev.IP, Cat: string(ev.Cat), Source: ev.Source, Host: s.cfg.Name, Domain: ev.Domain,
|
||||
Method: ev.Method, Path: ev.Path, User: ev.User, Jail: ev.Jail, Status: ev.Status, Unban: ev.Unban, Forged: ev.Forged, CC: ev.E.CC,
|
||||
UA: clipS(ev.UA, 200), ID: s.ids.Add(1), Fam: clipS(fam, 40), Tech: tech, Marker: clipS(marker, 80),
|
||||
Bytes: ev.Bytes, DurMS: ev.DurationNS / 1e6, Flags: flags}
|
||||
}
|
||||
|
||||
// listedRule is the blocklist rule: score of 50, a strong signal and not an admin.
|
||||
func listedRule(r *IPRec, now int64) bool {
|
||||
return r.Score >= core.HostileScore && (r.Strong || attackKinds(r.Counts) >= 2) && !r.adminAt(now)
|
||||
}
|
||||
|
||||
func updateListed(r *IPRec, ts, now int64) {
|
||||
switch ok := listedRule(r, now); {
|
||||
case ok && r.ListedSince == 0:
|
||||
r.ListedSince = ts
|
||||
case !ok && r.ListedSince != 0:
|
||||
r.ListedSince = 0
|
||||
}
|
||||
}
|
||||
|
||||
func statusClass(st int) int {
|
||||
switch {
|
||||
case st == 0:
|
||||
return 0
|
||||
case st >= 200 && st < 300:
|
||||
return 1
|
||||
case st >= 300 && st < 400:
|
||||
return 2
|
||||
case st >= 400 && st < 500:
|
||||
return 3
|
||||
case st >= 500 && st < 600:
|
||||
return 4
|
||||
}
|
||||
return 5
|
||||
}
|
||||
|
||||
// detailLocked updates the capped per-IP detail of an address.
|
||||
func (s *Store) detailLocked(r *IPRec, ev core.Event, ts int64, fam string, tech []string, wasSusp bool) {
|
||||
if ev.Cat.IsMalicious() && (r.FirstMal == 0 || ts < r.FirstMal) {
|
||||
r.FirstMal = ts
|
||||
}
|
||||
if ev.Cat == core.Ban && !ev.Unban && r.FirstMal > 0 && r.TTB == 0 && ts >= r.FirstMal {
|
||||
r.TTB = ts - r.FirstMal
|
||||
}
|
||||
touchDay(r, ts, ev.Cat.Index())
|
||||
if ev.Source == "traefik" {
|
||||
r.Status[statusClass(ev.Status)]++
|
||||
}
|
||||
if ev.Cat == core.SSHFail && ev.User != "" {
|
||||
u := clipS(ev.User, 64)
|
||||
found := false
|
||||
for i := range r.Users {
|
||||
if r.Users[i].U == u {
|
||||
r.Users[i].N++
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found && len(r.Users) < maxUsers {
|
||||
r.Users = append(r.Users, UserN{U: u, N: 1, First: ts})
|
||||
}
|
||||
}
|
||||
if fam != "" && ev.Source == "traefik" {
|
||||
var f *FamN
|
||||
for i := range r.Fams {
|
||||
if r.Fams[i].Fam == fam {
|
||||
f = &r.Fams[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if f == nil && len(r.Fams) < maxFams {
|
||||
r.Fams = append(r.Fams, FamN{Fam: fam})
|
||||
f = &r.Fams[len(r.Fams)-1]
|
||||
}
|
||||
if f != nil {
|
||||
f.N++
|
||||
if c := statusClass(ev.Status); c >= 1 && c <= 4 {
|
||||
f.S[c-1]++
|
||||
}
|
||||
if len(f.Ex) < maxExamp {
|
||||
f.Ex = addUnique(f.Ex, clipS(ev.Method+" "+ev.Path, maxText), maxExamp)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, id := range tech {
|
||||
var t *TechN
|
||||
for i := range r.Techs {
|
||||
if r.Techs[i].ID == id {
|
||||
t = &r.Techs[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if t == nil && len(r.Techs) < maxTechs {
|
||||
r.Techs = append(r.Techs, TechN{ID: id, First: ts})
|
||||
t = &r.Techs[len(r.Techs)-1]
|
||||
}
|
||||
if t != nil {
|
||||
t.N++
|
||||
if ts < t.First {
|
||||
t.First = ts
|
||||
}
|
||||
t.Last = max(t.Last, ts)
|
||||
}
|
||||
}
|
||||
// exposure: a successful answer (2xx, with a body that is not the typical
|
||||
// 404 or SPA page of the domain) to a request for a sensitive family
|
||||
if ev.Source == "traefik" && s.exposedLocked(ev, wasSusp) && len(r.Expo) < maxExpo {
|
||||
r.Expo = append(r.Expo, Expo{T: ts, Host: s.cfg.Name, Domain: clipS(ev.Domain, 100), Path: clipS(ev.Path, 160),
|
||||
Status: ev.Status, Bytes: ev.Bytes, Fam: intel.PathFamily(ev.Path)})
|
||||
}
|
||||
}
|
||||
|
||||
// sensitiveFams are the families whose 2xx answer is an exposure. The public
|
||||
// WordPress login page and robots.txt are not.
|
||||
var sensitiveFams = map[string]bool{
|
||||
intel.FamEnvCreds: true, intel.FamVCS: true, intel.FamBackup: true,
|
||||
intel.FamActuator: true, intel.FamPhpMyAdmin: true, intel.FamAdminPanel: true,
|
||||
}
|
||||
|
||||
// exposedLocked applies the exposure rule. Admin panels and phpMyAdmin pages
|
||||
// are public by design on some sites, so they also need a strong sign.
|
||||
func (s *Store) exposedLocked(ev core.Event, wasSusp bool) bool {
|
||||
if ev.Status < 200 || ev.Status > 299 || ev.Bytes <= 0 {
|
||||
return false
|
||||
}
|
||||
fam := intel.PathFamily(ev.Path)
|
||||
if !sensitiveFams[fam] {
|
||||
return false
|
||||
}
|
||||
if (fam == intel.FamAdminPanel || fam == intel.FamPhpMyAdmin) && !(ev.Strong || ev.E.Tool || wasSusp) {
|
||||
return false
|
||||
}
|
||||
if t := s.sizes[normDomain(ev.Domain)]; t != nil && t[ev.Bytes] >= 2 {
|
||||
return false // the same body the domain serves for a missing page or for its SPA
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// noteSizeLocked remembers the body sizes of 404 answers and of ordinary 2xx
|
||||
// pages per domain (at most 32 domains and 8 sizes each): the typical size of
|
||||
// a "not found" page or of a SPA shell.
|
||||
func (s *Store) noteSizeLocked(ev core.Event, fam string) {
|
||||
if ev.Source != "traefik" || ev.Bytes <= 0 || ev.Domain == "" {
|
||||
return
|
||||
}
|
||||
if ev.Status != 404 && !(ev.Status >= 200 && ev.Status < 300 && fam == "" && intel.PathFamily(ev.Path) == "") {
|
||||
return
|
||||
}
|
||||
d := normDomain(ev.Domain)
|
||||
if s.sizes == nil {
|
||||
s.sizes = map[string]map[int64]uint32{}
|
||||
}
|
||||
m := s.sizes[d]
|
||||
if m == nil {
|
||||
if len(s.sizes) >= 32 {
|
||||
return
|
||||
}
|
||||
m = map[int64]uint32{}
|
||||
s.sizes[d] = m
|
||||
}
|
||||
if _, ok := m[ev.Bytes]; !ok && len(m) >= 8 {
|
||||
var minK int64
|
||||
var minV uint32 = ^uint32(0)
|
||||
for k, v := range m {
|
||||
if v < minV {
|
||||
minK, minV = k, v
|
||||
}
|
||||
}
|
||||
delete(m, minK)
|
||||
}
|
||||
m[ev.Bytes]++
|
||||
}
|
||||
|
||||
// touchDay counts an event on its day: the 30 day bitmap of active days and
|
||||
// the per-day per-category counters (the coarse timeline of an address, kept
|
||||
// for the part of its history the event registry does not cover).
|
||||
func touchDay(r *IPRec, ts int64, ci int) {
|
||||
day := ts / 86400
|
||||
switch {
|
||||
case r.DayBase == 0:
|
||||
r.DayBase = day
|
||||
case day > r.DayBase:
|
||||
d := int(day - r.DayBase)
|
||||
if d >= 32 {
|
||||
r.Days, r.DayCats = 0, nil
|
||||
} else {
|
||||
r.Days = r.Days << uint(d) & (1<<30 - 1)
|
||||
if len(r.DayCats) > 0 {
|
||||
n := min(len(r.DayCats)+d, 30)
|
||||
nc := make([][core.NumCats]uint16, n)
|
||||
for k := range r.DayCats {
|
||||
if k+d < n {
|
||||
nc[k+d] = r.DayCats[k]
|
||||
}
|
||||
}
|
||||
r.DayCats = nc
|
||||
}
|
||||
}
|
||||
r.DayBase = day
|
||||
}
|
||||
k := int(r.DayBase - day)
|
||||
if k < 0 || k >= 30 {
|
||||
return
|
||||
}
|
||||
r.Days |= 1 << uint(k)
|
||||
for len(r.DayCats) <= k {
|
||||
r.DayCats = append(r.DayCats, [core.NumCats]uint16{})
|
||||
}
|
||||
if c := &r.DayCats[k][ci]; *c < 65535 {
|
||||
*c++
|
||||
}
|
||||
}
|
||||
|
||||
func malHTTPCat(c core.Category) bool {
|
||||
return c == core.Scanner || c == core.Exploit || c == core.BruteForce
|
||||
}
|
||||
|
||||
// isAdminUser: without an explicit --admin-users list nobody is immune (a
|
||||
// local user can forge an sshd "Accepted" line with logger).
|
||||
func (s *Store) isAdminUser(u string) bool {
|
||||
@@ -555,10 +953,16 @@ func (s *Store) Monitoring(t time.Time) {
|
||||
}
|
||||
m := ts / 60
|
||||
i := int(m % slots)
|
||||
h := ts / 3600
|
||||
s.mu.Lock()
|
||||
if s.monSt[i] != m {
|
||||
s.monSt[i], s.monN[i] = m, 0
|
||||
}
|
||||
s.monN[i]++
|
||||
hs := &s.hours[int(h%hourSlots)]
|
||||
if hs.Hour != h {
|
||||
*hs = hourSlot{Hour: h}
|
||||
}
|
||||
hs.Mon++
|
||||
s.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
)
|
||||
|
||||
// PeerStudy is what a hub pulls from a peer for the period and metrics views.
|
||||
type PeerStudy struct {
|
||||
V int `json:"v"`
|
||||
Period PeriodOut `json:"period"`
|
||||
Metrics MetricsOut `json:"metrics"`
|
||||
}
|
||||
|
||||
// StudyFor builds the peer document for a window.
|
||||
func (s *Store) StudyFor(q PeriodQuery) PeerStudy {
|
||||
now := s.now().Unix()
|
||||
rg := Range{Name: "custom", From: q.From, To: q.To, Dur: time.Duration(q.To-q.From) * time.Second, Step: stepFor(time.Duration(q.To-q.From) * time.Second)}
|
||||
if q.To > now {
|
||||
rg.To = now
|
||||
}
|
||||
return PeerStudy{V: ExportVersion, Period: s.Period(q), Metrics: s.Metrics(rg)}
|
||||
}
|
||||
|
||||
const (
|
||||
capSessions = 200
|
||||
capCampaigns = 50
|
||||
capEsc = 20
|
||||
capSteps = 16
|
||||
capTops = 20
|
||||
capSpikes = 200
|
||||
capFirstTech = 60
|
||||
capSpark = 800
|
||||
)
|
||||
|
||||
func capStrs(l []string, n, w int) []string {
|
||||
if len(l) > n {
|
||||
l = l[:n]
|
||||
}
|
||||
out := make([]string, 0, len(l))
|
||||
for _, v := range l {
|
||||
out = append(out, clipS(v, w))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func capIntMap(m map[string]int, n int, w int) map[string]int {
|
||||
out := map[string]int{}
|
||||
for k, v := range m {
|
||||
if len(out) >= n {
|
||||
break
|
||||
}
|
||||
if v < 0 || v > 1<<31 {
|
||||
continue
|
||||
}
|
||||
out[clipS(k, w)] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func okTime(t time.Time) bool {
|
||||
y := t.Year()
|
||||
return y >= 2000 && y <= 2100
|
||||
}
|
||||
|
||||
func sanitizeSession(x *intel.Session, host string) bool {
|
||||
key, ok := sanitizeKey(x.IP)
|
||||
if !ok || !okTime(x.Start) || !okTime(x.End) || x.End.Before(x.Start) {
|
||||
return false
|
||||
}
|
||||
x.IP, x.ID, x.Stage, x.CampaignID = key, clipS(x.ID, 32), clipS(x.Stage, 12), clipS(x.CampaignID, 32)
|
||||
x.Cats, x.Fams = capIntMap(x.Cats, 12, 20), capIntMap(x.Fams, 16, 40)
|
||||
x.Techs, x.Domains = capStrs(x.Techs, 16, 16), capStrs(x.Domains, 8, 100)
|
||||
x.Hosts = []string{host}
|
||||
x.N, x.UsersN, x.PeakRPM = max(0, min(x.N, 1<<30)), max(0, min(x.UsersN, 1<<20)), max(0, min(x.PeakRPM, 1<<20))
|
||||
x.DurS = max(0, min(x.DurS, 31*86400))
|
||||
if x.BannedAt != nil && !okTime(*x.BannedAt) {
|
||||
x.BannedAt = nil
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func sanitizeCounts(l []Count, n int) []Count {
|
||||
if l == nil {
|
||||
return []Count{}
|
||||
}
|
||||
return clipCounts(l, n)
|
||||
}
|
||||
|
||||
// Sanitize bounds a study received from a peer and marks everything with the
|
||||
// configured peer name; false means the document is unusable.
|
||||
func (p *PeerStudy) Sanitize(host string) bool {
|
||||
if p.V != ExportVersion {
|
||||
return false
|
||||
}
|
||||
d := &p.Period
|
||||
d.Range.Name = "custom"
|
||||
d.Events, d.SessionsN = max(0, min(d.Events, 1<<30)), max(0, min(d.SessionsN, 1<<30))
|
||||
ss := d.Sessions[:0]
|
||||
for _, x := range d.Sessions {
|
||||
if len(ss) < capSessions && sanitizeSession(&x, host) {
|
||||
ss = append(ss, x)
|
||||
}
|
||||
}
|
||||
d.Sessions = ss
|
||||
camps := d.Campaigns[:0]
|
||||
for _, c := range d.Campaigns {
|
||||
if len(camps) >= capCampaigns || !okTime(c.First) || !okTime(c.Last) {
|
||||
continue
|
||||
}
|
||||
c.ID, c.SignatureID = clipS(c.ID, 32), clipS(c.SignatureID, 32)
|
||||
var ips []string
|
||||
for _, ip := range c.IPs {
|
||||
if k, ok := sanitizeKey(ip); ok && len(ips) < 50 {
|
||||
ips = append(ips, k)
|
||||
}
|
||||
}
|
||||
c.IPs, c.IPsN = ips, max(0, min(c.IPsN, 1<<20))
|
||||
if len(c.ASNs) > 20 {
|
||||
c.ASNs = c.ASNs[:20]
|
||||
}
|
||||
var ccs []string
|
||||
for _, cc := range c.CCs {
|
||||
if v := validCC2(clipS(cc, 2)); v != "" && len(ccs) < 20 {
|
||||
ccs = append(ccs, v)
|
||||
}
|
||||
}
|
||||
c.CCs, c.NetTypes, c.Techs = ccs, capIntMap(c.NetTypes, 8, 24), capStrs(c.Techs, 16, 16)
|
||||
c.Signature.Paths, c.Signature.Tool, c.Signature.NetType = capStrs(c.Signature.Paths, 5, 200), clipS(c.Signature.Tool, 80), clipS(c.Signature.NetType, 24)
|
||||
c.Signature.CC = validCC2(clipS(c.Signature.CC, 2))
|
||||
c.SessionsN = max(0, min(c.SessionsN, 1<<20))
|
||||
camps = append(camps, c)
|
||||
}
|
||||
d.Campaigns = camps
|
||||
ft := d.FirstSeenTech[:0]
|
||||
for _, f := range d.FirstSeenTech {
|
||||
if k, ok := sanitizeKey(f.IP); ok && len(ft) < capFirstTech && f.T > 0 {
|
||||
f.IP, f.ID = k, clipS(f.ID, 16)
|
||||
f.Name = intel.TechniqueName(f.ID) // never trust a name from a peer
|
||||
ft = append(ft, f)
|
||||
}
|
||||
}
|
||||
d.FirstSeenTech = ft
|
||||
es := d.Escalations[:0]
|
||||
for _, e := range d.Escalations {
|
||||
k, ok := sanitizeKey(e.IP)
|
||||
if !ok || len(es) >= capEsc {
|
||||
continue
|
||||
}
|
||||
e.IP, e.Session, e.Stage, e.Host = k, clipS(e.Session, 32), clipS(e.Stage, 12), host
|
||||
steps := e.Steps[:0]
|
||||
for _, st := range e.Steps {
|
||||
if !okTime(st.T) || len(steps) >= capSteps {
|
||||
continue
|
||||
}
|
||||
st.Stage, st.Evidence = clipS(st.Stage, 12), clipS(st.Evidence, 200)
|
||||
steps = append(steps, st)
|
||||
}
|
||||
e.Steps = steps
|
||||
es = append(es, e)
|
||||
}
|
||||
d.Escalations = es
|
||||
sp := d.Spikes[:0]
|
||||
for _, x := range d.Spikes {
|
||||
if len(sp) < capSpikes && okTime(x.At) && finite(x.Baseline) && finite(x.Threshold) && x.Value >= 0 && x.Value <= 1<<30 && x.Baseline < 1e12 && x.Threshold < 1e12 {
|
||||
sp = append(sp, x)
|
||||
}
|
||||
}
|
||||
d.Spikes = sp
|
||||
for k, v := range d.NewVsReturning {
|
||||
if (k != "new" && k != "returning") || v < 0 || v > 1<<30 {
|
||||
delete(d.NewVsReturning, k)
|
||||
}
|
||||
}
|
||||
if d.NewVsReturning == nil {
|
||||
d.NewVsReturning = map[string]int{}
|
||||
}
|
||||
tg := d.TopTargets[:0]
|
||||
for _, t := range d.TopTargets {
|
||||
if len(tg) < capTops && t.N >= 0 && t.N <= 1<<30 {
|
||||
t.Host, t.Domain = host, clipS(t.Domain, 100)
|
||||
tg = append(tg, t)
|
||||
}
|
||||
}
|
||||
d.TopTargets = tg
|
||||
d.TopFams, d.TopTechs = sanitizeCounts(d.TopFams, capTops), sanitizeCounts(d.TopTechs, capTops)
|
||||
for i := range d.TopTechs {
|
||||
d.TopTechs[i].Label = intel.TechniqueName(d.TopTechs[i].Key) // never a label from a peer
|
||||
}
|
||||
d.TopUsers, d.TopASNs = sanitizeCounts(d.TopUsers, capTops), sanitizeCounts(d.TopASNs, capTops)
|
||||
d.EventsCursor = ""
|
||||
sanitizeMetrics(&p.Metrics)
|
||||
return true
|
||||
}
|
||||
|
||||
func fin(f float64) float64 {
|
||||
if math.IsNaN(f) || math.IsInf(f, 0) || f > 1e12 || f < -1e12 {
|
||||
return 0
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
func sanitizeMetric(m *Metric) {
|
||||
m.Value, m.Prev = fin(m.Value), fin(m.Prev)
|
||||
if m.DeltaPct != nil && (math.IsNaN(*m.DeltaPct) || math.IsInf(*m.DeltaPct, 0)) {
|
||||
m.DeltaPct = nil
|
||||
}
|
||||
if len(m.Spark) > capSpark {
|
||||
m.Spark = m.Spark[:capSpark]
|
||||
}
|
||||
for i := range m.Spark {
|
||||
m.Spark[i] = fin(m.Spark[i])
|
||||
}
|
||||
if m.Spark == nil {
|
||||
m.Spark = []float64{}
|
||||
}
|
||||
}
|
||||
|
||||
func metricList(m *MetricsOut) []*Metric {
|
||||
return []*Metric{&m.AttacksPerHour24h, &m.MovingAvg7d, &m.Trend, &m.Active24h, &m.Active1h, &m.NewAttackers, &m.ReturningRate,
|
||||
&m.SessionsPerDay, &m.ExposureRate, &m.ExploitsRefused, &m.BanCoverage, &m.BlocklistCoverage, &m.BlocklistLeak,
|
||||
&m.SSH.Fails24h, &m.SSH.UsersDistinct, &m.SSH.OKAfterFail, &m.Concentration.Top10IPs, &m.Concentration.Top5ASNs}
|
||||
}
|
||||
|
||||
func sanitizeMetrics(m *MetricsOut) {
|
||||
for _, x := range metricList(m) {
|
||||
sanitizeMetric(x)
|
||||
}
|
||||
m.MTTB.MedianS, m.MTTB.P90S, m.MTTB.PrevMed = fin(m.MTTB.MedianS), fin(m.MTTB.P90S), fin(m.MTTB.PrevMed)
|
||||
m.MTTB.N = max(0, min(m.MTTB.N, 1<<30))
|
||||
}
|
||||
|
||||
// MergePeriods adds the studies of several hosts: counts add up, sessions keep
|
||||
// the host they came from, first sightings take the earliest.
|
||||
func MergePeriods(parts []PeriodOut) PeriodOut {
|
||||
out := parts[0]
|
||||
if len(parts) == 1 {
|
||||
return out
|
||||
}
|
||||
out.Sessions = append([]intel.Session(nil), out.Sessions...)
|
||||
out.Campaigns = append([]intel.Campaign(nil), out.Campaigns...)
|
||||
out.Escalations = append([]EscalationOut(nil), out.Escalations...)
|
||||
out.NewVsReturning = map[string]int{"new": 0, "returning": 0}
|
||||
first := map[string]FirstTech{}
|
||||
spikes := map[int64]intel.Spike{}
|
||||
tg := map[[2]string]int{}
|
||||
var fams, techs, users, asns [][]Count
|
||||
out.Events, out.SessionsN, out.Truncated = 0, 0, false
|
||||
out.Spikes = nil
|
||||
for i, p := range parts {
|
||||
if i > 0 {
|
||||
out.Sessions = append(out.Sessions, p.Sessions...)
|
||||
out.Campaigns = append(out.Campaigns, p.Campaigns...)
|
||||
out.Escalations = append(out.Escalations, p.Escalations...)
|
||||
}
|
||||
out.Events += p.Events
|
||||
out.SessionsN += p.SessionsN
|
||||
out.Truncated = out.Truncated || p.Truncated
|
||||
out.Enabled = out.Enabled || p.Enabled
|
||||
for k, v := range p.NewVsReturning {
|
||||
out.NewVsReturning[k] += v
|
||||
}
|
||||
for _, f := range p.FirstSeenTech {
|
||||
if c, ok := first[f.ID]; !ok || f.T < c.T {
|
||||
first[f.ID] = f
|
||||
}
|
||||
}
|
||||
for _, sp := range p.Spikes {
|
||||
if c, ok := spikes[sp.At.Unix()]; !ok || sp.Value > c.Value {
|
||||
spikes[sp.At.Unix()] = sp
|
||||
}
|
||||
}
|
||||
for _, t := range p.TopTargets {
|
||||
tg[[2]string{t.Host, t.Domain}] += t.N
|
||||
}
|
||||
fams, techs, users, asns = append(fams, p.TopFams), append(techs, p.TopTechs), append(users, p.TopUsers), append(asns, p.TopASNs)
|
||||
}
|
||||
sort.SliceStable(out.Sessions, func(i, j int) bool { return out.Sessions[i].N > out.Sessions[j].N })
|
||||
if len(out.Sessions) > capSessions {
|
||||
out.Sessions = out.Sessions[:capSessions]
|
||||
}
|
||||
sort.SliceStable(out.Sessions, func(i, j int) bool { return out.Sessions[i].Start.Before(out.Sessions[j].Start) })
|
||||
sort.SliceStable(out.Campaigns, func(i, j int) bool { return out.Campaigns[i].IPsN > out.Campaigns[j].IPsN })
|
||||
if len(out.Campaigns) > capCampaigns {
|
||||
out.Campaigns = out.Campaigns[:capCampaigns]
|
||||
}
|
||||
sort.SliceStable(out.Escalations, func(i, j int) bool {
|
||||
return intel.StageRank(out.Escalations[i].Stage) > intel.StageRank(out.Escalations[j].Stage)
|
||||
})
|
||||
if len(out.Escalations) > capEsc {
|
||||
out.Escalations = out.Escalations[:capEsc]
|
||||
}
|
||||
out.FirstSeenTech = []FirstTech{}
|
||||
for _, f := range first {
|
||||
out.FirstSeenTech = append(out.FirstSeenTech, f)
|
||||
}
|
||||
sort.Slice(out.FirstSeenTech, func(i, j int) bool { return out.FirstSeenTech[i].T < out.FirstSeenTech[j].T })
|
||||
out.Spikes = []intel.Spike{}
|
||||
for _, sp := range spikes {
|
||||
out.Spikes = append(out.Spikes, sp)
|
||||
}
|
||||
sort.Slice(out.Spikes, func(i, j int) bool { return out.Spikes[i].At.Before(out.Spikes[j].At) })
|
||||
out.TopTargets = []Target{}
|
||||
for k, n := range tg {
|
||||
out.TopTargets = append(out.TopTargets, Target{k[0], k[1], n})
|
||||
}
|
||||
sort.Slice(out.TopTargets, func(i, j int) bool {
|
||||
if out.TopTargets[i].N != out.TopTargets[j].N {
|
||||
return out.TopTargets[i].N > out.TopTargets[j].N
|
||||
}
|
||||
return out.TopTargets[i].Domain < out.TopTargets[j].Domain
|
||||
})
|
||||
if len(out.TopTargets) > capTops {
|
||||
out.TopTargets = out.TopTargets[:capTops]
|
||||
}
|
||||
out.TopFams, out.TopTechs, out.TopUsers, out.TopASNs = mergeCounts(capTops, fams...), mergeCounts(capTops, techs...), mergeCounts(capTops, users...), mergeCounts(capTops, asns...)
|
||||
return out
|
||||
}
|
||||
|
||||
// MergeMetrics combines per-host metrics. Counts and per-hour rates add up;
|
||||
// ratios and percentages are averaged over the hosts that reported (the
|
||||
// merged value is an approximation, weights are not available for them).
|
||||
func MergeMetrics(parts []MetricsOut) MetricsOut {
|
||||
out := parts[0]
|
||||
if len(parts) == 1 {
|
||||
return out
|
||||
}
|
||||
sumLike := func(m *MetricsOut) map[*Metric]bool {
|
||||
return map[*Metric]bool{&m.AttacksPerHour24h: true, &m.MovingAvg7d: true, &m.Active24h: true, &m.Active1h: true, &m.NewAttackers: true,
|
||||
&m.SessionsPerDay: true, &m.BlocklistLeak: true, &m.SSH.Fails24h: true, &m.SSH.UsersDistinct: true, &m.SSH.OKAfterFail: true}
|
||||
}
|
||||
ol := metricList(&out)
|
||||
sums := sumLike(&out)
|
||||
for i, dst := range ol {
|
||||
var v, pv float64
|
||||
var spark []float64
|
||||
prevAll := true
|
||||
for _, p := range parts {
|
||||
pm := metricList(&p)[i]
|
||||
v += pm.Value
|
||||
pv += pm.Prev
|
||||
if pm.Prev == 0 {
|
||||
prevAll = false
|
||||
}
|
||||
if len(pm.Spark) > len(spark) {
|
||||
spark = append(spark, make([]float64, len(pm.Spark)-len(spark))...)
|
||||
}
|
||||
if len(pm.Spark) > 0 {
|
||||
for k, x := range pm.Spark {
|
||||
spark[len(spark)-len(pm.Spark)+k] += x
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sums[dst] {
|
||||
v, pv = v/float64(len(parts)), pv/float64(len(parts))
|
||||
if len(spark) > 0 {
|
||||
for k := range spark {
|
||||
spark[k] /= float64(len(parts))
|
||||
}
|
||||
}
|
||||
}
|
||||
*dst = mk(v, pv, spark)
|
||||
if !prevAll && pv == 0 {
|
||||
dst.DeltaPct = nil
|
||||
}
|
||||
}
|
||||
var wn, med, p90, pm float64
|
||||
var n int
|
||||
for _, p := range parts {
|
||||
w := float64(p.MTTB.N)
|
||||
wn += w
|
||||
med += p.MTTB.MedianS * w
|
||||
p90 += p.MTTB.P90S * w
|
||||
pm += p.MTTB.PrevMed * w
|
||||
n += p.MTTB.N
|
||||
}
|
||||
if wn > 0 {
|
||||
out.MTTB.MedianS, out.MTTB.P90S, out.MTTB.PrevMed = round1(med/wn), round1(p90/wn), round1(pm/wn)
|
||||
}
|
||||
out.MTTB.N = n
|
||||
for _, p := range parts {
|
||||
out.Truncated = out.Truncated || p.Truncated
|
||||
}
|
||||
_ = core.Scanner
|
||||
return out
|
||||
}
|
||||
+167
-55
@@ -7,28 +7,6 @@ import (
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
// Range describes a dashboard time window.
|
||||
type Range struct {
|
||||
Name string
|
||||
Dur time.Duration
|
||||
Step int64 // timeline bucket size in seconds
|
||||
}
|
||||
|
||||
// Ranges are the supported windows.
|
||||
var Ranges = map[string]Range{
|
||||
"1h": {"1h", time.Hour, 60},
|
||||
"24h": {"24h", 24 * time.Hour, 900},
|
||||
"7d": {"7d", 7 * 24 * time.Hour, 3600},
|
||||
}
|
||||
|
||||
// ParseRange returns the named range, defaulting to 24h.
|
||||
func ParseRange(name string) Range {
|
||||
if r, ok := Ranges[name]; ok {
|
||||
return r
|
||||
}
|
||||
return Ranges["24h"]
|
||||
}
|
||||
|
||||
// Count is one top-list row.
|
||||
type Count struct {
|
||||
Key string `json:"key"`
|
||||
@@ -116,11 +94,12 @@ type HostInfo struct {
|
||||
type Summary struct {
|
||||
Version string `json:"version"`
|
||||
Host string `json:"host"`
|
||||
Range string `json:"range"`
|
||||
Range RangeInfo `json:"range"`
|
||||
Generated int64 `json:"generated"`
|
||||
Hosts []HostInfo `json:"hosts"`
|
||||
Totals Totals `json:"totals"`
|
||||
Timeline Timeline `json:"timeline"`
|
||||
Rates Rates `json:"rates"`
|
||||
IPs []IPSummary `json:"ips"`
|
||||
TopPaths []Count `json:"top_paths"`
|
||||
TopDomains []Count `json:"top_domains"`
|
||||
@@ -132,6 +111,27 @@ type Summary struct {
|
||||
Attribution string `json:"attribution,omitempty"`
|
||||
}
|
||||
|
||||
// PeakHour is the busiest hour of a window.
|
||||
type PeakHour struct {
|
||||
T int64 `json:"t"`
|
||||
N uint32 `json:"n"`
|
||||
}
|
||||
|
||||
// Rates are the stable headline rates: counts of malicious events, per hour
|
||||
// (never per minute), independent of the chart granularity.
|
||||
type Rates struct {
|
||||
Last15m uint64 `json:"last15m"`
|
||||
Last1h uint64 `json:"last1h"`
|
||||
Last24h uint64 `json:"last24h"`
|
||||
PerHourAvg24h float64 `json:"per_hour_avg_24h"`
|
||||
PerHourAvg7d float64 `json:"per_hour_avg_7d"`
|
||||
PrevPeriod uint64 `json:"prev_period"`
|
||||
ChangePct *float64 `json:"change_pct"` // null when there is no comparable previous period
|
||||
PeakHour PeakHour `json:"peak_hour"`
|
||||
NewAttackers int `json:"new_attackers"`
|
||||
ActiveAttackers int `json:"active_attackers"`
|
||||
}
|
||||
|
||||
const (
|
||||
summaryIPs = 500
|
||||
topKeep = 50
|
||||
@@ -182,11 +182,11 @@ func round1(f float64) float64 { return float64(int64(f*10+0.5)) / 10 }
|
||||
|
||||
// AllIPs returns every IP seen inside the range, highest score first.
|
||||
func (s *Store) AllIPs(rg Range, detail bool) []IPSummary {
|
||||
cut := s.now().Add(-rg.Dur).Unix()
|
||||
from, to := rg.bounds(s.now().Unix())
|
||||
s.mu.RLock()
|
||||
out := make([]IPSummary, 0, len(s.ips))
|
||||
for ip, r := range s.ips {
|
||||
if r.Last >= cut {
|
||||
if r.Last >= from && r.First <= to {
|
||||
out = append(out, s.rowOf(ip, r, detail))
|
||||
}
|
||||
}
|
||||
@@ -270,47 +270,121 @@ func topN(m map[string]uint32, n int) []Count {
|
||||
return out
|
||||
}
|
||||
|
||||
// Summary builds the local summary for a range (cached for two seconds).
|
||||
func (s *Store) Summary(rangeName string) Summary {
|
||||
rg := ParseRange(rangeName)
|
||||
// Summary builds the local summary for a named range.
|
||||
func (s *Store) Summary(rangeName string) Summary { return s.SummaryFor(ParseRange(rangeName)) }
|
||||
|
||||
// SummaryFor builds the local summary for a window (cached for two seconds).
|
||||
func (s *Store) SummaryFor(rg Range) Summary {
|
||||
key := rg.Key()
|
||||
s.cacheMu.Lock()
|
||||
if c, ok := s.cache[rg.Name]; ok && time.Since(c.at) < 2*time.Second {
|
||||
if c, ok := s.cache[key]; ok && time.Since(c.at) < 2*time.Second {
|
||||
s.cacheMu.Unlock()
|
||||
return c.s
|
||||
}
|
||||
s.cacheMu.Unlock()
|
||||
sum := s.buildSummary(rg)
|
||||
s.cacheMu.Lock()
|
||||
s.cache[rg.Name] = cachedSummary{time.Now(), sum}
|
||||
if len(s.cache) >= 64 {
|
||||
s.cache = map[string]cachedSummary{}
|
||||
}
|
||||
s.cache[key] = cachedSummary{time.Now(), sum}
|
||||
s.cacheMu.Unlock()
|
||||
return sum
|
||||
}
|
||||
|
||||
var malIdx = func() []int {
|
||||
var l []int
|
||||
for i, c := range core.Categories {
|
||||
if c.IsMalicious() {
|
||||
l = append(l, i)
|
||||
}
|
||||
}
|
||||
return l
|
||||
}()
|
||||
|
||||
func malOf(c [core.NumCats]uint32) uint64 {
|
||||
var n uint64
|
||||
for _, i := range malIdx {
|
||||
n += uint64(c[i])
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// malLocked counts malicious events in [a, b): minute buckets when the window
|
||||
// is within the last 48 h, hour buckets otherwise (edge hours count whole).
|
||||
func (s *Store) malLocked(a, b, nowU int64) uint64 {
|
||||
if a < 0 {
|
||||
a = 0
|
||||
}
|
||||
if b <= a {
|
||||
return 0
|
||||
}
|
||||
var n uint64
|
||||
if a >= nowU-int64(minuteKeep/time.Second) {
|
||||
for m := a / 60; m <= (b-1)/60; m++ {
|
||||
if i := int(m % slots); s.stamps[i] == m {
|
||||
n += malOf(s.counts[i])
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
for h := a / 3600; h <= (b-1)/3600; h++ {
|
||||
if hs := &s.hours[int(h%hourSlots)]; hs.Hour == h {
|
||||
n += malOf(hs.C)
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func avg1(n uint64, hours float64) float64 { return round1(float64(n) / hours) }
|
||||
|
||||
func isAttacker(r *IPRec) bool { return malOf(r.Counts) > 0 || r.Counts[core.Ban.Index()] > 0 }
|
||||
|
||||
// PeakOf finds the busiest hour in a timeline (malicious categories only).
|
||||
func PeakOf(tl Timeline) PeakHour {
|
||||
byHour := map[int64]uint32{}
|
||||
for i := range tl.Series[string(core.Scanner)] {
|
||||
var n uint32
|
||||
for _, ci := range malIdx {
|
||||
if sr := tl.Series[string(core.Categories[ci])]; i < len(sr) {
|
||||
n += sr[i]
|
||||
}
|
||||
}
|
||||
byHour[(tl.Start+int64(i)*tl.Step)/3600] += n
|
||||
}
|
||||
var best PeakHour
|
||||
for h, n := range byHour {
|
||||
if n > best.N || n == best.N && n > 0 && h*3600 < best.T {
|
||||
best = PeakHour{T: h * 3600, N: n}
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
func pct(cur, prev uint64) *float64 {
|
||||
if prev == 0 {
|
||||
return nil
|
||||
}
|
||||
v := round1((float64(cur) - float64(prev)) / float64(prev) * 100)
|
||||
return &v
|
||||
}
|
||||
|
||||
func (s *Store) buildSummary(rg Range) Summary {
|
||||
now := s.now()
|
||||
nowU := now.Unix()
|
||||
cats := catStrings()
|
||||
nb := int(rg.Dur.Seconds()) / int(rg.Step)
|
||||
endB := nowU / rg.Step
|
||||
start := (endB - int64(nb) + 1) * rg.Step
|
||||
tl := Timeline{Start: start, Step: rg.Step, Cats: cats, Series: make(map[string][]uint32, len(cats))}
|
||||
from, to := rg.bounds(nowU)
|
||||
g := rg.grid(nowU)
|
||||
nb, start := g.N, g.Start
|
||||
tl := Timeline{Start: start, Step: g.Step, Cats: cats, Series: make(map[string][]uint32, len(cats))}
|
||||
for _, c := range cats {
|
||||
tl.Series[c] = make([]uint32, nb)
|
||||
}
|
||||
tot := Totals{Counts: map[string]uint64{}}
|
||||
var rates Rates
|
||||
|
||||
s.mu.RLock()
|
||||
startMin := start / 60
|
||||
for m := startMin; m <= nowU/60; m++ {
|
||||
i := int(m % slots)
|
||||
if s.stamps[i] != m {
|
||||
continue
|
||||
}
|
||||
b := int((m*60 - start) / rg.Step)
|
||||
if b < 0 || b >= nb {
|
||||
continue
|
||||
}
|
||||
for ci, n := range s.counts[i] {
|
||||
add := func(b int, counts [core.NumCats]uint32) {
|
||||
for ci, n := range counts {
|
||||
if n == 0 {
|
||||
continue
|
||||
}
|
||||
@@ -325,16 +399,39 @@ func (s *Store) buildSummary(rg Range) Summary {
|
||||
}
|
||||
}
|
||||
}
|
||||
for m := startMin; m <= nowU/60; m++ {
|
||||
if i := int(m % slots); s.monSt[i] == m {
|
||||
tot.Monitoring += uint64(s.monN[i])
|
||||
s.mu.RLock()
|
||||
if g.minute() {
|
||||
for m := start / 60; m <= to/60; m++ {
|
||||
i := int(m % slots)
|
||||
if s.stamps[i] != m {
|
||||
continue
|
||||
}
|
||||
if b := int((m*60 - start) / g.Step); b >= 0 && b < nb {
|
||||
add(b, s.counts[i])
|
||||
}
|
||||
}
|
||||
for m := start / 60; m <= to/60; m++ {
|
||||
if i := int(m % slots); s.monSt[i] == m {
|
||||
tot.Monitoring += uint64(s.monN[i])
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for h := start / 3600; h <= to/3600; h++ {
|
||||
hs := &s.hours[int(h%hourSlots)]
|
||||
if hs.Hour != h {
|
||||
continue
|
||||
}
|
||||
if b := int(h - start/3600); b >= 0 && b < nb {
|
||||
add(b, hs.C)
|
||||
}
|
||||
tot.Monitoring += uint64(hs.Mon)
|
||||
}
|
||||
}
|
||||
paths, doms, uas, users, ctry := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
|
||||
firstHour := (nowU - int64(rg.Dur.Seconds())) / 3600
|
||||
firstHour, lastHour := start/3600, to/3600
|
||||
for i := range s.hours {
|
||||
h := &s.hours[i]
|
||||
if h.Hour == 0 || h.Hour < firstHour || h.Hour > nowU/3600+1 {
|
||||
if h.Hour == 0 || h.Hour < firstHour || h.Hour > lastHour {
|
||||
continue
|
||||
}
|
||||
for _, p := range [...]struct {
|
||||
@@ -346,16 +443,21 @@ func (s *Store) buildSummary(rg Range) Summary {
|
||||
}
|
||||
}
|
||||
}
|
||||
cut := nowU - int64(rg.Dur.Seconds())
|
||||
ips := make([]IPSummary, 0, 1024)
|
||||
for ip, r := range s.ips {
|
||||
if len(r.Jails) > 0 {
|
||||
tot.ActiveBans++
|
||||
}
|
||||
if r.Last < cut {
|
||||
if r.Last < from || r.First > to {
|
||||
continue
|
||||
}
|
||||
tot.UniqueIPs++
|
||||
if isAttacker(r) {
|
||||
rates.ActiveAttackers++
|
||||
if r.First >= from {
|
||||
rates.NewAttackers++
|
||||
}
|
||||
}
|
||||
row := s.rowOf(ip, r, true)
|
||||
switch row.Level {
|
||||
case core.LevelHostile:
|
||||
@@ -367,6 +469,16 @@ func (s *Store) buildSummary(rg Range) Summary {
|
||||
ips = append(ips, row)
|
||||
}
|
||||
}
|
||||
rates.Last15m = s.malLocked(nowU-900, nowU+1, nowU)
|
||||
rates.Last1h = s.malLocked(nowU-3600, nowU+1, nowU)
|
||||
rates.Last24h = s.malLocked(nowU-86400, nowU+1, nowU)
|
||||
rates.PerHourAvg24h = avg1(rates.Last24h, 24)
|
||||
rates.PerHourAvg7d = avg1(s.malLocked(nowU-7*86400, nowU+1, nowU), 7*24)
|
||||
if span := to - from; from-span >= nowU-int64(s.cfg.Retention/time.Second) {
|
||||
rates.PrevPeriod = s.malLocked(from-span, from, nowU)
|
||||
rates.ChangePct = pct(tot.Malicious, rates.PrevPeriod)
|
||||
}
|
||||
rates.PeakHour = PeakOf(tl)
|
||||
recent := s.recentLocked(60)
|
||||
s.mu.RUnlock()
|
||||
|
||||
@@ -405,11 +517,11 @@ func (s *Store) buildSummary(rg Range) Summary {
|
||||
}
|
||||
}
|
||||
return Summary{
|
||||
Version: s.cfg.Version, Host: s.cfg.Name, Range: rg.Name, Generated: nowU,
|
||||
Version: s.cfg.Version, Host: s.cfg.Name, Range: rg.Info(nowU), Generated: nowU,
|
||||
Hosts: []HostInfo{{Name: s.cfg.Name, Self: true, Online: true, Version: s.cfg.Version, LastSeen: nowU,
|
||||
Requests: tot.Requests, Malicious: tot.Malicious, HostileIPs: tot.HostileIPs, ActiveBans: tot.ActiveBans,
|
||||
Live: true, Location: s.Location()}},
|
||||
Totals: tot, Timeline: tl, IPs: ips,
|
||||
Totals: tot, Timeline: tl, Rates: rates, IPs: ips,
|
||||
TopPaths: topN(paths, topKeep), TopDomains: topN(doms, topKeep), TopUAs: topUAs, TopUsers: topN(users, topKeep), Countries: topN(ctry, 120),
|
||||
Recent: recent, Sources: srcs, Attribution: s.attrib,
|
||||
}
|
||||
|
||||
+22
-27
@@ -17,7 +17,8 @@ import (
|
||||
// cannot be linked across days, and nothing here reaches a snapshot or the API.
|
||||
|
||||
const (
|
||||
anMinutes = 24 * 60
|
||||
anMinutes = 49 * 60 // minute buckets (48 h plus one hour of margin)
|
||||
anDays = 31 // daily buckets for the tops
|
||||
maxDomains = 24
|
||||
visCap = 20000
|
||||
anTop = 40
|
||||
@@ -46,7 +47,7 @@ type domData struct {
|
||||
MinReq [anMinutes]uint32
|
||||
MinPages [anMinutes]uint32
|
||||
Hours [hourSlots]anHour
|
||||
Days [8]anDay
|
||||
Days [anDays]anDay
|
||||
Last int64 // unix time of the last request, for pruning idle domains
|
||||
// in memory only, never in a snapshot (unexported fields are skipped by gob)
|
||||
vis map[uint64]struct{}
|
||||
@@ -254,7 +255,7 @@ func (s *Store) Traffic(ev core.Event) {
|
||||
hs.Lat[latBucket(ev.DurationNS)]++
|
||||
}
|
||||
|
||||
dd := &d.Days[int(day%8)]
|
||||
dd := &d.Days[int(day%anDays)]
|
||||
if dd.Day != day {
|
||||
*dd = anDay{Day: day}
|
||||
}
|
||||
@@ -340,7 +341,7 @@ func orUnknown(s string) string {
|
||||
// TrafficData is the mergeable analytics payload.
|
||||
type TrafficData struct {
|
||||
Host string `json:"host"`
|
||||
Range string `json:"range"`
|
||||
Range RangeInfo `json:"range"`
|
||||
Domain string `json:"domain"`
|
||||
Generated int64 `json:"generated"`
|
||||
Domains []Count `json:"domains"`
|
||||
@@ -399,32 +400,26 @@ func (t *TrafficData) Finish() {
|
||||
t.P50, t.P95 = round1(quantile(t.Lat, 0.5)), round1(quantile(t.Lat, 0.95))
|
||||
}
|
||||
|
||||
// Traffic returns the analytics of one domain ("" or "all": every domain).
|
||||
// TrafficSummary returns the analytics of one domain for a named range.
|
||||
func (s *Store) TrafficSummary(rangeName, domain string) TrafficData {
|
||||
rg := ParseRange(rangeName)
|
||||
return s.TrafficFor(ParseRange(rangeName), domain)
|
||||
}
|
||||
|
||||
// TrafficFor returns the analytics of one domain ("" or "all": every domain).
|
||||
func (s *Store) TrafficFor(rg Range, domain string) TrafficData {
|
||||
now := s.now().Unix()
|
||||
out := TrafficData{Host: s.cfg.Name, Range: rg.Name, Domain: domain, Generated: now}
|
||||
from, to := rg.bounds(now)
|
||||
out := TrafficData{Host: s.cfg.Name, Range: rg.Info(now), Domain: domain, Generated: now}
|
||||
if out.Domain == "" {
|
||||
out.Domain = "all"
|
||||
}
|
||||
// timeline grid
|
||||
var nb int
|
||||
var step int64
|
||||
switch rg.Name {
|
||||
case "1h":
|
||||
nb, step = 60, 60
|
||||
case "24h":
|
||||
nb, step = 96, 900
|
||||
default:
|
||||
nb, step = 168, 3600
|
||||
}
|
||||
endB := now / step
|
||||
start := (endB - int64(nb) + 1) * step
|
||||
g := rg.grid(now)
|
||||
nb, step, start := g.N, g.Step, g.Start
|
||||
out.Timeline.Start, out.Timeline.Step = start, step
|
||||
out.Timeline.Req, out.Timeline.Pages = make([]uint32, nb), make([]uint32, nb)
|
||||
|
||||
firstHour := (now - int64(rg.Dur.Seconds())) / 3600
|
||||
firstDay := (now - int64(rg.Dur.Seconds())) / 86400
|
||||
firstHour, lastHour := start/3600, to/3600
|
||||
firstDay, lastDay := from/86400, to/86400
|
||||
maps := [8]map[string]uint32{{}, {}, {}, {}, {}, {}, {}, {}}
|
||||
domReq := map[string]uint32{}
|
||||
|
||||
@@ -433,14 +428,14 @@ func (s *Store) TrafficSummary(rangeName, domain string) TrafficData {
|
||||
var reqRange uint32
|
||||
for i := range d.Hours {
|
||||
h := &d.Hours[i]
|
||||
if h.Hour == 0 || h.Hour < firstHour || h.Hour > now/3600+1 {
|
||||
if h.Hour == 0 || h.Hour < firstHour || h.Hour > lastHour {
|
||||
continue
|
||||
}
|
||||
reqRange += h.Req
|
||||
if out.Domain != "all" && out.Domain != name {
|
||||
continue
|
||||
}
|
||||
if rg.Name == "7d" {
|
||||
if !g.minute() {
|
||||
out.Requests += uint64(h.Req)
|
||||
out.Pages += uint64(h.Pages)
|
||||
if b := (h.Hour*3600 - start) / step; b >= 0 && b < int64(nb) {
|
||||
@@ -461,8 +456,8 @@ func (s *Store) TrafficSummary(rangeName, domain string) TrafficData {
|
||||
if out.Domain != "all" && out.Domain != name {
|
||||
continue
|
||||
}
|
||||
if rg.Name != "7d" {
|
||||
for m := start / 60; m <= now/60; m++ {
|
||||
if g.minute() {
|
||||
for m := start / 60; m <= to/60; m++ {
|
||||
i := int(m % anMinutes)
|
||||
if d.MinSt[i] != m {
|
||||
continue
|
||||
@@ -477,7 +472,7 @@ func (s *Store) TrafficSummary(rangeName, domain string) TrafficData {
|
||||
}
|
||||
for i := range d.Days {
|
||||
dd := &d.Days[i]
|
||||
if dd.Day == 0 || dd.Day < firstDay || dd.Day > now/86400 {
|
||||
if dd.Day == 0 || dd.Day < firstDay || dd.Day > lastDay {
|
||||
continue
|
||||
}
|
||||
out.Visitors += uint64(dd.Visitors)
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/gob"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
)
|
||||
|
||||
func store30(name string) *Store {
|
||||
s := New(Config{Name: name, Version: "t", Retention: 720 * time.Hour})
|
||||
s.now = func() time.Time { return t0 }
|
||||
return s
|
||||
}
|
||||
|
||||
func TestResolveRange(t *testing.T) {
|
||||
s := store30("x")
|
||||
now := t0.Unix()
|
||||
for _, n := range RangeOrder {
|
||||
if rg, err := s.ResolveRange(n, "", ""); err != nil || rg.Name != n {
|
||||
t.Fatalf("%s: %v", n, err)
|
||||
}
|
||||
}
|
||||
if rg, _ := s.ResolveRange("", "", ""); rg.Name != "24h" {
|
||||
t.Fatal("default must be 24h")
|
||||
}
|
||||
for _, bad := range [][3]string{{"4h", "", ""}, {"garbage", "", ""}, {"", "abc", ""}, {"", "100", "50"}, {"", "", "100"}, {"", "-5", ""},
|
||||
{"", fmt.Sprint(now - 40*86400), fmt.Sprint(now)}, {"", fmt.Sprint(now - 3600), "x"}, {"", fmt.Sprint(now + 100), ""}} {
|
||||
if _, err := s.ResolveRange(bad[0], bad[1], bad[2]); !errors.Is(err, ErrRange) {
|
||||
t.Errorf("%v must be a range error, got %v", bad, err)
|
||||
}
|
||||
}
|
||||
rg, err := s.ResolveRange("", fmt.Sprint(now-7200), "")
|
||||
if err != nil || !rg.Custom() || rg.To != now || rg.Clipped {
|
||||
t.Fatalf("custom: %+v %v", rg, err)
|
||||
}
|
||||
// older than the retention: clipped and reported
|
||||
short := New(Config{Name: "x", Retention: 48 * time.Hour})
|
||||
short.now = s.now
|
||||
rg, err = short.ResolveRange("", fmt.Sprint(now-5*86400), fmt.Sprint(now-86400))
|
||||
if err != nil || !rg.Clipped || rg.From != now-48*3600 {
|
||||
t.Fatalf("clip: %+v %v", rg, err)
|
||||
}
|
||||
if info := rg.Info(now); !info.Clipped || info.From != rg.From || info.To != rg.To {
|
||||
t.Fatalf("info %+v", info)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGridSteps(t *testing.T) {
|
||||
now := t0.Unix()
|
||||
want := map[string][2]int64{"1h": {60, 60}, "2h": {60, 120}, "3h": {60, 180}, "6h": {120, 180}, "12h": {300, 144}, "24h": {900, 96},
|
||||
"2d": {900, 192}, "3d": {3600, 72}, "5d": {3600, 120}, "7d": {3600, 168}, "15d": {3600, 360}, "30d": {3600, 720}}
|
||||
for n, w := range want {
|
||||
g := Ranges[n].grid(now)
|
||||
if g.Step != w[0] || int64(g.N) != w[1] {
|
||||
t.Errorf("%s: step %d n %d, want %v", n, g.Step, g.N, w)
|
||||
}
|
||||
}
|
||||
// minute buckets only exist for 48 h: an old custom window is hourly
|
||||
s := store30("x")
|
||||
rg, _ := s.ResolveRange("", fmt.Sprint(now-10*86400), fmt.Sprint(now-10*86400+7200))
|
||||
if g := rg.grid(now); g.Step != 3600 {
|
||||
t.Fatalf("old custom step %d", g.Step)
|
||||
}
|
||||
rg, _ = s.ResolveRange("", fmt.Sprint(now-7200), "")
|
||||
if g := rg.grid(now); g.Step != 60 || g.N < 120 {
|
||||
t.Fatalf("recent custom %+v", g)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThirtyDaysRetentionAndTimelines(t *testing.T) {
|
||||
s := store30("x")
|
||||
for d := 0; d < 30; d++ {
|
||||
e := ev("1.1.1.1", core.Scanner, time.Duration(d)*24*time.Hour+time.Hour)
|
||||
e.IP = fmt.Sprintf("9.9.%d.1", d)
|
||||
s.Ingest(e)
|
||||
}
|
||||
s.Ingest(ev("2.2.2.2", core.Scanner, 31*24*time.Hour)) // beyond retention
|
||||
sum := s.Summary("30d")
|
||||
if sum.Totals.Counts["scanner"] != 30 || sum.Timeline.Step != 3600 || len(sum.Timeline.Series["scanner"]) != 720 {
|
||||
t.Fatalf("30d %+v step %d", sum.Totals.Counts, sum.Timeline.Step)
|
||||
}
|
||||
if sum.Range.Name != "30d" || sum.Range.To != t0.Unix() {
|
||||
t.Fatalf("range info %+v", sum.Range)
|
||||
}
|
||||
if len(sum.TopPaths) != 1 || sum.TopPaths[0].N != 30 {
|
||||
t.Fatalf("hour tops over 30 days: %+v", sum.TopPaths)
|
||||
}
|
||||
if s7 := s.Summary("7d"); s7.Totals.Counts["scanner"] != 7 {
|
||||
t.Fatalf("7d %d", s7.Totals.Counts["scanner"])
|
||||
}
|
||||
if s2 := s.Summary("2d"); s2.Timeline.Step != 900 || s2.Totals.Counts["scanner"] != 2 {
|
||||
t.Fatalf("2d %+v", s2.Totals.Counts)
|
||||
}
|
||||
if _, ok := s.IP("2.2.2.2"); ok {
|
||||
t.Fatal("beyond retention")
|
||||
}
|
||||
// IP table: last within 30 d
|
||||
if len(s.AllIPs(Ranges["30d"], false)) != 30 {
|
||||
t.Fatal("ip table over 30d")
|
||||
}
|
||||
// custom window
|
||||
rg, _ := s.ResolveRange("", fmt.Sprint(t0.Unix()-3*86400-7200), fmt.Sprint(t0.Unix()-2*86400))
|
||||
cs := s.SummaryFor(rg)
|
||||
if cs.Totals.Counts["scanner"] < 1 || cs.Range.Name != "custom" {
|
||||
t.Fatalf("custom window: %+v %+v", cs.Totals.Counts, cs.Range)
|
||||
}
|
||||
tr := s.TrafficFor(Ranges["30d"], "all")
|
||||
if tr.Range.Name != "30d" || len(tr.Timeline.Req) != 720 {
|
||||
t.Fatalf("traffic grid %d", len(tr.Timeline.Req))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRates(t *testing.T) {
|
||||
s := store30("x")
|
||||
for i := 0; i < 5; i++ {
|
||||
s.Ingest(ev(fmt.Sprintf("1.1.1.%d", i+1), core.Exploit, time.Duration(i+1)*time.Minute))
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
s.Ingest(ev("1.1.1.1", core.Scanner, 3*time.Hour+time.Duration(i)*time.Minute))
|
||||
}
|
||||
old := ev("8.8.8.8", core.Scanner, 50*time.Hour) // previous period of a 24h window? no: 2 days back
|
||||
s.Ingest(old)
|
||||
s.Ingest(ev("3.3.3.3", core.OK, time.Minute))
|
||||
r := s.Summary("24h").Rates
|
||||
if r.Last15m != 5 || r.Last1h != 5 || r.Last24h != 8 || r.PerHourAvg24h != 0.3 {
|
||||
t.Fatalf("rates %+v", r)
|
||||
}
|
||||
if r.PeakHour.N != 5 || r.ActiveAttackers != 5 || r.NewAttackers != 5 {
|
||||
t.Fatalf("peak/attackers %+v", r)
|
||||
}
|
||||
if r.ChangePct != nil || r.PrevPeriod != 0 {
|
||||
t.Fatalf("no previous activity must be null: %+v", r)
|
||||
}
|
||||
r2 := s.Summary("7d").Rates
|
||||
if r2.PerHourAvg7d != round1(9.0/168) || r2.Last24h != 8 {
|
||||
t.Fatalf("7d %+v", r2)
|
||||
}
|
||||
s.Ingest(ev("7.7.7.7", core.Scanner, 30*time.Hour)) // previous 24h period
|
||||
s.invalidate()
|
||||
if r := s.Summary("24h").Rates; r.PrevPeriod != 1 || r.ChangePct == nil || *r.ChangePct != 700 {
|
||||
t.Fatalf("change %+v", r)
|
||||
}
|
||||
b, _ := json.Marshal(s.Summary("24h").Rates)
|
||||
for _, k := range []string{"last15m", "last1h", "last24h", "per_hour_avg_24h", "per_hour_avg_7d", "prev_period", "change_pct", "peak_hour", "new_attackers", "active_attackers"} {
|
||||
if !bytes.Contains(b, []byte(`"`+k+`"`)) {
|
||||
t.Errorf("missing %s", k)
|
||||
}
|
||||
}
|
||||
m := Merge("all", []Summary{s.Summary("24h"), s.Summary("24h")})
|
||||
if m.Rates.Last24h != 2*r.Last24h || m.Rates.PeakHour.N != 10 {
|
||||
t.Fatalf("merged rates %+v", m.Rates)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotMigrationFromV1(t *testing.T) {
|
||||
var v snapshotV1
|
||||
v.V, v.Saved = 1, t0.Unix()
|
||||
m := t0.Unix()/60 - 90
|
||||
i := int(m % (7 * 24 * 60))
|
||||
v.Stamps[i], v.Counts[i][core.Exploit.Index()] = m, 4
|
||||
old := t0.Unix()/60 - 3*24*60 // 3 days ago: older than the new minute window
|
||||
j := int(old % (7 * 24 * 60))
|
||||
v.Stamps[j], v.Counts[j][core.Scanner.Index()] = old, 6
|
||||
v.MonSt[i], v.MonN[i] = m, 3
|
||||
hr := old / 60
|
||||
v.Hours[int(hr%(7*24))] = hourSlot{Hour: hr, Paths: map[string]uint32{"/x": 6}}
|
||||
v.IPs = map[string]*IPRec{"1.2.3.4": {First: t0.Unix() - 100, Last: t0.Unix() - 50, Score: 8, Counts: [core.NumCats]uint32{3: 1}}}
|
||||
d := &domDataV1{Last: t0.Unix()}
|
||||
d.MinSt[5], d.MinReq[5] = t0.Unix()/60-5, 7
|
||||
d.Hours[10] = anHour{Hour: t0.Unix()/3600 - 2, Req: 11}
|
||||
d.Days[3] = anDay{Day: t0.Unix()/86400 - 1, Visitors: 4, Pages: map[string]uint32{"/": 4}}
|
||||
v.Dom = map[string]*domDataV1{"a.example": d}
|
||||
var buf bytes.Buffer
|
||||
if err := gob.NewEncoder(&buf).Encode(&v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "state.gob")
|
||||
os.WriteFile(path, buf.Bytes(), 0o600)
|
||||
s := store30("x")
|
||||
if _, err := s.Load(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sum := s.Summary("3h"); sum.Totals.Counts["exploit"] != 4 || sum.Totals.Monitoring != 3 {
|
||||
t.Fatalf("minute data lost: %+v", sum.Totals)
|
||||
}
|
||||
if sum := s.Summary("7d"); sum.Totals.Counts["exploit"] != 4 || sum.Totals.Counts["scanner"] != 6 || len(sum.TopPaths) != 1 {
|
||||
t.Fatalf("hour data lost: %+v %+v", sum.Totals.Counts, sum.TopPaths)
|
||||
}
|
||||
if r, ok := s.IP("1.2.3.4"); !ok || r.Score != 8 {
|
||||
t.Fatal("ip lost")
|
||||
}
|
||||
if tr := s.TrafficSummary("24h", "all"); tr.Requests != 7+0 && tr.Requests != 7 {
|
||||
t.Fatalf("traffic minutes lost: %d", tr.Requests)
|
||||
}
|
||||
if tr := s.TrafficSummary("7d", "all"); tr.Requests != 11 || tr.Visitors != 0 && tr.Visitors > tr.Pages {
|
||||
t.Fatalf("traffic hours: %+v", tr.Requests)
|
||||
}
|
||||
// the migrated state saves and reloads as version 2
|
||||
p2 := filepath.Join(t.TempDir(), "s2.gob")
|
||||
if err := s.Save(p2, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s2 := store30("x")
|
||||
if _, err := s2.Load(p2); err != nil || s2.Summary("7d").Totals.Counts["scanner"] != 6 {
|
||||
t.Fatalf("v2 round trip: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func openLog(t *testing.T) *evlog.Log {
|
||||
l, err := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events"), Now: func() time.Time { return t0 }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func TestEventRegistryContentAndPrivacy(t *testing.T) {
|
||||
s := store30("oracle")
|
||||
l := openLog(t)
|
||||
s.SetEventLog(l)
|
||||
// a visitor: ok and 404, never recorded
|
||||
s.Ingest(ev("3.3.3.3", core.OK, time.Minute))
|
||||
s.Ingest(ev("4.4.4.4", core.NotFound, time.Minute))
|
||||
// an attacker; once suspicious its ok answers are recorded too
|
||||
for i := 0; i < 4; i++ {
|
||||
e := ev("1.1.1.1", core.Exploit, time.Duration(i)*time.Second+time.Minute)
|
||||
e.Path, e.Status, e.Bytes, e.DurationNS, e.Strong = "/.git/config", 200, 321, 5e6, true
|
||||
s.Ingest(e)
|
||||
}
|
||||
ok := ev("1.1.1.1", core.OK, 30*time.Second)
|
||||
ok.Status, ok.Path = 200, "/index.html"
|
||||
s.Ingest(ok)
|
||||
s.Ingest(core.Event{Time: t0.Add(-20 * time.Second), IP: "1.1.1.1", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
|
||||
s.Ingest(core.Event{Time: t0.Add(-10 * time.Second), IP: "1.1.1.1", Cat: core.Ban, Source: "fail2ban", Jail: "sshd", Unban: true})
|
||||
s.Ingest(core.Event{Time: t0.Add(-9 * time.Second), IP: "5.5.5.5", Cat: core.SSHOK, Source: "ssh", User: "root"})
|
||||
s.Ingest(core.Event{Time: t0.Add(-8 * time.Second), IP: "6.6.6.6", Cat: core.Ban, Source: "fail2ban", Jail: "sshd", Restore: true})
|
||||
page, err := s.QueryEvents(EventsQuery{From: t0.Unix() - 3600, To: t0.Unix(), Limit: 100})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ips = map[string]int{}
|
||||
var first map[string]any
|
||||
for _, raw := range page.Events {
|
||||
var m map[string]any
|
||||
json.Unmarshal(raw, &m)
|
||||
ips[m["ip"].(string)]++
|
||||
if first == nil && m["cat"] == "exploit" {
|
||||
first = m
|
||||
}
|
||||
if m["id"] == nil || m["host"] != "oracle" {
|
||||
t.Fatalf("id and host are required: %s", raw)
|
||||
}
|
||||
}
|
||||
if ips["3.3.3.3"] != 0 || ips["4.4.4.4"] != 0 || ips["6.6.6.6"] != 0 {
|
||||
t.Fatalf("visitors and restored bans must not be recorded: %v", ips)
|
||||
}
|
||||
if ips["1.1.1.1"] != 7 || ips["5.5.5.5"] != 1 {
|
||||
t.Fatalf("recorded %v", ips)
|
||||
}
|
||||
for _, k := range []string{"t", "ip", "cat", "source", "host", "domain", "method", "path", "status", "ua", "fam", "tech", "marker", "bytes", "dur_ms", "flags"} {
|
||||
if _, ok := first[k]; !ok {
|
||||
t.Errorf("event line misses %q: %v", k, first)
|
||||
}
|
||||
}
|
||||
if first["fam"] != "vcs-exposure" && first["fam"] == "" {
|
||||
t.Fatalf("family: %v", first["fam"])
|
||||
}
|
||||
if !strings.Contains(first["flags"].(string), "S") {
|
||||
t.Fatalf("flags %v", first["flags"])
|
||||
}
|
||||
// ids increase
|
||||
var last float64
|
||||
desc, _ := s.QueryEvents(EventsQuery{From: t0.Unix() - 3600, To: t0.Unix(), Limit: 100, IP: "1.1.1.1"})
|
||||
if len(desc.Events) != 7 {
|
||||
t.Fatal(len(desc.Events))
|
||||
}
|
||||
for _, raw := range page.Events {
|
||||
var m struct{ ID float64 }
|
||||
json.Unmarshal(raw, &m)
|
||||
if m.ID == last {
|
||||
t.Fatal("duplicate id")
|
||||
}
|
||||
last = m.ID
|
||||
}
|
||||
// peer event
|
||||
le := LiveEvent{FeedEvent: FeedEvent{T: t0.Unix() - 5, IP: "9.9.9.9", Cat: "exploit", Source: "traefik", Host: "peer1"}}
|
||||
s.RecordPeerEvent(&le)
|
||||
if le.ID == 0 {
|
||||
t.Fatal("peer event needs a local id")
|
||||
}
|
||||
if p, _ := s.QueryEvents(EventsQuery{From: t0.Unix() - 3600, To: t0.Unix(), Host: "peer1"}); len(p.Events) != 1 {
|
||||
t.Fatalf("peer filter %d", len(p.Events))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionsAndIPDetail(t *testing.T) {
|
||||
s := store30("oracle")
|
||||
s.SetEventLog(openLog(t))
|
||||
for i, off := range []time.Duration{0, 2 * time.Minute, 4 * time.Minute, 3 * time.Hour, 3*time.Hour + time.Minute} {
|
||||
e := ev("1.1.1.1", core.Exploit, 6*time.Hour-off)
|
||||
e.Path = fmt.Sprintf("/wp-login.php?%d", i)
|
||||
e.Status = 404
|
||||
s.Ingest(e)
|
||||
}
|
||||
s.Ingest(ev("1.1.1.2", core.Scanner, time.Hour))
|
||||
ss, trunc := s.Sessions(t0.Unix()-86400, t0.Unix(), "", "", 900)
|
||||
if trunc || len(ss) != 3 {
|
||||
t.Fatalf("sessions %d: %+v", len(ss), ss)
|
||||
}
|
||||
for i := 1; i < len(ss); i++ {
|
||||
if ss[i].Start < ss[i-1].Start {
|
||||
t.Fatal("order")
|
||||
}
|
||||
}
|
||||
if ss[0].Events != 3 || ss[0].IP != "1.1.1.1" || ss[0].Score != 24 || len(ss[0].Cats) != 1 {
|
||||
t.Fatalf("%+v", ss[0])
|
||||
}
|
||||
if one, _ := s.Sessions(t0.Unix()-86400, t0.Unix(), "", "1.1.1.1", 86400); len(one) != 1 || one[0].Events != 5 {
|
||||
t.Fatalf("gap %+v", one)
|
||||
}
|
||||
il := s.IPLogOf("1.1.1.1", t0.Unix()-30*86400, t0.Unix())
|
||||
if !il.Available || il.Events != 5 || len(il.Paths) != 5 || il.Paths[0].N != 1 || len(il.Statuses) != 1 || il.Statuses[0].Key != "404" {
|
||||
t.Fatalf("ip log %+v", il)
|
||||
}
|
||||
var tot uint32
|
||||
for _, v := range il.Timeline.Series["exploit"] {
|
||||
tot += v
|
||||
}
|
||||
if tot != 5 || len(il.Timeline.Series["exploit"]) != 722 && len(il.Timeline.Series["exploit"]) < 720 {
|
||||
t.Fatalf("timeline %d", tot)
|
||||
}
|
||||
if len(il.Sessions) != 2 || il.Cadence.N == 0 {
|
||||
t.Fatalf("sessions %d cadence %+v", len(il.Sessions), il.Cadence)
|
||||
}
|
||||
info, ok := s.IPInfoOf("1.1.1.1")
|
||||
if !ok || info.ScoreBreakdown["exploit"] != 40 || info.Status[3] != 5 {
|
||||
t.Fatalf("info %+v", info)
|
||||
}
|
||||
sub, _, _ := s.Neighbors("1.1.1.1", t0.Unix()-86400, t0.Unix())
|
||||
_ = sub
|
||||
if n, _, _ := s.Neighbors("1.1.1.1", t0.Unix()-86400, t0.Unix()); len(n) != 1 || n[0].IP != "1.1.1.2" {
|
||||
t.Fatalf("/24 neighbors %+v", n)
|
||||
}
|
||||
p := s.Period(PeriodQuery{From: t0.Unix() - 86400, To: t0.Unix()})
|
||||
if !p.Enabled || p.SessionsN != 3 || p.Events != 6 || len(p.TopFams) == 0 || p.NewVsReturning["new"] != 2 || p.EventsCursor == "" {
|
||||
t.Fatalf("period %+v", p)
|
||||
}
|
||||
m := s.Metrics(Ranges["24h"])
|
||||
if m.AttacksPerHour24h.Value == 0 || m.SessionsPerDay.Value == 0 || len(m.AttacksPerHour24h.Spark) != 24 {
|
||||
t.Fatalf("metrics %+v", m)
|
||||
}
|
||||
}
|
||||
|
||||
// Worst case memory and snapshot size of the 30 day layout.
|
||||
func TestWorstCaseThirtyDayMemoryAndSnapshot(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip()
|
||||
}
|
||||
st := New(Config{Name: "x", Retention: 720 * time.Hour})
|
||||
h0 := heapMiB()
|
||||
now := time.Now()
|
||||
// every hour of the 30 days has full top lists
|
||||
for h := 0; h < 720; h++ {
|
||||
ts := now.Add(-time.Duration(h) * time.Hour)
|
||||
for k := 0; k < 80; k++ {
|
||||
st.Ingest(core.Event{Time: ts, IP: fmt.Sprintf("10.%d.%d.%d", h%200+20, k, h/200), Cat: core.Scanner, Source: "traefik", Method: "GET", Status: 404,
|
||||
Domain: fmt.Sprintf("d%d-%d.", h, k) + strings.Repeat("x", 60), Path: fmt.Sprintf("/%d-%d-", h, k) + strings.Repeat("A", 150),
|
||||
UA: fmt.Sprintf("ua%d-%d", h, k) + strings.Repeat("U", 100), E: core.Enrich{CC: fmt.Sprintf("%c%c", 'A'+k%26, 'A'+(k/26)%26)}})
|
||||
st.Ingest(core.Event{Time: ts, IP: fmt.Sprintf("10.%d.%d.%d", h%200+20, k, h/200), Cat: core.SSHFail, Source: "ssh", User: fmt.Sprintf("user%d-%d", h, k)})
|
||||
}
|
||||
}
|
||||
// analytics: 24 domains, 31 days, full top lists
|
||||
for d := 0; d < 24; d++ {
|
||||
for day := 0; day < 30; day++ {
|
||||
ts := now.Add(-time.Duration(day) * 24 * time.Hour)
|
||||
for k := 0; k < 45; k++ {
|
||||
st.Traffic(core.Event{Time: ts, IP: fmt.Sprintf("20.%d.%d.%d", d, day, k), Cat: core.OK, Source: "traefik", Domain: fmt.Sprintf("site%d.example", d),
|
||||
Method: "GET", Path: fmt.Sprintf("/p%d/%d", day, k), Status: 200, UA: fmt.Sprintf("ua%d", k), Referer: fmt.Sprintf("https://r%d.example/", k),
|
||||
E: core.Enrich{CC: "BR", City: fmt.Sprintf("City%d", k), Browser: fmt.Sprintf("B%d", k), OS: fmt.Sprintf("O%d", k), Device: "desktop"}})
|
||||
}
|
||||
}
|
||||
}
|
||||
grew := heapMiB() - h0
|
||||
path := filepath.Join(t.TempDir(), "s.gob")
|
||||
if err := st.Save(path, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fi, _ := os.Stat(path)
|
||||
var ms runtime.MemStats
|
||||
runtime.ReadMemStats(&ms)
|
||||
t.Logf("WORST CASE 30d: IPs=%d heap growth=%d MiB snapshot=%d KiB", st.IPCount(), grew, fi.Size()>>10)
|
||||
if grew > 120 {
|
||||
t.Fatalf("worst case heap growth %d MiB", grew)
|
||||
}
|
||||
runtime.KeepAlive(st)
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
)
|
||||
|
||||
func TestListedSinceAndMigration(t *testing.T) {
|
||||
s := store30("x")
|
||||
s.SetAdminUsers([]string{"lucas"})
|
||||
var at int64
|
||||
for i := 0; i < 8; i++ {
|
||||
e := ev("1.1.1.1", core.Exploit, time.Duration(8-i)*time.Minute)
|
||||
e.Strong = true
|
||||
s.Ingest(e) // 8 per event: crosses 50 on the 7th
|
||||
if r := s.ips["1.1.1.1"]; r.ListedSince != 0 && at == 0 {
|
||||
at = r.ListedSince
|
||||
}
|
||||
}
|
||||
if at != e0(t0, 2*time.Minute) {
|
||||
t.Fatalf("ListedSince %d, want the instant of the 7th event", at)
|
||||
}
|
||||
s.ips["1.1.1.1"].ListedSince = 0 // a record saved before the field existed
|
||||
path := filepath.Join(t.TempDir(), "s.gob")
|
||||
if err := s.Save(path, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s2 := store30("x")
|
||||
if _, err := s2.Load(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := s2.ips["1.1.1.1"].ListedSince; got == 0 || got != s2.ips["1.1.1.1"].Last {
|
||||
t.Fatalf("migration must estimate it: %d", got)
|
||||
}
|
||||
if info, _ := s2.IPInfoOf("1.1.1.1"); info.ListedSince == 0 {
|
||||
t.Fatal("info")
|
||||
}
|
||||
// an admin login ends it
|
||||
s.ips["1.1.1.1"].ListedSince = at
|
||||
s.Ingest(core.Event{Time: t0.Add(time.Second), IP: "1.1.1.1", Cat: core.SSHOK, Source: "ssh", User: "lucas"})
|
||||
if s.ips["1.1.1.1"].ListedSince != 0 {
|
||||
t.Fatalf("an admin login ends the listing: %d", s.ips["1.1.1.1"].ListedSince)
|
||||
}
|
||||
if !s.IsAdminUser("lucas") || s.IsAdminUser("root") {
|
||||
t.Fatal("IsAdminUser")
|
||||
}
|
||||
}
|
||||
|
||||
func e0(t time.Time, ago time.Duration) int64 { return t.Add(-ago).Unix() }
|
||||
|
||||
func TestIPLogForgedFlag(t *testing.T) {
|
||||
s := store30("x")
|
||||
s.SetEventLog(openLog(t))
|
||||
e := ev("1.1.1.1", core.Exploit, time.Minute)
|
||||
e.Forged = true
|
||||
s.Ingest(e)
|
||||
s.Ingest(ev("2.2.2.2", core.Exploit, time.Minute))
|
||||
if !s.IPLogOf("1.1.1.1", t0.Unix()-3600, t0.Unix()).Forged || s.IPLogOf("2.2.2.2", t0.Unix()-3600, t0.Unix()).Forged {
|
||||
t.Fatal("forged flag")
|
||||
}
|
||||
}
|
||||
|
||||
func samplePeriod(host string, ips ...string) PeriodOut {
|
||||
p := PeriodOut{Enabled: true, Events: 10, SessionsN: len(ips), NewVsReturning: map[string]int{"new": len(ips)},
|
||||
TopFams: []Count{{Key: "vcs", N: 3}}, TopTechs: []Count{{Key: "T1190", N: 2}}}
|
||||
for _, ip := range ips {
|
||||
p.Sessions = append(p.Sessions, intel.Session{ID: "s-" + ip, IP: ip, Start: t0.Add(-time.Hour), End: t0, N: 3, Hosts: []string{host}, Stage: "exploit",
|
||||
Cats: map[string]int{"exploit": 3}})
|
||||
}
|
||||
p.FirstSeenTech = []FirstTech{{ID: "T1190", Name: "x", T: t0.Unix() - 100, IP: ips[0]}}
|
||||
p.TopTargets = []Target{{Host: host, Domain: "a.example", N: 5}}
|
||||
return p
|
||||
}
|
||||
|
||||
func TestSanitizePeerStudyAndMerge(t *testing.T) {
|
||||
st := PeerStudy{V: ExportVersion, Period: samplePeriod("EVIL", "1.2.3.4", "not-an-ip", "5.6.7.8"), Metrics: MetricsOut{}}
|
||||
st.Period.Sessions[0].Cats = map[string]int{}
|
||||
for i := 0; i < 500; i++ {
|
||||
st.Period.Sessions[0].Cats[strings.Repeat("c", 1+i)] = i
|
||||
st.Period.Sessions = append(st.Period.Sessions, st.Period.Sessions[2])
|
||||
}
|
||||
st.Period.Sessions[2].Start = time.Date(1900, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
st.Period.FirstSeenTech[0].Name = "<script>"
|
||||
st.Period.Escalations = []EscalationOut{{Session: "s", IP: "1.2.3.4", Stage: "exploit", Steps: append([]intel.Step{{}}, func() []intel.Step {
|
||||
l := make([]intel.Step, 100)
|
||||
for i := range l {
|
||||
l[i].T = t0
|
||||
}
|
||||
return l
|
||||
}()...)}}
|
||||
st.Metrics.AttacksPerHour24h = Metric{Value: math.Inf(1), Spark: make([]float64, 5000)}
|
||||
st.Metrics.MTTB.MedianS = math.NaN()
|
||||
if !st.Sanitize("hostinger") {
|
||||
t.Fatal("rejected")
|
||||
}
|
||||
if len(st.Period.Sessions) > capSessions || len(st.Period.Sessions[0].Cats) > 12 {
|
||||
t.Fatalf("caps: %d sessions, %d cats", len(st.Period.Sessions), len(st.Period.Sessions[0].Cats))
|
||||
}
|
||||
for _, x := range st.Period.Sessions {
|
||||
if x.IP == "not-an-ip" || x.Start.Year() < 2000 || len(x.Hosts) != 1 || x.Hosts[0] != "hostinger" {
|
||||
t.Fatalf("bad session kept: %+v", x)
|
||||
}
|
||||
}
|
||||
if st.Period.FirstSeenTech[0].Name == "<script>" || len(st.Period.Escalations[0].Steps) != capSteps || st.Period.Escalations[0].Host != "hostinger" {
|
||||
t.Fatalf("names are never taken from a peer: %+v", st.Period.FirstSeenTech)
|
||||
}
|
||||
if st.Metrics.AttacksPerHour24h.Value != 0 || len(st.Metrics.AttacksPerHour24h.Spark) > capSpark || st.Metrics.MTTB.MedianS != 0 {
|
||||
t.Fatalf("metrics %+v", st.Metrics.AttacksPerHour24h.Value)
|
||||
}
|
||||
if b, _ := json.Marshal(st); len(b) > 4<<20 {
|
||||
t.Fatalf("sanitized document is %d bytes", len(b))
|
||||
}
|
||||
if (&PeerStudy{V: 99}).Sanitize("x") {
|
||||
t.Fatal("wrong version")
|
||||
}
|
||||
|
||||
a := samplePeriod("oracle", "1.1.1.1")
|
||||
b := samplePeriod("hostinger", "2.2.2.2", "3.3.3.3")
|
||||
b.FirstSeenTech[0].T = a.FirstSeenTech[0].T - 50
|
||||
m := MergePeriods([]PeriodOut{a, b})
|
||||
if m.SessionsN != 3 || m.Events != 20 || len(m.Sessions) != 3 || m.NewVsReturning["new"] != 3 || m.FirstSeenTech[0].T != b.FirstSeenTech[0].T {
|
||||
t.Fatalf("merge %+v", m)
|
||||
}
|
||||
hosts := map[string]bool{}
|
||||
for _, x := range m.Sessions {
|
||||
hosts[x.Hosts[0]] = true
|
||||
}
|
||||
if !hosts["oracle"] || !hosts["hostinger"] || m.TopFams[0].N != 6 || len(m.TopTargets) != 2 {
|
||||
t.Fatalf("hosts %v fams %v targets %v", hosts, m.TopFams, m.TopTargets)
|
||||
}
|
||||
ma := MetricsOut{AttacksPerHour24h: mk(2, 1, []float64{1, 2}), ExposureRate: mk(10, 0, nil)}
|
||||
mb := MetricsOut{AttacksPerHour24h: mk(4, 3, []float64{3, 4}), ExposureRate: mk(30, 0, nil)}
|
||||
ma.MTTB.MedianS, ma.MTTB.N = 10, 1
|
||||
mb.MTTB.MedianS, mb.MTTB.N = 40, 3
|
||||
mm := MergeMetrics([]MetricsOut{ma, mb})
|
||||
if mm.AttacksPerHour24h.Value != 6 || mm.AttacksPerHour24h.Prev != 4 || mm.AttacksPerHour24h.Spark[1] != 6 || mm.ExposureRate.Value != 20 || mm.MTTB.MedianS != 32.5 || mm.MTTB.N != 4 {
|
||||
t.Fatalf("metrics merge %+v %+v", mm.AttacksPerHour24h, mm.MTTB)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPTimelineAndActiveDaysWithoutRegistryHistory(t *testing.T) {
|
||||
s := store30("x")
|
||||
// events from three days, ingested before any registry exists (an upgrade
|
||||
// from a snapshot, or a registry that was just enabled)
|
||||
for i, d := range []time.Duration{50 * time.Hour, 26 * time.Hour, time.Hour} {
|
||||
e := ev("1.1.1.1", core.Scanner, d)
|
||||
s.Ingest(e)
|
||||
if i == 2 {
|
||||
n := ev("1.1.1.1", core.NotFound, d)
|
||||
n.E.Tool = true
|
||||
s.Ingest(n) // not malicious, still an active day
|
||||
}
|
||||
}
|
||||
s.SetEventLog(openLog(t))
|
||||
il := s.IPLogOf("1.1.1.1", t0.Unix()-30*86400, t0.Unix())
|
||||
if il.Source != "counters" || il.Timeline.Step != 86400 {
|
||||
t.Fatalf("source %q step %d", il.Source, il.Timeline.Step)
|
||||
}
|
||||
var sc, nf uint32
|
||||
for _, v := range il.Timeline.Series["scanner"] {
|
||||
sc += v
|
||||
}
|
||||
for _, v := range il.Timeline.Series["notfound"] {
|
||||
nf += v
|
||||
}
|
||||
if sc != 3 || nf != 1 {
|
||||
t.Fatalf("daily counters: scanner %d notfound %d", sc, nf)
|
||||
}
|
||||
if info, _ := s.IPInfoOf("1.1.1.1"); info.ActiveDays != 3 {
|
||||
t.Fatalf("active days %d", info.ActiveDays)
|
||||
}
|
||||
// once the registry has events, the hourly timeline wins
|
||||
s.Ingest(ev("1.1.1.1", core.Exploit, 30*time.Minute))
|
||||
s.ipx.m = nil
|
||||
il = s.IPLogOf("1.1.1.1", t0.Unix()-30*86400, t0.Unix())
|
||||
if il.Source != "events" || il.Timeline.Step != 3600 {
|
||||
t.Fatalf("source %q", il.Source)
|
||||
}
|
||||
if info, _ := s.IPInfoOf("1.1.1.1"); info.ActiveDays != 3 { // same day as an earlier event
|
||||
t.Fatalf("active days %d", info.ActiveDays)
|
||||
}
|
||||
// a record saved by the previous version gets the counters on load
|
||||
s.ips["2.2.2.2"] = &IPRec{First: t0.Unix() - 100, Last: t0.Unix() - 50, Score: 3, Counts: func() (c [core.NumCats]uint32) { c[core.Scanner.Index()] = 4; return }()}
|
||||
path := filepath.Join(t.TempDir(), "s.gob")
|
||||
s.Save(path, nil)
|
||||
s2 := store30("x")
|
||||
s2.Load(path)
|
||||
s2.SetEventLog(openLog(t))
|
||||
il = s2.IPLogOf("2.2.2.2", t0.Unix()-30*86400, t0.Unix())
|
||||
var tot uint32
|
||||
for _, v := range il.Timeline.Series["scanner"] {
|
||||
tot += v
|
||||
}
|
||||
if il.Source != "counters" || tot != 4 {
|
||||
t.Fatalf("migrated record: %q %d", il.Source, tot)
|
||||
}
|
||||
if info, _ := s2.IPInfoOf("2.2.2.2"); info.ActiveDays != 1 {
|
||||
t.Fatalf("migrated active days %d", info.ActiveDays)
|
||||
}
|
||||
// the day ring shifts correctly over many days
|
||||
r := &IPRec{}
|
||||
for d := int64(0); d < 40; d++ {
|
||||
touchDay(r, (20000+d)*86400, core.Scanner.Index())
|
||||
}
|
||||
if len(r.DayCats) != 30 || r.DayCats[0][core.Scanner.Index()] != 1 || r.Days != 1<<30-1 {
|
||||
t.Fatalf("ring: len %d days %b", len(r.DayCats), r.Days)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExposureOnlyForSensitiveFamilies(t *testing.T) {
|
||||
s := store30("x")
|
||||
req := func(ip, path string, status int, bytes int64) {
|
||||
e := ev(ip, core.Scanner, time.Minute)
|
||||
e.Path, e.Status, e.Bytes, e.Soft = path, status, bytes, status < 400
|
||||
e.Strong = true // the address is plainly hostile
|
||||
s.Ingest(e)
|
||||
}
|
||||
// the domain's typical 404 / SPA body is 1200 bytes
|
||||
for i := 0; i < 3; i++ {
|
||||
nf := ev("30.0.0.1", core.NotFound, time.Minute)
|
||||
nf.Path, nf.Status, nf.Bytes = "/nope"+string(rune('a'+i)), 404, 1200
|
||||
s.Ingest(nf)
|
||||
}
|
||||
exposed := func(ip string) int {
|
||||
info, _ := s.IPInfoOf(ip)
|
||||
return len(info.Expo)
|
||||
}
|
||||
req("1.0.0.1", "/robots.txt", 200, 80)
|
||||
req("1.0.0.2", "/wp-login.php", 200, 5000)
|
||||
req("1.0.0.3", "/.env", 200, 0) // empty body
|
||||
req("1.0.0.4", "/.env", 200, 1200) // the SPA / typical 404 page
|
||||
req("1.0.0.5", "/.env", 200, 412) // a real file
|
||||
req("1.0.0.6", "/.git/config", 200, 150)
|
||||
req("1.0.0.7", "/.env", 404, 412) // refused
|
||||
req("1.0.0.8", "/.env", 302, 412) // redirect
|
||||
req("1.0.0.9", "/actuator/env", 200, 3000)
|
||||
for ip, want := range map[string]int{"1.0.0.1": 0, "1.0.0.2": 0, "1.0.0.3": 0, "1.0.0.4": 0, "1.0.0.5": 1, "1.0.0.6": 1, "1.0.0.7": 0, "1.0.0.8": 0, "1.0.0.9": 1} {
|
||||
if got := exposed(ip); got != want {
|
||||
t.Errorf("%s: %d exposures, want %d", ip, got, want)
|
||||
}
|
||||
}
|
||||
info, _ := s.IPInfoOf("1.0.0.5")
|
||||
if info.Expo[0].Fam != "env-credentials" || info.Expo[0].Bytes != 412 {
|
||||
t.Fatalf("%+v", info.Expo)
|
||||
}
|
||||
// a plain visitor-like address with no strong sign does not expose an admin page
|
||||
e := ev("1.0.0.10", core.Scanner, time.Minute)
|
||||
e.Path, e.Status, e.Bytes = "/admin", 200, 900
|
||||
s.Ingest(e)
|
||||
if exposed("1.0.0.10") != 0 {
|
||||
t.Fatal("a public /admin page without a strong sign is not an exposure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStudyDeadlineSingleflightAndGap(t *testing.T) {
|
||||
s := store30("x")
|
||||
s.SetEventLog(openLog(t))
|
||||
for i := 0; i < 40; i++ { // 40 events 30 s apart from one address
|
||||
e := ev("1.1.1.1", core.Scanner, time.Duration(40-i)*30*time.Second)
|
||||
e.Path = "/wp-login.php"
|
||||
s.Ingest(e)
|
||||
}
|
||||
q := PeriodQuery{From: t0.Unix() - 3600, To: t0.Unix(), Gap: 5} // a gap under 60 s is raised to 60 s
|
||||
if p := s.period(q); p.SessionsN != 1 {
|
||||
t.Fatalf("gap floor: %d sessions", p.SessionsN)
|
||||
}
|
||||
old := studyDead
|
||||
studyDead = time.Nanosecond
|
||||
p := s.period(PeriodQuery{From: t0.Unix() - 3600, To: t0.Unix()})
|
||||
studyDead = old
|
||||
if !p.Truncated {
|
||||
t.Fatal("a study past its deadline must be returned partial with truncated")
|
||||
}
|
||||
// concurrent callers of one key share one computation
|
||||
var calls atomic.Int32
|
||||
k := studyKey{kind: "sf"}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
s.cached(k, func() any { calls.Add(1); time.Sleep(80 * time.Millisecond); return 1 })
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("computed %d times", calls.Load())
|
||||
}
|
||||
// the slow cache keeps a campaign study for minutes
|
||||
a := s.PeriodSlow(PeriodQuery{From: t0.Unix() - 3600, To: t0.Unix()})
|
||||
s.Ingest(ev("1.1.1.2", core.Scanner, time.Minute))
|
||||
if b := s.PeriodSlow(PeriodQuery{From: t0.Unix() - 3600, To: t0.Unix()}); b.Events != a.Events {
|
||||
t.Fatal("PeriodSlow must serve the cached study")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerStudySanitizeSecurityFields(t *testing.T) {
|
||||
c := intel.Campaign{ID: strings.Repeat("i", 100), SignatureID: strings.Repeat("s", 100), First: t0, Last: t0, IPs: []string{"1.2.3.4"}}
|
||||
st := PeerStudy{V: ExportVersion, Period: PeriodOut{
|
||||
Campaigns: []intel.Campaign{c},
|
||||
Escalations: []EscalationOut{{IP: "1.2.3.4", Steps: []intel.Step{{Stage: "recon", T: t0}, {Stage: "x"}, {Stage: "y", T: time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)}}}},
|
||||
TopTechs: []Count{{Key: "T1190", Label: "<script>", N: 2}},
|
||||
Spikes: []intel.Spike{{At: t0, Value: 1 << 40, Baseline: 1, Threshold: 2}, {At: t0, Value: 5, Baseline: 1, Threshold: 2}},
|
||||
TopTargets: []Target{{Domain: "a", N: 1 << 40}, {Domain: "b", N: 3}},
|
||||
}}
|
||||
if !st.Sanitize("p") {
|
||||
t.Fatal("rejected")
|
||||
}
|
||||
p := st.Period
|
||||
if len(p.Campaigns[0].ID) != 32 || len(p.Campaigns[0].SignatureID) != 32 {
|
||||
t.Fatal("campaign ids must be clipped")
|
||||
}
|
||||
if len(p.Escalations[0].Steps) != 1 {
|
||||
t.Fatalf("steps with an invalid time are dropped: %d", len(p.Escalations[0].Steps))
|
||||
}
|
||||
if p.TopTechs[0].Label != intel.TechniqueName("T1190") || p.TopTechs[0].Label == "<script>" {
|
||||
t.Fatalf("label %q", p.TopTechs[0].Label)
|
||||
}
|
||||
if len(p.Spikes) != 1 || p.Spikes[0].Value != 5 || len(p.TopTargets) != 1 || p.TopTargets[0].Domain != "b" {
|
||||
t.Fatalf("upper bounds: %+v %+v", p.Spikes, p.TopTargets)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBanPairingAndOldRecordFallbacks(t *testing.T) {
|
||||
s := store30("x")
|
||||
s.SetEventLog(openLog(t))
|
||||
ban := func(ip, jail string, ago time.Duration, un bool) {
|
||||
s.Ingest(core.Event{Time: t0.Add(-ago), IP: ip, Cat: core.Ban, Source: "fail2ban", Jail: jail, Unban: un})
|
||||
}
|
||||
ban("203.0.113.45", "traefik-botsearch", 3*time.Hour, false)
|
||||
ban("203.0.113.45", "traefik-botsearch", 2*time.Hour, true)
|
||||
ban("203.0.113.45", "sshd", 90*time.Minute, false)
|
||||
ban("203.0.113.45", "sshd", 80*time.Minute, true)
|
||||
ban("203.0.113.45", "sshd", 20*time.Minute, false) // banned again, no unban yet
|
||||
ban("203.0.113.45", "sshd", 10*time.Minute, false) // a repeat of the same ban (restart): still one ban
|
||||
ban("203.0.113.45", "recidive", 5*time.Minute, false)
|
||||
il := s.IPLogOf("203.0.113.45", t0.Unix()-86400, t0.Unix())
|
||||
info, _ := s.IPInfoOf("203.0.113.45")
|
||||
if len(info.Jails) != 2 || len(il.Bans) != 7 {
|
||||
t.Fatalf("jails %v bans %d", info.Jails, len(il.Bans))
|
||||
}
|
||||
// the pairing lives in the server (activeBans); the store gives it jails and history
|
||||
for _, b := range il.Bans {
|
||||
if b.Jail == "traefik-botsearch" && b.Active {
|
||||
t.Fatal("registry rows are never marked active by the store")
|
||||
}
|
||||
}
|
||||
// a record from before the registry/counters existed: only the old fields
|
||||
r := s.ips["203.0.113.45"]
|
||||
r.Users, r.Fams, r.Techs, r.DayCats, r.Days, r.DayBase, r.DayEst = nil, nil, nil, nil, 0, 0, false
|
||||
r.Samples = []string{"GET /.env", "GET /.git/config", "ssh user root"}
|
||||
r.First = t0.Unix() - 7*86400
|
||||
r.Counts[core.SSHFail.Index()] = 21
|
||||
path := filepath.Join(t.TempDir(), "o.gob")
|
||||
s.Save(path, nil)
|
||||
s2 := store30("x")
|
||||
s2.Load(path)
|
||||
i2, _ := s2.IPInfoOf("203.0.113.45")
|
||||
if len(i2.DayCats) == 0 || i2.ActiveDays < 7 || !i2.Estimated {
|
||||
t.Fatalf("migration spreads the totals over first..last: days %d active %d", len(i2.DayCats), i2.ActiveDays)
|
||||
}
|
||||
var tot uint32
|
||||
for _, row := range i2.DayCats {
|
||||
for _, v := range row {
|
||||
tot += uint32(v)
|
||||
}
|
||||
}
|
||||
var want uint32
|
||||
for _, n := range s2.ips["203.0.113.45"].Counts {
|
||||
want += n
|
||||
}
|
||||
if tot != want {
|
||||
t.Fatalf("spread must conserve the totals: %d vs %d", tot, want)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user