Files
urutau/internal/store/hardening_test.go
T
Lucas RayanandClaude Opus 5.5 b4a2c2c9ec
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 1m29s
CI / Tests (Linux, race detector) (push) Failing after 1m48s
CI / Dependency audit (push) Successful in 21s
Release / ci (push) Failing after 1m50s
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
feat: Urutau 1.0.0, lightweight threat intelligence and web analytics
Always-on Go service (stdlib only) that follows the Traefik JSON access
log, the sshd log and the fail2ban log of a host, classifies attacks,
scores sources, keeps bounded aggregates with snapshots, and serves an
embedded dashboard with live updates, offline geolocation (DB-IP Lite),
privacy-friendly traffic analytics, an exportable blocklist and
token-authenticated federation between instances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 16:13:34 -03:00

217 lines
7.5 KiB
Go

package store
import (
"fmt"
"math"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
func TestIPv6AggregatesBy64(t *testing.T) {
s := newStore("x", 100)
for i := 0; i < 300; i++ {
e := ev(fmt.Sprintf("2001:db8:0:1:%x::%x", i, i+1), core.Scanner, time.Minute)
s.Ingest(e)
}
s.Ingest(ev("2001:db8:0:2::5", core.Scanner, time.Minute))
if n := s.IPCount(); n != 2 {
t.Fatalf("one /64 is one entry, got %d entries", n)
}
if KeyOf("2001:db8:0:1:ffff::9") != "2001:db8:0:1::/64" || KeyOf("8.8.8.8") != "8.8.8.8" || KeyOf("::ffff:8.8.8.8") != "8.8.8.8" {
t.Fatal("KeyOf")
}
d, ok := s.IP("2001:db8:0:1::77")
if !ok || d.IP != "2001:db8:0:1::/64" || d.Counts["scanner"] != 300 {
t.Fatalf("lookup by any address of the /64: %+v", d)
}
}
func TestPerIPTextIsBoundedAndJailedIPsAreCapped(t *testing.T) {
s := newStore("x", 100)
for k := 0; k < 20; k++ {
e := ev("5.5.5.5", core.Scanner, time.Minute)
e.Path = fmt.Sprintf("/%d-", k) + strings.Repeat("A", 220)
e.UA = fmt.Sprintf("ua%d", k) + strings.Repeat("U", 190)
e.Domain = fmt.Sprintf("d%d.", k) + strings.Repeat("x", 90)
s.Ingest(e)
}
d, _ := s.IP("5.5.5.5")
if len(d.Samples) > 4 || len(d.UAs) > 2 || len(d.Domains) > 3 {
t.Fatalf("too many items: %d %d %d", len(d.Samples), len(d.UAs), len(d.Domains))
}
for _, l := range [][]string{d.Samples, d.UAs, d.Domains} {
for _, v := range l {
if len(v) > 120 {
t.Fatalf("item of %d bytes", len(v))
}
}
}
for i := 0; i < 300; i++ {
s.Ingest(core.Event{Time: t0, IP: fmt.Sprintf("1.1.%d.%d", i/250, i%250+1), Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
}
if n := s.IPCount(); n > 100 {
t.Fatalf("jailed IPs bypass the cap: %d > 100", n)
}
}
func TestLevelNeedsAStrongSignalAndAdminsAreNeverHostile(t *testing.T) {
s := newStore("x", 100)
s.SetAdminUsers([]string{"admin", "root", "lucas"})
// an SPA answering 200 to /config.json (not a scanner hit) and soft probes weigh little
for i := 0; i < 17; i++ {
e := ev("7.7.7.7", core.Scanner, time.Minute)
e.Soft = true
s.Ingest(e)
}
if d, _ := s.IP("7.7.7.7"); d.Score != 8.5 || d.Level == core.LevelHostile {
t.Fatalf("soft probes: %+v", d)
}
// a huge score of one weak kind is suspicious, not hostile
for i := 0; i < 40; i++ {
s.Ingest(ev("7.7.7.8", core.Scanner, time.Minute)) // 120 points, one category, no tool
}
if d, _ := s.IP("7.7.7.8"); d.Level != core.LevelSuspicious || d.Strong {
t.Fatalf("one weak category: %+v", d)
}
// two distinct attack categories are a strong signal
s.Ingest(ev("7.7.7.8", core.BruteForce, time.Minute))
if d, _ := s.IP("7.7.7.8"); d.Level != core.LevelHostile {
t.Fatalf("two categories: %+v", d)
}
// an attack tool is a strong signal by itself
for i := 0; i < 20; i++ {
e := ev("7.7.7.9", core.Scanner, time.Minute)
e.E.Tool = true
s.Ingest(e)
}
if d, _ := s.IP("7.7.7.9"); d.Level != core.LevelHostile {
t.Fatalf("tool: %+v", d)
}
// the admin: many failed publickeys, but a successful login too
s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: "9.9.9.1", Cat: core.SSHOK, Source: "ssh", User: "admin"})
for i := 0; i < 40; i++ {
s.Ingest(core.Event{Time: t0, IP: "9.9.9.1", Cat: core.SSHFail, Source: "ssh", User: "admin"})
s.Ingest(core.Event{Time: t0, IP: "9.9.9.1", Cat: core.SSHProbe, Source: "ssh"})
}
d, _ := s.IP("9.9.9.1")
if !d.Admin || d.Level != core.LevelLow {
t.Fatalf("a recent ssh-ok must keep the address out of hostile: %+v", d)
}
if sum := s.Summary("24h"); sum.Totals.HostileIPs != 2 {
t.Fatalf("hostile count %d", sum.Totals.HostileIPs)
}
}
func TestTrafficDomainSlotsAreNotExhaustedByJunkHosts(t *testing.T) {
s := newStore("x", 100)
for i := 0; i < 30; i++ {
s.Traffic(core.Event{Time: t0, Source: "traefik", Domain: fmt.Sprintf("junk%d.invalid", i), Method: "GET", Path: "/", Status: 404, IP: "2.2.2.2"})
}
s.Traffic(core.Event{Time: t0, Source: "traefik", Domain: "real.example.com", Method: "GET", Path: "/", Status: 200, IP: "2.2.2.2"})
d := s.TrafficSummary("24h", "all")
if len(d.Domains) != 1 || d.Domains[0].Key != "real.example.com" {
t.Fatalf("domains: %+v", d.Domains)
}
// allowlist
a := newStore("x", 100)
a.SetDomains([]string{"real.example.com", "*.shop.example"})
for _, dom := range []string{"real.example.com", "x.shop.example", "evil.test"} {
a.Traffic(core.Event{Time: t0, Source: "traefik", Domain: dom, Method: "GET", Path: "/", Status: 200, IP: "2.2.2.2"})
}
if d := a.TrafficSummary("24h", "all"); len(d.Domains) != 2 {
t.Fatalf("allowlist: %+v", d.Domains)
}
// idle domains are pruned
a.now = func() time.Time { return t0.Add(8 * 24 * time.Hour) }
a.Prune()
if len(a.tr.dom) != 0 {
t.Fatalf("idle domains must be pruned: %d", len(a.tr.dom))
}
}
func TestNormalizePath(t *testing.T) {
for in, want := range map[string]string{
"/blog/post": "/blog/post",
"/u/550e8400-e29b-41d4-a716-446655440000/edit": "/u/:id/edit",
"/reset/9f86d081884c7d659a2feaa0c55ad015a3bf4f1b": "/reset/:id",
"/order/20261114123456": "/order/:id",
"/blog/how-to-use-this-long-slug-text-2024": "/blog/how-to-use-this-long-slug-text-2024",
"/v2/items": "/v2/items",
"/token/AbCdEfGh1234567890XyZ": "/token/:id",
} {
if got := normalizePath(in); got != want {
t.Errorf("%s -> %s, want %s", in, got, want)
}
}
}
func TestTamperedSnapshotCannotBreakTheRing(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "s.gob")
a := newStore("x", 100)
for i := 0; i < 5; i++ {
a.Ingest(ev("1.2.3.4", core.Exploit, time.Minute))
}
a.mu.Lock()
a.rhead = 9999
a.mu.Unlock()
if err := a.Save(p, nil); err != nil {
t.Fatal(err)
}
b := newStore("x", 100)
if _, err := b.Load(p); err != nil {
t.Fatal(err)
}
b.Summary("24h")
b.Recent(10)
b.Ingest(ev("1.2.3.5", core.Exploit, time.Minute))
if len(b.Recent(10)) == 0 {
t.Fatal("ring unusable")
}
}
func TestSanitizeRejectsZonesClampsScoresAndWhitelists(t *testing.T) {
e := PeerExport{V: 1}
e.Summary.IPs = []IPSummary{
{IP: "2001:db8::1%a\n8.8.8.8", Score: 99}, {IP: "fe80::1%eth0", Score: 5}, {IP: "1.2.3.4", Score: 1e300},
{IP: "1.2.3.5", Score: math.Inf(1)}, {IP: "1.2.3.6", Score: -5}, {IP: "2001:db8:0:5::/64", Score: 3},
{IP: "2001:db8:0:6::9", Score: 3, Admin: true}, {IP: "1.2.3.7", Score: 9999, Strong: false},
}
e.Summary.Recent = []FeedEvent{{Cat: "exploit", IP: "1.1.1.1"}, {Cat: `"><img src=x>`, IP: "1.1.1.1"}}
e.Summary.Sources = []SourceStatus{{Name: "traefik", Path: "/data/coolify/proxy/access.log", State: "following"}, {Name: "x", State: "evil\" onload=\""}}
if err := e.Sanitize("24h"); err != nil {
t.Fatal(err)
}
got := map[string]IPSummary{}
for _, x := range e.Summary.IPs {
got[x.IP] = x
}
if _, ok := got["2001:db8::1%a\n8.8.8.8"]; ok || len(got) != 5 {
t.Fatalf("rows kept: %v", got)
}
if got["1.2.3.4"].Score != 1e6 || got["1.2.3.6"].Score != 0 {
t.Fatalf("scores must be clamped to 0..1e6: %+v %+v", got["1.2.3.4"], got["1.2.3.6"])
}
if got["1.2.3.7"].Level != core.LevelSuspicious {
t.Fatalf("a peer cannot declare hostile without a strong signal: %+v", got["1.2.3.7"])
}
if _, ok := got["2001:db8:0:5::/64"]; !ok {
t.Fatalf("a /64 key is valid: %v", got)
}
if _, ok := got["2001:db8:0:6::/64"]; !ok || got["2001:db8:0:6::/64"].Level != core.LevelLow {
t.Fatalf("a plain IPv6 is normalized to its /64: %v", got)
}
if len(e.Summary.Recent) != 1 {
t.Fatalf("unknown categories must be dropped: %+v", e.Summary.Recent)
}
for _, src := range e.Summary.Sources {
if src.Path != "" || !validStates[src.State] {
t.Fatalf("source %+v", src)
}
}
}