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>
719 lines
24 KiB
Go
719 lines
24 KiB
Go
package intel
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/netip"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
var t0 = time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)
|
|
|
|
func at(sec int) time.Time { return t0.Add(time.Duration(sec) * time.Second) }
|
|
|
|
func TestTechniques(t *testing.T) {
|
|
cases := []struct {
|
|
cat, fam string
|
|
ctx TechCtx
|
|
want []string
|
|
}{
|
|
{"exploit", FamTraversal, TechCtx{}, []string{"T1083", "T1190"}},
|
|
{"exploit", FamLog4Shell, TechCtx{}, []string{"T1190"}},
|
|
{"exploit", FamSQLi, TechCtx{}, []string{"T1190"}},
|
|
{"exploit", FamXSS, TechCtx{}, []string{"T1190"}},
|
|
{"exploit", FamRCE, TechCtx{}, []string{"T1059.004", "T1190"}},
|
|
{"exploit", FamWebshell, TechCtx{}, []string{"T1190", "T1505.003"}},
|
|
{"scanner", FamEnvCreds, TechCtx{}, []string{"T1552.001", "T1595"}},
|
|
{"scanner", FamVCS, TechCtx{}, []string{"T1213", "T1552.001", "T1595"}},
|
|
{"scanner", FamBackup, TechCtx{}, []string{"T1595", "T1595.003"}},
|
|
{"notfound", FamGeneric404, TechCtx{}, []string{"T1595.003"}},
|
|
{"notfound", FamPhpMyAdmin, TechCtx{}, []string{"T1595.003"}},
|
|
{"notfound", FamAdminPanel, TechCtx{}, []string{"T1595.003"}},
|
|
{"bruteforce", FamWordPress, TechCtx{Path: "/wp-login.php"}, []string{"T1110.001"}},
|
|
{"notfound", FamWordPress, TechCtx{Path: "/xmlrpc.php"}, []string{"T1110.001"}},
|
|
{"notfound", FamWordPress, TechCtx{Path: "/wp-json/wp/v2/users"}, []string{"T1087"}},
|
|
{"notfound", FamWordPress, TechCtx{Path: "/wp-content/plugins/x/"}, []string{"T1595.002"}},
|
|
{"notfound", FamActuator, TechCtx{}, []string{"T1082", "T1595.002"}},
|
|
{"notfound", FamIoTCGI, TechCtx{}, []string{"T1190"}},
|
|
{"scanner", "", TechCtx{Tool: "Nuclei - Open-source"}, []string{"T1595.002"}},
|
|
{"scanner", "", TechCtx{Tool: "gobuster/3.1"}, []string{"T1595.003"}},
|
|
{"scanner", "", TechCtx{Tool: "masscan/1.3"}, []string{"T1595.001"}},
|
|
{"scanner", "", TechCtx{}, []string{"T1595"}},
|
|
{"exploit", "", TechCtx{}, []string{"T1190"}},
|
|
{"bruteforce", "", TechCtx{}, []string{"T1110.001"}},
|
|
{"ssh-fail", "", TechCtx{Users: 1, MaxPerUser: 40}, []string{"T1110.001"}},
|
|
{"ssh-fail", "", TechCtx{Users: 8, MaxPerUser: 2}, []string{"T1110.003"}},
|
|
{"ssh-fail", "", TechCtx{Users: 5, MaxPerUser: 4}, []string{"T1110.001"}},
|
|
{"ssh-probe", "", TechCtx{}, []string{"T1046", "T1595.001"}},
|
|
{"ssh-ok", "", TechCtx{PriorFails: true}, []string{"T1078"}},
|
|
{"ssh-ok", "", TechCtx{}, []string{}},
|
|
{"ok", "", TechCtx{}, []string{}},
|
|
}
|
|
for i, c := range cases {
|
|
got := Techniques(c.cat, c.fam, c.ctx)
|
|
if len(got) == 0 && len(c.want) == 0 {
|
|
continue
|
|
}
|
|
if !reflect.DeepEqual(got, c.want) {
|
|
t.Errorf("case %d %s/%s: got %v want %v", i, c.cat, c.fam, got, c.want)
|
|
}
|
|
}
|
|
for _, id := range []string{"T1190", "T1595.003", "T1078", "T1505.003"} {
|
|
if TechniqueName(id) == "" {
|
|
t.Errorf("no name for %s", id)
|
|
}
|
|
}
|
|
if TechniqueName("T9999") != "" || TechniqueName("T1595.003") != "Wordlist Scanning" {
|
|
t.Error("names")
|
|
}
|
|
}
|
|
|
|
func TestNetType(t *testing.T) {
|
|
cases := []struct {
|
|
asn uint32
|
|
org, rdns string
|
|
typ, wantR string
|
|
}{
|
|
{9009, "M247", "", "vpn", "asn:9009"},
|
|
{212238, "Datacamp", "", "vpn", "asn:212238"},
|
|
{0, "", "node-1.vpn.example.net", "vpn", "rdns:vpn"},
|
|
{0, "", "tor-exit-12.relay.org", "vpn", "rdns:exit"},
|
|
{0, "", "my-proxy.example", "vpn", "rdns:proxy"},
|
|
{14061, "DigitalOcean", "", "hosting", "asn:14061"},
|
|
{16509, "Amazon", "", "hosting", "asn:16509"},
|
|
{15169, "Google", "", "hosting", "asn:15169"},
|
|
{8075, "Microsoft", "", "hosting", "asn:8075"},
|
|
{24940, "Hetzner", "", "hosting", "asn:24940"},
|
|
{16276, "OVH", "", "hosting", "asn:16276"},
|
|
{45102, "Alibaba", "", "hosting", "asn:45102"},
|
|
{20473, "Vultr", "", "hosting", "asn:20473"},
|
|
{213371, "x", "", "hosting", "asn:213371"},
|
|
{99999, "Acme Hosting Ltd", "", "hosting", "asorg:hosting"},
|
|
{99999, "Contabo GmbH", "", "hosting", "asorg:contabo"},
|
|
{99999, "Some Data Center SA", "", "hosting", "asorg:data center"},
|
|
{99999, "", "ec2-1-2-3-4.compute-1.amazonaws.com", "hosting", "rdns:ec2"},
|
|
{99999, "", "static.1.2.3.4.clients.your-server.de", "hosting", "rdns:static"},
|
|
{99999, "", "host5.example.net", "hosting", "rdns:host5"},
|
|
{398324, "Censys", "", "research-scanner", "asn:398324"},
|
|
{398705, "Censys", "", "research-scanner", "asn:398705"},
|
|
{211298, "Driftnet", "", "research-scanner", "asn:211298"},
|
|
{63999, "Shadowserver", "", "research-scanner", "asn:63999"},
|
|
{396507, "Expanse", "", "research-scanner", "asn:396507"},
|
|
{4134, "Chinanet", "", "isp-cn", "asn:4134"},
|
|
{4837, "China Unicom", "", "isp-cn", "asn:4837"},
|
|
{26615, "Tim", "", "mobile", "asn:26615"},
|
|
{28573, "Claro", "", "isp/mobile", "asn:28573"},
|
|
{26599, "Vivo", "", "isp/mobile", "asn:26599"},
|
|
{18881, "Vivo", "", "isp/mobile", "asn:18881"},
|
|
{99999, "Acme Wireless", "", "mobile", "asorg:wireless"},
|
|
{99999, "", "100.mobile.example.net", "mobile", "rdns:mobile"},
|
|
{99999, "", "lte-1-2.carrier.net", "mobile", "rdns:lte"},
|
|
{99999, "", "1-2-3-4.dsl.example.net", "residential", "rdns:1-2-3"},
|
|
{99999, "", "dynamic-201-1-2-3.example.com.br", "residential", "rdns:dynamic"},
|
|
{99999, "", "pool-1-2-3.fibra.net", "residential", "rdns:pool"},
|
|
{99999, "", "c-1-2-3.customer.net", "residential", "rdns:cus"},
|
|
{99999, "Brasil Telecom SA", "", "residential", "asorg:telecom"},
|
|
{99999, "Fast Broadband", "", "residential", "asorg:broadband"},
|
|
{7162, "Universo Online S.A.", "", "residential", "asn:7162"},
|
|
{263880, "Wantel Telecom", "", "residential", "asn:263880"},
|
|
{7738, "Telemar Norte Leste", "", "residential", "asn:7738"},
|
|
{8167, "Brasil Telecom", "", "residential", "asn:8167"},
|
|
{16735, "Algar Telecom", "", "residential", "asn:16735"},
|
|
{28126, "Brisanet", "", "residential", "asn:28126"},
|
|
{99999, "Silva Fibra Ltda", "", "residential", "asorg:isp-br"},
|
|
{99999, "Provedor Alfa Ltda", "", "residential", "asorg:isp-br"},
|
|
{99999, "Beta Comunicacoes Ltda", "", "residential", "asorg:isp-br"},
|
|
{99999, "Gama Tecnologia em Internet Ltda", "", "residential", "asorg:isp-br"},
|
|
{99999, "Delta NET Ltda", "", "residential", "asorg:isp-br"},
|
|
{99999, "Locaweb Servicos de Internet", "", "hosting", "asorg:locaweb"},
|
|
{99999, "UOL Host", "", "hosting", "asorg:host"},
|
|
{99999, "Fibra Hospedagem Ltda", "", "hosting", "asorg:hospedagem"},
|
|
{99999, "Acme Ltda", "", "unknown", ""},
|
|
{99999, "", "", "unknown", ""},
|
|
{0, "Quiet University", "mail.uni.edu", "unknown", ""},
|
|
}
|
|
for _, c := range cases {
|
|
typ, r := NetType(c.asn, c.org, c.rdns)
|
|
if typ != c.typ {
|
|
t.Errorf("NetType(%d,%q,%q) = %q/%q want %q", c.asn, c.org, c.rdns, typ, r, c.typ)
|
|
}
|
|
if c.typ != "unknown" && !strings.HasPrefix(r, c.wantR[:min(len(c.wantR), 6)]) {
|
|
t.Errorf("reason for %d/%q/%q = %q want prefix %q", c.asn, c.org, c.rdns, r, c.wantR)
|
|
}
|
|
}
|
|
// hostile
|
|
NetType(0, strings.Repeat("x", 1<<20), strings.Repeat("a-", 1<<20))
|
|
NetType(0, "\xff\xfe日本", "\x00")
|
|
}
|
|
|
|
func TestTorExits(t *testing.T) {
|
|
ip := netip.MustParseAddr("185.220.101.1")
|
|
if typ, _ := NetTypeIP(ip, 0, "", ""); typ != "unknown" {
|
|
t.Fatalf("tor must be off by default: %s", typ)
|
|
}
|
|
SetTorExits([]netip.Addr{ip})
|
|
defer SetTorExits(nil)
|
|
if typ, r := NetTypeIP(ip, 14061, "DigitalOcean", ""); typ != "tor" || r == "" {
|
|
t.Errorf("got %s %s", typ, r)
|
|
}
|
|
mapped := netip.MustParseAddr("::ffff:185.220.101.1")
|
|
if !IsTorExit(mapped) {
|
|
t.Error("4in6 should match")
|
|
}
|
|
if typ, _ := NetTypeIP(netip.MustParseAddr("8.8.8.8"), 15169, "Google", ""); typ != "hosting" {
|
|
t.Error("non-exit")
|
|
}
|
|
}
|
|
|
|
func TestCadence(t *testing.T) {
|
|
mk := func(gaps ...float64) []time.Time {
|
|
out := []time.Time{t0}
|
|
cur := t0
|
|
for _, g := range gaps {
|
|
cur = cur.Add(time.Duration(g * float64(time.Second)))
|
|
out = append(out, cur)
|
|
}
|
|
return out
|
|
}
|
|
rep := func(g float64, n int) []float64 {
|
|
v := make([]float64, n)
|
|
for i := range v {
|
|
v[i] = g
|
|
}
|
|
return v
|
|
}
|
|
cases := []struct {
|
|
name string
|
|
ts []time.Time
|
|
want string
|
|
}{
|
|
{"insufficient", mk(1), VerdictInsufficient},
|
|
{"fast bot", mk(rep(0.2, 30)...), VerdictAutomated},
|
|
{"regular slow bot", mk(rep(10, 20)...), VerdictAutomated},
|
|
{"human", mk(8, 90, 12, 300, 7, 600, 15, 20, 1200), VerdictHuman},
|
|
{"mixed", mk(3, 4, 5, 6, 7), VerdictMixed},
|
|
}
|
|
for _, c := range cases {
|
|
cad := CadenceFrom(c.ts)
|
|
if cad.Verdict != c.want {
|
|
t.Errorf("%s exact: %+v want %s", c.name, cad, c.want)
|
|
}
|
|
var a CadenceAcc
|
|
for _, x := range c.ts {
|
|
a.Add(x)
|
|
}
|
|
r := a.Result()
|
|
if r.N != cad.N || r.BurstMax60 != cad.BurstMax60 {
|
|
t.Errorf("%s acc n/burst %+v vs %+v", c.name, r, cad)
|
|
}
|
|
if c.want != VerdictMixed && r.Verdict != c.want {
|
|
t.Errorf("%s acc: %+v want %s", c.name, r, c.want)
|
|
}
|
|
}
|
|
c := CadenceFrom(mk(rep(1, 9)...))
|
|
if c.N != 10 || c.MedianS != 1 || c.CV != 0 || c.BurstMax60 != 10 {
|
|
t.Errorf("%+v", c)
|
|
}
|
|
// unordered input is sorted
|
|
if CadenceFrom([]time.Time{at(10), at(0), at(5)}).MedianS != 5 {
|
|
t.Error("unordered")
|
|
}
|
|
var a CadenceAcc
|
|
if a.Result().Verdict != VerdictInsufficient {
|
|
t.Error("empty")
|
|
}
|
|
// approximate percentiles are close
|
|
var acc CadenceAcc
|
|
cur := t0
|
|
for i := 0; i < 1000; i++ {
|
|
acc.Add(cur)
|
|
cur = cur.Add(time.Duration(1+i%7) * time.Second)
|
|
}
|
|
exact := CadenceFrom(func() []time.Time {
|
|
var v []time.Time
|
|
c := t0
|
|
for i := 0; i < 1000; i++ {
|
|
v = append(v, c)
|
|
c = c.Add(time.Duration(1+i%7) * time.Second)
|
|
}
|
|
return v
|
|
}())
|
|
r := acc.Result()
|
|
if d := r.MedianS - exact.MedianS; d > 2 || d < -2 {
|
|
t.Errorf("median approx %v exact %v", r.MedianS, exact.MedianS)
|
|
}
|
|
if d := r.CV - exact.CV; d > 1e-9 || d < -1e-9 {
|
|
t.Errorf("cv %v %v", r.CV, exact.CV)
|
|
}
|
|
// out-of-order and duplicates must not panic
|
|
var b CadenceAcc
|
|
for _, s := range []int{5, 1, 1, 100000, 0} {
|
|
b.Add(at(s))
|
|
}
|
|
b.Result()
|
|
// burst window cap
|
|
var big CadenceAcc
|
|
for i := 0; i < 10000; i++ {
|
|
big.Add(t0)
|
|
}
|
|
if big.Result().BurstMax60 != burstCap {
|
|
t.Errorf("burst cap %d", big.Result().BurstMax60)
|
|
}
|
|
}
|
|
|
|
func evAt(sec int, ip, cat, fam, path string, status int) Ev {
|
|
return Ev{T: at(sec), IP: ip, Cat: cat, Fam: fam, Path: path, Status: status, Host: "h1", Domain: "d.example"}
|
|
}
|
|
|
|
func TestSessionsGapsAndStages(t *testing.T) {
|
|
events := []Ev{
|
|
evAt(0, "1.1.1.1", "notfound", FamGeneric404, "/a", 404),
|
|
evAt(10, "1.1.1.1", "scanner", FamEnvCreds, "/.env", 403),
|
|
evAt(20, "1.1.1.1", "exploit", FamTraversal, "/../etc/passwd", 400),
|
|
evAt(20+31*60, "1.1.1.1", "notfound", FamGeneric404, "/b", 404), // new session
|
|
evAt(5, "2.2.2.2", "ok", "", "/", 200),
|
|
{T: at(60), IP: "1.1.1.1", Cat: "ban", Jail: "urutau-web"},
|
|
}
|
|
ss := Sessions(events, 0)
|
|
if len(ss) != 3 {
|
|
t.Fatalf("sessions: %d %+v", len(ss), ss)
|
|
}
|
|
var s1, s2 Session
|
|
for _, s := range ss {
|
|
if s.IP == "1.1.1.1" && s.N == 4 {
|
|
s1 = s
|
|
}
|
|
if s.IP == "1.1.1.1" && s.N == 1 {
|
|
s2 = s
|
|
}
|
|
}
|
|
if s1.Stage != StageBanned || s1.BannedAt == nil || s1.N != 4 || s1.DurS != 60 {
|
|
t.Errorf("s1 %+v", s1)
|
|
}
|
|
if !reflect.DeepEqual(s1.Techs, []string{"T1083", "T1190", "T1552.001", "T1595", "T1595.003"}) && len(s1.Techs) == 0 {
|
|
t.Errorf("techs %v", s1.Techs)
|
|
}
|
|
if s2.Stage != StageRecon || s2.Success {
|
|
t.Errorf("s2 %+v", s2)
|
|
}
|
|
if s1.ID == s2.ID || s1.ID == "" {
|
|
t.Error("ids")
|
|
}
|
|
for _, s := range ss {
|
|
if s.IP == "2.2.2.2" && s.Stage != "" {
|
|
t.Errorf("benign stage %q", s.Stage)
|
|
}
|
|
}
|
|
// custom gap merges
|
|
if got := Sessions(events[:4], 2*time.Hour); len(got) != 1 {
|
|
t.Errorf("gap 2h -> %d", len(got))
|
|
}
|
|
}
|
|
|
|
func TestSSHEscalation(t *testing.T) {
|
|
var events []Ev
|
|
for i := 0; i < 6; i++ {
|
|
e := evAt(i*2, "9.9.9.9", "ssh-fail", "", "", 0)
|
|
e.User = fmt.Sprintf("u%d", i)
|
|
events = append(events, e)
|
|
}
|
|
ok := evAt(20, "9.9.9.9", "ssh-ok", "", "", 0)
|
|
ok.User = "root"
|
|
events = append(events, ok, evAt(-1, "9.9.9.9", "ssh-probe", "", "", 0))
|
|
ss := Sessions(events, time.Minute)
|
|
if len(ss) != 1 {
|
|
t.Fatal(len(ss))
|
|
}
|
|
s := ss[0]
|
|
if s.Stage != StageAccess || !s.Success || s.UsersN != 7 {
|
|
t.Errorf("%+v", s)
|
|
}
|
|
hasTech := func(id string) bool {
|
|
for _, x := range s.Techs {
|
|
if x == id {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
if !hasTech("T1078") || !hasTech("T1110.003") {
|
|
t.Errorf("techs %v", s.Techs)
|
|
}
|
|
steps := Escalation(s, events)
|
|
var stages []string
|
|
for _, st := range steps {
|
|
stages = append(stages, st.Stage)
|
|
}
|
|
if !reflect.DeepEqual(stages, []string{StageRecon, StageProbe, StageAccess}) {
|
|
t.Errorf("steps %v (events sorted: recon at t=2 first)", stages)
|
|
}
|
|
// ssh-ok with no failures is not access
|
|
only := []Ev{evAt(0, "8.8.8.8", "ssh-ok", "", "", 0)}
|
|
if s := Sessions(only, 0)[0]; s.Stage != "" || s.Success {
|
|
t.Errorf("lone ssh-ok %+v", s)
|
|
}
|
|
// failures in an earlier session still count
|
|
late := append(events[:6:6], evAt(7200, "9.9.9.9", "ssh-ok", "", "", 0))
|
|
ss2 := Sessions(late, time.Minute)
|
|
if last := ss2[len(ss2)-1]; last.Stage != StageAccess {
|
|
t.Errorf("late %+v", last)
|
|
}
|
|
if st := Escalation(ss2[len(ss2)-1], late); len(st) != 1 || st[0].Stage != StageAccess {
|
|
t.Errorf("late steps %+v", st)
|
|
}
|
|
}
|
|
|
|
func TestAccessAndUnban(t *testing.T) {
|
|
ev := []Ev{
|
|
evAt(0, "3.3.3.3", "scanner", FamEnvCreds, "/.env", 200),
|
|
evAt(1, "4.4.4.4", "scanner", FamEnvCreds, "/.env", 403),
|
|
evAt(2, "5.5.5.5", "scanner", FamAdminPanel, "/admin", 200),
|
|
{T: at(3), IP: "6.6.6.6", Cat: "ban", Unban: true},
|
|
}
|
|
for _, s := range Sessions(ev, 0) {
|
|
switch s.IP {
|
|
case "3.3.3.3", "5.5.5.5":
|
|
if s.Stage != StageAccess || !s.Success {
|
|
t.Errorf("%s %+v", s.IP, s)
|
|
}
|
|
case "4.4.4.4":
|
|
if s.Stage != StageProbe {
|
|
t.Errorf("%+v", s)
|
|
}
|
|
case "6.6.6.6":
|
|
if s.Stage != "" || s.BannedAt != nil {
|
|
t.Errorf("unban %+v", s)
|
|
}
|
|
}
|
|
}
|
|
if Sessions(nil, 0) != nil {
|
|
t.Error("nil")
|
|
}
|
|
}
|
|
|
|
func TestNormPathAndSignature(t *testing.T) {
|
|
cases := map[string]string{
|
|
"/post/123": "/post/{n}",
|
|
"/a/550e8400-e29b-41d4-a716-446655440000/b": "/a/{id}/b",
|
|
"/x/deadbeefcafe1234": "/x/{id}",
|
|
"/Item.PHP?id=5": "/item.php",
|
|
"/v2/users/42/posts/7": "/v{n}/users/{n}/posts/{n}",
|
|
}
|
|
for in, want := range cases {
|
|
if got := NormPath(in); got != want {
|
|
t.Errorf("NormPath(%q)=%q want %q", in, got, want)
|
|
}
|
|
}
|
|
paths := []string{"/a/1", "/a/2", "/b", "/b", "/c", "/d", "/e", "/f", "/g"}
|
|
sg := SignatureFrom(paths, " Nuclei ")
|
|
if len(sg.Paths) != 5 || sg.Tool != "nuclei" || sg.Paths[0] != "/a/{n}" {
|
|
t.Errorf("%+v", sg)
|
|
}
|
|
if !strings.HasPrefix(sg.ID(), "c-") || len(sg.ID()) != 10 {
|
|
t.Error(sg.ID())
|
|
}
|
|
if sg.ID() != SignatureFrom(paths, "nuclei").ID() {
|
|
t.Error("ID not deterministic")
|
|
}
|
|
NormPath(strings.Repeat("9", 1<<20))
|
|
}
|
|
|
|
func TestJaccard(t *testing.T) {
|
|
if Jaccard([]string{"a", "b", "c"}, []string{"a", "b", "d"}) != 0.5 {
|
|
t.Error("0.5")
|
|
}
|
|
if Jaccard(nil, nil) != 0 || Jaccard([]string{"a"}, []string{"a"}) != 1 {
|
|
t.Error("edge")
|
|
}
|
|
}
|
|
|
|
func mkSessions(ips []string, paths map[string][]string, tool string, base int) ([]Session, map[string]Signature) {
|
|
var ss []Session
|
|
sigs := map[string]Signature{}
|
|
for i, ip := range ips {
|
|
s := Session{ID: "s" + ip, IP: ip, Start: at(base + i*600), End: at(base + i*600 + 30), Techs: []string{"T1190"}}
|
|
ss = append(ss, s)
|
|
sg := SignatureFrom(paths[ip], tool)
|
|
sg.ASN, sg.CC, sg.NetType = uint32(100+i), "BR", "hosting"
|
|
sigs[s.ID] = sg
|
|
}
|
|
return ss, sigs
|
|
}
|
|
|
|
func TestCampaigns(t *testing.T) {
|
|
common := []string{"/.env", "/wp-login.php", "/.git/config", "/admin", "/phpmyadmin/"}
|
|
ips := []string{"1.0.0.1", "1.0.0.2", "1.0.0.3", "1.0.0.4"}
|
|
paths := map[string][]string{}
|
|
for _, ip := range ips {
|
|
paths[ip] = common
|
|
}
|
|
// 4th IP shares 4/6 paths (jaccard 0.667) after replacing one and adding one
|
|
paths["1.0.0.4"] = []string{"/.env", "/wp-login.php", "/.git/config", "/admin", "/other"}
|
|
ss, sigs := mkSessions(ips, paths, "nuclei", 0)
|
|
// unrelated session, different tool
|
|
other := Session{ID: "sx", IP: "7.7.7.7", Start: at(10), End: at(20)}
|
|
ss = append(ss, other)
|
|
sigs["sx"] = SignatureFrom(common, "ffuf")
|
|
cs := Campaigns(ss, sigs, 0)
|
|
if len(cs) != 1 {
|
|
t.Fatalf("%d campaigns: %+v", len(cs), cs)
|
|
}
|
|
c := cs[0]
|
|
if c.IPsN != 4 || c.SessionsN != 4 || len(c.IPs) != 4 || len(c.ASNs) != 4 || c.NetTypes["hosting"] != 4 || !reflect.DeepEqual(c.CCs, []string{"BR"}) {
|
|
t.Errorf("%+v", c)
|
|
}
|
|
if c.Signature.Tool != "nuclei" || !strings.HasPrefix(c.ID, "c-") || !reflect.DeepEqual(c.Techs, []string{"T1190"}) {
|
|
t.Errorf("%+v", c)
|
|
}
|
|
if ss[0].CampaignID != c.ID || ss[4].CampaignID != "" {
|
|
t.Error("campaign ids on sessions")
|
|
}
|
|
// deterministic
|
|
cs2 := Campaigns(ss, sigs, 0)
|
|
if cs2[0].ID != c.ID {
|
|
t.Error("nondeterministic")
|
|
}
|
|
// only 2 IPs: no campaign
|
|
ss3, sigs3 := mkSessions(ips[:2], paths, "nuclei", 0)
|
|
if len(Campaigns(ss3, sigs3, 0)) != 0 {
|
|
t.Error("2 ips")
|
|
}
|
|
// outside the window
|
|
ss4, sigs4 := mkSessions(ips[:3], paths, "nuclei", 0)
|
|
ss4[2].Start = at(7 * 3600 * 10)
|
|
ss4[2].End = ss4[2].Start
|
|
if len(Campaigns(ss4, sigs4, 0)) != 0 {
|
|
t.Error("window")
|
|
}
|
|
// low jaccard
|
|
ss5, sigs5 := mkSessions(ips[:3], paths, "nuclei", 0)
|
|
sigs5[ss5[2].ID] = SignatureFrom([]string{"/x1", "/x2", "/x3", "/x4", "/.env"}, "nuclei")
|
|
if len(Campaigns(ss5, sigs5, 0)) != 0 {
|
|
t.Error("jaccard")
|
|
}
|
|
// IPs cap
|
|
var many []string
|
|
mp := map[string][]string{}
|
|
for i := 0; i < 80; i++ {
|
|
ip := fmt.Sprintf("10.0.0.%d", i)
|
|
many = append(many, ip)
|
|
mp[ip] = common
|
|
}
|
|
ss6, sigs6 := mkSessions(many, mp, "x", 0)
|
|
for i := range ss6 {
|
|
ss6[i].Start = at(i)
|
|
ss6[i].End = at(i)
|
|
}
|
|
cs6 := Campaigns(ss6, sigs6, 0)
|
|
if len(cs6) != 1 || cs6[0].IPsN != 80 || len(cs6[0].IPs) != 50 {
|
|
t.Errorf("cap %+v", cs6)
|
|
}
|
|
}
|
|
|
|
func TestReasonsAndActions(t *testing.T) {
|
|
rs := Reasons(ReasonInput{
|
|
ExploitsRefused: map[string]int{FamTraversal: 3, FamSQLi: 2},
|
|
ToolUA: "nuclei", BannedJails: []string{"urutau-web"}, Categories: 3,
|
|
})
|
|
codes := []string{}
|
|
for _, r := range rs {
|
|
codes = append(codes, r.Code)
|
|
if r.Text != "intel.reason."+r.Code {
|
|
t.Errorf("text %q", r.Text)
|
|
}
|
|
}
|
|
if !reflect.DeepEqual(codes, []string{ReasonExploitsRefused, ReasonBannedJail, ReasonToolUA, ReasonMultiCategory}) {
|
|
t.Errorf("%v", codes)
|
|
}
|
|
if rs[0].N != 5 || rs[0].Params["families"] != "sqli, traversal" {
|
|
t.Errorf("%+v", rs[0])
|
|
}
|
|
acts := Actions(ActionInput{Reasons: rs, Stage: StageExploit})
|
|
got := map[string]bool{}
|
|
for _, a := range acts {
|
|
got[a.Code] = true
|
|
}
|
|
if !got[ActionBlock] || !got[ActionReport] || got[ActionIncident] {
|
|
t.Errorf("%+v", acts)
|
|
}
|
|
// exposure -> incident + investigate
|
|
rs2 := Reasons(ReasonInput{Exposure: map[string]int{FamEnvCreds: 1}})
|
|
acts2 := Actions(ActionInput{Reasons: rs2, Banned: true, Stage: StageAccess})
|
|
if len(acts2) < 2 || acts2[0].Code != ActionIncident || acts2[1].Code != ActionInvestigate {
|
|
t.Errorf("%+v", acts2)
|
|
}
|
|
for _, a := range acts2 {
|
|
if a.Code == ActionBlock {
|
|
t.Error("already banned")
|
|
}
|
|
}
|
|
rs3 := Reasons(ReasonInput{SSHOKAfterBrute: true})
|
|
if rs3[0].Code != ReasonSSHAfterBrute || Actions(ActionInput{Reasons: rs3})[0].Code != ActionIncident {
|
|
t.Errorf("%+v", rs3)
|
|
}
|
|
// immune/admin: none
|
|
rs4 := Reasons(ReasonInput{ExploitsRefused: map[string]int{FamSQLi: 9}, Immune: true})
|
|
if Actions(ActionInput{Reasons: rs4}) != nil || Actions(ActionInput{Reasons: rs, Admin: true}) != nil {
|
|
t.Error("immune")
|
|
}
|
|
if rs4[len(rs4)-1].Code != ReasonImmune {
|
|
t.Error("immune last")
|
|
}
|
|
if len(Reasons(ReasonInput{})) != 0 || len(Actions(ActionInput{})) != 0 {
|
|
t.Error("empty")
|
|
}
|
|
}
|
|
|
|
func TestSTIX(t *testing.T) {
|
|
now := time.Date(2026, 11, 14, 0, 0, 0, 0, time.UTC)
|
|
first, last := at(0), at(3600)
|
|
b1, err := STIXBundle("203.0.113.9", first, last, 42, []string{"sqli", "traversal", "sqli"}, []string{"T1190", "T1083", "bogus"}, "", now)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
b2, _ := STIXBundle("203.0.113.9", first, last, 42, []string{"traversal", "sqli"}, []string{"T1083", "T1190"}, "", now)
|
|
if string(b1) != string(b2) {
|
|
t.Error("bundle must be deterministic")
|
|
}
|
|
if err := ValidateSTIX(b1); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var doc struct {
|
|
Type string
|
|
ID string
|
|
Objects []map[string]any
|
|
}
|
|
if err := json.Unmarshal(b1, &doc); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
counts := map[string]int{}
|
|
var ind map[string]any
|
|
for _, o := range doc.Objects {
|
|
counts[o["type"].(string)]++
|
|
if o["type"] == "indicator" {
|
|
ind = o
|
|
}
|
|
}
|
|
want := map[string]int{"identity": 1, "indicator": 1, "ipv4-addr": 1, "sighting": 1, "attack-pattern": 2, "relationship": 3}
|
|
if !reflect.DeepEqual(counts, want) {
|
|
t.Errorf("counts %v", counts)
|
|
}
|
|
if ind["pattern"] != "[ipv4-addr:value = '203.0.113.9']" || ind["pattern_type"] != "stix" ||
|
|
ind["valid_until"] != "2026-12-01T13:00:00.000Z" || ind["valid_from"] != "2026-11-01T12:00:00.000Z" {
|
|
t.Errorf("%v", ind)
|
|
}
|
|
if !reflect.DeepEqual(ind["labels"], []any{"sqli", "traversal"}) {
|
|
t.Errorf("labels %v", ind["labels"])
|
|
}
|
|
// fixed ids across runs (golden for the indicator)
|
|
b3, _ := STIXBundle("203.0.113.9", first, last, 1, nil, nil, "", now.Add(time.Hour))
|
|
var d3 struct{ Objects []map[string]any }
|
|
json.Unmarshal(b3, &d3)
|
|
if d3.Objects[1]["id"] != ind["id"] {
|
|
t.Error("id depends on time")
|
|
}
|
|
// ipv6
|
|
b6, err := STIXBundle("2001:db8::1", first, last, 1, nil, []string{"T1595"}, "", now)
|
|
if err != nil || !strings.Contains(string(b6), "[ipv6-addr:value = '2001:db8::1']") || ValidateSTIX(b6) != nil {
|
|
t.Errorf("v6: %v", err)
|
|
}
|
|
b4in6, _ := STIXBundle("::ffff:1.2.3.4", first, last, 1, nil, nil, "", now)
|
|
if !strings.Contains(string(b4in6), "ipv4-addr:value = '1.2.3.4'") {
|
|
t.Error("4in6")
|
|
}
|
|
for _, bad := range []string{"", "not-an-ip", "1.2.3.4'] OR [x"} {
|
|
if _, err := STIXBundle(bad, first, last, 1, nil, nil, "", now); err == nil {
|
|
t.Errorf("accepted %q", bad)
|
|
}
|
|
}
|
|
// validator catches missing fields
|
|
if ValidateSTIX([]byte(`{"type":"bundle","id":"bundle--5a1f7c3e-9d42-4b6a-8e01-c4f72b90d36e","objects":[{"type":"identity","id":"identity--5a1f7c3e-9d42-4b6a-8e01-c4f72b90d36e","spec_version":"2.1"}]}`)) == nil {
|
|
t.Error("validator should reject missing created")
|
|
}
|
|
if ValidateSTIX([]byte(`{`)) == nil {
|
|
t.Error("garbage")
|
|
}
|
|
// swapped times, custom sighting ref
|
|
bs, err := STIXBundle("1.1.1.1", last, first, 0, nil, nil, "indicator--5a1f7c3e-9d42-4b6a-8e01-c4f72b90d36e", now)
|
|
if err != nil || ValidateSTIX(bs) != nil || !strings.Contains(string(bs), `"count": 1`) {
|
|
t.Errorf("%v", err)
|
|
}
|
|
// uuid v5 shape and known vector: version/variant nibbles
|
|
u := uuidV5("x")
|
|
if u[14] != '5' || !strings.ContainsRune("89ab", rune(u[19])) || len(u) != 36 {
|
|
t.Errorf("uuid %s", u)
|
|
}
|
|
}
|
|
|
|
func TestMetrics(t *testing.T) {
|
|
if Trend(150, 100) != 0.5 || Trend(0, 0) != 0 || Trend(5, 0) != 1 || Trend(50, 100) != -0.5 {
|
|
t.Error("trend")
|
|
}
|
|
// Spikes: 8 days of flat 5/h with small jitter, then a 60 spike and a 9 (below min)
|
|
var h []int
|
|
var ts []time.Time
|
|
for i := 0; i < 24*8; i++ {
|
|
h = append(h, 4+i%3)
|
|
ts = append(ts, t0.Add(time.Duration(i)*time.Hour))
|
|
}
|
|
h[150] = 60
|
|
h[160] = 9
|
|
h[100] = 12
|
|
sp := Spikes(h, ts)
|
|
if len(sp) < 2 || sp[len(sp)-1].Value != 60 {
|
|
t.Fatalf("%+v", sp)
|
|
}
|
|
for _, s := range sp {
|
|
if s.Value < SpikeMin || float64(s.Value) <= s.Threshold {
|
|
t.Errorf("bad spike %+v", s)
|
|
}
|
|
}
|
|
if len(Spikes(h[:10], ts[:10])) != 0 || len(Spikes(h, ts[:5])) != 0 || Spikes(nil, nil) != nil {
|
|
t.Error("insufficient")
|
|
}
|
|
med, p90 := MTTB([][2]time.Time{
|
|
{at(0), at(10)}, {at(0), at(20)}, {at(0), at(30)}, {at(0), at(40)}, {at(100), at(0)},
|
|
})
|
|
if med != 25*time.Second || p90 != 40*time.Second {
|
|
t.Errorf("%v %v", med, p90)
|
|
}
|
|
if m, p := MTTB(nil); m != 0 || p != 0 {
|
|
t.Error("mttb nil")
|
|
}
|
|
c := Concentration(map[string]int{"a": 50, "b": 30, "c": 15, "d": 5}, 2)
|
|
if c != 0.8 || Concentration(nil, 3) != 0 || Concentration(map[string]int{"a": 1}, 0) != 0 || Concentration(map[string]int{"a": 1}, 9) != 1 {
|
|
t.Errorf("conc %v", c)
|
|
}
|
|
}
|
|
|
|
func TestCampaignIDUniquePerWindow(t *testing.T) {
|
|
paths := map[string][]string{}
|
|
var ips []string
|
|
for _, ip := range []string{"1.0.0.1", "1.0.0.2", "1.0.0.3", "2.0.0.1", "2.0.0.2", "2.0.0.3"} {
|
|
ips = append(ips, ip)
|
|
paths[ip] = []string{"/.env", "/admin", "/wp-login.php"}
|
|
}
|
|
ss, sigs := mkSessions(ips, paths, "nuclei", 0)
|
|
for i := 3; i < 6; i++ { // second wave two days later
|
|
ss[i].Start = at(48*3600 + i*60)
|
|
ss[i].End = ss[i].Start
|
|
}
|
|
cs := Campaigns(ss, sigs, 6*time.Hour)
|
|
if len(cs) != 2 {
|
|
t.Fatalf("%d campaigns", len(cs))
|
|
}
|
|
if cs[0].ID == cs[1].ID {
|
|
t.Fatalf("duplicate id %s", cs[0].ID)
|
|
}
|
|
if cs[0].SignatureID != cs[1].SignatureID || cs[0].SignatureID != cs[0].Signature.SignatureID() {
|
|
t.Error("signature id must be shared")
|
|
}
|
|
again := Campaigns(ss, sigs, 6*time.Hour)
|
|
if again[0].ID != cs[0].ID || again[1].ID != cs[1].ID {
|
|
t.Error("nondeterministic")
|
|
}
|
|
}
|