feat: 1.4.0 second firewall, egress analysis and HTML report
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 28s
CI / Dependency audit (push) Successful in 16s
CI / Tests (Linux, race detector) (push) Successful in 1m3s
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 3s

Optional second firewall (URUTAU_ENFORCE off/observe/on) through the host
fail2ban, outbound traffic analysis (beaconing, mining, spam, DNS bypass,
unauthorised scans) with authorised scanner workloads, host kit in
deploy/host and a printable HTML report.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-14 23:35:34 -03:00
1 parent 3adaa007ec
commit c33cca22e3
59 files changed
+7364 -24

No files matched your search

+497
View File
@@ -0,0 +1,497 @@
package enforce
import (
"fmt"
"net/netip"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
var t0 = time.Date(2026, 11, 14, 22, 0, 0, 0, time.UTC)
func TestDecide(t *testing.T) {
p := Params{Threshold: 5}
cases := []struct {
name string
in Input
act string
why string
}{
{"below", Input{Attacks: 4, Top: ReasonScannerFlood}, ActNone, ""},
{"threshold", Input{Attacks: 5, Top: ReasonWPBrute}, ActBan, ReasonWPBrute},
{"critical single hit", Input{Crit: ReasonEnvProbe, Crits: 1, Attacks: 1}, ActNone, ""},
{"critical two hits", Input{Crit: ReasonEnvProbe, Crits: 2, Attacks: 2}, ActBan, ReasonEnvProbe},
{"ssh", Input{SSHFails: 5}, ActBan, ReasonSSHBrute},
{"ssh below", Input{SSHFails: 4}, ActNone, ""},
{"trusted", Input{Attacks: 9, Exclude: SkipTrusted}, ActSkip, ""},
{"crawler", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipCrawler}, ActSkip, ""},
{"infra", Input{Crit: ReasonRCE, Crits: 2, Exclude: SkipInfra}, ActSkip, ""},
{"legit doubles", Input{Attacks: 9, Legit: true, Top: ReasonScannerFlood}, ActNone, ""},
{"legit doubles ok", Input{Attacks: 10, Legit: true, Top: ReasonScannerFlood}, ActBan, ReasonScannerFlood},
{"legit never stops crit", Input{Crit: ReasonRCE, Crits: 2, Attacks: 2, Legit: true}, ActBan, ReasonRCE},
{"legit one crit", Input{Crit: ReasonRCE, Crits: 1, Attacks: 1, Legit: true}, ActNone, ""},
{"legit ssh", Input{SSHFails: 9, Legit: true}, ActNone, ""},
{"already", Input{Attacks: 5, Top: ReasonScannerFlood, Banned: true}, ActAlready, ""},
{"active", Input{Attacks: 5, Top: ReasonScannerFlood, Active: true}, ActActive, ""},
}
for _, c := range cases {
d := Decide(c.in, p)
if d.Action != c.act || (c.why != "" && d.Reason != c.why) {
t.Errorf("%s: %+v", c.name, d)
}
}
}
func TestTTLEscalation(t *testing.T) {
want := []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour, 7 * 24 * time.Hour}
for i, w := range want {
if TTLFor(i) != w {
t.Errorf("offence %d: %v", i, TTLFor(i))
}
}
}
func TestExclusions(t *testing.T) {
x := Exclusions{Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Peers: map[netip.Addr]bool{netip.MustParseAddr("46.1.1.1"): true},
Infra: map[netip.Addr]bool{netip.MustParseAddr("47.1.1.1"): true}}
for ip, want := range map[string]string{
"10.1.2.3": SkipPrivate, "127.0.0.1": SkipPrivate, "169.254.1.1": SkipPrivate, "100.64.1.1": SkipPrivate,
"::1": SkipPrivate, "fe80::1": SkipPrivate, "fc00::1": SkipPrivate, "ff02::1": SkipPrivate, "224.0.0.1": SkipPrivate,
"240.0.0.1": SkipPrivate, "0.0.0.0": SkipPrivate, "::ffff:10.0.0.1": SkipPrivate, "2001:db8::1": SkipPrivate,
"45.9.9.9": SkipTrusted, "47.1.1.1": SkipInfra, "46.1.1.1": SkipPeer, "::ffff:46.1.1.1": SkipPeer,
"8.8.8.8": SkipInfra, "2606:4700::1111": SkipInfra, "104.16.1.1": SkipInfra, "2a06:98c0::1": SkipInfra, "93.184.216.34": "",
} {
if got := x.Excluded(netip.MustParseAddr(ip)); got != want {
t.Errorf("%s: %q want %q", ip, got, want)
}
}
}
func atk(ip string, at time.Time, path string, st int) core.Event {
return core.Event{Time: at, IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Path: path, Status: st, UA: "x"}
}
type rig struct {
e *Engine
now time.Time
log string
}
func newRig(t *testing.T, mode string, mod func(*Config)) *rig {
r := &rig{now: t0, log: filepath.Join(t.TempDir(), "enf", "decisions.log")}
c := Config{Mode: mode, Path: r.log, StatePath: filepath.Join(t.TempDir(), "enforce.json"), Host: "oracle", Threshold: 5, MaxPerMin: 60,
Trusted: []netip.Prefix{netip.MustParsePrefix("45.0.0.0/8")}, Now: func() time.Time { return r.now }}
if mod != nil {
mod(&c)
}
r.e = New(c)
return r
}
func (r *rig) lines(t *testing.T) []string {
b, err := os.ReadFile(r.log)
if err != nil {
return nil
}
return strings.Split(strings.TrimSpace(string(b)), "\n")
}
func (r *rig) hits(ip string, n int, path string, st int) {
for i := 0; i < n; i++ {
r.e.process(atk(ip, r.now.Add(-time.Duration(i)*time.Second), path, st), "")
}
}
func TestEngineThresholdAndLine(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.hits("203.0.114.7", 4, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatal("banned below threshold")
}
r.hits("203.0.114.7", 1, "/x", 404)
l := r.lines(t)
if len(l) != 1 || !strings.HasPrefix(l[0], "2026-11-14T22:00:00Z urutau decision=ban ip=203.0.114.7 reason=scanner-flood score=") ||
!strings.HasSuffix(l[0], " ttl=3600 host=oracle src=local") {
t.Fatalf("line %q", l)
}
// dedupe: more hits while the TTL holds write nothing
r.hits("203.0.114.7", 10, "/x", 404)
if len(r.lines(t)) != 1 {
t.Fatal("rewrote during TTL")
}
// escalation after the TTL: 6 h, persisted
r.now = r.now.Add(61 * time.Minute)
r.hits("203.0.114.7", 5, "/x", 404)
l = r.lines(t)
if len(l) != 2 || !strings.Contains(l[1], "ttl=21600") {
t.Fatalf("escalation %q", l)
}
r.e.saveState()
e2 := New(r.e.cfg)
if e2.bans[netip.MustParseAddr("203.0.114.7")].Offences != 2 {
t.Fatalf("state %+v", e2.bans)
}
if fi, err := os.Stat(r.log); err != nil || fi.Mode().Perm() != 0o640 {
t.Fatalf("mode %v %v", fi, err)
}
}
func TestEngineCriticalAndFamily(t *testing.T) {
r := newRig(t, ModeOn, nil)
ev := atk("203.0.114.8", r.now, "/.env", 404)
ev.Cat = core.Exploit
r.e.process(ev, intel.FamEnvCreds)
if len(r.lines(t)) != 0 {
t.Fatal("a single critical hit banned")
}
ev.Time = r.now.Add(time.Second)
r.e.process(ev, intel.FamEnvCreds)
ev2 := atk("203.0.114.9", r.now, "/wp-login.php", 404)
r.e.process(ev2, intel.FamWordPress)
l := r.lines(t)
if len(l) != 1 || !strings.Contains(l[0], "reason=env-probe") {
t.Fatalf("%q", l)
}
}
func TestEngineNeverCounts(t *testing.T) {
r := newRig(t, ModeOn, nil)
for _, st := range []int{404, 400, 405, 500, 502} {
ev := atk("203.0.114.10", r.now, "/x", st)
ev.Cat = core.NotFound // a plain 404 is not an attack category
for i := 0; i < 20; i++ {
r.e.process(ev, "")
}
}
// app and proxy errors on attack-category requests do not count either
for i := 0; i < 20; i++ {
ev := atk("203.0.114.11", r.now, "/x", 500)
ev.Proto, ev.Router, ev.OriginStatus = "HTTP/2", "r@docker", 500
r.e.process(ev, "")
ev = atk("203.0.114.11", r.now, "/x", 502)
ev.Proto, ev.Router, ev.Retries = "HTTP/2", "r@docker", 2
r.e.process(ev, "")
fr := atk("203.0.114.11", r.now, "/x", 404)
fr.Framed = true
r.e.process(fr, "")
}
if len(r.lines(t)) != 0 {
t.Fatalf("banned: %q", r.lines(t))
}
}
func TestEngineExclusionsAndCounts(t *testing.T) {
r := newRig(t, ModeOn, func(c *Config) {
c.Crawler = func(ip string, uas []string) bool { return ip == "66.249.66.1" }
c.PeerHosts = []string{"46.1.1.1"}
})
r.hits("45.1.1.1", 6, "/x", 404)
r.hits("10.0.0.5", 6, "/x", 404)
r.hits("46.1.1.1", 6, "/x", 404)
r.hits("66.249.66.1", 6, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatalf("banned excluded: %q", r.lines(t))
}
rep := r.e.Report(0)
for _, k := range []string{SkipTrusted, SkipPrivate, SkipPeer, SkipCrawler} {
if rep.Counts.Skipped[k] != 1 {
t.Errorf("skip %s: %v", k, rep.Counts.Skipped)
}
}
// the skip is reported once, not once per event
r.hits("45.1.1.1", 30, "/x", 404)
if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 {
t.Fatal("skip spam")
}
}
func TestEngineLegitVisitor(t *testing.T) {
r := newRig(t, ModeOn, nil)
vis := core.Event{Time: r.now.Add(-time.Hour), IP: "203.0.114.20", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"}
r.e.process(vis, "")
ev := atk("203.0.114.20", r.now, "/.env", 404)
ev.Cat = core.Exploit
r.e.process(ev, intel.FamEnvCreds)
r.hits("203.0.114.20", 7, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatalf("legit banned: %q", r.lines(t))
}
r.hits("203.0.114.20", 2, "/y", 404)
if len(r.lines(t)) != 1 {
t.Fatalf("legit double threshold: %q", r.lines(t))
}
}
func TestEngineAlreadyBlocked(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.e.process(core.Event{Time: r.now, IP: "203.0.114.30", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}, "")
r.hits("203.0.114.30", 8, "/x", 404)
if len(r.lines(t)) != 0 || r.e.Report(0).Counts.AlreadyBlocked != 1 {
t.Fatalf("%q %+v", r.lines(t), r.e.Report(0).Counts)
}
rep := r.e.Report(0)
if rep.Coverage.AttackIPs != 1 || rep.Coverage.BlockedByFirewall != 1 {
t.Fatalf("coverage %+v", rep.Coverage)
}
}
func TestEngineSSH(t *testing.T) {
r := newRig(t, ModeOn, nil)
for i := 0; i < 5; i++ {
r.e.process(core.Event{Time: r.now.Add(-time.Duration(i) * time.Minute), IP: "203.0.114.40", Cat: core.SSHFail, Source: "ssh", User: "root"}, "")
}
if l := r.lines(t); len(l) != 1 || !strings.Contains(l[0], "reason=ssh-bruteforce") {
t.Fatalf("%q", l)
}
}
func TestEngineRateCapAndObserve(t *testing.T) {
r := newRig(t, ModeOn, func(c *Config) { c.MaxPerMin = 3 })
for i := 0; i < 6; i++ {
r.hits(fmt.Sprintf("203.0.114.%d", 50+i), 5, "/x", 404)
}
rep := r.e.Report(0)
if len(r.lines(t)) != 3 || rep.Counts.Written != 3 || rep.Counts.DroppedRate != 3 || rep.Counts.Decided != 6 {
t.Fatalf("%q %+v", r.lines(t), rep.Counts)
}
o := newRig(t, ModeObserve, nil)
o.hits("203.0.114.60", 5, "/x", 404)
rep = o.e.Report(0)
if _, err := os.Stat(o.log); err == nil {
t.Fatal("observe wrote the file")
}
if len(rep.Recent) != 1 || rep.Recent[0].Action != "would_ban" || rep.Coverage.WouldBlock != 1 || rep.Counts.Written != 0 {
t.Fatalf("%+v", rep)
}
}
func TestOldEventsDoNotBan(t *testing.T) {
r := newRig(t, ModeOn, nil)
for i := 0; i < 20; i++ {
r.e.process(atk("203.0.114.70", r.now.Add(-3*time.Hour), "/x", 404), "")
}
if len(r.lines(t)) != 0 {
t.Fatal("replayed events banned")
}
if r.e.Report(0).Coverage.AttackIPs != 1 {
t.Fatal("coverage lost old events")
}
}
func TestObserveNeverBlocks(t *testing.T) {
e := New(Config{Mode: ModeOn, Path: filepath.Join(t.TempDir(), "d.log")})
for i := 0; i < 10000; i++ {
e.Observe(atk("203.0.114.1", t0, "/x", 404), "")
}
if e.dropQ.Load() == 0 {
t.Fatal("full queue must drop and count")
}
}
func (r *rig) seen(ip string) { r.hits(ip, 2, "/x", 404) }
func TestAcceptPeer(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.seen("203.0.114.80")
acc, bad := r.e.AcceptPeer("hostinger", []Wire{
{T: t0.Unix(), IP: "203.0.114.80", Reason: ReasonRCE, Score: 90, TTL: 3600},
{T: t0.Unix(), IP: "203.0.114.81", Reason: "evil\nreason", Score: 90, TTL: 3600},
{T: t0.Unix(), IP: "10.0.0.1", Reason: ReasonRCE, TTL: 3600},
{T: t0.Unix(), IP: "45.2.2.2", Reason: ReasonRCE, TTL: 3600},
{T: t0.Unix(), IP: "nope", Reason: ReasonRCE, TTL: 3600},
})
l := r.lines(t)
if acc != 1 || bad != 3 || len(l) != 1 || !strings.HasSuffix(l[0], "src=peer:hostinger") {
t.Fatalf("%d %d %q", acc, bad, l)
}
if len(r.e.LocalSince(0)) != 0 {
t.Fatal("peer decisions must not be re-shared")
}
if r.e.Report(0).Counts.Skipped[SkipTrusted] != 1 {
t.Fatalf("%+v", r.e.Report(0).Counts)
}
}
func TestAcceptPeerUnconfirmedTTLAndInfra(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.seen("203.0.114.90")
r.seen("1.1.1.1")
r.seen("104.16.5.5")
acc, _ := r.e.AcceptPeer("h", []Wire{
{T: t0.Unix(), IP: "203.0.114.99", Reason: ReasonRCE, Score: 90, TTL: 3600}, // never seen here
{T: t0.Unix(), IP: "203.0.114.90", Reason: ReasonRCE, Score: 90, TTL: 7 * 24 * 3600},
{T: t0.Unix(), IP: "1.1.1.1", Reason: ReasonRCE, Score: 90, TTL: 3600},
{T: t0.Unix(), IP: "104.16.5.5", Reason: ReasonRCE, Score: 90, TTL: 3600},
})
l := r.lines(t)
if acc != 1 || len(l) != 1 || !strings.Contains(l[0], "ip=203.0.114.90") || !strings.Contains(l[0], "ttl=21600") {
t.Fatalf("%d %q", acc, l)
}
sk := r.e.Report(0).Counts.Skipped
if sk[SkipUnconfirmed] != 1 || sk[SkipInfra] < 2 {
t.Fatalf("%v", sk)
}
// an attack seen only long ago does not confirm
r2 := newRig(t, ModeOn, nil)
for i := 0; i < 3; i++ {
r2.e.process(atk("203.0.114.91", r2.now.Add(-8*24*time.Hour), "/x", 404), "")
}
if acc, _ := r2.e.AcceptPeer("h", []Wire{{T: t0.Unix(), IP: "203.0.114.91", Reason: ReasonRCE, TTL: 60}}); acc != 0 {
t.Fatal("stale confirmation accepted")
}
}
func TestInfraNeverBannedLocally(t *testing.T) {
r := newRig(t, ModeOn, func(c *Config) {
c.PeerHosts = []string{"hub.example"}
c.InfraHosts = []string{"hub.example"}
c.LocalAddrs = func() []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.200")} }
c.Resolve = func(string) []netip.Addr { return []netip.Addr{netip.MustParseAddr("203.0.114.201")} }
})
for _, ip := range []string{"104.16.9.9", "8.8.4.4", "2606:4700:4700::1001", "203.0.114.200", "203.0.114.201"} {
r.hits(ip, 9, "/x", 404)
}
if len(r.lines(t)) != 0 {
t.Fatalf("infra banned: %q", r.lines(t))
}
}
func TestPeerResolutionKeepsLastGood(t *testing.T) {
fail := false
r := newRig(t, ModeOn, func(c *Config) {
c.PeerHosts = []string{"peer.example"}
c.Resolve = func(string) []netip.Addr {
if fail {
return nil
}
return []netip.Addr{netip.MustParseAddr("203.0.114.210")}
}
})
fail = true
r.e.refreshPeers()
r.hits("203.0.114.210", 9, "/x", 404)
if len(r.lines(t)) != 0 {
t.Fatal("peer banned after DNS failure")
}
}
func TestCriticalNeedsTwoHits(t *testing.T) {
r := newRig(t, ModeOn, nil)
mk := func(at time.Time) {
ev := atk("203.0.114.220", at, "/.env", 404)
ev.Cat = core.Exploit
r.e.process(ev, intel.FamEnvCreds)
}
mk(r.now)
if len(r.lines(t)) != 0 {
t.Fatal("one hit")
}
// a forged legitimate visit does not cancel a critical ban
r.e.process(core.Event{Time: r.now, IP: "203.0.114.220", Cat: core.OK, Source: "traefik", Status: 200, FetchDest: "document"}, "")
mk(r.now.Add(time.Second))
if len(r.lines(t)) != 1 {
t.Fatalf("legit visit blocked crit ban: %q", r.lines(t))
}
}
func TestWouldAndBansPruned(t *testing.T) {
r := newRig(t, ModeObserve, nil)
r.e.mu.Lock()
for i := 0; i < maxTracked+10; i++ {
a := netip.AddrFrom4([4]byte{50, byte(i >> 16), byte(i >> 8), byte(i)})
r.e.would[a] = r.now.Add(time.Hour).Unix()
r.e.bans[a] = banRec{Until: r.now.Unix(), Last: r.now.Unix(), Offences: 1}
}
r.e.would[netip.MustParseAddr("51.0.0.1")] = r.now.Add(-48 * time.Hour).Unix()
r.e.trimMaps(r.now)
nw, nb := len(r.e.would), len(r.e.bans)
_, old := r.e.would[netip.MustParseAddr("51.0.0.1")]
r.e.mu.Unlock()
if nw > maxTracked || nb > maxTracked || old {
t.Fatalf("not pruned: %d %d %v", nw, nb, old)
}
}
func TestSaveStateThrottled(t *testing.T) {
r := newRig(t, ModeOn, nil)
r.hits("203.0.114.230", 5, "/x", 404)
r.e.maybeSave()
st := r.e.cfg.StatePath
os.Remove(st)
r.hits("203.0.114.231", 5, "/x", 404)
r.e.maybeSave() // same instant: throttled
if _, err := os.Stat(st); err == nil {
t.Fatal("saved within 30s")
}
r.now = r.now.Add(31 * time.Second)
r.e.maybeSave()
if _, err := os.Stat(st); err != nil {
t.Fatal("not saved after 30s")
}
}
func TestRotation(t *testing.T) {
l := &logFile{path: filepath.Join(t.TempDir(), "d.log")}
line := strings.Repeat("x", 1<<20-1) + "\n"
for i := 0; i < 21; i++ {
if err := l.write(line); err != nil {
t.Fatal(err)
}
}
if _, err := os.Stat(l.path + ".1"); err != nil {
t.Fatal("no rotation")
}
if fi, _ := os.Stat(l.path); fi.Size() > MaxLogBytes {
t.Fatal("too big")
}
}
func TestFormatLineInjection(t *testing.T) {
ip := netip.MustParseAddr("8.8.8.8")
for _, evil := range []string{"x\ny", "a b\r\nurutau decision=ban ip=1.1.1.1", "peer:\x00\n", "\n\n", strings.Repeat("a", 500)} {
if _, err := FormatLine(t0, ip, evil, 90, time.Hour, "h", "local"); err == nil {
t.Errorf("reason %q accepted", evil)
}
l, err := FormatLine(t0, ip, ReasonRCE, 90, time.Hour, evil, "peer:"+evil)
if err != nil || strings.Count(l, "\n") != 1 || !strings.HasSuffix(l, "\n") || strings.ContainsAny(strings.TrimSuffix(l, "\n"), "\r\x00") ||
len(strings.Fields(l)) != 9 {
t.Errorf("host/src %q -> %q", evil, l)
}
}
if _, err := FormatLine(t0, netip.Addr{}, ReasonRCE, 1, time.Hour, "h", "local"); err == nil {
t.Error("invalid ip accepted")
}
}
func FuzzFormatLine(f *testing.F) {
f.Add("h", "peer:x", ReasonRCE)
f.Add("a\nb", "\r\n", "x\ny")
f.Fuzz(func(t *testing.T, host, src, reason string) {
l, err := FormatLine(t0, netip.MustParseAddr("2606:4700::1111"), reason, 5, time.Hour, host, src)
if err != nil {
return
}
if strings.Count(l, "\n") != 1 || len(strings.Fields(l)) != 9 {
t.Fatalf("%q", l)
}
})
}
func TestWritable(t *testing.T) {
d := t.TempDir()
if !Writable(filepath.Join(d, "sub", "x.log")) || !Writable(filepath.Join(d, "x.log")) {
t.Fatal("should be writable")
}
if _, err := os.Stat(filepath.Join(d, "x.log")); err == nil {
t.Fatal("Writable must not create the file")
}
if Writable("") {
t.Fatal("empty path")
}
}
+723
View File
@@ -0,0 +1,723 @@
package enforce
import (
"context"
"encoding/json"
"net/netip"
"os"
"path/filepath"
"sort"
"sync"
"sync/atomic"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// Config configures the engine. Mode must be observe or on (off means no engine).
type Config struct {
Mode string
Path string // decision file
StatePath string // enforce.json, empty: no persistence
Host string // name of this instance, written in every line
Threshold int // attack events in Window
MaxPerMin int
Share bool
Trusted []netip.Prefix
PeerHosts []string // host names or addresses of the peers
InfraHosts []string // hub and other infrastructure hosts, never banned
LocalAddrs func() []netip.Addr // default: the addresses of the local interfaces
Resolve func(host string) []netip.Addr // default: literal parse only
Crawler func(ip string, uas []string) bool // FCrDNS verified crawler
Geo func(ip string) (string, uint32, string) // cc, asn, org
Now func() time.Time
}
// Wire is a decision as exchanged between peers.
type Wire struct {
T int64 `json:"t"`
IP string `json:"ip"`
Reason string `json:"reason"`
Score int `json:"score"`
TTL int `json:"ttl"`
}
// MaxWire is the most decisions accepted or returned in one exchange.
const MaxWire = 500
// Recent is one row of the report.
type Recent struct {
T int64 `json:"t"`
IP string `json:"ip"`
Reason string `json:"reason"`
Score int `json:"score"`
TTL int `json:"ttl"`
Action string `json:"action"` // ban, would_ban, skip
SkipReason string `json:"skip_reason"`
Src string `json:"src"`
CC string `json:"cc"`
ASN uint32 `json:"asn"`
Org string `json:"org"`
}
// Counts are the cumulative counters since start.
type Counts struct {
Decided int `json:"decided"`
Written int `json:"written"`
DroppedRate int `json:"dropped_rate"`
AlreadyBlocked int `json:"already_blocked"`
Skipped map[string]int `json:"skipped"`
DroppedQueue int64 `json:"dropped_queue"`
WriteErrors int `json:"write_errors"`
}
// Coverage tells how many attacking addresses were stopped, by whom.
type Coverage struct {
AttackIPs int `json:"attack_ips"`
BlockedByFirewall int `json:"blocked_by_firewall"`
BlockedByUrutau int `json:"blocked_by_urutau"`
WouldBlock int `json:"would_block"`
Unblocked int `json:"unblocked"`
}
// Report is what the API serves (mode and file status are added by the handler).
type Report struct {
Coverage Coverage `json:"coverage"`
Counts Counts `json:"counts"`
Recent []Recent `json:"recent"`
}
type aevt struct {
ts int64
slug string
}
type ipState struct {
ev []aevt
ssh []int64
legit int64
uas []string
lastAttack int64
f2bAt int64
urutauAt int64
wouldAt int64
banned int64 // fail2ban holds it until (unix), 0 none
}
type banRec struct {
Until int64 `json:"until"`
Offences int `json:"offences"`
Last int64 `json:"last"`
}
type item struct {
ev core.Event
fam string
}
const (
maxIPs = 50000
maxEvents = 128
maxRecent = 200
skipQuiet = 10 * time.Minute
banAssume = 24 * time.Hour
peerRefresh = 10 * time.Minute
maxPeerTTL = 6 * time.Hour
peerConfirmAge = 7 * 24 * time.Hour
maxTracked = 50000 // would and bans
saveEvery = 30 * time.Second
)
// Engine is the second firewall.
type Engine struct {
cfg Config
log *logFile
ch chan item
dropQ atomic.Int64
mu sync.Mutex
ips map[netip.Addr]*ipState
bans map[netip.Addr]banRec
would map[netip.Addr]int64
skipSeen map[netip.Addr]int64
excl Exclusions
counts Counts
recent []Recent
shared []Wire
minute int64
inMinute int
dirty bool
lastSave time.Time
hostIPs map[string][]netip.Addr // last good resolution per host
}
// New builds an engine and loads its state.
func New(c Config) *Engine {
if c.Now == nil {
c.Now = time.Now
}
if c.Threshold < 1 {
c.Threshold = 5
}
if c.MaxPerMin < 1 {
c.MaxPerMin = 60
}
if c.Resolve == nil {
c.Resolve = func(h string) []netip.Addr {
if a, err := netip.ParseAddr(h); err == nil {
return []netip.Addr{a.Unmap()}
}
return nil
}
}
e := &Engine{cfg: c, log: &logFile{path: c.Path}, ch: make(chan item, 4096), ips: map[netip.Addr]*ipState{},
bans: map[netip.Addr]banRec{}, would: map[netip.Addr]int64{}, skipSeen: map[netip.Addr]int64{},
counts: Counts{Skipped: map[string]int{}}}
e.hostIPs = map[string][]netip.Addr{}
e.excl = Exclusions{Trusted: c.Trusted, Peers: map[netip.Addr]bool{}, Infra: map[netip.Addr]bool{}}
e.refreshPeers()
e.loadState()
return e
}
// Mode returns the mode of the engine.
func (e *Engine) Mode() string { return e.cfg.Mode }
// Host is the name of this instance.
func (e *Engine) Host() string { return e.cfg.Host }
// Share reports whether decisions are exchanged with peers.
func (e *Engine) Share() bool { return e.cfg.Share }
// Threshold is the attack-event threshold in use.
func (e *Engine) Threshold() int { return e.cfg.Threshold }
// LogPath is the decision file.
func (e *Engine) LogPath() string { return e.cfg.Path }
// Observe is the ingestion hook: cheap, never blocks; a full queue drops the
// event and counts it.
func (e *Engine) Observe(ev core.Event, fam string) {
switch ev.Cat {
case core.Ban, core.SSHFail, core.Scanner, core.Exploit, core.BruteForce:
case core.OK:
if ev.FetchDest != "document" || ev.Status < 200 || ev.Status > 299 {
return
}
default:
return
}
select {
case e.ch <- item{ev, fam}:
default:
e.dropQ.Add(1)
}
}
// Run processes events until ctx is done.
func (e *Engine) Run(ctx context.Context) {
flush := time.NewTicker(5 * time.Second)
peers := time.NewTicker(peerRefresh)
defer flush.Stop()
defer peers.Stop()
defer e.log.close()
for {
select {
case <-ctx.Done():
e.saveState()
return
case it := <-e.ch:
e.process(it.ev, it.fam)
case <-flush.C:
e.maybeSave()
case <-peers.C:
e.refreshPeers()
}
}
}
// resolveKeep resolves h; an empty answer (DNS failure) keeps the last good one.
func (e *Engine) resolveKeep(h string, into map[netip.Addr]bool) {
as := e.cfg.Resolve(h)
e.mu.Lock()
if len(as) == 0 {
as = e.hostIPs[h]
} else {
e.hostIPs[h] = as
}
e.mu.Unlock()
for _, a := range as {
into[a.Unmap()] = true
}
}
func (e *Engine) refreshPeers() {
m := map[netip.Addr]bool{}
for _, h := range e.cfg.PeerHosts {
e.resolveKeep(h, m)
}
infra := map[netip.Addr]bool{}
for _, h := range e.cfg.InfraHosts {
e.resolveKeep(h, infra)
}
la := e.cfg.LocalAddrs
if la == nil {
la = interfaceAddrs
}
for _, a := range la() {
infra[a.Unmap()] = true
}
e.mu.Lock()
e.excl.Peers = m
e.excl.Infra = infra
e.mu.Unlock()
}
func (e *Engine) stateOf(a netip.Addr) *ipState {
st := e.ips[a]
if st == nil {
if len(e.ips) >= maxIPs {
e.evict()
}
st = &ipState{}
e.ips[a] = st
}
return st
}
func (e *Engine) evict() {
cut := e.cfg.Now().Add(-24 * time.Hour).Unix()
for a, st := range e.ips {
if max(st.lastAttack, st.f2bAt, st.legit) < cut {
delete(e.ips, a)
}
}
for a := range e.ips {
if len(e.ips) < maxIPs/2 {
break
}
delete(e.ips, a)
}
if len(e.skipSeen) > 10000 {
e.skipSeen = map[netip.Addr]int64{}
}
}
// trimMaps prunes would (expired or older than 24 h) and bans (older than 30 d)
// and caps both at maxTracked, dropping the least recent first; the lock is held.
func (e *Engine) trimMaps(now time.Time) {
cutW := now.Unix()
for a, u := range e.would {
if u < cutW || u < now.Add(-24*time.Hour).Unix() {
delete(e.would, a)
}
}
if len(e.would) > maxTracked {
type kv struct {
a netip.Addr
t int64
}
l := make([]kv, 0, len(e.would))
for a, u := range e.would {
l = append(l, kv{a, u})
}
sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t })
for _, x := range l[:len(l)-maxTracked/2] {
delete(e.would, x.a)
}
}
cutB := now.Add(-30 * 24 * time.Hour).Unix()
for a, b := range e.bans {
if b.Last < cutB {
delete(e.bans, a)
}
}
if len(e.bans) > maxTracked {
type kv struct {
a netip.Addr
t int64
}
l := make([]kv, 0, len(e.bans))
for a, b := range e.bans {
l = append(l, kv{a, b.Last})
}
sort.Slice(l, func(i, j int) bool { return l[i].t < l[j].t })
for _, x := range l[:len(l)-maxTracked/2] {
delete(e.bans, x.a)
}
}
}
// process handles one classified event (called by Run, or directly by tests).
func (e *Engine) process(ev core.Event, fam string) {
a, err := netip.ParseAddr(ev.IP)
if err != nil {
return
}
a = a.Unmap().WithZone("")
now := e.cfg.Now()
ts := ev.Time.Unix()
e.mu.Lock()
defer e.mu.Unlock()
switch {
case ev.Cat == core.Ban:
if ts < now.Add(-30*24*time.Hour).Unix() {
return
}
st := e.stateOf(a)
switch {
case ev.Unban:
st.banned = 0
default:
if ev.Jail == "urutau" { // our own decision, enforced by the host jail
st.urutauAt = max(st.urutauAt, ts)
} else {
st.banned = max(st.banned, ev.Time.Add(banAssume).Unix())
st.f2bAt = max(st.f2bAt, ts)
}
}
return
case LegitVisit(ev):
if ts >= now.Add(-LegitWindow).Unix() {
e.stateOf(a).legit = max(e.stateOf(a).legit, ts)
}
return
case ev.Cat == core.SSHFail:
case CountsAsAttack(ev):
default:
return
}
if ts < now.Add(-30*24*time.Hour).Unix() {
return
}
st := e.stateOf(a)
st.lastAttack = max(st.lastAttack, ts)
if ts < now.Add(-Window).Unix() { // a replayed old event: coverage only
return
}
cut := now.Add(-Window).Unix()
slug, crit := attackSlug(ev, fam)
if ev.Cat == core.SSHFail {
st.ssh = prune(append(st.ssh, ts), cut)
} else {
st.ev = append(st.ev, aevt{ts, slug})
k := 0
for _, x := range st.ev {
if x.ts >= cut {
st.ev[k] = x
k++
}
}
st.ev = st.ev[:k]
if len(st.ev) > maxEvents {
st.ev = st.ev[len(st.ev)-maxEvents:]
}
}
if ev.UA != "" && len(st.uas) < 3 {
ua := ev.UA
if len(ua) > 200 {
ua = ua[:200]
}
dup := false
for _, u := range st.uas {
dup = dup || u == ua
}
if !dup {
st.uas = append(st.uas, ua)
}
}
crits := 0
for _, x := range st.ev {
if criticalReasons[x.slug] {
crits++
}
}
in := Input{Now: now, Attacks: len(st.ev), Top: topSlug(st.ev), SSHFails: len(st.ssh), Crits: crits,
Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.excl.Excluded(a)}
if crit {
in.Crit = slug
}
e.fill(a, st, &in, now)
d := Decide(in, Params{Threshold: e.cfg.Threshold})
if d.Action == ActBan && e.cfg.Crawler != nil && len(st.uas) > 0 && e.cfg.Crawler(a.String(), st.uas) {
in.Exclude = SkipCrawler
d = Decide(in, Params{Threshold: e.cfg.Threshold})
}
e.apply(a, st, d, "local", now)
}
func (e *Engine) fill(a netip.Addr, st *ipState, in *Input, now time.Time) {
in.Banned = st.banned > now.Unix()
if b, ok := e.bans[a]; ok {
in.Offences = b.Offences
if b.Until > now.Unix() && e.cfg.Mode == ModeOn {
in.Active = true
}
if now.Unix() > b.Until+30*24*3600 {
in.Offences = 0
}
}
if u, ok := e.would[a]; ok && u > now.Unix() && e.cfg.Mode == ModeObserve {
in.Active = true
}
}
func prune(l []int64, cut int64) []int64 {
k := 0
for _, t := range l {
if t >= cut {
l[k] = t
k++
}
}
l = l[:k]
if len(l) > maxEvents {
l = l[len(l)-maxEvents:]
}
return l
}
func topSlug(evs []aevt) string {
cnt := map[string]int{}
best, bn := "", 0
for _, x := range evs {
cnt[x.slug]++
if cnt[x.slug] >= bn {
best, bn = x.slug, cnt[x.slug]
}
}
return best
}
// apply records the outcome of a decision; the lock is held.
func (e *Engine) apply(a netip.Addr, st *ipState, d Decision, src string, now time.Time) {
switch d.Action {
case ActSkip, ActAlready:
if until, ok := e.skipSeen[a]; ok && until > now.Unix() {
return
}
e.skipSeen[a] = now.Add(skipQuiet).Unix()
r := Recent{T: now.Unix(), IP: a.String(), Action: "skip", SkipReason: d.Skip, Src: src}
if d.Action == ActAlready {
e.counts.AlreadyBlocked++
r.SkipReason = "already_blocked"
} else {
e.counts.Skipped[d.Skip]++
}
e.addRecent(a, r)
case ActBan:
e.counts.Decided++
m := now.Unix() / 60
if m != e.minute {
e.minute, e.inMinute = m, 0
}
if e.inMinute >= e.cfg.MaxPerMin {
e.counts.DroppedRate++
return
}
e.inMinute++
r := Recent{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: int(d.TTL / time.Second), Src: src}
if e.cfg.Mode != ModeOn {
r.Action = "would_ban"
if len(e.would) >= maxTracked {
e.trimMaps(now)
}
e.would[a] = now.Add(d.TTL).Unix()
st.wouldAt = now.Unix()
e.addRecent(a, r)
return
}
line, err := FormatLine(now, a, d.Reason, d.Score, d.TTL, e.cfg.Host, src)
if err == nil {
err = e.log.write(line)
}
if err != nil {
e.counts.WriteErrors++
return
}
r.Action = "ban"
e.counts.Written++
if len(e.bans) >= maxTracked {
e.trimMaps(now)
}
b := e.bans[a]
if now.Unix() > b.Until+30*24*3600 {
b.Offences = 0
}
if src == "local" {
b.Offences++
e.shared = append(e.shared, Wire{T: now.Unix(), IP: a.String(), Reason: d.Reason, Score: d.Score, TTL: r.TTL})
if len(e.shared) > MaxWire {
e.shared = e.shared[len(e.shared)-MaxWire:]
}
}
b.Until, b.Last = now.Add(d.TTL).Unix(), now.Unix()
e.bans[a] = b
st.urutauAt = now.Unix()
e.dirty = true
e.addRecent(a, r)
}
}
func (e *Engine) addRecent(a netip.Addr, r Recent) {
if e.cfg.Geo != nil {
r.CC, r.ASN, r.Org = e.cfg.Geo(a.String())
}
e.recent = append(e.recent, r)
if len(e.recent) > maxRecent*2 {
e.recent = append([]Recent(nil), e.recent[len(e.recent)-maxRecent:]...)
}
}
// LocalSince returns the decisions this instance wrote since the unix time.
func (e *Engine) LocalSince(since int64) []Wire {
e.mu.Lock()
defer e.mu.Unlock()
out := []Wire{}
for _, w := range e.shared {
if w.T >= since {
out = append(out, w)
}
}
return out
}
// AcceptPeer applies decisions received from a peer, after this instance's own
// exclusions. It returns how many were accepted for the policy (written or
// would-ban) and how many were refused as malformed.
func (e *Engine) AcceptPeer(name string, in []Wire) (accepted, invalid int) {
if len(in) > MaxWire {
in = in[:MaxWire]
}
src := "peer:" + token(name, "peer")
now := e.cfg.Now()
e.mu.Lock()
defer e.mu.Unlock()
for _, w := range in {
a, err := netip.ParseAddr(w.IP)
if err != nil || !ValidReason(w.Reason) || !Public(a) {
invalid++
continue
}
a = a.Unmap().WithZone("")
ttl := min(time.Duration(min(max(w.TTL, 60), 7*24*3600))*time.Second, maxPeerTTL)
if w.T > 0 && w.T+int64(ttl/time.Second) < now.Unix() {
continue // already expired
}
st := e.stateOf(a)
in := Input{Now: now, Crit: w.Reason, Crits: CritHits, Exclude: e.excl.Excluded(a)}
if in.Exclude == "" && st.lastAttack < now.Add(-peerConfirmAge).Unix() {
in.Exclude = SkipUnconfirmed // a peer's word alone never bans: this node must have seen the address attack
}
e.fill(a, st, &in, now)
d := Decide(in, Params{})
if d.Action == ActBan {
d.Reason, d.Score, d.TTL = w.Reason, max(0, min(100, w.Score)), ttl
accepted++
}
e.apply(a, st, d, src, now)
}
return accepted, invalid
}
// Report summarizes the activity since the unix time from.
func (e *Engine) Report(from int64) Report {
e.mu.Lock()
defer e.mu.Unlock()
var cv Coverage
for _, st := range e.ips {
if st.lastAttack < from {
continue
}
cv.AttackIPs++
switch {
case st.f2bAt > 0 && st.f2bAt >= from:
cv.BlockedByFirewall++
case st.urutauAt > 0 && st.urutauAt >= from:
cv.BlockedByUrutau++
case st.wouldAt > 0 && st.wouldAt >= from:
cv.WouldBlock++
default:
cv.Unblocked++
}
}
c := e.counts
c.Skipped = map[string]int{SkipTrusted: 0, SkipPrivate: 0, SkipCrawler: 0, SkipLegit: 0, SkipPeer: 0, SkipInfra: 0, SkipUnconfirmed: 0}
for k, v := range e.counts.Skipped {
c.Skipped[k] = v
}
c.DroppedQueue = e.dropQ.Load()
rec := []Recent{}
for i := len(e.recent) - 1; i >= 0 && len(rec) < maxRecent; i-- {
if e.recent[i].T >= from {
rec = append(rec, e.recent[i])
}
}
return Report{Coverage: cv, Counts: c, Recent: rec}
}
type stateFile struct {
V int `json:"v"`
Bans map[string]banRec `json:"bans"`
}
func (e *Engine) loadState() {
if e.cfg.StatePath == "" {
return
}
b, err := os.ReadFile(e.cfg.StatePath)
if err != nil {
return
}
var sf stateFile
if json.Unmarshal(b, &sf) != nil {
return
}
cut := e.cfg.Now().Add(-30 * 24 * time.Hour).Unix()
for k, v := range sf.Bans {
if a, err := netip.ParseAddr(k); err == nil && v.Last >= cut && v.Offences >= 0 && v.Offences < 1000 {
e.bans[a.Unmap()] = v
}
}
}
// maybeSave writes the state at most every saveEvery.
func (e *Engine) maybeSave() {
if e.cfg.Now().Sub(e.lastSave) < saveEvery {
return
}
e.saveState()
}
// saveState writes enforce.json atomically when something changed.
func (e *Engine) saveState() {
if e.cfg.StatePath == "" {
return
}
e.mu.Lock()
if !e.dirty {
e.mu.Unlock()
return
}
e.lastSave = e.cfg.Now()
e.trimMaps(e.lastSave)
sf := stateFile{V: 1, Bans: map[string]banRec{}}
for a, b := range e.bans {
sf.Bans[a.String()] = b
}
e.dirty = false
e.mu.Unlock()
b, _ := json.Marshal(sf)
tmp := e.cfg.StatePath + ".tmp"
if err := os.MkdirAll(filepath.Dir(tmp), 0o700); err == nil {
if err = os.WriteFile(tmp, b, 0o600); err == nil {
if err = os.Rename(tmp, e.cfg.StatePath); err == nil {
return
}
}
}
e.mu.Lock()
e.dirty = true
e.mu.Unlock()
}
+78
View File
@@ -0,0 +1,78 @@
package enforce
import (
"net"
"net/netip"
)
// SkipInfra is the skip reason of the fixed infrastructure allowlist.
const SkipInfra = "infrastructure"
func mustPrefixes(l ...string) []netip.Prefix {
out := make([]netip.Prefix, 0, len(l))
for _, s := range l {
out = append(out, netip.MustParsePrefix(s))
}
return out
}
// cloudflare are the published Cloudflare ranges (https://www.cloudflare.com/ips/).
// They are never banned: behind the CDN the "client" of a request is an edge
// address shared by thousands of innocent visitors.
var cloudflare = mustPrefixes(
"173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
"108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17",
"162.158.0.0/15", "104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
"2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
"2a06:98c0::/29", "2c0f:f248::/32")
// publicResolvers are the well known public DNS resolvers.
var publicResolvers = func() map[netip.Addr]bool {
m := map[netip.Addr]bool{}
for _, s := range []string{"1.1.1.1", "1.0.0.1", "8.8.8.8", "8.8.4.4", "9.9.9.9", "149.112.112.112",
"208.67.222.222", "208.67.220.220", "2606:4700:4700::1111", "2606:4700:4700::1001",
"2001:4860:4860::8888", "2001:4860:4860::8844", "2620:fe::fe", "2620:fe::9",
"2620:119:35::35", "2620:119:53::53"} {
m[netip.MustParseAddr(s)] = true
}
return m
}()
// IsCloudflare reports whether a belongs to a Cloudflare range.
func IsCloudflare(a netip.Addr) bool {
a = a.Unmap()
for _, p := range cloudflare {
if p.Contains(a) {
return true
}
}
return false
}
// IsInfrastructure reports whether a is in the fixed allowlist (Cloudflare, public resolvers).
func IsInfrastructure(a netip.Addr) bool {
a = a.Unmap()
return publicResolvers[a] || IsCloudflare(a)
}
// interfaceAddrs lists the addresses of the local interfaces.
func interfaceAddrs() []netip.Addr {
var out []netip.Addr
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil
}
for _, x := range addrs {
var ip net.IP
switch v := x.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if a, ok := netip.AddrFromSlice(ip); ok {
out = append(out, a.Unmap())
}
}
return out
}
+145
View File
@@ -0,0 +1,145 @@
package enforce
import (
"errors"
"fmt"
"net/netip"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// MaxLogBytes is the size at which the decision file is rotated (one .1 kept).
const MaxLogBytes = 20 << 20
// token reduces s to [A-Za-z0-9._-] (at most 32 bytes); fallback if nothing is left.
func token(s, fallback string) string {
var b strings.Builder
for i := 0; i < len(s) && b.Len() < 32; i++ {
c := s[i]
if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '.' || c == '_' || c == '-' {
b.WriteByte(c)
}
}
if b.Len() == 0 {
return fallback
}
return b.String()
}
// FormatLine renders one decision. Nothing the attacker controls enters it:
// the address is re-formatted by netip, the reason must be a fixed slug and the
// host and source names are reduced to a safe alphabet.
func FormatLine(t time.Time, ip netip.Addr, reason string, score int, ttl time.Duration, host, src string) (string, error) {
ip = ip.Unmap().WithZone("")
if !ip.IsValid() {
return "", errors.New("invalid ip")
}
if !ValidReason(reason) {
return "", errors.New("invalid reason")
}
score = max(0, min(100, score))
secs := max(1, int64(ttl/time.Second))
if src != "local" {
src = "peer:" + token(strings.TrimPrefix(src, "peer:"), "peer")
}
return fmt.Sprintf("%s urutau decision=ban ip=%s reason=%s score=%d ttl=%d host=%s src=%s\n",
t.UTC().Format("2006-01-02T15:04:05Z"), ip.String(), reason, score, secs, token(host, "urutau"), src), nil
}
// logFile appends to the decision file, rotating by size.
type logFile struct {
mu sync.Mutex
path string
f *os.File
size int64
}
func (l *logFile) open() error {
if err := os.MkdirAll(filepath.Dir(l.path), 0o750); err != nil {
return err
}
f, err := os.OpenFile(l.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o640)
if err != nil {
return err
}
fi, err := f.Stat()
if err != nil {
f.Close()
return err
}
l.f, l.size = f, fi.Size()
return nil
}
func (l *logFile) write(line string) error {
l.mu.Lock()
defer l.mu.Unlock()
if l.f == nil {
if err := l.open(); err != nil {
return err
}
}
if l.size+int64(len(line)) > MaxLogBytes {
l.f.Close()
l.f = nil
if err := os.Rename(l.path, l.path+".1"); err != nil {
return err
}
if err := l.open(); err != nil {
return err
}
}
n, err := l.f.WriteString(line)
l.size += int64(n)
if err != nil {
l.f.Close()
l.f = nil
}
return err
}
func (l *logFile) close() {
l.mu.Lock()
defer l.mu.Unlock()
if l.f != nil {
l.f.Close()
l.f = nil
}
}
// Writable reports whether the decision file can be appended to, without
// creating anything: an existing file is opened for writing, otherwise a
// temporary file is created next to where it would live.
func Writable(path string) bool {
if path == "" {
return false
}
if _, err := os.Stat(path); err == nil {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0)
if err != nil {
return false
}
f.Close()
return true
}
dir := filepath.Dir(path)
if _, err := os.Stat(dir); err != nil {
// the directory is created on first write: check the nearest parent
for dir != "/" && dir != "." {
dir = filepath.Dir(dir)
if _, err := os.Stat(dir); err == nil {
break
}
}
}
f, err := os.CreateTemp(dir, ".urutau-w-*")
if err != nil {
return false
}
f.Close()
os.Remove(f.Name())
return true
}
+280
View File
@@ -0,0 +1,280 @@
// Package enforce is the optional "second firewall": it decides which source
// addresses deserve a ban and appends one line per decision to a file. The
// process never gains privileges: a host side fail2ban jail reads the file.
package enforce
import (
"net/netip"
"os"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
// Modes.
const (
ModeOff = "off"
ModeObserve = "observe"
ModeOn = "on"
)
// Fixed reason slugs. Anything else is refused (also from peers).
const (
ReasonScannerFlood = "scanner-flood"
ReasonExploitFlood = "exploit-flood"
ReasonWebBrute = "web-bruteforce"
ReasonWPBrute = "wp-bruteforce"
ReasonSSHBrute = "ssh-bruteforce"
ReasonRCE = "rce"
ReasonTraversal = "path-traversal"
ReasonEnvProbe = "env-probe"
ReasonVCSProbe = "vcs-probe"
ReasonWebshell = "webshell"
ReasonSQLi = "sqli"
ReasonLog4Shell = "log4shell"
)
var reasons = map[string]bool{
ReasonScannerFlood: true, ReasonExploitFlood: true, ReasonWebBrute: true, ReasonWPBrute: true,
ReasonSSHBrute: true, ReasonRCE: true, ReasonTraversal: true, ReasonEnvProbe: true,
ReasonVCSProbe: true, ReasonWebshell: true, ReasonSQLi: true, ReasonLog4Shell: true,
}
// ValidReason reports whether s is one of the fixed slugs.
func ValidReason(s string) bool { return reasons[s] }
// criticalFam maps the attack families that justify a ban on one hit.
var criticalFam = map[string]string{
intel.FamRCE: ReasonRCE,
intel.FamTraversal: ReasonTraversal,
intel.FamEnvCreds: ReasonEnvProbe,
intel.FamVCS: ReasonVCSProbe,
intel.FamWebshell: ReasonWebshell,
intel.FamSQLi: ReasonSQLi,
intel.FamLog4Shell: ReasonLog4Shell,
}
// Policy constants.
const (
Window = 10 * time.Minute
LegitWindow = 24 * time.Hour
SSHThreshold = 5
// CritHits is how many critical events of one address (in Window) justify a ban.
CritHits = 2
)
// ttls is the advisory duration by number of previous bans.
var ttls = []time.Duration{time.Hour, 6 * time.Hour, 24 * time.Hour, 7 * 24 * time.Hour}
// TTLFor is the advisory TTL of a ban preceded by n earlier bans.
func TTLFor(offences int) time.Duration {
if offences < 0 {
offences = 0
}
if offences >= len(ttls) {
offences = len(ttls) - 1
}
return ttls[offences]
}
// Skip reasons, also the keys of Counts.Skipped.
const (
SkipTrusted = "trusted"
SkipPrivate = "private"
SkipCrawler = "crawler"
SkipLegit = "legit_visitor"
SkipPeer = "peer"
// SkipUnconfirmed: a peer's decision about an address this node never saw attacking.
SkipUnconfirmed = "peer_unconfirmed"
)
// Actions of a Decision.
const (
ActNone = "" // nothing to do
ActBan = "ban" // write (or would write)
ActSkip = "skip" // excluded
ActAlready = "already" // fail2ban already blocks it
ActActive = "active" // an advisory ban is still valid
)
// Input is everything Decide needs about one address.
type Input struct {
Now time.Time
Attacks int // counted attack events in the window
Top string // reason slug of the dominant attack in the window
SSHFails int // failed SSH logins in the window
Crit string // reason of a critical family hit just seen, "" if none
Crits int // critical events of the address in the window (a single hit is not enough)
Legit bool // a document 2xx from a browser within the last 24 h
Exclude string // Excluded() result or "crawler"
Banned bool // fail2ban already blocks it
Active bool // an advisory ban is still valid
Offences int
}
// Params are the thresholds.
type Params struct{ Threshold int }
// Decision is the verdict of Decide.
type Decision struct {
Action string
Reason string
Score int
TTL time.Duration
Skip string
}
// Decide is the pure policy. It returns ActNone while nothing justifies a ban.
func Decide(in Input, p Params) Decision {
th, sshTh := p.Threshold, SSHThreshold
if th < 1 {
th = 5
}
if in.Legit { // a (forgeable) legitimate visit only relaxes the volumetric thresholds
th, sshTh = th*2, sshTh*2
}
var reason string
score := 0
switch {
case in.Crit != "" && in.Crits >= CritHits:
reason, score = in.Crit, 90
case in.SSHFails >= sshTh:
reason, score = ReasonSSHBrute, min(100, 60+(in.SSHFails-sshTh)*5)
case in.Attacks >= th:
reason, score = in.Top, min(100, 55+(in.Attacks-th)*5)
if !ValidReason(reason) {
reason = ReasonScannerFlood
}
default:
return Decision{}
}
switch {
case in.Exclude != "":
return Decision{Action: ActSkip, Skip: in.Exclude}
case in.Banned:
return Decision{Action: ActAlready}
case in.Active:
return Decision{Action: ActActive}
}
return Decision{Action: ActBan, Reason: reason, Score: score, TTL: TTLFor(in.Offences)}
}
// reservedV4/V6 are special purpose ranges not covered by netip helpers.
var reserved = func() []netip.Prefix {
var out []netip.Prefix
for _, s := range []string{"0.0.0.0/8", "100.64.0.0/10", "192.0.0.0/24", "192.0.2.0/24", "198.18.0.0/15",
"198.51.100.0/24", "203.0.113.0/24", "240.0.0.0/4", "2001:db8::/32", "100::/64", "fc00::/7", "fe80::/10", "ff00::/8"} {
out = append(out, netip.MustParsePrefix(s))
}
return out
}()
// demoReservedPublic is a hidden switch ONLY for the documentation screenshots
// (scripts/screenshots.sh): the demo data uses reserved documentation ranges, which
// production policy rightly treats as private. Never set URUTAU_DEMO_RESERVED_PUBLIC
// outside the screenshot run.
var demoReservedPublic = os.Getenv("URUTAU_DEMO_RESERVED_PUBLIC") == "1"
func demoRanges(p netip.Prefix) bool {
switch p.String() {
case "198.18.0.0/15", "203.0.113.0/24", "198.51.100.0/24", "192.0.2.0/24", "2001:db8::/32":
return true
}
return false
}
// Public reports whether a is a routable unicast address worth blocking.
func Public(a netip.Addr) bool {
a = a.Unmap()
if !a.IsValid() || a.Zone() != "" || a.IsUnspecified() || a.IsLoopback() || a.IsPrivate() || a.IsMulticast() ||
a.IsLinkLocalUnicast() || a.IsLinkLocalMulticast() || a.IsInterfaceLocalMulticast() {
return false
}
for _, p := range reserved {
if demoReservedPublic && demoRanges(p) {
continue
}
if p.Contains(a) {
return false
}
}
return true
}
// Exclusions are the addresses that are never banned.
type Exclusions struct {
Trusted []netip.Prefix // --trusted and --ignore
Peers map[netip.Addr]bool // addresses of the peers
Infra map[netip.Addr]bool // hub, local interfaces (resolved at runtime)
}
var criticalReasons = func() map[string]bool {
m := map[string]bool{}
for _, r := range criticalFam {
m[r] = true
}
return m
}()
// Excluded returns the skip reason of a, or "".
func (x Exclusions) Excluded(a netip.Addr) string {
a = a.Unmap()
if !Public(a) {
return SkipPrivate
}
if x.Peers[a] {
return SkipPeer
}
for _, p := range x.Trusted {
if p.Contains(a) {
return SkipTrusted
}
}
if x.Infra[a] || IsInfrastructure(a) {
return SkipInfra
}
return ""
}
// attackSlug is the reason slug of one attack event, and whether it is critical.
func attackSlug(ev core.Event, fam string) (slug string, crit bool) {
if ev.Cat == core.SSHFail {
return ReasonSSHBrute, false
}
if r, ok := criticalFam[fam]; ok {
return r, true
}
switch {
case fam == intel.FamWordPress:
return ReasonWPBrute, false
case ev.Cat == core.BruteForce:
return ReasonWebBrute, false
case ev.Cat == core.Exploit:
return ReasonExploitFlood, false
}
return ReasonScannerFlood, false
}
// CountsAsAttack reports whether an HTTP event is an attack the policy counts:
// an attack category that was not merely framed, and whose answer is not a
// client, application or proxy error.
func CountsAsAttack(ev core.Event) bool {
if ev.Source != "traefik" || ev.Framed {
return false
}
if ev.Cat != core.Scanner && ev.Cat != core.Exploit && ev.Cat != core.BruteForce {
return false
}
if ev.Status >= 400 {
c := core.ErrorClass(ev, false)
return c == core.ClassAttack || c == core.ClassBlocked
}
return true
}
// LegitVisit reports whether ev is a browser loading a page successfully.
func LegitVisit(ev core.Event) bool {
return ev.Source == "traefik" && ev.Cat == core.OK && ev.Status >= 200 && ev.Status < 300 &&
ev.FetchDest == "document" && !ev.E.Tool && !ev.E.Bot && !ev.Prefetch
}