Files
urutau/internal/app/enforce.go
T
Lucas RayanandClaude Opus 5.5 c33cca22e3
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
feat: 1.4.0 second firewall, egress analysis and HTML report
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>
2026-11-14 23:35:34 -03:00

165 lines
4.8 KiB
Go

package app
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
// newEnforce builds the second firewall and hooks it into the store; nil when off.
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enforce.Engine {
mode := strings.ToLower(c.Enforce)
if mode != enforce.ModeObserve && mode != enforce.ModeOn {
return nil
}
trusted, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
var hosts []string
for _, p := range peers {
if u, err := url.Parse(p.URL); err == nil && u.Hostname() != "" {
hosts = append(hosts, u.Hostname())
}
}
e := enforce.New(enforce.Config{
Mode: mode, Path: c.EnforceLog, StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"),
Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost,
Crawler: func(ip string, uas []string) bool { v := st.FCrDNS(ip, uas); return v != nil && *v },
Geo: func(ip string) (string, uint32, string) {
if en.g == nil {
return "", 0, ""
}
g := en.Geo(ip)
return g.CC, g.ASN, g.ASOrg
},
})
st.SetIngestHook(e.Observe)
return e
}
func resolveHost(h string) []netip.Addr {
if a, err := netip.ParseAddr(h); err == nil {
return []netip.Addr{a.Unmap()}
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
ips, err := net.DefaultResolver.LookupNetIP(ctx, "ip", h)
if err != nil {
return nil
}
for i := range ips {
ips[i] = ips[i].Unmap()
}
return ips
}
// shareDecisions pulls the decisions of every peer and pushes the local ones, every 30 s.
func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) {
pulled := map[string]int64{}
pushed := map[string]int64{}
t := time.NewTicker(30 * time.Second)
defer t.Stop()
for {
for _, p := range hub.Peers {
start := time.Now().Unix()
var in struct {
Decisions []enforce.Wire `json:"decisions"`
}
if err := hub.Get(ctx, p, fmt.Sprintf("/api/v1/peer/decisions?since=%d", pulled[p.Name]), &in); err == nil {
e.AcceptPeer(p.Name, in.Decisions)
pulled[p.Name] = start - 5
} else if ctx.Err() == nil {
log.Debug("enforce: pull failed", "peer", p.Name, "err", err)
}
if mine := e.LocalSince(pushed[p.Name]); len(mine) > 0 {
if err := hub.PostJSON(ctx, p, "/api/v1/peer/decisions?from="+url.QueryEscape(e.Host()), map[string]any{"decisions": mine}); err == nil {
pushed[p.Name] = start
} else if ctx.Err() == nil {
log.Debug("enforce: push failed", "peer", p.Name, "err", err)
}
}
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
// doctorEnforce reports the mode of the second firewall and its file.
func doctorEnforce(c Config, add func(name, status, detail string)) {
mode := strings.ToLower(c.Enforce)
if mode == "" || mode == "off" {
add("enforce", "off", "disabled (--enforce=off)")
return
}
w := enforce.Writable(c.EnforceLog)
detail := fmt.Sprintf("mode=%s share=%s threshold=%d file=%s writable=%v", mode, strings.ToLower(orDefault(c.EnforceShare, "off")), c.EnforceThreshold, c.EnforceLog, w)
switch {
case mode == "on" && !w:
add("enforce", "fail", detail)
case !w:
add("enforce", "warn", detail)
default:
add("enforce", "ok", detail)
}
if mode == "on" {
if n, tot := cloudflareClients(c.TraefikLog); n > 0 {
add("enforce-cdn", "warn", fmt.Sprintf("%d of the last %d requests in %s come from Cloudflare addresses: Traefik is not "+
"restoring the real client IP (set entryPoints.*.forwardedHeaders.trustedIPs to the Cloudflare ranges); "+
"Cloudflare is never banned, but the real attackers stay invisible", n, tot, c.TraefikLog))
}
}
}
// cloudflareClients counts, in the tail of the Traefik JSON access log, the
// requests whose ClientHost is a Cloudflare address.
func cloudflareClients(path string) (cf, total int) {
if path == "" {
return 0, 0
}
f, err := os.Open(path)
if err != nil {
return 0, 0
}
defer f.Close()
const tail = 512 << 10
if fi, err := f.Stat(); err == nil && fi.Size() > tail {
f.Seek(fi.Size()-tail, io.SeekStart)
}
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 0, 64<<10), 1<<20)
for sc.Scan() {
var l struct {
ClientHost string `json:"ClientHost"`
}
if json.Unmarshal(sc.Bytes(), &l) != nil || l.ClientHost == "" {
continue
}
a, err := netip.ParseAddr(l.ClientHost)
if err != nil {
continue
}
total++
if enforce.IsCloudflare(a) {
cf++
}
}
return cf, total
}