fix(fed): sanitize peer rows, cap peer bytes, add --peer-blocklist
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 24s
CI / Tests (Linux, race detector) (push) Successful in 34s
CI / Dependency audit (push) Successful in 14s
Release / Plan (reuse the published image?) (push) Successful in 3s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 4s

Peer events and summary rows are rebuilt from validated fields (address,
country code, category) and the forged/unban flags from peers are
ignored. The live relay drops a peer that exceeds about 1 MB/s, also
within a single window. --peer-blocklist=off keeps the hub's blocklist
to local observations. UI polish: plural forms, blocklist preview and
downloads follow the active slice, compact IP cards on phones. Docs for
the 1.1.0 interface.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Lucas RayanandClaude Opus 5.5 committed 2026-11-14 18:10:54 -03:00
1 parent f4b295f582
commit 783b0cba3e
31 files changed
+355 -127

No files matched your search

+28 -23
View File
@@ -19,29 +19,30 @@ import (
// 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
Location string // "lat,lon" or "lat,lon,label" (--location)
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
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
Location string // "lat,lon" or "lat,lon,label" (--location)
PeerBlocklist string // "on" (default) or "off"
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
@@ -118,6 +119,7 @@ func ParseFlags(name string, args []string) (Config, error) {
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.StringVar(&c.Location, "location", env("URUTAU_LOCATION", ""), `where this instance lives, "lat,lon" or "lat,lon,label"; shown as the destination of live arcs (URUTAU_LOCATION)`)
fs.StringVar(&c.PeerBlocklist, "peer-blocklist", env("URUTAU_PEER_BLOCKLIST", "on"), "on: the blocklist also lists strong hostile IPs seen only by peers; off: local IPs only (URUTAU_PEER_BLOCKLIST)")
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 != "" {
@@ -174,6 +176,9 @@ func (c Config) Validate(token string) ([]fed.Peer, error) {
if _, err := store.ParseLocation(c.Location); err != nil {
return nil, err
}
if v := strings.ToLower(c.PeerBlocklist); v != "" && v != "on" && v != "off" {
return nil, fmt.Errorf("--peer-blocklist must be on or off")
}
var peers []fed.Peer
seen := map[string]bool{}
envSeen := map[string]string{}
+1 -1
View File
@@ -69,7 +69,7 @@ func Serve(c Config) error {
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})
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub})
ln, err := net.Listen("tcp", c.Bind)
if err != nil {
return err
+13
View File
@@ -0,0 +1,13 @@
package fed
import "time"
// SetLiveLimits shrinks the flood window, the byte ceiling and the first backoff; it returns the restore func.
func SetLiveLimits(window time.Duration, bytesPerSec int, backoff time.Duration) func() {
w, b, k := liveByteWindow, maxLiveBytes, liveBackoff0
liveByteWindow, maxLiveBytes, liveBackoff0 = window, bytesPerSec, backoff
return func() { liveByteWindow, maxLiveBytes, liveBackoff0 = w, b, k }
}
// WaitStream blocks until the live stream goroutines have returned (after ctx is cancelled).
func (h *Hub) WaitStream() { h.swg.Wait() }
+1
View File
@@ -72,6 +72,7 @@ type Hub struct {
client *http.Client
stream *http.Client // long-lived SSE: no overall timeout, no redirects
swg sync.WaitGroup // live stream goroutines
lmu sync.Mutex
live liveState
+20 -2
View File
@@ -18,10 +18,16 @@ const (
maxLiveRate = 50 // events per second accepted from one peer
liveBuffer = 500 // events kept for /api/v1/live/recent
liveIdle = 70 * time.Second
liveBackoff0 = time.Second
liveBackoffTo = 60 * time.Second
)
// Variables so tests can shrink them.
var (
maxLiveBytes = 1 << 20 // sustained bytes per second accepted from one peer
liveByteWindow = 10 * time.Second
liveBackoff0 = time.Second
)
type liveState struct {
recent []store.LiveEvent // ring of the newest peer events
head int
@@ -97,7 +103,8 @@ func (h *Hub) peerLocation(name string) *store.Location {
// with an exponential backoff (1 s up to 60 s).
func (h *Hub) Stream(ctx context.Context) {
for _, p := range h.Peers {
go h.streamPeer(ctx, p)
h.swg.Add(1)
go func() { defer h.swg.Done(); h.streamPeer(ctx, p) }()
}
}
@@ -152,6 +159,7 @@ func (h *Hub) consume(ctx context.Context, p Peer) error {
rd := bufio.NewReaderSize(resp.Body, maxLiveLine)
var evName string
var tokens = float64(maxLiveRate)
winStart, winBytes := time.Now(), 0
last := time.Now()
for {
line, err := rd.ReadSlice('\n') // ErrBufferFull: a line over 16 KB ends the stream
@@ -159,6 +167,16 @@ func (h *Hub) consume(ctx context.Context, p Peer) error {
return err
}
idle.Reset(liveIdle)
winBytes += len(line)
if float64(winBytes) > float64(maxLiveBytes)*liveByteWindow.Seconds() {
return errLive // a window's worth of budget burned already: flooding
}
if el := time.Since(winStart); el >= liveByteWindow {
if float64(winBytes)/el.Seconds() > float64(maxLiveBytes) {
return errLive // flooding: drop the connection, the backoff applies
}
winStart, winBytes = time.Now(), 0
}
line = bytes.TrimRight(line, "\r\n")
switch {
case bytes.HasPrefix(line, []byte("event:")):
+28 -3
View File
@@ -56,7 +56,7 @@ func TestLiveRelaySanitizesAndDrops(t *testing.T) {
ch, stop := h.Subscribe()
defer stop()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
var got []store.LiveEvent
@@ -110,7 +110,7 @@ func TestLiveRateLimitAndFlag(t *testing.T) {
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
for len(h.Recent(500)) == 0 && time.Now().Before(deadline) {
@@ -133,7 +133,7 @@ func TestLiveWithRealPeerServer(t *testing.T) {
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "peer-secret-0123456789-abcdefghijklmnopqr")
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
defer func() { cancel(); h.WaitStream() }()
h.Refresh(ctx)
h.Stream(ctx)
deadline := time.Now().Add(5 * time.Second)
@@ -153,3 +153,28 @@ func TestLiveWithRealPeerServer(t *testing.T) {
t.Fatalf("hosts %+v", hs)
}
}
func TestLiveByteFloodDropsConnection(t *testing.T) {
defer fed.SetLiveLimits(200*time.Millisecond, 10_000, 100*time.Millisecond)()
start := time.Now()
var conns atomic.Int32
pad := strings.Repeat("a", 1000)
srv := fakeStream(t, &conns, func(w http.ResponseWriter) {
for i := 0; i < 200; i++ { // ~200 KB at once: far above 10 KB/s
fmt.Fprintf(w, ": %s\n", pad)
}
})
defer srv.Close()
p, _ := fed.ParsePeer("edge=" + srv.URL)
h := fed.NewHub([]fed.Peer{p}, "tok")
ctx, cancel := context.WithCancel(context.Background())
defer func() { cancel(); h.WaitStream() }()
h.Stream(ctx)
// the flood ends the connection (window check), then the hub reconnects after the backoff
for conns.Load() < 2 {
if time.Since(start) > 2500*time.Millisecond {
t.Fatalf("no drop and reconnection (%d connections)", conns.Load())
}
time.Sleep(20 * time.Millisecond)
}
}
+31
View File
@@ -2,6 +2,7 @@ package server
import (
"bufio"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -10,6 +11,7 @@ import (
"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"
)
@@ -240,3 +242,32 @@ func TestPeerStreamIsPeerOnly(t *testing.T) {
t.Fatal("no event")
}
}
func TestPeerBlocklistOffUsesLocalOnly(t *testing.T) {
const ptk = "peer-secret-0123456789-abcdefghijklmnopqr"
strongHits := func(st *store.Store, ip string) {
for i := 0; i < 8; i++ {
st.Ingest(core.Event{Time: time.Now(), IP: ip, Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"})
}
}
remote := store.New(store.Config{Name: "remote"})
strongHits(remote, "45.94.31.7") // only the peer saw it
rs := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptk}, Store: remote}))
defer rs.Close()
p, _ := fed.ParsePeer("edge=" + rs.URL)
hub := fed.NewHub([]fed.Peer{p}, ptk)
hub.Refresh(context.Background())
for _, off := range []bool{false, true} {
st := store.New(store.Config{Name: "o"})
strongHits(st, "45.94.31.5")
hh := New(Options{Token: utok, Store: st, Hub: hub, LocalBlocklist: off})
w := do(hh, "GET", "/api/v1/blocklist.txt", map[string]string{"Authorization": "Bearer " + utok}, nil)
b := w.Body.String()
if w.Code != 200 || !strings.Contains(b, "45.94.31.5") {
t.Fatalf("off=%v: local IP missing: %d %s", off, w.Code, b)
}
if has := strings.Contains(b, "45.94.31.7"); has == off {
t.Fatalf("off=%v: peer-only IP listed=%v: %s", off, has, b)
}
}
}
+12 -6
View File
@@ -62,10 +62,12 @@ type Options struct {
PeerAllow []netip.Prefix
TrustedProxy []netip.Prefix
NoAuth bool
Version string
Store *store.Store
Hub *fed.Hub
Now func() time.Time
// LocalBlocklist makes the blocklist use only this instance's IPs (--peer-blocklist=off).
LocalBlocklist bool
Version string
Store *store.Store
Hub *fed.Hub
Now func() time.Time
}
// Server is the HTTP handler.
@@ -464,13 +466,17 @@ func (s *Server) summary(w http.ResponseWriter, r *http.Request) {
// allIPs returns the merged IP table for the requested host selection.
func (s *Server) allIPs(rangeName, host string) []store.IPSummary {
return s.ipsOf(rangeName, host, false)
}
func (s *Server) ipsOf(rangeName, host string, localOnly bool) []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 {
if s.opt.Hub != nil && host != self && !localOnly {
only := ""
if host != "" && host != "all" {
only = host
@@ -711,7 +717,7 @@ func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
family = "all"
}
var out []store.IPSummary
for _, x := range s.allIPs(rangeName, q.Get("host")) {
for _, x := range s.ipsOf(rangeName, q.Get("host"), s.opt.LocalBlocklist) {
if x.Score < min || !x.Strong || x.Admin {
continue
}
+14 -12
View File
@@ -54,6 +54,8 @@
if (typeof vars !== 'object') vars = { n: vars };
return s.replace(/\{(\w+)\}/g, function (m, k) { return Object.prototype.hasOwnProperty.call(vars, k) ? String(vars[k]) : m; });
}
// plural: picks key.one when count is 1, key.other otherwise
function pl(key, count, vars) { vars = vars || {}; if (vars.n === undefined) vars.n = nf(count); return t(key + (count === 1 ? '.one' : '.other'), vars); }
function registerI18n(dict) {
Object.keys(dict || {}).forEach(function (l) {
if (!D[l]) D[l] = {};
@@ -485,7 +487,7 @@
// ---------------------------------------------------------------- IP table
function sumCounts(c) { var s = 0; for (var k in c) s += c[k]; return s; }
function ipTable(full) {
var st = { sort: 'score', order: 'desc', page: 1, per: full ? 50 : 25, q: '', level: '', banned: false, total: 0, sig: '', ctxKey: '', multi: false, headSig: '' };
var st = { sort: 'score', order: 'desc', page: 1, per: window.innerWidth <= 720 ? 25 : (full ? 50 : 25), q: '', level: '', banned: false, total: 0, sig: '', ctxKey: '', multi: false, headSig: '' };
var timer = 0, alive = true, onTotal = null;
var search = el('input', { type: 'search', autocomplete: 'off', placeholder: t('ips.search'), 'aria-label': t('ips.search') });
var levelSel = el('select', { 'aria-label': t('ips.level') });
@@ -574,7 +576,7 @@
cell('cats', chips, 'nw'); break;
}
case 'origin': {
var org = h('span', 'origin', x.cc ? (flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + (x.country || countryName(x.cc))) : '-');
var org = h('span', 'origin', x.cc ? (flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + countryName(x.cc)) : '-');
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');
@@ -592,7 +594,7 @@
tbody.appendChild(tr);
});
var pages = Math.max(1, Math.ceil(st.total / st.per));
count.textContent = t('pager.count', nf(st.total));
count.textContent = pl('pager.count', st.total, { n: nf(st.total) });
page.textContent = full ? t('pager.page', { n: nf(st.page), m: nf(pages) }) : '';
prev.disabled = st.page <= 1;
next.disabled = st.page >= pages;
@@ -847,7 +849,7 @@
if (n > bestN) { bestN = n; best = c; }
});
if (!best) return lead(t('th.lead.none'), t('th.lead.noneBody'), 'neutral');
var body = [t('th.lead.body', { n: nf(bestN), m: nf(total), p: pct(bestN, total) })];
var body = [pl('th.lead.body', total, { n: nf(bestN), m: nf(total), p: pct(bestN, total) })];
if (s.top_domains && s.top_domains.length) body.push(t('th.lead.domain', { name: s.top_domains[0].key }));
if (s.countries && s.countries.length) body.push(t('th.lead.origin', { name: countryLabel(s.countries[0].key) }));
return lead(t('th.lead.top', { cat: t('cat.' + best) }), body.join(' '), s.totals.hostile_ips > 0 ? 'danger' : 'ok');
@@ -971,7 +973,7 @@
var v = {};
v.lead = h('div');
v.tbl = ipTable(true);
v.tbl.onTotal(function (n) { setSliceNote(t('slice.ips', nf(n))); });
v.tbl.onTotal(function (n) { setSliceNote(pl('slice.ips', n, { n: nf(n) })); });
v.ips = panel({ title: t('ips.title'), hint: t('ips.hint') }, v.tbl.node);
root.appendChild(v.lead); root.appendChild(v.ips);
return v;
@@ -986,7 +988,7 @@
render: function (v, s) {
var T = s.totals;
clear(v.lead);
v.lead.appendChild(lead(t('ips.lead', { n: nf(T.unique_ips), h: nf(T.hostile_ips), s: nf(T.suspicious_ips) }), t('ips.lead.body', { b: nf(T.active_bans) }), T.hostile_ips > 0 ? 'danger' : T.unique_ips ? 'ok' : 'neutral'));
v.lead.appendChild(lead(pl('ips.lead', T.unique_ips, { n: nf(T.unique_ips), h: nf(T.hostile_ips), s: nf(T.suspicious_ips) }), t('ips.lead.body', { b: nf(T.active_bans) }), T.hostile_ips > 0 ? 'danger' : T.unique_ips ? 'ok' : 'neutral'));
},
dispose: function (v) { v.tbl.dispose(); setSliceNote(''); }
});
@@ -1005,7 +1007,7 @@
h('div', 'toolbar', h('label', 'check', h('span', null, t('blocklist.minScore')), minScore), fam, copy, dlTxt, dlJson), count, msg);
var timer = 0, alive = true;
function query(extra) {
var o = { host: state.host, min_score: minScore.value || '50', family: fam.value };
var o = { host: state.host, range: state.range, min_score: minScore.value || '50', family: fam.value };
for (var k in extra) o[k] = extra[k];
return new URLSearchParams(o).toString();
}
@@ -1014,10 +1016,10 @@
dlJson.setAttribute('href', '/api/v1/blocklist.json?' + query({ download: '1' }));
clearTimeout(timer);
timer = setTimeout(function () {
api('/api/v1/blocklist.json', { host: state.host, min_score: minScore.value || '50', family: fam.value }).then(function (j) {
api('/api/v1/blocklist.json', { host: state.host, range: state.range, min_score: minScore.value || '50', family: fam.value }).then(function (j) {
if (!alive) return;
var arr = Array.isArray(j) ? j : (j.items || j.ips || []);
count.textContent = t('blocklist.count', nf(typeof j.count === 'number' ? j.count : arr.length));
count.textContent = pl('blocklist.count', typeof j.count === 'number' ? j.count : arr.length, { n: nf(typeof j.count === 'number' ? j.count : arr.length) });
}).catch(function () { /* optional preview */ });
}, 250);
}
@@ -1029,7 +1031,7 @@
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)); });
return copyText(txt).then(function () { msg.textContent = pl('blocklist.copied', n, { n: nf(n) }); });
}).catch(function () { msg.textContent = t('blocklist.failed'); });
});
return { node: node, sync: sync, dispose: function () { alive = false; clearTimeout(timer); } };
@@ -1073,7 +1075,7 @@
var lines = 0, bad = 0;
srcs.forEach(function (r) { lines += r.lines || 0; bad += r.malformed || 0; });
var online = hosts.filter(function (x) { return x.online; }).length;
var title = !srcs.length ? t('src.lead.none') : following === srcs.length ? t('src.lead.all', { n: nf(srcs.length) }) : t('src.lead.some', { a: nf(following), n: nf(srcs.length), x: nf(srcs.length - following) });
var title = !srcs.length ? t('src.lead.none') : following === srcs.length ? pl('src.lead.all', srcs.length, { n: nf(srcs.length) }) : t('src.lead.some', { a: nf(following), n: nf(srcs.length), x: nf(srcs.length - following) });
clear(v.lead);
v.lead.appendChild(lead(title, t('src.lead.body', { h: nf(online), m: nf(hosts.length), l: nf(lines), f: nf(bad) }), !srcs.length ? 'neutral' : following === srcs.length && online === hosts.length ? 'ok' : 'danger'));
clear(v.hostsBox);
@@ -1278,7 +1280,7 @@
}
window.Urutau = {
registerPage: registerPage, registerI18n: registerI18n, t: t, api: api, onEvent: onEvent, openIP: openIP,
registerPage: registerPage, registerI18n: registerI18n, t: t, pl: pl, api: api, onEvent: onEvent, openIP: openIP,
fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime },
world: world, el: el, css: cssVar, setSliceNote: setSliceNote,
ui: { panel: panel, stat: stat, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart }
+46 -32
View File
@@ -42,7 +42,8 @@ window.URUTAU_I18N = {
'slice.host': 'host {name}',
'slice.allDomains': 'all domains',
'slice.domain': 'domain {name}',
'slice.ips': '{n} IPs',
'slice.ips.one': '{n} IP',
'slice.ips.other': '{n} IPs',
'kpi.requests': 'Requests',
'kpi.malicious': 'Malicious events',
'kpi.hostile': 'Hostile IPs',
@@ -50,7 +51,7 @@ window.URUTAU_I18N = {
'kpi.bans': 'Active bans',
'kpi.ips': 'Distinct IPs',
'kpi.monitoring': '{n} monitoring requests filtered out.',
'kpi.sub.hosts': '{n} of {m} hosts online',
'kpi.sub.hosts': 'hosts online: {n} of {m}',
'kpi.sub.malicious': 'HTTP and SSH events',
'kpi.sub.share': '{p} of {n} distinct IPs',
'kpi.sub.bans': 'reported by fail2ban',
@@ -59,7 +60,7 @@ window.URUTAU_I18N = {
'ov.lead.hostile.one': '1 hostile IP in the selected slice',
'ov.lead.calm': 'No hostile IPs in the selected slice',
'ov.lead.empty': 'No events recorded in the selected slice',
'ov.lead.body': '{m} malicious events against {r} requests, from {ips} distinct IPs; {b} active bans.',
'ov.lead.body': 'Malicious events: {m}; requests: {r}; distinct IPs: {ips}; active bans: {b}.',
'ov.lead.bodyEmpty': 'Widen the time range or choose another host. Sources report their state under Sources and hosts.',
'ov.countries': 'Top countries',
'ov.countries.hint': 'Origin of the events in the slice, by number of events.',
@@ -71,19 +72,22 @@ window.URUTAU_I18N = {
'th.lead.top': 'Most activity is classified as "{cat}"',
'th.lead.none': 'No attack activity in the selected slice',
'th.lead.noneBody': 'No scanner, exploit, brute force or SSH events were classified in this slice.',
'th.lead.body': '{n} of {m} classified events ({p}).',
'th.lead.body.one': '{n} of {m} classified event ({p}).',
'th.lead.body.other': '{n} of {m} classified events ({p}).',
'th.lead.domain': 'Most targeted domain: {name}.',
'th.lead.origin': 'Main origin: {name}.',
'tr.lead.some': '{n} visitors viewed {p} pages',
'tr.lead.some': 'Visitors: {n} · page views: {p}',
'tr.lead.none': 'No traffic recorded in the selected slice',
'tr.lead.noneBody': 'Analytics count only successful responses to non-bot clients on the configured domains.',
'tr.lead.body': '{r} requests, {b} from search and AI bots; latency p50 {a} ms and p95 {c} ms.',
'ips.lead': '{n} distinct IPs, {h} hostile and {s} suspicious',
'ips.lead.body': '{b} IPs are banned. Select a row for the full history of an IP.',
'src.lead.all': 'All {n} sources are following',
'src.lead.some': '{a} of {n} sources following; {x} need attention',
'tr.lead.body': 'Requests: {r}, of which {b} from search and AI bots; latency p50 {a} ms and p95 {c} ms.',
'ips.lead.one': '{n} distinct IP: {h} hostile, {s} suspicious',
'ips.lead.other': '{n} distinct IPs: {h} hostile, {s} suspicious',
'ips.lead.body': 'Banned IPs: {b}. Select a row for the full history of an IP.',
'src.lead.all.one': 'The only source is being followed',
'src.lead.all.other': 'All {n} sources are being followed',
'src.lead.some': 'Sources following: {a} of {n}; needing attention: {x}',
'src.lead.none': 'No log sources reported',
'src.lead.body': '{h} of {m} hosts online; {l} lines read, {f} malformed.',
'src.lead.body': 'Hosts online: {h} of {m}; lines read: {l}; malformed: {f}.',
'feed.forged': 'forged monitor user agent',
'timeline.title': 'Activity by category',
'timeline.hint': 'Events per time bucket, stacked by category. Select a legend item to hide it.',
@@ -116,7 +120,8 @@ window.URUTAU_I18N = {
'col.lastEvent': 'Last event',
'pager.prev': 'Previous',
'pager.next': 'Next',
'pager.count': '{n} IPs',
'pager.count.one': '{n} IP',
'pager.count.other': '{n} IPs',
'pager.page': 'Page {n} of {m}',
'feed.title': 'Live feed',
'feed.empty': 'Waiting for events.',
@@ -135,9 +140,11 @@ window.URUTAU_I18N = {
'blocklist.copy': 'Copy list',
'blocklist.download': 'Download .txt',
'blocklist.downloadJson': 'Download .json',
'blocklist.copied': '{n} IPs copied.',
'blocklist.copied.one': '{n} IP copied.',
'blocklist.copied.other': '{n} IPs copied.',
'blocklist.failed': 'Could not copy the list.',
'blocklist.count': '{n} IPs would be listed (last 7 days).',
'blocklist.count.one': '{n} IP would be listed (selected range).',
'blocklist.count.other': '{n} IPs would be listed (selected range).',
'hosts.title': 'Hosts and peers',
'hosts.hint': 'This instance and the peers it federates with.',
'host.online': 'online',
@@ -154,8 +161,8 @@ window.URUTAU_I18N = {
'sources.empty': 'No log source configured on the reporting hosts.',
'src.geo.title': 'Geolocation',
'src.geo.hint': 'Country, city and network of each IP come from a local database; nothing is queried online.',
'src.geo.known': '{n} of {m} listed IPs have a known origin',
'src.geo.countries': '{n} countries in the slice',
'src.geo.known': 'Listed IPs with a known origin: {n} of {m}',
'src.geo.countries': 'Countries in the slice: {n}',
'src.geo.attrib': 'Data attribution',
'src.geo.none': 'No attribution reported by the geo database.',
'state.following': 'following',
@@ -271,7 +278,8 @@ window.URUTAU_I18N = {
'slice.host': 'host {name}',
'slice.allDomains': 'todos os domínios',
'slice.domain': 'domínio {name}',
'slice.ips': '{n} IPs',
'slice.ips.one': '{n} IP',
'slice.ips.other': '{n} IPs',
'kpi.requests': 'Requisições',
'kpi.malicious': 'Eventos maliciosos',
'kpi.hostile': 'IPs hostis',
@@ -279,7 +287,7 @@ window.URUTAU_I18N = {
'kpi.bans': 'Bans ativos',
'kpi.ips': 'IPs distintos',
'kpi.monitoring': '{n} requisições de monitoramento filtradas.',
'kpi.sub.hosts': '{n} de {m} hosts online',
'kpi.sub.hosts': 'hosts online: {n} de {m}',
'kpi.sub.malicious': 'eventos HTTP e SSH',
'kpi.sub.share': '{p} dos {n} IPs distintos',
'kpi.sub.bans': 'informados pelo fail2ban',
@@ -288,7 +296,7 @@ window.URUTAU_I18N = {
'ov.lead.hostile.one': '1 IP hostil no recorte selecionado',
'ov.lead.calm': 'Nenhum IP hostil no recorte selecionado',
'ov.lead.empty': 'Nenhum evento registrado no recorte selecionado',
'ov.lead.body': '{m} eventos maliciosos frente a {r} requisições, de {ips} IPs distintos; {b} bans ativos.',
'ov.lead.body': 'Eventos maliciosos: {m}; requisições: {r}; IPs distintos: {ips}; bans ativos: {b}.',
'ov.lead.bodyEmpty': 'Recomenda-se ampliar o período ou escolher outro host. O estado das fontes está em Fontes e hosts.',
'ov.countries': 'Principais países',
'ov.countries.hint': 'Origem dos eventos do recorte, por número de eventos.',
@@ -300,19 +308,22 @@ window.URUTAU_I18N = {
'th.lead.top': 'A maior parte da atividade é classificada como "{cat}"',
'th.lead.none': 'Nenhuma atividade de ataque no recorte selecionado',
'th.lead.noneBody': 'Nenhum evento de scanner, exploit, força bruta ou SSH foi classificado neste recorte.',
'th.lead.body': '{n} de {m} eventos classificados ({p}).',
'th.lead.body.one': '{n} de {m} evento classificado ({p}).',
'th.lead.body.other': '{n} de {m} eventos classificados ({p}).',
'th.lead.domain': 'Domínio mais visado: {name}.',
'th.lead.origin': 'Origem principal: {name}.',
'tr.lead.some': '{n} visitantes em {p} páginas vistas',
'tr.lead.some': 'Visitantes: {n} · páginas vistas: {p}',
'tr.lead.none': 'Nenhum tráfego registrado no recorte selecionado',
'tr.lead.noneBody': 'A análise de tráfego conta apenas respostas bem-sucedidas a clientes que não são bots, nos domínios configurados.',
'tr.lead.body': '{r} requisições, {b} de bots de busca e de IA; latência p50 de {a} ms e p95 de {c} ms.',
'ips.lead': '{n} IPs distintos, {h} hostis e {s} suspeitos',
'ips.lead.body': '{b} IPs estão banidos. Selecione uma linha para ver o histórico completo do IP.',
'src.lead.all': 'As {n} fontes estão sendo acompanhadas',
'src.lead.some': '{a} de {n} fontes acompanhadas; {x} exigem atenção',
'tr.lead.body': 'Requisições: {r}, das quais {b} de bots de busca e de IA; latência p50 de {a} ms e p95 de {c} ms.',
'ips.lead.one': '{n} IP distinto: {h} hostis, {s} suspeitos',
'ips.lead.other': '{n} IPs distintos: {h} hostis, {s} suspeitos',
'ips.lead.body': 'IPs banidos: {b}. Selecione uma linha para ver o histórico completo do IP.',
'src.lead.all.one': 'A única fonte está sendo acompanhada',
'src.lead.all.other': 'As {n} fontes estão sendo acompanhadas',
'src.lead.some': 'Fontes acompanhadas: {a} de {n}; exigem atenção: {x}',
'src.lead.none': 'Nenhuma fonte de log informada',
'src.lead.body': '{h} de {m} hosts online; {l} linhas lidas, {f} malformadas.',
'src.lead.body': 'Hosts online: {h} de {m}; linhas lidas: {l}; malformadas: {f}.',
'feed.forged': 'user-agent de monitor forjado',
'timeline.title': 'Atividade por categoria',
'timeline.hint': 'Eventos por intervalo de tempo, empilhados por categoria. Selecione um item da legenda para ocultá-lo.',
@@ -345,7 +356,8 @@ window.URUTAU_I18N = {
'col.lastEvent': 'Último evento',
'pager.prev': 'Anterior',
'pager.next': 'Próxima',
'pager.count': '{n} IPs',
'pager.count.one': '{n} IP',
'pager.count.other': '{n} IPs',
'pager.page': 'Página {n} de {m}',
'feed.title': 'Feed ao vivo',
'feed.empty': 'Aguardando eventos.',
@@ -364,9 +376,11 @@ window.URUTAU_I18N = {
'blocklist.copy': 'Copiar lista',
'blocklist.download': 'Baixar .txt',
'blocklist.downloadJson': 'Baixar .json',
'blocklist.copied': '{n} IPs copiados.',
'blocklist.copied.one': '{n} IP copiado.',
'blocklist.copied.other': '{n} IPs copiados.',
'blocklist.failed': 'Não foi possível copiar a lista.',
'blocklist.count': '{n} IPs seriam listados (últimos 7 dias).',
'blocklist.count.one': '{n} IP seria listado (período selecionado).',
'blocklist.count.other': '{n} IPs seriam listados (período selecionado).',
'hosts.title': 'Hosts e pares',
'hosts.hint': 'Esta instância e os pares com os quais ela se federa.',
'host.online': 'online',
@@ -383,8 +397,8 @@ window.URUTAU_I18N = {
'sources.empty': 'Nenhuma fonte de log configurada nos hosts informantes.',
'src.geo.title': 'Geolocalização',
'src.geo.hint': 'País, cidade e rede de cada IP vêm de uma base local; nenhuma consulta é feita online.',
'src.geo.known': '{n} de {m} IPs listados têm origem conhecida',
'src.geo.countries': '{n} países no recorte',
'src.geo.known': 'IPs listados com origem conhecida: {n} de {m}',
'src.geo.countries': 'Países no recorte: {n}',
'src.geo.attrib': 'Atribuição dos dados',
'src.geo.none': 'Nenhuma atribuição informada pela base de geolocalização.',
'state.following': 'acompanhando',
+6
View File
@@ -412,6 +412,12 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
table.stack td::before { content: attr(data-label); color: var(--ink-muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; text-align: left; flex: none; }
table.stack td > * { min-width: 0; }
table.stack td.nw, table.stack td.nw * { white-space: normal; }
table.stack tr.row { display: grid; grid-template-columns: 1fr 1fr; gap: 2px 12px; padding: 8px 10px; margin: 6px 0; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); }
table.stack tr.row td { display: block; text-align: left; min-width: 0; padding: 0; }
table.stack tr.row td::before { display: block; margin-bottom: 0; }
table.stack tr.row td:first-child { grid-column: 1 / -1; font-weight: 600; }
table.stack tr.row td:first-child::before { display: none; }
table.stack tr.row td:nth-child(4), table.stack tr.row td:nth-child(5) { grid-column: 1 / -1; }
.origin { max-width: none; white-space: normal; }
.kv { grid-template-columns: 1fr; gap: 0; }
.kv dt { margin-top: 8px; }
+9 -2
View File
@@ -149,7 +149,7 @@ func (e *PeerExport) Sanitize(rangeName string) error {
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)
x.RDNS, x.CC, x.Country, x.City, x.ASOrg = clipS(x.RDNS, 200), validCC2(clipS(x.CC, 2)), clipS(x.Country, 80), clipS(x.City, 80), clipS(x.ASOrg, 120)
ips = append(ips, x)
}
s.IPs = ips
@@ -170,8 +170,15 @@ func (e *PeerExport) Sanitize(rangeName string) error {
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)
r.User, r.Jail = clipS(r.User, 64), clipS(r.Jail, 40)
}
kept := s.Recent[:0]
for _, r := range s.Recent {
if SanitizeFeed(&r) {
kept = append(kept, r)
}
}
s.Recent = kept
if len(s.Sources) > 16 {
s.Sources = s.Sources[:16]
}
+13 -1
View File
@@ -136,7 +136,7 @@ func (e *LiveEvent) Sanitize(now int64) bool {
if e.Status < 0 || e.Status > 999 {
e.Status = 0
}
e.Unban = false
e.Unban, e.Forged = false, false
e.CC = validCC2(clipS(e.CC, 2))
if e.Src != nil {
if !validLatLon(e.Src.Lat, e.Src.Lon) {
@@ -158,3 +158,15 @@ func validCC2(cc string) string {
// String is for debugging.
func (l Location) String() string { return fmt.Sprintf("%.4f,%.4f %s", l.Lat, l.Lon, l.Label) }
// SanitizeFeed validates a feed row that came from a peer's summary; false drops it.
func SanitizeFeed(r *FeedEvent) bool {
a, err := netip.ParseAddr(r.IP)
if err != nil || a.Zone() != "" {
return false
}
r.IP = a.Unmap().String()
r.CC = validCC2(clipS(r.CC, 2))
r.Unban, r.Forged = false, false
return true
}
+21
View File
@@ -35,3 +35,24 @@ func TestPeerLocationAndLiveSanitize(t *testing.T) {
t.Fatalf("%+v", le)
}
}
func TestPeerRowsAreSanitized(t *testing.T) {
le := LiveEvent{FeedEvent: FeedEvent{IP: "1.2.3.4", Cat: "scanner", T: 1, Forged: true, Unban: true, CC: "<s"}}
if !le.Sanitize(1_800_000_000) || le.Forged || le.Unban || le.CC != "" {
t.Fatalf("%+v", le)
}
e := PeerExport{V: ExportVersion, Summary: Summary{
Recent: []FeedEvent{{IP: "<script>", Cat: "scanner"}, {IP: "5.6.7.8", Cat: "scanner", CC: "<s", Forged: true}},
IPs: []IPSummary{{IP: "9.9.9.9", CC: "<s", Score: 1}},
}}
if err := e.Sanitize("24h"); err != nil {
t.Fatal(err)
}
r := e.Summary.Recent
if len(r) != 1 || r[0].IP != "5.6.7.8" || r[0].CC != "" || r[0].Forged {
t.Fatalf("%+v", r)
}
if e.Summary.IPs[0].CC != "" {
t.Fatal("cc must be validated")
}
}