Compare commits

..
5 Commits
Author SHA1 Message Date
Lucas RayanandClaude Opus 5.5 1ef5a0ce9f fix: 1.4.5 second firewall uses history, reputation and a periodic sweep
Release / Publish tags (push) Successful in 15s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m2s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 1m10s
CI / Format and vet (push) Successful in 26s
CI / Tests (Linux, race detector) (push) Successful in 20s
CI / Dependency audit (push) Successful in 35s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:37:25 -03:00
Lucas RayanandClaude Opus 5.5 0dc3268b29 fix: 1.4.4 read Traefik text logs, degraded source alert, mobile menu
Release / Publish tags (push) Successful in 16s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 1m46s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 23s
CI / Format and vet (push) Successful in 24s
CI / Tests (Linux, race detector) (push) Successful in 1m22s
CI / Dependency audit (push) Successful in 27s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:20:03 -03:00
Lucas RayanandClaude Opus 5.5 50cd2bd3ce fix: mobile More menu scrolls when it is taller than the screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:18:10 -03:00
Lucas RayanandClaude Opus 5.5 045ed53e43 feat: 1.4.3 Tor lists and classification, egress provider and peer allowlist
Release / Publish tags (push) Successful in 17s
Release / Plan (reuse the published image?) (push) Successful in 6s
Release / ci (push) Successful in 59s
Release / Build image (amd64) (push) Successful in 24s
Release / Build image (arm64) (push) Successful in 1m29s
CI / Format and vet (push) Successful in 26s
CI / Tests (Linux, race detector) (push) Successful in 33s
CI / Dependency audit (push) Successful in 33s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:57:22 -03:00
Lucas RayanandClaude Opus 5.5 ec46fb94ff feat: 1.4.2 services page redesign
Release / Publish tags (push) Successful in 14s
Release / Plan (reuse the published image?) (push) Successful in 5s
Release / ci (push) Successful in 58s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 1m19s
CI / Format and vet (push) Successful in 37s
CI / Tests (Linux, race detector) (push) Successful in 34s
CI / Dependency audit (push) Successful in 21s
CI / Docker image (build and smoke test) (push) Skipped
Release / Gitea release (push) Successful in 4s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 00:30:50 -03:00
40 changed files with 1895 additions and 198 deletions

No files matched your search

+30
View File
@@ -6,6 +6,36 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
## [1.4.5] - 2026-11-15
### Fixed
- Second firewall: it now uses the history. An address whose verdict is hostile (or suspicious with score 100 or more) is banned on its first new malicious event (`known-attacker`); 10 SSH failures or 20 web scan/exploit events in 24 h also ban (slow attackers); a sweep every 10 minutes (and after the start-up backfill) bans the addresses active in the last 24 h that nothing blocks yet, at most `--enforce-max-per-min` per minute, with every exclusion kept. Coverage in `/api/v1/enforce` is computed from the store, so it survives restarts.
## [1.4.4] - 2026-11-15
### Fixed
- Traefik access logs in the default text format are now read too (fewer fields than JSON: no host or service), so a proxy that loses its JSON setting no longer silently drops the web traffic.
- A source with more than 20% unreadable lines in its last 1000 is shown as degraded (red) in Integrity and Sources, logged once an hour, and checked by `urutau doctor`.
- Mobile: the More menu scrolls when it is taller than the screen.
## [1.4.3] - 2026-11-15
### Added
- Tor network: the official exit and relay lists are downloaded every 6 hours (`URUTAU_TOR_AUTO`, cached in the data directory). Requests from Tor exits are marked `tor`; a workload talking to a Tor relay is a high outbound finding.
### Fixed
- Outbound traffic: the servers themselves (trusted addresses, peers, local public addresses) never raise findings; regular connections of the host to its own provider (`URUTAU_EGRESS_PROVIDER_ASN` or the provider of its address) are shown as provider services, outside the verdict; regular connections to large CDNs and clouds are low severity unless the destination attacked the server.
## [1.4.2] - 2026-11-15
### Changed
- Services page redesigned: plain-language verdict, KPIs with sparklines, services from worst to best with availability against the 99.5% SLO, error budget left, burn rate, Apdex and latency, and a service detail with requests and errors, how requests were answered, p95 by hour and failing routes split into service errors, blocked attacks and client mistakes. API: `err_spark` in `/api/v1/services`.
## [1.4.1] - 2026-11-15
### Added
+30
View File
@@ -6,6 +6,36 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Unreleased]
## [1.4.5] - 2026-11-15
### Corrigido
- Segundo firewall: agora usa o histórico. Endereço com veredito hostil (ou suspeito com score 100 ou mais) é banido no primeiro evento malicioso novo (`known-attacker`); 10 falhas SSH ou 20 eventos de varredura/exploração web em 24 h também banem (atacantes lentos); uma varredura a cada 10 minutos (e após o backfill da partida) bane os endereços ativos nas últimas 24 h que nada bloqueia ainda, no máximo `--enforce-max-per-min` por minuto, mantidas todas as exclusões. A cobertura de `/api/v1/enforce` sai do store e sobrevive a reinícios.
## [1.4.4] - 2026-11-15
### Corrigido
- O log de acesso do Traefik no formato texto padrão agora também é lido (menos campos que o JSON: sem host nem serviço), então um proxy que perde a configuração JSON não descarta mais o tráfego web em silêncio.
- Uma fonte com mais de 20% de linhas ilegíveis nas últimas 1000 aparece como degradada (vermelho) em Integridade e Fontes, é registrada no log uma vez por hora e é verificada pelo `urutau doctor`.
- Celular: o menu Mais rola quando é maior que a tela.
## [1.4.3] - 2026-11-15
### Adicionado
- Rede Tor: as listas oficiais de saídas e relays são baixadas a cada 6 horas (`URUTAU_TOR_AUTO`, com cache no diretório de dados). Requisições vindas de saídas Tor são marcadas `tor`; um workload falando com um relay Tor é um achado de saída de gravidade alta.
### Corrigido
- Tráfego de saída: os próprios servidores (endereços confiáveis, peers, endereços públicos locais) nunca geram achados; conexões regulares do host com o próprio provedor (`URUTAU_EGRESS_PROVIDER_ASN` ou o provedor do seu endereço) aparecem como serviços do provedor, fora do veredito; conexões regulares com grandes CDNs e nuvens têm gravidade baixa, salvo se o destino atacou o servidor.
## [1.4.2] - 2026-11-15
### Alterado
- Página Serviços refeita: veredito em linguagem leiga, indicadores com mini gráficos, serviços dos piores para os melhores com disponibilidade contra o SLO de 99,5%, orçamento de erro restante, consumo, Apdex e latência, e detalhe do serviço com requisições e erros, como as requisições foram respondidas, p95 por hora e rotas que falham separadas em erros do serviço, ataques barrados e enganos do cliente. API: `err_spark` em `/api/v1/services`.
## [1.4.1] - 2026-11-15
### Adicionado
Binary file not shown.

Before

Width:  |  Height:  |  Size: 200 KiB

After

Width:  |  Height:  |  Size: 390 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 201 KiB

After

Width:  |  Height:  |  Size: 380 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 203 KiB

After

Width:  |  Height:  |  Size: 381 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 221 KiB

After

Width:  |  Height:  |  Size: 312 KiB

+2
View File
@@ -44,6 +44,7 @@ type Config struct {
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
TorAuto string // on (default) or off: download the official Tor lists every 6 h
TorExits string // file with Tor exit addresses, one per line; empty disables the check
EventsMax string // size cap of the event registry ("512MB", "0" disables it)
NoAuth bool
@@ -174,6 +175,7 @@ func ParseFlags(name string, args []string) (Config, error) {
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", store.DefaultRetention, "how long data is kept, at most 720h (URUTAU_RETENTION)")
fs.StringVar(&c.TorAuto, "tor-auto", env("URUTAU_TOR_AUTO", "on"), "download the official Tor exit and relay lists every 6 h into <data-dir>/tor: on or off (URUTAU_TOR_AUTO)")
fs.StringVar(&c.TorExits, "tor-exits", env("URUTAU_TOR_EXITS", ""), "file with Tor exit node addresses, one per line, reloaded every 24 h when it changes; empty disables (URUTAU_TOR_EXITS)")
fs.StringVar(&c.EventsMax, "events-max", env("URUTAU_EVENTS_MAX", DefaultEventsMax), "size cap of the event registry in <data-dir>/events, 0 disables it (URUTAU_EVENTS_MAX)")
fs.StringVar(&c.Enforce, "enforce", env("URUTAU_ENFORCE", "off"), "second firewall: off, observe (decide in memory only) or on (write decisions for the host fail2ban) (URUTAU_ENFORCE)")
+50
View File
@@ -1,10 +1,13 @@
package app
import (
"bytes"
"errors"
"time"
"encoding/json"
"fmt"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"io"
@@ -46,6 +49,11 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
fi, _ := f.Stat()
f.Close()
add("source "+s.name, "ok", fmt.Sprintf("%s readable (%d bytes)", s.path, fi.Size()))
if s.name == "traefik" {
if bad, n := sampleMalformed(s.path); n >= winMin && bad*5 > n {
add("source traefik format", "warn", fmt.Sprintf("degraded: %d of the last %d lines are malformed: %s", bad, n, degradedMsg))
}
}
}
if err := os.MkdirAll(c.DataDir, 0o700); err != nil {
add("data-dir", "fail", err.Error())
@@ -134,3 +142,45 @@ func doctorState(c Config, add func(name, status, detail string)) map[string]any
add("state", "ok", fmt.Sprintf("%d IPs, %d domains, %d requests in 7 days", st.IPCount(), len(tr.Domains), tr.Requests))
return info
}
// sampleMalformed parses up to the last winSize lines of a Traefik log and
// counts the malformed ones.
func sampleMalformed(path string) (bad, n int) {
f, err := os.Open(path)
if err != nil {
return 0, 0
}
defer f.Close()
const tailBytes = 512 << 10
off := int64(0)
if fi, err := f.Stat(); err == nil && fi.Size() > tailBytes {
off = fi.Size() - tailBytes
}
if _, err := f.Seek(off, io.SeekStart); err != nil {
return 0, 0
}
b, err := io.ReadAll(io.LimitReader(f, tailBytes))
if err != nil {
return 0, 0
}
lines := bytes.Split(b, []byte("\n"))
if off > 0 && len(lines) > 0 {
lines = lines[1:] // first line is cut
}
if len(lines) > 0 && len(lines[len(lines)-1]) == 0 {
lines = lines[:len(lines)-1]
}
if len(lines) > winSize {
lines = lines[len(lines)-winSize:]
}
for _, l := range lines {
if len(bytes.TrimSpace(l)) == 0 {
continue
}
n++
if _, err := core.ParseTraefik(l); err != nil && !errors.Is(err, core.ErrIgnored) {
bad++
}
}
return bad, n
}
+93 -11
View File
@@ -2,11 +2,13 @@ package app
import (
"log/slog"
"net"
"net/netip"
"net/url"
"os"
"strconv"
"strings"
"sync"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
@@ -28,20 +30,24 @@ func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, err
return nil, nil
}
}
var allow []netip.Prefix
if nets, err := core.ParseCIDRs(c.Trusted); err == nil {
for _, n := range nets {
if p, err := netip.ParsePrefix(n.String()); err == nil {
allow = append(allow, p)
}
allow := egressAllow(c)
var provMu sync.Mutex
var provCache []string
provider := func() []string {
provMu.Lock()
defer provMu.Unlock()
if provCache == nil {
provCache = providerASNs(os.Getenv("URUTAU_EGRESS_PROVIDER_ASN"), func(ip string) uint32 { return st.GeoOf(ip).ASN })
}
return provCache
}
allow = append(allow, egressExtraAllow(c)...)
eng, err := egress.New(egress.Config{
Workloads: c.EgressWorkloads,
Resolvers: c.EgressResolvers,
Allow: allow,
Containers: c.EgressContainers,
Workloads: c.EgressWorkloads,
Resolvers: c.EgressResolvers,
Allow: allow,
Containers: c.EgressContainers,
TorRelay: func(a netip.Addr) bool { return intel.IsTorRelay(a) && !intel.IsTorExit(a) },
ProviderASNs: provider,
Geo: func(ip string) (string, string, string) {
g := st.GeoOf(ip)
asn := ""
@@ -96,3 +102,79 @@ func egressExtraAllow(c Config) []netip.Prefix {
}
return out
}
// ownPublicPrefixes returns the global unicast addresses of the local
// interfaces: the server's own addresses never produce a finding.
func ownPublicPrefixes() []netip.Prefix {
var out []netip.Prefix
for _, a := range localPublicAddrs() {
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
return out
}
func localPublicAddrs() []netip.Addr {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil
}
var out []netip.Addr
for _, ad := range addrs {
ipn, ok := ad.(*net.IPNet)
if !ok {
continue
}
a, ok := netip.AddrFromSlice(ipn.IP)
if !ok {
continue
}
a = a.Unmap()
if a.IsGlobalUnicast() && !a.IsPrivate() && !a.IsLoopback() && !a.IsLinkLocalUnicast() && !(a.Is4() && netip.MustParsePrefix("100.64.0.0/10").Contains(a)) {
out = append(out, a)
}
}
return out
}
// providerASNs lists the hosting provider's ASNs ("AS31898"): the explicit
// list (env, "31898,AS47583") wins, otherwise the ASN of the server's public
// interface addresses. nil (retried later) when none is known yet.
func providerASNs(explicit string, asnOf func(ip string) uint32) []string {
var out []string
seen := map[string]bool{}
add := func(n uint64) {
k := "AS" + strconv.FormatUint(n, 10)
if n != 0 && !seen[k] {
seen[k] = true
out = append(out, k)
}
}
for _, s := range strings.Split(explicit, ",") {
s = strings.TrimPrefix(strings.ToUpper(strings.TrimSpace(s)), "AS")
if n, err := strconv.ParseUint(s, 10, 32); err == nil {
add(n)
}
}
if len(out) > 0 {
return out
}
for _, a := range localPublicAddrs() {
add(uint64(asnOf(a.String())))
}
return out
}
// egressAllow is the list of destinations that never produce a finding: the
// trusted origins (our own servers, an invalid item does not discard the
// others), the federation peers, URUTAU_EGRESS_ALLOW and the local public
// addresses.
func egressAllow(c Config) []netip.Prefix {
var allow []netip.Prefix
for _, part := range strings.Split(c.Trusted, ",") {
if nets, err := core.ParseCIDRs(part); err == nil {
allow = append(allow, nets...)
}
}
allow = append(allow, egressExtraAllow(c)...)
return append(allow, ownPublicPrefixes()...)
}
+20 -1
View File
@@ -22,7 +22,7 @@ import (
)
// newEnforce builds the second firewall and hooks it into the store; nil when off.
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enforce.Engine {
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready func() bool) *enforce.Engine {
mode := strings.ToLower(c.Enforce)
if mode != enforce.ModeObserve && mode != enforce.ModeOn {
return nil
@@ -39,6 +39,25 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enfor
Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"),
Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost,
Crawler: func(ip string, uas []string) bool { v := st.FCrDNS(ip, uas); return v != nil && *v },
Rep: st.Reputation,
Tally: func(ip string, from int64) (int, int) { t := st.AttackTally(ip, from); return t.SSH, t.Web },
Roster: func(from int64) []enforce.Seen {
rows := st.AttackRoster(from)
out := make([]enforce.Seen, len(rows))
for i, r := range rows {
out[i] = enforce.Seen{IP: r.IP, Score: r.Score, Level: r.Level, Jails: r.Jails}
}
return out
},
Tallies: func(from int64) map[string]enforce.Tally {
m := st.AttackTallies(from)
out := make(map[string]enforce.Tally, len(m))
for k, v := range m {
out[k] = enforce.Tally{SSH: v.SSH, Web: v.Web}
}
return out
},
Ready: ready,
Geo: func(ip string) (string, uint32, string) {
if en.g == nil {
return "", 0, ""
+11 -1
View File
@@ -46,6 +46,9 @@ func Serve(c Config) error {
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
st.SetDomains(splitList(c.Domains))
watchTorExits(ctx, c.TorExits, 24*time.Hour, log)
if !strings.EqualFold(c.TorAuto, "off") {
watchTorLists(ctx, filepath.Join(c.DataDir, "tor"), torExitURL, torRelayURL, 6*time.Hour, log)
}
var elog *evlog.Log
if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 {
if elog, err = evlog.Open(evlog.Options{Dir: filepath.Join(c.DataDir, "events"), MaxBytes: max, Retention: c.Retention, Log: log}); err != nil {
@@ -106,7 +109,14 @@ func Serve(c Config) error {
extra := runner.Extra
runner.Extra = func() []store.SourceStatus { return append(extra(), egressSrc.Status()) }
}
eng := newEnforce(c, st, peers, en)
eng := newEnforce(c, st, peers, en, func() bool {
for _, s := range runner.Sources {
if s.backfilling.Load() {
return false
}
}
return true
})
if eng != nil {
server.SetEnforce(eng)
}
+53 -1
View File
@@ -23,6 +23,8 @@ type source struct {
parse func([]byte) (core.Event, error)
lines, malformed atomic.Uint64
win window
lastWarn atomic.Int64
lastEvent atomic.Int64
backfilling atomic.Bool
fol atomic.Pointer[tail.Follower]
@@ -32,6 +34,44 @@ 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)) }
const (
winSize = 1000
winMin = 50 // fewer samples than this never mark a source degraded
degradedMsg = "formato inesperado (JSON esperado?)"
)
// window remembers whether each of the last winSize lines was malformed.
type window struct {
mu sync.Mutex
ring [winSize]bool
n int // lines recorded so far, capped at winSize
pos int
bad int
}
func (w *window) add(bad bool) {
w.mu.Lock()
defer w.mu.Unlock()
if w.n == winSize && w.ring[w.pos] {
w.bad--
}
w.ring[w.pos] = bad
if bad {
w.bad++
}
w.pos = (w.pos + 1) % winSize
if w.n < winSize {
w.n++
}
}
// degraded reports whether more than 20% of the recent lines were malformed.
func (w *window) degraded() bool {
w.mu.Lock()
defer w.mu.Unlock()
return w.n >= winMin && w.bad*5 > w.n
}
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"}
@@ -55,6 +95,9 @@ func (s *source) status() store.SourceStatus {
}
}
}
if st.State == "following" && s.win.degraded() {
st.State, st.Error = "degraded", degradedMsg
}
return st
}
@@ -148,11 +191,20 @@ func (r *Runner) handle(s *source) func([]byte) {
s.lines.Add(1)
ev, err := s.parse(line)
if err != nil {
if !errors.Is(err, core.ErrIgnored) {
bad := !errors.Is(err, core.ErrIgnored)
if bad {
s.malformed.Add(1)
}
s.win.add(bad)
if bad && s.win.degraded() {
now := time.Now().Unix()
if last := s.lastWarn.Load(); now-last >= 3600 && s.lastWarn.CompareAndSwap(last, now) {
r.Log.Warn("many lines of this source are malformed", "source", s.name, "detail", degradedMsg)
}
}
return
}
s.win.add(false)
if core.Ignored(r.Ignore, ev.IP) {
return
}
+182 -1
View File
@@ -3,12 +3,17 @@ package app
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/netip"
"os"
"path/filepath"
"strings"
"sync"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
@@ -69,7 +74,7 @@ func watchTorExits(ctx context.Context, path string, every time.Duration, log *s
log.Warn("tor exit list unreadable", "err", err)
return
}
intel.SetTorExits(addrs)
torLists.setManual(addrs)
lastMod, lastSize = st.ModTime(), st.Size()
log.Info("tor exit list loaded", "n", len(addrs))
}
@@ -87,3 +92,179 @@ func watchTorExits(ctx context.Context, path string, every time.Duration, log *s
}
}()
}
const (
torExitURL = "https://check.torproject.org/torbulkexitlist"
torRelayURL = "https://onionoo.torproject.org/details?running=true&fields=or_addresses,exit_addresses"
maxTorList = 32 << 20
torFetchTO = 60 * time.Second
torUserAgent = "urutau"
maxTorRelays = 400000
torExitCache = "exits.txt"
torRelayCache = "relays.json"
)
// torLists merges the manual exit file (URUTAU_TOR_EXITS) with the downloaded
// lists into the intel package.
var torLists = &torSource{}
type torSource struct {
mu sync.Mutex
manual, auto, rels []netip.Addr
}
func (t *torSource) apply() {
all := append(append([]netip.Addr(nil), t.manual...), t.auto...)
intel.SetTorExits(all)
intel.SetTorRelays(append(all, t.rels...))
}
func (t *torSource) setManual(a []netip.Addr) {
t.mu.Lock()
defer t.mu.Unlock()
t.manual = a
t.apply()
}
func (t *torSource) setAuto(exits, relays []netip.Addr) {
t.mu.Lock()
defer t.mu.Unlock()
if exits != nil {
t.auto = exits
}
if relays != nil {
t.rels = relays
}
t.apply()
}
func torAddr(s string) (netip.Addr, bool) {
s = strings.TrimSpace(s)
if ap, err := netip.ParseAddrPort(s); err == nil {
s = ap.Addr().String()
}
a, err := netip.ParseAddr(strings.Trim(s, "[]"))
if err != nil || a.Zone() != "" {
return netip.Addr{}, false
}
return a.Unmap(), true
}
// ParseTorExitList parses the plain-text exit list (one address per line,
// junk and # comments ignored, at most maxTorExits addresses, input limited to
// 32 MB).
func ParseTorExitList(r io.Reader) []netip.Addr {
var out []netip.Addr
sc := bufio.NewScanner(io.LimitReader(r, maxTorList))
sc.Buffer(make([]byte, 0, 4096), 4096)
for sc.Scan() && len(out) < maxTorExits {
l := sc.Text()
if i := strings.IndexByte(l, '#'); i >= 0 {
l = l[:i]
}
if a, ok := torAddr(l); ok {
out = append(out, a)
}
}
return out
}
// ParseOnionoo extracts the relay and exit addresses (v4 and v6) of an Onionoo
// "details" document (input limited to 32 MB, at most 400000 addresses).
func ParseOnionoo(r io.Reader) ([]netip.Addr, error) {
var doc struct {
Relays []struct {
OR []string `json:"or_addresses"`
Exit []string `json:"exit_addresses"`
} `json:"relays"`
}
if err := json.NewDecoder(io.LimitReader(r, maxTorList)).Decode(&doc); err != nil {
return nil, err
}
var out []netip.Addr
for _, rl := range doc.Relays {
for _, s := range append(rl.OR, rl.Exit...) {
if a, ok := torAddr(s); ok && len(out) < maxTorRelays {
out = append(out, a)
}
}
}
return out, nil
}
func fetchTor(ctx context.Context, url string) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, torFetchTO)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", torUserAgent)
resp, err := (&http.Client{Timeout: torFetchTO}).Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status %d", resp.StatusCode)
}
b, err := io.ReadAll(io.LimitReader(resp.Body, maxTorList+1))
if err != nil {
return nil, err
}
if len(b) > maxTorList {
return nil, errors.New("list larger than 32 MB")
}
return b, nil
}
// refreshTorLists reads the cache in dir and, when force or the cache is older
// than maxAge, downloads the lists again. A failed download keeps the cache.
func refreshTorLists(ctx context.Context, dir, exitURL, relayURL string, maxAge time.Duration, log *slog.Logger) {
_ = os.MkdirAll(dir, 0o750)
one := func(name, url string, parse func([]byte) ([]netip.Addr, error)) []netip.Addr {
path := filepath.Join(dir, name)
st, statErr := os.Stat(path)
if statErr != nil || time.Since(st.ModTime()) >= maxAge {
if b, err := fetchTor(ctx, url); err != nil {
log.Warn("tor list download failed", "list", name, "err", err)
} else if a, err := parse(b); err != nil || len(a) == 0 {
log.Warn("tor list invalid, kept the cache", "list", name, "err", err)
} else if err := os.WriteFile(path+".tmp", b, 0o640); err == nil && os.Rename(path+".tmp", path) == nil {
return a
}
}
b, err := os.ReadFile(path)
if err != nil || len(b) > maxTorList {
return nil
}
a, _ := parse(b)
return a
}
exits := one(torExitCache, exitURL, func(b []byte) ([]netip.Addr, error) {
return ParseTorExitList(strings.NewReader(string(b))), nil
})
relays := one(torRelayCache, relayURL, func(b []byte) ([]netip.Addr, error) {
return ParseOnionoo(strings.NewReader(string(b)))
})
torLists.setAuto(exits, relays)
log.Info("tor lists", "exits", len(exits), "relays", len(relays))
}
// watchTorLists refreshes the official lists now (in the background, so
// startup is not blocked) and every interval.
func watchTorLists(ctx context.Context, dir, exitURL, relayURL string, every time.Duration, log *slog.Logger) {
go func() {
refreshTorLists(ctx, dir, exitURL, relayURL, every*9/10, log)
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
refreshTorLists(ctx, dir, exitURL, relayURL, every*9/10, log)
}
}
}()
}
+110
View File
@@ -0,0 +1,110 @@
package app
import (
"context"
"log/slog"
"net/http"
"net/http/httptest"
"net/netip"
"os"
"path/filepath"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
)
func TestParseTorLists(t *testing.T) {
got := ParseTorExitList(strings.NewReader("1.2.3.4\n# c\nlixo\n2001:db8::1 # x\n999.1.1.1\n::ffff:5.6.7.8\n"))
if len(got) != 3 || got[2].String() != "5.6.7.8" {
t.Fatalf("exits: %v", got)
}
js := `{"relays":[{"or_addresses":["10.1.1.1:9001","[2001:db8::2]:443","junk"],"exit_addresses":["10.1.1.2"]},{"or_addresses":[]}]}`
a, err := ParseOnionoo(strings.NewReader(js))
if err != nil || len(a) != 3 || a[1].String() != "2001:db8::2" {
t.Fatalf("onionoo: %v %v", a, err)
}
if _, err := ParseOnionoo(strings.NewReader("<html>")); err == nil {
t.Fatal("garbage must fail")
}
// the size limit truncates the input: broken JSON, an error
if _, err := ParseOnionoo(strings.NewReader(`{"relays":[{"or_addresses":["1.1.1.1:1"]}` + strings.Repeat(" ", maxTorList+10) + `]}`)); err == nil {
t.Fatal("oversize must fail")
}
}
func TestRefreshTorListsCache(t *testing.T) {
hits := 0
fail := false
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits++
if fail || r.Header.Get("User-Agent") != "urutau" {
http.Error(w, "x", 500)
return
}
if r.URL.Path == "/exit" {
w.Write([]byte("198.51.100.1\n"))
return
}
w.Write([]byte(`{"relays":[{"or_addresses":["198.51.100.2:9001"]}]}`))
}))
defer srv.Close()
defer torLists.setManual(nil)
defer torLists.setAuto([]netip.Addr{}, []netip.Addr{})
dir := filepath.Join(t.TempDir(), "tor")
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
ctx := context.Background()
refreshTorLists(ctx, dir, srv.URL+"/exit", srv.URL+"/relays", time.Hour, log)
if !intel.IsTorExit(netip.MustParseAddr("198.51.100.1")) || !intel.IsTorRelay(netip.MustParseAddr("198.51.100.2")) || hits != 2 {
t.Fatalf("lists not loaded, hits=%d", hits)
}
refreshTorLists(ctx, dir, srv.URL+"/exit", srv.URL+"/relays", time.Hour, log) // fresh cache: no download
if hits != 2 {
t.Fatalf("cache ignored: %d", hits)
}
torLists.setAuto([]netip.Addr{}, []netip.Addr{})
fail = true
refreshTorLists(ctx, dir, srv.URL+"/exit", srv.URL+"/relays", 0, log) // stale + failing: the cache serves
if !intel.IsTorExit(netip.MustParseAddr("198.51.100.1")) || !intel.IsTorRelay(netip.MustParseAddr("198.51.100.2")) {
t.Fatal("fallback to cache failed")
}
// the manual list coexists
torLists.setManual([]netip.Addr{netip.MustParseAddr("203.0.113.9")})
if !intel.IsTorExit(netip.MustParseAddr("203.0.113.9")) || !intel.IsTorExit(netip.MustParseAddr("198.51.100.1")) {
t.Fatal("manual + auto merge failed")
}
}
func TestNetTypeTorEntry(t *testing.T) {
a := netip.MustParseAddr("198.51.100.5")
intel.SetTorExits([]netip.Addr{a})
defer intel.SetTorExits(nil)
if typ, _ := intel.NetTypeIP(a, 0, "", ""); typ != "tor" {
t.Fatal(typ)
}
}
func TestEgressOwnAllowAndProvider(t *testing.T) {
if got := providerASNs("31898, AS47583,x", nil); len(got) != 2 || got[0] != "AS31898" || got[1] != "AS47583" {
t.Fatalf("%v", got)
}
ps := ownPublicPrefixes()
for _, p := range ps {
if p.Addr().IsPrivate() || p.Addr().IsLoopback() {
t.Fatal(p)
}
}
// the peer has no URUTAU_PEERS: URUTAU_TRUSTED carries both servers, and a
// bad item does not discard the others
al := egressAllow(Config{Trusted: "136.248.78.83,lixo,195.200.0.252/32"})
for _, ipS := range []string{"136.248.78.83", "195.200.0.252"} {
ok := false
for _, p := range al {
ok = ok || p.Contains(netip.MustParseAddr(ipS))
}
if !ok {
t.Fatal("not allowed: ", ipS)
}
}
}
+22
View File
@@ -257,3 +257,25 @@ func TestEgressExtraAllow(t *testing.T) {
t.Fatalf("%v", s)
}
}
func TestSourceDegradedWindow(t *testing.T) {
var w window
for i := 0; i < 100; i++ {
w.add(i%10 == 0)
}
if w.degraded() {
t.Fatal("10% must not degrade")
}
for i := 0; i < 400; i++ {
w.add(true)
}
if !w.degraded() {
t.Fatal("expected degraded")
}
for i := 0; i < winSize; i++ {
w.add(false)
}
if w.degraded() {
t.Fatal("window must recover")
}
}
+1 -1
View File
@@ -2,4 +2,4 @@ package app
// Version is the release version (SemVer). Release builds may override it with
// -ldflags "-X .../internal/app.Version=...".
var Version = "1.4.1"
var Version = "1.4.5"
+22
View File
@@ -266,3 +266,25 @@ func TestZonesAreRejectedEverywhere(t *testing.T) {
}
_ = strings.ToLower
}
func TestParseTraefikText(t *testing.T) {
ev, err := ParseTraefik([]byte(`10.0.15.1 - - [15/Nov/2026:04:10:51 +0000] "GET /wp-content/uploads/2026/08/IMG.jpg HTTP/2.0" 200 252131 "-" "-" 22219 "https-0-fwl1r20xzp8uf2g48log9q49-wordpress-1870@docker" "http://10.0.5.2:80" 3ms`))
if err != nil {
t.Fatal(err)
}
if ev.IP != "10.0.15.1" || ev.Method != "GET" || ev.Path != "/wp-content/uploads/2026/08/IMG.jpg" || ev.Proto != "HTTP/2.0" ||
ev.Status != 200 || ev.Bytes != 252131 || ev.UA != "" || ev.Referer != "" || ev.OriginStatus != 200 ||
ev.DurationNS != 3e6 || ev.Domain != "" || ev.Router != "https-0-fwl1r20xzp8uf2g48log9q49-wordpress-1870@docker" ||
ev.Time.Format("2006-01-02T15:04:05Z") != "2026-11-15T04:10:51Z" {
t.Fatalf("%+v", ev)
}
ev, err = ParseTraefik([]byte(`203.0.113.9 - - [15/Nov/2026:04:10:52 +0000] "POST /wp-login.php HTTP/1.1" 404 19 "https://x/\"y" "Mozilla \"q\" 5.0" 1 "web@docker" "-" 12ms`))
if err != nil || ev.Method != "POST" || ev.Status != 404 || ev.UA != `Mozilla "q" 5.0` || ev.Referer != `https://x/"y` || ev.OriginStatus != 0 {
t.Fatalf("%+v %v", ev, err)
}
for _, bad := range []string{"garbage", `1.2.3.4 - - [bad] "GET / HTTP/1.1" 200 1 "-" "-" 1`, `1.2.3.4 - - [15/Nov/2026:04:10:52 +0000] "GET / HTTP/1.1" 200 1 "-" "-`, `nope - - [15/Nov/2026:04:10:52 +0000] "GET / HTTP/1.1" 200 1 "-" "-" 1`} {
if _, err := ParseTraefik([]byte(bad)); err == nil {
t.Errorf("accepted %q", bad)
}
}
}
+121
View File
@@ -1,10 +1,12 @@
package core
import (
"bytes"
"encoding/json"
"errors"
"net/netip"
"regexp"
"strconv"
"strings"
"time"
)
@@ -72,6 +74,9 @@ type traefikLine struct {
// ParseTraefik parses one Traefik JSON access log line.
func ParseTraefik(line []byte) (Event, error) {
if t := bytes.TrimLeft(line, " \t"); len(t) > 0 && t[0] != '{' {
return parseTraefikText(string(t))
}
var l traefikLine
if err := json.Unmarshal(line, &l); err != nil {
return Event{}, err
@@ -213,3 +218,119 @@ func ParseFail2ban(line string) (Event, error) {
Unban: m[3] == "Unban", Restore: m[3] == "Restore Ban",
}, nil
}
// textFields splits a Traefik text (extended CLF) access log line into its
// fields. Quoted fields may carry backslash escapes, the [time] field is read
// up to the closing bracket.
func textFields(s string) ([]string, bool) {
var out []string
i := 0
for i < len(s) {
switch c := s[i]; {
case c == ' ' || c == '\t':
i++
case c == '"':
var b strings.Builder
i++
closed := false
for i < len(s) {
if s[i] == '\\' && i+1 < len(s) {
b.WriteByte(s[i+1])
i += 2
continue
}
if s[i] == '"' {
closed = true
i++
break
}
b.WriteByte(s[i])
i++
}
if !closed {
return nil, false
}
out = append(out, b.String())
case c == '[':
j := strings.IndexByte(s[i:], ']')
if j < 0 {
return nil, false
}
out = append(out, s[i+1:i+j])
i += j + 1
default:
j := i
for j < len(s) && s[j] != ' ' && s[j] != '\t' {
j++
}
out = append(out, s[i:j])
i = j
}
}
return out, true
}
func dash(s string) string {
if s == "-" {
return ""
}
return s
}
// parseTraefikText parses the default Traefik access log format:
// host ident user [time] "METHOD path PROTO" status size "referer" "ua" count "router" "backend" Nms
// The format carries no Host header, so Domain stays empty.
func parseTraefikText(line string) (Event, error) {
f, ok := textFields(line)
if !ok || len(f) < 9 {
return Event{}, errors.New("not a traefik text line")
}
ip, ok := cleanIP(f[0])
if !ok {
if _, err := netip.ParseAddr(strings.TrimSpace(f[0])); err != nil {
return Event{}, errors.New("bad client address")
}
return Event{}, ErrIgnored
}
t, err := time.Parse("02/Jan/2006:15:04:05 -0700", f[3])
if err != nil {
return Event{}, err
}
rl := strings.Fields(f[4])
if len(rl) < 2 {
return Event{}, errors.New("bad request line")
}
method, path, proto := rl[0], rl[1], ""
if len(rl) >= 3 {
proto = rl[len(rl)-1]
}
status, err := strconv.Atoi(f[5])
if err != nil || status < 100 || status > 999 {
return Event{}, errors.New("bad status")
}
var size int64
if f[6] != "-" {
if size, err = strconv.ParseInt(f[6], 10, 64); err != nil {
return Event{}, err
}
}
ev := Event{
Time: t.UTC(), IP: ip, Source: "traefik", Status: status,
Method: clip(method, 12), Path: clip(path, maxPath), Proto: clip(proto, 12),
Bytes: size, Referer: clip(dash(f[7]), 300), UA: clip(dash(f[8]), maxUA),
}
if len(f) > 10 {
ev.Router = clip(dash(f[10]), 64)
}
if len(f) > 11 && dash(f[11]) != "" {
ev.OriginStatus = status
}
if len(f) > 12 {
if d, err := time.ParseDuration(strings.TrimSpace(f[12])); err == nil {
ev.DurationNS = d.Nanoseconds()
}
}
c := Classify(method, path, status)
ev.Cat, ev.Soft, ev.Strong, ev.Weak = c.Cat, c.Soft, c.Strong, c.Weak
return ev, nil
}
+57
View File
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"sort"
"strings"
"testing"
"time"
)
@@ -548,3 +549,59 @@ func TestBeaconDuringContinuousScan(t *testing.T) {
t.Fatal("fanSeen unbounded")
}
}
func TestBeaconProviderAndCDN(t *testing.T) {
geo := func(s string) (string, string, string) {
switch s {
case "192.0.2.10":
return "US", "AS31898", "Oracle Corporation"
case "192.0.2.20":
return "US", "AS13335", "Cloudflare"
}
return "BR", "AS2", "y"
}
bad := func(a netip.Addr) (bool, string) { return a == ip("192.0.2.30"), "known attacker" }
e := newEng(t, Config{Geo: geo, BadDst: bad, ProviderASNs: func() []string { return []string{"AS31898"} }})
rnd := rand.New(rand.NewSource(2))
for _, src := range []string{"10.0.3.5"} {
feedBeacon(e, src, "192.0.2.10", 443, t0, 50, 60*time.Second, 0.05, rnd)
feedBeacon(e, src, "192.0.2.20", 443, t0, 50, 60*time.Second, 0.05, rnd)
}
// the host itself towards the provider network
for i := 0; i < 50; i++ {
ev := mk(t0.Add(time.Duration(i)*60*time.Second), "10.0.3.5", "192.0.2.10", "tcp", 8443)
ev.Host = true
e.IngestEvent(ev)
ev2 := mk(t0.Add(time.Duration(i)*60*time.Second), "10.0.3.5", "192.0.2.30", "tcp", 8443)
ev2.Host = true
e.IngestEvent(ev2)
}
r := rep(e)
var inf, cont, cdn, hi bool
for _, f := range r.Findings {
switch {
case f.Kind == "infra" && f.Dst == "192.0.2.10" && f.Workload == "host" && f.Severity == "info" && strings.Contains(f.Detail, "provider service (Oracle Corporation)"):
inf = true
case f.Kind == "beacon" && f.Dst == "192.0.2.10" && f.Severity == "medium":
cont = true // container to the provider ASN: evaluated normally
case f.Kind == "beacon" && f.Dst == "192.0.2.20" && f.Severity == "low" && strings.Contains(f.Detail, "API"):
cdn = true
case f.Kind == "beacon" && f.Dst == "192.0.2.30" && f.Severity == "high":
hi = true
}
}
if !inf || !cont || !cdn || !hi {
t.Fatalf("infra=%v container=%v cdn=%v bad=%v: %+v", inf, cont, cdn, hi, r.Findings)
}
}
func TestTorRelayFinding(t *testing.T) {
e := newEng(t, Config{Workloads: "sc=10.0.5.0/24:scanner", TorRelay: func(a netip.Addr) bool { return a == ip("192.0.2.77") }})
e.IngestEvent(mk(t0, "10.0.3.5", "192.0.2.77", "tcp", 443))
e.IngestEvent(mk(t0, "10.0.5.2", "192.0.2.77", "tcp", 443)) // scanner outside a burst
e.IngestEvent(mk(t0, "10.0.3.5", "192.0.2.78", "tcp", 443))
f := kinds(rep(e), "tor")
if len(f) != 2 || f[0].Severity != "high" || f[0].Dst != "192.0.2.77" {
t.Fatalf("tor: %+v", f)
}
}
+55 -7
View File
@@ -61,7 +61,13 @@ type Config struct {
// destination is a known attacker or Tor exit (and why).
Geo func(ip string) (cc, asn, org string)
BadDst func(netip.Addr) (bool, string)
Now func() time.Time
// TorRelay says whether an address is a Tor relay (a connection to one is
// a "tor" finding).
TorRelay func(netip.Addr) bool
// ProviderASNs ("AS31898") are the hosting provider's own networks: a
// beacon from the host itself to them is informational ("infra").
ProviderASNs func() []string
Now func() time.Time
// Learn is the per-workload learning time before new_geo (default 24h).
Learn time.Duration
// ResolvConf lists resolv.conf files whose nameservers are allowed resolvers
@@ -700,6 +706,9 @@ func (e *Engine) checks(ws *wstate, ev Event, dport uint16, t int64, ds *dstStat
e.addFinding("bad_dst", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
}
}
if e.cfg.TorRelay != nil && e.cfg.TorRelay(ev.Dst) {
e.addFinding("tor", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, "connection to a Tor relay", 1)
}
if ev.Proto == "tcp" {
if sev, why := suspiciousPort(dport, ws.role); why != "" {
e.addFinding("port", sev, ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
@@ -744,7 +753,15 @@ func suspiciousPort(port uint16, role string) (sev, why string) {
func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairState, ds *dstStat) {
if p.flagged {
if f := e.addFinding("beacon", "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1); f != nil {
kind := "beacon"
if ev.Host && e.cfg.Geo != nil {
if _, asn, _ := e.cfg.Geo(ev.Dst.String()); e.providerASN(asn) {
if _, ok := e.findings[fmt.Sprintf("infra|%s|%s|%d", ws.name, ev.Dst, dport)]; ok {
kind = "infra"
}
}
}
if f := e.addFinding(kind, "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1); f != nil {
if n := len(f.Samples); n == 0 || f.Samples[n-1] != p.last {
if n >= MaxSamples {
f.Samples = append(f.Samples[:0], f.Samples[1:]...)
@@ -802,15 +819,27 @@ func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairSta
if mad < cv {
jit = mad
}
sev := "medium"
sev, kind := "medium", "beacon"
why := fmt.Sprintf("regular connections every %.0f s (jitter %.0f%%)", med, jit*100)
bad := false
if e.cfg.BadDst != nil {
if bad, r := e.cfg.BadDst(ev.Dst); bad {
sev, why = "high", why+"; destination: "+r
if b, r := e.cfg.BadDst(ev.Dst); b {
bad, sev, why = true, "high", why+"; destination: "+r
}
}
if !bad && e.cfg.Geo != nil {
_, asn, org := e.cfg.Geo(ev.Dst.String())
switch {
case ev.Host && e.providerASN(asn):
sev, kind = "info", "infra"
why = fmt.Sprintf("%s; provider service (%s)", why, org)
case commonCloudASNs[asn]:
sev = "low"
why += "; large CDN/cloud network: regular connections are common for API calls"
}
}
p.flagged, p.interval, p.cv = true, med, jit
f := e.addFinding("beacon", sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
f := e.addFinding(kind, sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
if f != nil {
f.Count, f.First = int(p.total), p.first
f.Samples = make([]int64, 0, MaxSamples)
@@ -820,6 +849,25 @@ func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairSta
}
}
// commonCloudASNs are large CDNs/clouds whose regular connections usually are
// API calls.
var commonCloudASNs = map[string]bool{"AS13335": true, "AS15169": true, "AS14618": true, "AS16509": true, "AS8075": true, "AS20940": true, "AS54113": true}
func (e *Engine) providerASN(asn string) bool {
if asn == "" {
return false
}
if e.cfg.ProviderASNs == nil {
return false
}
for _, a := range e.cfg.ProviderASNs() {
if strings.EqualFold(a, asn) {
return true
}
}
return false
}
func median(v []float64) float64 {
s := append([]float64(nil), v...)
sort.Float64s(s)
@@ -833,7 +881,7 @@ func median(v []float64) float64 {
return (s[n/2-1] + s[n/2]) / 2
}
var sevRank = map[string]int{"low": 1, "medium": 2, "high": 3}
var sevRank = map[string]int{"info": 0, "low": 1, "medium": 2, "high": 3}
func (e *Engine) addFinding(kind, sev, wl, dst string, dport uint16, proto string, t int64, iv, jit float64, detail string, inc int) *Finding {
key := fmt.Sprintf("%s|%s|%s|%d", kind, wl, dst, dport)
+70 -2
View File
@@ -31,6 +31,36 @@ type Config struct {
Crawler func(ip string, uas []string) bool // FCrDNS verified crawler
Geo func(ip string) (string, uint32, string) // cc, asn, org
Now func() time.Time
// History hooks (all optional, supplied by the store).
Rep func(ip string) (score float64, level core.Level, ok bool) // verdict of an address
Tally func(ip string, from int64) (ssh, web int) // 24 h counts of one address
Roster func(from int64) []Seen // addresses with malicious activity since from
Tallies func(from int64) map[string]Tally // 24 h counts of every address, one pass
Ready func() bool // false while sources still backfill
}
// Seen is one address with malicious activity, as listed by Config.Roster.
type Seen struct {
IP string
Score float64
Level core.Level
Jails []string
}
// Tally counts malicious events of one address in LongWindow.
type Tally struct{ SSH, Web int }
type longRec struct {
ssh, web int
at int64 // when loaded from the registry
known bool
fresh bool // just loaded: the current event is already counted
}
type cand struct {
a netip.Addr
d Decision
}
// Wire is a decision as exchanged between peers.
@@ -151,6 +181,8 @@ type Engine struct {
dirty bool
lastSave time.Time
hostIPs map[string][]netip.Addr // last good resolution per host
long map[netip.Addr]*longRec
queue []cand
}
// New builds an engine and loads its state.
@@ -174,7 +206,7 @@ func New(c Config) *Engine {
}
e := &Engine{cfg: c, log: &logFile{path: c.Path}, ch: make(chan item, 4096), ips: map[netip.Addr]*ipState{},
bans: map[netip.Addr]banRec{}, would: map[netip.Addr]int64{}, skipSeen: map[netip.Addr]int64{},
counts: Counts{Skipped: map[string]int{}}}
counts: Counts{Skipped: map[string]int{}}, long: map[netip.Addr]*longRec{}}
e.hostIPs = map[string][]netip.Addr{}
e.excl = Exclusions{Trusted: c.Trusted, Peers: map[netip.Addr]bool{}, Infra: map[netip.Addr]bool{}}
e.refreshPeers()
@@ -223,15 +255,28 @@ func (e *Engine) Run(ctx context.Context) {
defer flush.Stop()
defer peers.Stop()
defer e.log.close()
sweepT := time.NewTicker(SweepEvery)
defer sweepT.Stop()
started := e.cfg.Now()
swept := false
for {
select {
case <-ctx.Done():
e.saveState()
return
case it := <-e.ch:
e.process(it.ev, it.fam)
e.handle(it.ev, it.fam)
case <-sweepT.C:
if swept {
e.Sweep()
}
case <-flush.C:
e.maybeSave()
if !swept && e.cfg.Now().Sub(started) >= 20*time.Second && (e.cfg.Ready == nil || e.cfg.Ready()) {
swept = true
e.Sweep()
}
e.drain()
case <-peers.C:
e.refreshPeers()
}
@@ -431,6 +476,16 @@ func (e *Engine) process(ev core.Event, fam string) {
st.uas = append(st.uas, ua)
}
}
lr := e.long[a]
if lr != nil {
if lr.fresh {
lr.fresh = false
} else if ev.Cat == core.SSHFail {
lr.ssh++
} else {
lr.web++
}
}
crits := 0
for _, x := range st.ev {
if criticalReasons[x.slug] {
@@ -442,6 +497,9 @@ func (e *Engine) process(ev core.Event, fam string) {
if crit {
in.Crit = slug
}
if lr != nil {
in.Known, in.SSH24, in.Web24 = lr.known, lr.ssh, lr.web
}
e.fill(a, st, &in, now)
d := Decide(in, Params{Threshold: e.cfg.Threshold})
if d.Action == ActBan && e.cfg.Crawler != nil && len(st.uas) > 0 && e.cfg.Crawler(a.String(), st.uas) {
@@ -627,10 +685,20 @@ func (e *Engine) AcceptPeer(name string, in []Wire) (accepted, invalid int) {
// Report summarizes the activity since the unix time from.
func (e *Engine) Report(from int64) Report {
var roster []Seen
if e.cfg.Roster != nil {
roster = e.cfg.Roster(from) // outside the lock: it walks the store
}
e.mu.Lock()
defer e.mu.Unlock()
var cv Coverage
if e.cfg.Roster != nil {
cv = e.coverageOf(roster, from)
}
for _, st := range e.ips {
if e.cfg.Roster != nil {
break
}
if st.lastAttack < from {
continue
}
+197
View File
@@ -0,0 +1,197 @@
package enforce
import (
"net/netip"
"sort"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
// SweepEvery is the period of the proactive sweep.
const SweepEvery = 10 * time.Minute
const (
longTTL = 10 * time.Minute // a loaded 24 h count is trusted this long, then reloaded
maxLong = 20000
jailOurs = "urutau"
)
// IsKnown reports whether a verdict alone justifies a ban.
func IsKnown(score float64, level core.Level) bool {
return level == core.LevelHostile || (level == core.LevelSuspicious && score >= KnownSuspiciousScore)
}
// handle is the live path of one event: it loads the history of a malicious
// address (outside the lock, at most once per longTTL) and then decides.
func (e *Engine) handle(ev core.Event, fam string) {
e.prefetch(ev)
e.process(ev, fam)
}
func (e *Engine) prefetch(ev core.Event) {
if e.cfg.Rep == nil && e.cfg.Tally == nil {
return
}
if ev.Cat != core.SSHFail && !CountsAsAttack(ev) {
return
}
a, err := netip.ParseAddr(ev.IP)
if err != nil {
return
}
a = a.Unmap().WithZone("")
now := e.cfg.Now()
if ev.Time.Unix() < now.Add(-Window).Unix() { // replayed history: no decision, no query
return
}
e.mu.Lock()
skip := e.excl.Excluded(a) != ""
lr := e.long[a]
stale := lr == nil || now.Unix()-lr.at > int64(longTTL/time.Second)
e.mu.Unlock()
if skip {
return
}
var known bool
if e.cfg.Rep != nil {
if sc, lv, ok := e.cfg.Rep(a.String()); ok {
known = IsKnown(sc, lv)
}
}
var ssh, web int
if stale && e.cfg.Tally != nil {
ssh, web = e.cfg.Tally(a.String(), now.Add(-LongWindow).Unix())
}
e.mu.Lock()
defer e.mu.Unlock()
if len(e.long) >= maxLong {
cut := now.Add(-LongWindow).Unix()
for k, v := range e.long {
if v.at < cut {
delete(e.long, k)
}
}
if len(e.long) >= maxLong {
e.long = map[netip.Addr]*longRec{}
}
}
lr = e.long[a]
if lr == nil {
lr = &longRec{}
e.long[a] = lr
}
lr.known = known
if stale {
lr.ssh, lr.web, lr.at, lr.fresh = ssh, web, now.Unix(), true
}
}
// Sweep evaluates the addresses with malicious activity in the last 24 h that
// nothing blocks yet and queues a ban for those the long rules justify. The
// queue is drained at most MaxPerMin per minute by Run.
func (e *Engine) Sweep() {
if e.cfg.Roster == nil {
return
}
now := e.cfg.Now()
from := now.Add(-LongWindow).Unix()
roster := e.cfg.Roster(from)
var tallies map[string]Tally
if e.cfg.Tallies != nil {
tallies = e.cfg.Tallies(from)
}
sort.SliceStable(roster, func(i, j int) bool { return roster[i].Score > roster[j].Score })
var q []cand
e.mu.Lock()
defer e.mu.Unlock()
for _, r := range roster {
if len(r.Jails) > 0 {
continue // fail2ban or our own jail holds it
}
a, err := netip.ParseAddr(r.IP)
if err != nil {
continue
}
a = a.Unmap().WithZone("")
st := e.stateOf(a)
t := tallies[a.String()]
in := Input{Now: now, Known: IsKnown(r.Score, r.Level), SSH24: t.SSH, Web24: t.Web,
Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.excl.Excluded(a)}
e.fill(a, st, &in, now)
d := Decide(in, Params{Threshold: e.cfg.Threshold})
if d.Action == ActBan && e.cfg.Crawler != nil && len(st.uas) > 0 && e.cfg.Crawler(a.String(), st.uas) {
in.Exclude = SkipCrawler
d = Decide(in, Params{Threshold: e.cfg.Threshold})
}
switch d.Action {
case ActBan:
q = append(q, cand{a, d})
case ActSkip:
e.apply(a, st, d, "sweep", now)
}
}
e.queue = q
}
// drain applies queued sweep bans while this minute has budget left.
func (e *Engine) drain() {
e.mu.Lock()
defer e.mu.Unlock()
now := e.cfg.Now()
for len(e.queue) > 0 {
if m := now.Unix() / 60; m != e.minute {
e.minute, e.inMinute = m, 0
}
if e.inMinute >= e.cfg.MaxPerMin {
return
}
c := e.queue[0]
e.queue = e.queue[1:]
st := e.stateOf(c.a)
if st.banned > now.Unix() {
continue
}
in := Input{Now: now}
e.fill(c.a, st, &in, now)
if in.Active {
continue
}
c.d.TTL = TTLFor(in.Offences)
e.apply(c.a, st, c.d, "local", now)
}
}
// coverageOf computes the coverage from the registry's roster plus the engine's
// durable decisions; the lock is held.
func (e *Engine) coverageOf(roster []Seen, from int64) Coverage {
var cv Coverage
for _, r := range roster {
cv.AttackIPs++
a, _ := netip.ParseAddr(r.IP)
a = a.Unmap().WithZone("")
f2b, ours := false, false
for _, j := range r.Jails {
if j == jailOurs {
ours = true
} else {
f2b = true
}
}
if b, ok := e.bans[a]; ok && b.Last >= from {
ours = true
}
st := e.ips[a]
switch {
case f2b:
cv.BlockedByFirewall++
case ours || (st != nil && st.urutauAt >= from && st.urutauAt > 0):
cv.BlockedByUrutau++
case e.would[a] > 0 || (st != nil && st.wouldAt >= from && st.wouldAt > 0):
cv.WouldBlock++
default:
cv.Unblocked++
}
}
return cv
}
+179
View File
@@ -0,0 +1,179 @@
package enforce
import (
"net/netip"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
func sshEv(ip string, at time.Time) core.Event {
return core.Event{Time: at, IP: ip, Cat: core.SSHFail, Source: "ssh", User: "root"}
}
func histRig(t *testing.T, mod func(*Config)) *rig {
return newRig(t, ModeOn, func(c *Config) {
c.Trusted = append(c.Trusted, netip.MustParsePrefix("168.196.85.0/24"))
if mod != nil {
mod(c)
}
})
}
func TestKnownAttackerBansOnFirstEvent(t *testing.T) {
lv := map[string]core.Level{"203.0.114.50": core.LevelHostile, "203.0.114.51": core.LevelSuspicious}
sc := map[string]float64{"203.0.114.50": 80, "203.0.114.51": 40, "203.0.114.52": 120}
lv["203.0.114.52"] = core.LevelSuspicious
r := histRig(t, func(c *Config) {
c.Rep = func(ip string) (float64, core.Level, bool) { l, ok := lv[ip]; return sc[ip], l, ok }
})
for _, ip := range []string{"203.0.114.50", "203.0.114.51", "203.0.114.52"} {
r.e.handle(atk(ip, r.now, "/x", 404), "")
}
got := map[string]bool{}
for _, l := range r.lines(t) {
for _, ip := range []string{"203.0.114.50", "203.0.114.51", "203.0.114.52"} {
if len(l) > 0 && contains(l, ip) {
got[ip] = true
if !contains(l, "known-attacker") {
t.Errorf("reason: %s", l)
}
}
}
}
if !got["203.0.114.50"] || got["203.0.114.51"] || !got["203.0.114.52"] {
t.Fatalf("bans: %v", got)
}
}
func contains(s, sub string) bool {
for i := 0; i+len(sub) <= len(s); i++ {
if s[i:i+len(sub)] == sub {
return true
}
}
return false
}
func TestSlowSSH24h(t *testing.T) {
r := histRig(t, func(c *Config) {
c.Tally = func(ip string, from int64) (int, int) { return 9, 0 } // 9 already in the registry
})
r.e.handle(sshEv("203.0.114.60", r.now), "")
if len(r.lines(t)) != 0 {
t.Fatal("9 in 24h must not ban")
}
r.now = r.now.Add(time.Minute)
r.e.handle(sshEv("203.0.114.60", r.now), "") // the 10th
if l := r.lines(t); len(l) != 1 || !contains(l[0], "ssh-bruteforce") {
t.Fatalf("lines: %v", l)
}
}
func TestTrustedNeverBannedByHistory(t *testing.T) {
r := histRig(t, func(c *Config) {
c.Rep = func(string) (float64, core.Level, bool) { return 200, core.LevelHostile, true }
c.Tally = func(string, int64) (int, int) { return 500, 500 }
c.Roster = func(int64) []Seen {
return []Seen{{IP: "168.196.85.9", Score: 200, Level: core.LevelHostile}}
}
})
r.e.handle(sshEv("168.196.85.9", r.now), "")
r.e.Sweep()
r.e.drain()
if len(r.lines(t)) != 0 {
t.Fatalf("trusted banned: %v", r.lines(t))
}
}
func TestSweepRespectsExclusionsAndCap(t *testing.T) {
var roster []Seen
tal := map[string]Tally{}
for i := 1; i <= 5; i++ {
ip := "203.0.114." + itoa(100+i)
roster = append(roster, Seen{IP: ip, Score: float64(60 - i), Level: core.LevelHostile})
}
roster = append(roster,
Seen{IP: "168.196.85.7", Score: 90, Level: core.LevelHostile}, // trusted
Seen{IP: "10.0.0.5", Score: 90, Level: core.LevelHostile}, // private
Seen{IP: "203.0.114.120", Score: 90, Level: core.LevelHostile, Jails: []string{"sshd"}}, // already
Seen{IP: "203.0.114.121", Score: 20, Level: core.LevelSuspicious}, // slow web
)
tal["203.0.114.121"] = Tally{Web: 25}
r := histRig(t, func(c *Config) {
c.MaxPerMin = 2
c.Roster = func(int64) []Seen { return roster }
c.Tallies = func(int64) map[string]Tally { return tal }
})
r.e.Sweep()
r.e.drain()
if n := len(r.lines(t)); n != 2 {
t.Fatalf("minute 1: %d lines", n)
}
r.now = r.now.Add(time.Minute)
r.e.drain()
r.now = r.now.Add(time.Minute)
r.e.drain()
r.now = r.now.Add(time.Minute)
r.e.drain()
ls := r.lines(t)
if len(ls) != 6 {
t.Fatalf("total %d: %v", len(ls), ls)
}
for _, l := range ls {
for _, bad := range []string{"168.196.85.7", "10.0.0.5", "203.0.114.120"} {
if contains(l, bad) {
t.Errorf("banned %s", bad)
}
}
}
if !contains(ls[len(ls)-1], "203.0.114.121") || !contains(ls[len(ls)-1], "scanner-flood") {
t.Errorf("last: %s", ls[len(ls)-1])
}
if r.e.counts.DroppedRate != 0 {
t.Errorf("cap must defer, not drop: %d", r.e.counts.DroppedRate)
}
}
func TestCoverageSurvivesRestart(t *testing.T) {
roster := []Seen{
{IP: "203.0.114.70", Jails: []string{"sshd"}},
{IP: "203.0.114.71", Jails: []string{"urutau"}},
{IP: "203.0.114.72"},
{IP: "203.0.114.73"},
}
cfg := func(c *Config) { c.Roster = func(int64) []Seen { return roster } }
r := histRig(t, cfg)
r.e.AcceptPeer("x", nil)
r.e.process(atk("203.0.114.72", r.now, "/.env", 200), "env-credentials")
// 72 gets banned by the engine (written decision), 73 stays unblocked.
r.e.mu.Lock()
r.e.bans[netip.MustParseAddr("203.0.114.72")] = banRec{Until: r.now.Add(time.Hour).Unix(), Last: r.now.Unix(), Offences: 1}
r.e.dirty = true
r.e.mu.Unlock()
r.e.saveState()
from := r.now.Add(-24 * time.Hour).Unix()
want := r.e.Report(from).Coverage
if want.AttackIPs != 4 || want.BlockedByFirewall != 1 || want.BlockedByUrutau != 2 || want.Unblocked != 1 {
t.Fatalf("coverage: %+v", want)
}
// restart: a new engine over the same state file and the same store
c := Config{Mode: ModeOn, Path: r.log, StatePath: r.e.cfg.StatePath, Host: "oracle", Now: func() time.Time { return r.now }}
cfg(&c)
e2 := New(c)
if got := e2.Report(from).Coverage; got != want {
t.Fatalf("after restart %+v want %+v", got, want)
}
}
func itoa(n int) string {
if n == 0 {
return "0"
}
s := ""
for ; n > 0; n /= 10 {
s = string(rune('0'+n%10)) + s
}
return s
}
+31 -14
View File
@@ -21,26 +21,27 @@ const (
// Fixed reason slugs. Anything else is refused (also from peers).
const (
ReasonScannerFlood = "scanner-flood"
ReasonExploitFlood = "exploit-flood"
ReasonWebBrute = "web-bruteforce"
ReasonWPBrute = "wp-bruteforce"
ReasonSSHBrute = "ssh-bruteforce"
ReasonRCE = "rce"
ReasonTraversal = "path-traversal"
ReasonEnvProbe = "env-probe"
ReasonVCSProbe = "vcs-probe"
ReasonWebshell = "webshell"
ReasonSQLi = "sqli"
ReasonLog4Shell = "log4shell"
ReasonPortScan = "port-scan"
ReasonScannerFlood = "scanner-flood"
ReasonExploitFlood = "exploit-flood"
ReasonWebBrute = "web-bruteforce"
ReasonWPBrute = "wp-bruteforce"
ReasonSSHBrute = "ssh-bruteforce"
ReasonRCE = "rce"
ReasonTraversal = "path-traversal"
ReasonEnvProbe = "env-probe"
ReasonVCSProbe = "vcs-probe"
ReasonWebshell = "webshell"
ReasonSQLi = "sqli"
ReasonLog4Shell = "log4shell"
ReasonPortScan = "port-scan"
ReasonKnownAttacker = "known-attacker"
)
var reasons = map[string]bool{
ReasonScannerFlood: true, ReasonExploitFlood: true, ReasonWebBrute: true, ReasonWPBrute: true,
ReasonSSHBrute: true, ReasonRCE: true, ReasonTraversal: true, ReasonEnvProbe: true,
ReasonVCSProbe: true, ReasonWebshell: true, ReasonSQLi: true, ReasonLog4Shell: true,
ReasonPortScan: true,
ReasonPortScan: true, ReasonKnownAttacker: true,
}
// ValidReason reports whether s is one of the fixed slugs.
@@ -66,6 +67,13 @@ const (
PortScanPorts = 10
// CritHits is how many critical events of one address (in Window) justify a ban.
CritHits = 2
// SSH24Threshold SSH failures, or Web24Threshold web scan/exploit events, in
// LongWindow justify a ban (slow attackers never cross the 10 minute rules).
SSH24Threshold = 10
Web24Threshold = 20
LongWindow = 24 * time.Hour
// KnownSuspiciousScore: a "suspicious" address at or above this score counts as a known attacker.
KnownSuspiciousScore = 100
)
// ttls is the advisory duration by number of previous bans.
@@ -116,6 +124,9 @@ type Input struct {
Banned bool // fail2ban already blocks it
Active bool // an advisory ban is still valid
Offences int
Known bool // the store's verdict is hostile (or suspicious with a high score)
SSH24 int // failed SSH logins in LongWindow
Web24 int // web scan/exploit events in LongWindow
}
// Params are the thresholds.
@@ -153,6 +164,12 @@ func Decide(in Input, p Params) Decision {
if !ValidReason(reason) {
reason = ReasonScannerFlood
}
case in.Known:
reason, score = ReasonKnownAttacker, 80
case in.SSH24 >= SSH24Threshold:
reason, score = ReasonSSHBrute, min(100, 60+(in.SSH24-SSH24Threshold))
case in.Web24 >= Web24Threshold:
reason, score = ReasonScannerFlood, min(100, 55+(in.Web24-Web24Threshold)/2)
default:
return Decision{}
}
+21
View File
@@ -11,8 +11,29 @@ import (
var (
torMu sync.RWMutex
torExits map[netip.Addr]struct{}
torRelay map[netip.Addr]struct{}
)
// SetTorRelays loads (or clears) the list of running Tor relays.
func SetTorRelays(addrs []netip.Addr) {
m := make(map[netip.Addr]struct{}, len(addrs))
for _, a := range addrs {
m[a.Unmap()] = struct{}{}
}
torMu.Lock()
torRelay = m
torMu.Unlock()
}
// IsTorRelay reports whether ip is a running Tor relay (exits included when the
// relay list carries them).
func IsTorRelay(ip netip.Addr) bool {
torMu.RLock()
defer torMu.RUnlock()
_, ok := torRelay[ip.Unmap()]
return ok
}
// SetTorExits loads (or clears, with nil/empty) the Tor exit list. It is off
// by default; the caller decides where the list comes from.
func SetTorExits(addrs []netip.Addr) {
+2 -1
View File
@@ -13,6 +13,7 @@ type integritySource struct {
Lines uint64 `json:"lines"`
Malformed uint64 `json:"malformed"`
Last int64 `json:"last"`
Error string `json:"error,omitempty"`
}
type integrityHost struct {
@@ -97,7 +98,7 @@ func (s *Server) integrity(w http.ResponseWriter, r *http.Request) {
}
continue
}
hh.Sources = append(hh.Sources, integritySource{Name: src.Name, State: src.State, Lines: src.Lines, Malformed: src.Malformed, Last: src.LastEvent})
hh.Sources = append(hh.Sources, integritySource{Name: src.Name, State: src.State, Lines: src.Lines, Malformed: src.Malformed, Last: src.LastEvent, Error: src.Error})
lines += src.Lines
bad += src.Malformed
if src.LastEvent > hh.LastEvent {
+4 -3
View File
@@ -63,12 +63,13 @@ func serviceItem(v store.SvcView, to int64) map[string]any {
if t.Req > 0 {
retries = float64(t.Retries) / float64(t.Req) * 100
}
spark := make([]uint32, 0, 48)
spark, errSpark := make([]uint32, 0, 48), make([]uint32, 0, 48)
for _, h := range v.Hours {
spark = append(spark, h.Req)
errSpark = append(errSpark, h.Cls[store.ClsApp]+h.Cls[store.ClsProxy])
}
if len(spark) > 48 {
spark = spark[len(spark)-48:]
spark, errSpark = spark[len(spark)-48:], errSpark[len(errSpark)-48:]
}
mix := map[string]uint32{}
for i, n := range store.ClsNames {
@@ -83,7 +84,7 @@ func serviceItem(v store.SvcView, to int64) map[string]any {
"p50": tri{q(t.Dur, .5), q(t.Org, .5), q(t.Ov, .5)},
"p95": tri{q(t.Dur, .95), q(t.Org, .95), q(t.Ov, .95)},
"p99": tri{q(t.Dur, .99), q(t.Org, .99), q(t.Ov, .99)},
"retries_pct": round(retries, 3), "mix": mix, "spark": spark,
"retries_pct": round(retries, 3), "mix": mix, "spark": spark, "err_spark": errSpark,
}
}
+7
View File
@@ -39,6 +39,13 @@ func TestServicesAndErrorsAPI(t *testing.T) {
if len(s) != 1 || s[0].(map[string]any)["svc"] != "r-app" {
t.Fatalf("services: %v", s)
}
var errSum float64
for _, n := range s[0].(map[string]any)["err_spark"].([]any) {
errSum += n.(float64)
}
if errSum != 1 { // the one application error, hour by hour
t.Fatalf("err_spark: %v", s[0])
}
d := getJSON(t, h, "/api/v1/services/r-app?range=24h", auth)
if d["histograms"] == nil || d["timeline"] == nil {
t.Fatalf("service: %v", d)
+1 -1
View File
@@ -224,7 +224,7 @@
function countryLabel(cc) { return (flag(cc) + ' ' + countryName(cc)).trim(); }
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_STATES = ['following', 'waiting', 'backfill', 'error', 'degraded', 'disabled'];
var KNOWN_LEVELS = ['hostile', 'suspicious', 'low'];
var KNOWN_TONES = ['neutral', 'ok', 'warn', 'danger', 'info'];
var CHART_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban'];
+2
View File
@@ -114,6 +114,7 @@
'df.en.reason.sqli': 'Attempt to tamper with the database (SQL injection)',
'df.en.reason.log4shell': 'Log4Shell exploit attempt',
'df.en.reason.port-scan': 'Scanning many network ports on the server',
'df.en.reason.known-attacker': 'Known attacker returning (hostile verdict)',
'df.en.error': 'Could not load the second firewall data.'
},
'pt-BR': {
@@ -219,6 +220,7 @@
'df.en.reason.sqli': 'Tentativa de adulterar o banco de dados (injeção de SQL)',
'df.en.reason.log4shell': 'Tentativa de explorar o Log4Shell',
'df.en.reason.port-scan': 'Varredura de muitas portas de rede do servidor',
'df.en.reason.known-attacker': 'Atacante conhecido voltando (veredito hostil)',
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.'
}
});
+27 -2
View File
@@ -11,8 +11,8 @@
var SEV = { high: 0, medium: 1, low: 2 };
var SEV_NAME = ['high', 'medium', 'low'];
var SEV_TONE = { high: 'danger', medium: 'warn', low: 'info' };
var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', 'new_geo'];
var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.eg_baddst', dns_bypass: 'term.dot', new_geo: 'term.new_geo' };
var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', 'new_geo', 'tor'];
var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.eg_baddst', dns_bypass: 'term.dot', new_geo: 'term.new_geo', tor: 'term.tor' };
var LAT_TOP = 84, LAT_SPAN = 142;
function boot() {
@@ -58,6 +58,11 @@
'eg.kind.bad_dst': 'Known-bad destination',
'eg.kind.dns_bypass': 'DNS outside the resolver',
'eg.kind.new_geo': 'New country',
'eg.kind.tor': 'Talking to the Tor network',
'eg.why.tor': 'The workload connected to a relay of the Tor network (anonymous routing). On a server this is common in malware, command-and-control and data exfiltration.',
'eg.do.tor': 'Find the process that opened the connection. Unless Tor is intended on this server, treat it as compromised and rebuild it from a clean image.',
'eg.infra': 'Regular connections with provider services ({n})',
'eg.infra.hint': 'Not counted as findings: the host talking to its own cloud provider (agents, metadata, updates).',
'eg.why.beacon': 'The workload talks to the same destination at regular intervals, like a clock. This is the typical pattern of malware checking in with its controller.',
'eg.why.scan': 'The workload tried to connect to many different addresses in a short time. A server that scans the internet usually means it was taken over.',
'eg.why.port': 'Connection to a port used by mining pools or remote-control tools, which normal software on this server does not use.',
@@ -167,6 +172,11 @@
'eg.kind.bad_dst': 'Destino sabidamente ruim',
'eg.kind.dns_bypass': 'DNS fora do resolvedor',
'eg.kind.new_geo': 'País novo',
'eg.kind.tor': 'Conversa com a rede Tor',
'eg.why.tor': 'O workload conectou a um relay da rede Tor (roteamento anônimo). Em um servidor isso é comum em malware, comando e controle e exfiltração de dados.',
'eg.do.tor': 'Descubra o processo que abriu a conexão. Se o Tor não é esperado neste servidor, trate-o como comprometido e reconstrua a partir de uma imagem limpa.',
'eg.infra': 'Conexões regulares com serviços do provedor ({n})',
'eg.infra.hint': 'Não contam como achados: o servidor falando com a própria nuvem (agentes, metadados, atualizações).',
'eg.why.beacon': 'O workload fala com o mesmo destino em intervalos regulares, como um relógio. É o padrão típico de um malware avisando seu controlador que está vivo.',
'eg.why.scan': 'O workload tentou conectar a muitos endereços diferentes em pouco tempo. Um servidor que varre a internet costuma ter sido invadido.',
'eg.why.port': 'Conexão a uma porta usada por mineração de criptomoeda ou ferramentas de controle remoto, que os programas normais deste servidor não usam.',
@@ -274,6 +284,18 @@
el('div', { class: 'eg-v-txt' }, el('h2', null, title), el('p', null, sub), pills.firstChild ? pills : null, srcLine));
}
function infraLine(st) {
var box = el('details', { class: 'eg-infra hint' }, el('summary', { title: t('eg.infra.hint') }, t('eg.infra', { n: nf(st.infra.length) })));
var ul = el('ul', null);
st.infra.slice(0, 50).forEach(function (f) {
var li = el('li', { class: 'mono' }, (f.workload || '-') + ' → ' + (f.dst || '-') + (f.dport ? ':' + f.dport : ''));
if (f.detail) li.appendChild(el('span', null, ' · ' + f.detail));
ul.appendChild(li);
});
box.appendChild(ul);
return box;
}
function kpis(st) {
var kp = el('div', { class: 'eg-kpis' });
kp.appendChild(U.ui.metric(t('eg.kpi.conns'), nf(st.conns), { sub: t('eg.kpi.conns.sub'), spark: st.total }));
@@ -482,6 +504,8 @@
// ------------------------------------------------------------ paint
function stats(d) {
var st = { wls: d.workloads || [], fnd: (d.findings || []).slice(), dsts: d.top_dst || [], bursts: (d.scanner && d.scanner.bursts) || [], tl: d.timeline || {} };
st.infra = st.fnd.filter(function (f) { return f.severity === 'info' || f.kind === 'infra'; });
st.fnd = st.fnd.filter(function (f) { return f.severity !== 'info' && f.kind !== 'infra'; });
st.fnd.sort(function (a, b) { return SEV[sevOf(a)] - SEV[sevOf(b)] || (b.last || 0) - (a.last || 0); });
st.ser = st.tl.series || {};
st.conns = 0; st.active = 0; st.sev = { high: 0, medium: 0, low: 0 };
@@ -516,6 +540,7 @@
var st = stats(data), range = U.rangeLabel({ inline: true });
root.appendChild(verdict(data, st, range));
root.appendChild(kpis(st));
if (st.infra.length) root.appendChild(infraLine(st));
var grid = el('div', { class: 'grid-12' });
var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12' });
+6
View File
@@ -243,6 +243,7 @@ window.URUTAU_I18N = {
'state.waiting': 'waiting for file',
'state.backfill': 'reading history',
'state.error': 'error',
'state.degraded': 'degraded',
'state.disabled': 'disabled',
'cat.ok': 'ok',
'cat.notfound': 'Nonexistent page (404)',
@@ -468,6 +469,8 @@ window.URUTAU_I18N = {
'help.term.authorized_scanner.do': 'Make sure it only aims at targets you own or may test.',
'help.term.ban_ttl': 'Block duration (TTL): how long an address stays blocked before being released. Repeat offenders get longer blocks.',
'help.term.ban_ttl.do': 'Short blocks are safer against mistakes; long ones stop persistent attackers.',
'help.term.tor': 'Tor is a network that hides who is connecting. Some visitors use it for privacy, but attackers also use it to hide. An origin marked Tor is a Tor exit; a server of yours talking to Tor relays is suspicious.',
'help.term.tor.do': 'Treat requests from Tor with caution (do not trust them for sensitive actions). If one of your servers connects to Tor and you did not set that up, investigate it.',
'help.term.new_geo': 'New country: the workload connected to a country it had not reached before in this window.',
'help.term.new_geo.do': 'Check whether the destination is a service you use.',
'help.term.error_class.app': 'Errors caused by your own application (5xx coming from the app).',
@@ -742,6 +745,7 @@ window.URUTAU_I18N = {
'state.waiting': 'aguardando arquivo',
'state.backfill': 'lendo histórico',
'state.error': 'erro',
'state.degraded': 'degradada',
'state.disabled': 'desativada',
'cat.ok': 'ok',
'cat.notfound': 'Página inexistente (404)',
@@ -967,6 +971,8 @@ window.URUTAU_I18N = {
'help.term.authorized_scanner.do': 'Garanta que ele só mire alvos seus ou que você pode testar.',
'help.term.ban_ttl': 'Duração do bloqueio (TTL): por quanto tempo o endereço fica bloqueado antes de ser liberado. Reincidentes recebem bloqueios mais longos.',
'help.term.ban_ttl.do': 'Bloqueios curtos são mais seguros contra enganos; longos barram atacantes persistentes.',
'help.term.tor': 'Tor é uma rede que esconde quem está conectando. Algumas pessoas usam por privacidade, mas atacantes também usam para se esconder. Origem marcada como Tor é uma saída Tor; um servidor seu falando com relays Tor é suspeito.',
'help.term.tor.do': 'Trate requisições vindas do Tor com cautela (não confie nelas em ações sensíveis). Se um servidor seu conecta ao Tor e você não configurou isso, investigue.',
'help.term.new_geo': 'País novo: o workload conectou a um país que ainda não tinha alcançado nesta janela.',
'help.term.new_geo.do': 'Confira se o destino é um serviço que você usa.',
'help.term.error_class.app': 'Erros causados pela sua própria aplicação (5xx vindos do app).',
+6 -4
View File
@@ -5,7 +5,7 @@
(function () {
'use strict';
var STATES = { following: 1, waiting: 1, backfill: 1, error: 1, disabled: 1 };
var STATES = { following: 1, waiting: 1, backfill: 1, error: 1, degraded: 1, disabled: 1 };
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3 4 6v6c0 4.5 3.2 7.8 8 9 4.8-1.2 8-4.5 8-9V6l-8-3z"/><path d="m9 12 2 2 4-4"/></svg>';
function boot() {
@@ -44,6 +44,7 @@
'ig.state.waiting': 'waiting',
'ig.state.backfill': 'catching up',
'ig.state.error': 'error',
'ig.state.degraded': 'degraded',
'ig.state.disabled': 'disabled',
'ig.peers.title': 'Peers',
'ig.peers.none': 'No peers configured.',
@@ -96,6 +97,7 @@
'ig.state.waiting': 'aguardando',
'ig.state.backfill': 'recuperando',
'ig.state.error': 'erro',
'ig.state.degraded': 'degradada',
'ig.state.disabled': 'desativada',
'ig.peers.title': 'Peers',
'ig.peers.none': 'Nenhum peer configurado.',
@@ -172,7 +174,7 @@
hosts.forEach(function (x) {
gaps += (x.gaps || []).length;
if (x.online) onlineN++;
(x.sources || []).forEach(function (s) { lines += s.lines; bad += s.malformed; if (s.state === 'error') errors++; });
(x.sources || []).forEach(function (s) { lines += s.lines; bad += s.malformed; if (s.state === 'error' || s.state === 'degraded') errors++; });
});
var offline = peers.filter(function (p) { return !p.online; }).length;
var rate = lines + bad > 0 ? bad / (lines + bad) : 0;
@@ -233,8 +235,8 @@
var rows = [];
hosts.forEach(function (x) {
(x.sources || []).forEach(function (s) {
var tone = s.state === 'error' ? 'danger' : s.state === 'following' ? 'ok' : 'neutral';
rows.push([x.name, s.name, U.ui.badge(STATES[s.state] ? t('ig.state.' + s.state) : String(s.state || ''), tone), nf(s.lines), nf(s.malformed), s.last ? U.fmt.ago(s.last) : '-']);
var tone = (s.state === 'error' || s.state === 'degraded') ? 'danger' : s.state === 'following' ? 'ok' : 'neutral';
rows.push([x.name, s.name, U.ui.badge(STATES[s.state] ? t('ig.state.' + s.state) + (s.state === 'degraded' && s.error ? ' (' + s.error + ')' : '') : String(s.state || ''), tone), nf(s.lines), nf(s.malformed), s.last ? U.fmt.ago(s.last) : '-']);
});
});
sp2.body.appendChild(rows.length ? table([t('ig.src.host'), t('ig.src.name'), t('ig.src.state'), t('ig.src.lines'), t('ig.src.bad'), t('ig.src.last')], rows) : U.ui.empty(t('ig.src.none')));
+4 -2
View File
@@ -124,7 +124,7 @@
'ip.ntr.asn': 'known ASN {v}',
'ip.ntr.asorg': 'organization name contains "{v}"',
'ip.ntr.rdns': 'reverse DNS contains "{v}"',
'ip.ntr.tor': 'listed as a Tor exit node',
'ip.ntr.tor': 'listed as a Tor exit node (official list)',
'ip.untrusted': 'text sent by the attacker',
'ip.act.copy': 'Copy IP',
'ip.act.ioc': 'Copy as IOC',
@@ -1010,7 +1010,9 @@
box.appendChild(chip('ip.id.rdns', rv));
if (id.net_type) {
var nt = pick(NETTYPES, id.net_type, 'unknown'), why = ntReason(id.net_type_reason);
box.appendChild(chip('ip.id.nettype', h('span', null, badge(t('ip.nt.' + nt.replace('/', '-')), NT_TONE[nt]), why ? h('small', 'ipx-faint ipx-why', ' ' + why) : null)));
var ntw = h('span', null, badge(t('ip.nt.' + nt.replace('/', '-')), NT_TONE[nt]), why ? h('small', 'ipx-faint ipx-why', ' ' + why) : null);
if (nt === 'tor' && U.help) U.help(ntw, 'term.tor');
box.appendChild(chip('ip.id.nettype', ntw));
}
if (id.prefix) box.appendChild(chip('ip.id.prefix', h('span', 'ipx-mono', clip(id.prefix, 50))));
return box;
+98 -30
View File
@@ -1,31 +1,99 @@
/* Services (SLO) page */
.hl-cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--grid-gap, 16px); }
.hl-card { border: 1px solid var(--line); border-radius: var(--radius); padding: var(--s-4, 14px); background: var(--surface-raised); display: grid; gap: 8px; min-width: 0; border-top: 3px solid var(--ok); }
.hl-card.tone-warn { border-top-color: var(--warn); }
.hl-card.tone-danger { border-top-color: var(--danger); }
.hl-card header { display: grid; gap: 2px; min-width: 0; }
.hl-name { margin: 0; font-size: 1rem; overflow-wrap: anywhere; color: var(--heading); }
.hl-svc { color: var(--ink-faint); font-size: .75rem; overflow-wrap: anywhere; }
.hl-big { font: 600 1.75rem var(--font-display); color: var(--heading); display: flex; align-items: baseline; gap: 8px; }
.hl-big small { font: 500 .75rem var(--font-sans); color: var(--ink-muted); }
.hl-bar { height: 6px; border-radius: 3px; background: var(--surface-sunken); overflow: hidden; }
.hl-bar i { display: block; height: 100%; background: var(--ok); }
.tone-warn .hl-bar i { background: var(--warn); } .tone-danger .hl-bar i { background: var(--danger); }
.hl-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; }
.hl-st { display: grid; min-width: 0; }
.hl-sv { font-weight: 600; font-size: .9375rem; color: var(--ink); }
.hl-sl { font-size: .6875rem; color: var(--ink-muted); }
.hl-spark { height: 28px; color: var(--accent); }
.hl-spark svg { width: 100%; height: 100%; fill: none; stroke: currentColor; stroke-width: 1.5; }
.hl-card footer { font-size: .75rem; color: var(--ink-muted); }
.hl-bands { display: grid; gap: var(--s-4, 14px); }
.hl-bgrp h4 { margin: 0 0 4px; font-size: .875rem; color: var(--heading); overflow-wrap: anywhere; }
.hl-brow { display: grid; grid-template-columns: 34px repeat(3, minmax(0, 1fr)); gap: 8px; align-items: center; margin: 2px 0; }
.hl-bq { font-size: .75rem; color: var(--ink-muted); }
.hl-btrack { position: relative; display: block; height: 16px; background: var(--surface-sunken); border-radius: 3px; overflow: hidden; }
.hl-btrack i { display: block; height: 100%; opacity: .85; }
.hl-btrack b { position: absolute; left: 6px; top: 0; font-weight: 500; font-size: .6875rem; line-height: 16px; color: var(--ink); }
.hl-legend { display: flex; gap: 14px; font-size: .75rem; color: var(--ink-muted); }
.hl-legend i { display: inline-block; width: 10px; height: 10px; border-radius: 2px; margin-right: 5px; }
.hl-page .panel { min-width: 0; }
@media (max-width: 900px) { .hl-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
.sl-page { display: grid; gap: var(--grid-gap, 16px); min-width: 0; }
.sl-page .panel, .sl-page .card-metric { min-width: 0; }
.sl-top { display: grid; gap: var(--grid-gap, 16px); min-width: 0; }
/* verdict */
.sl-verdict { --tn: var(--ok); --tn-soft: var(--ok-soft); display: flex; gap: 18px; align-items: flex-start; padding: 20px 22px; border: 1px solid color-mix(in srgb, var(--tn) 45%, var(--line)); border-radius: 14px;
background: linear-gradient(120deg, var(--tn-soft), var(--surface-raised) 70%); min-width: 0; }
.sl-verdict.tone-danger { --tn: var(--danger); --tn-soft: var(--danger-soft); }
.sl-verdict.tone-warn { --tn: var(--warn); --tn-soft: var(--warn-soft); }
.sl-verdict.tone-neutral { --tn: var(--ink-faint); --tn-soft: var(--surface-raised); }
.sl-v-ico { flex: none; width: 52px; height: 52px; border-radius: 50%; display: grid; place-items: center; font-size: 1.6rem; font-weight: 800; color: var(--surface-base); background: var(--tn);
box-shadow: 0 0 0 6px color-mix(in srgb, var(--tn) 18%, transparent); }
.sl-v-txt { min-width: 0; display: grid; gap: 6px; }
.sl-v-txt h2 { margin: 0; font-size: 1.5rem; line-height: 1.2; color: var(--ink); }
.sl-v-txt > p { margin: 0; color: var(--ink-muted); overflow-wrap: anywhere; }
.sl-v-pills { display: flex; flex-wrap: wrap; gap: 6px; }
.sl-kpis { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: var(--grid-gap, 16px); }
/* service list */
.sl-list { display: grid; min-width: 0; }
.sl-row { --tn: var(--ok); display: grid; grid-template-columns: minmax(150px, 1.6fr) minmax(86px, .8fr) minmax(130px, 1.2fr) minmax(90px, .8fr) minmax(56px, .5fr) minmax(80px, .7fr) minmax(64px, .6fr) minmax(90px, 1fr);
gap: 12px; align-items: center; padding: 10px 14px 10px 16px; border: 0; border-bottom: 1px solid var(--line); background: transparent; color: inherit; font: inherit; text-align: left; width: 100%; position: relative; min-width: 0; cursor: pointer; }
.sl-row::before { content: ""; position: absolute; inset: 6px auto 6px 0; width: 3px; border-radius: 2px; background: var(--tn); }
.sl-row.tone-warn { --tn: var(--warn); } .sl-row.tone-danger { --tn: var(--danger); }
.sl-row:hover { background: var(--surface-raised); }
.sl-row:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.sl-row.is-sel { background: color-mix(in srgb, var(--accent) 9%, var(--surface-raised)); }
.sl-head { cursor: default; padding-top: 6px; padding-bottom: 6px; font-size: .6875rem; text-transform: uppercase; letter-spacing: .05em; color: var(--ink-faint); }
.sl-head::before { display: none; } .sl-head:hover { background: transparent; }
.sl-head .sl-c > span { display: inline-flex; align-items: center; gap: 4px; }
.sl-c { display: grid; gap: 2px; min-width: 0; }
.sl-c strong { font-weight: 600; color: var(--ink); }
.sl-c small { font-size: .75rem; color: var(--ink-faint); overflow-wrap: anywhere; }
.sl-c-svc { grid-template-columns: auto minmax(0, 1fr); align-items: center; gap: 10px; }
.sl-name { display: grid; min-width: 0; }
.sl-name strong { overflow-wrap: anywhere; color: var(--heading); }
.sl-dot { width: 10px; height: 10px; border-radius: 50%; background: var(--tn, var(--ok)); box-shadow: 0 0 0 3px color-mix(in srgb, var(--tn, var(--ok)) 22%, transparent); }
.sl-c-inline { display: flex; align-items: baseline; gap: 4px; }
.sl-sep { color: var(--ink-faint); }
.sl-burn { font-weight: 600; color: var(--ink-muted); }
.is-warn { color: var(--warn) !important; } .is-danger { color: var(--danger) !important; }
.sl-bar { display: block; height: 8px; border-radius: 4px; background: var(--surface-sunken); overflow: hidden; }
.sl-bar i { display: block; height: 100%; border-radius: 4px; background: var(--tn); }
.sl-c-trend { height: 28px; color: var(--danger); }
.sl-c-trend svg { width: 100%; height: 100%; fill: none; stroke: currentColor; stroke-width: 1.5; }
.sl-flat { display: block; height: 1px; margin-top: 14px; background: var(--line-strong); }
/* detail */
.sl-detail-wrap { display: grid; gap: var(--grid-gap, 16px); min-width: 0; scroll-margin-top: 80px; }
.sl-dhead { --tn: var(--ok); display: flex; flex-wrap: wrap; align-items: center; gap: 10px 16px; padding: 14px 18px; border: 1px solid var(--line); border-left: 4px solid var(--tn); border-radius: 12px; background: var(--surface-raised); min-width: 0; }
.sl-dhead.tone-warn { --tn: var(--warn); } .sl-dhead.tone-danger { --tn: var(--danger); }
.sl-dtitle { min-width: 0; flex: 1 1 240px; }
.sl-dtitle h2 { margin: 0; font-size: 1.125rem; overflow-wrap: anywhere; color: var(--heading); }
.sl-dtitle .hint { margin: 2px 0 0; }
.sl-dfacts { display: flex; flex-wrap: wrap; gap: 8px; }
.sl-dfacts > span { display: grid; padding: 6px 12px; border-radius: 8px; background: var(--surface-panel); border: 1px solid var(--line); min-width: 0; }
.sl-dfacts b { font-size: 1.05rem; }
.sl-dfacts small { font-size: .75rem; color: var(--ink-faint); display: inline-flex; align-items: center; gap: 4px; }
.sl-dgrid .panel { min-width: 0; }
.sl-p95 { width: 100%; height: 120px; display: block; background: var(--surface-sunken); border-radius: 8px; }
.sl-p95-a { fill: color-mix(in srgb, var(--viz-1) 22%, transparent); }
.sl-p95-l { fill: none; stroke: var(--viz-1); stroke-width: 2; vector-effect: non-scaling-stroke; }
.sl-groups { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
.sl-grp { --g: var(--danger); min-width: 0; display: grid; align-content: start; gap: 6px; }
.sl-grp-atk { --g: var(--info); } .sl-grp-cli { --g: var(--ink-faint); }
.sl-grp h4 { margin: 0; }
.sl-grp .hint { margin: 0; font-size: .75rem; }
.sl-routes { list-style: none; margin: 4px 0 0; padding: 0; display: grid; gap: 8px; }
.sl-routes li { display: grid; gap: 3px; min-width: 0; }
.sl-rt { display: flex; justify-content: space-between; gap: 8px; min-width: 0; }
.sl-rt code { overflow-wrap: anywhere; font-size: .8125rem; color: var(--ink); min-width: 0; }
.sl-rbar { display: block; height: 5px; border-radius: 3px; background: var(--surface-sunken); overflow: hidden; }
.sl-rbar i { display: block; height: 100%; background: var(--g); }
.sl-routes small { font-size: .6875rem; color: var(--ink-faint); }
.sl-none { margin: 4px 0 0; color: var(--ink-faint); font-size: .8125rem; }
@media (max-width: 1100px) {
.sl-row { grid-template-columns: minmax(0, 1.4fr) repeat(3, minmax(0, 1fr)); row-gap: 10px; }
.sl-head { display: none; }
.sl-row .sl-c:not(.sl-c-svc)::before { content: attr(data-l); font-size: .625rem; text-transform: uppercase; letter-spacing: .04em; color: var(--ink-faint); }
.sl-c-inline { display: grid; grid-template-columns: auto auto auto; justify-content: start; align-items: baseline; column-gap: 4px; }
.sl-c-inline::before { grid-column: 1 / -1; }
.sl-c-trend { height: auto; } .sl-c-trend svg { height: 24px; }
}
@media (max-width: 900px) {
.sl-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.sl-groups { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 560px) {
.sl-row { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 10px 12px 14px; }
.sl-c-svc, .sl-c-budget { grid-column: 1 / -1; }
.sl-verdict { padding: 16px; gap: 12px; } .sl-v-ico { width: 40px; height: 40px; font-size: 1.2rem; }
.sl-v-txt h2 { font-size: 1.2rem; }
}
/* the service list grows with its rows (the shared .card-list keeps a fixed height and would cut the last one) */
.sl-page .card-list .panel-b { height: auto; overflow: visible; }
.sl-head .sl-c { padding-right: 18px; }
+249 -112
View File
@@ -1,150 +1,287 @@
/* Urutau - page SLO ("Services"): one card per backend service with its SLI, error budget,
Apdex, p95 latency and traffic; latency bands (total, origin, proxy) and a profile radar.
Data: /api/v1/services. Log data is hostile: textContent only. */
/* Urutau - page SLO ("Services"): a plain-words verdict, KPIs, a scannable list of the
backend services (worst first: availability vs the 99.5% objective, error budget, burn
rate, Apdex, p50/p95, req/s, error trend) and the detail of the selected service
(requests vs errors over time, p95, answer mix, failing routes split between real
service errors and blocked attacks).
Data: /api/v1/services and /api/v1/services/{svc}. Log data is hostile: textContent only. */
(function () {
'use strict';
var U = window.Urutau;
if (!U || !U.registerPage) return;
var el = U.el, t = U.t;
var SLO = 0.995, LANG = 'en';
U.registerI18n({
en: {
'hl.sl.title': 'Services',
'hl.sl.lead': '{n} services, {ok} within their objective',
'hl.sl.lead.body': 'Objective: 99.5% of legitimate requests without an application or proxy error. {worst} has the least budget left ({budget}) {range}.',
'hl.sl.lead.body.all': 'Objective: 99.5% of legitimate requests without an application or proxy error, {range}.',
'hl.sl.lead.empty': 'No services seen yet',
'hl.sl.lead.empty.body': 'No Traefik requests with service data {range}.',
'hl.sl.cards': 'Service health', 'hl.sl.cards.hint': 'SLI is the share of legitimate requests answered without an application or proxy error.',
'hl.sl.sli': 'SLI', 'hl.sl.budget': 'Budget left', 'hl.sl.apdex': 'Apdex', 'hl.sl.p95': 'p95', 'hl.sl.rps': 'peak req/s', 'hl.sl.burn': 'Burn 1h',
'hl.sl.req': '{n} requests',
'hl.sl.bands': 'Latency bands', 'hl.sl.bands.hint': 'p50, p95 and p99 of the total time, the backend time and the proxy overhead (ms), for the busiest services.',
'hl.sl.band.total': 'Total', 'hl.sl.band.origin': 'Backend', 'hl.sl.band.overhead': 'Proxy',
'hl.sl.radar': 'Profile', 'hl.sl.radar.hint': 'Each axis is scaled to the best service: availability, Apdex, speed (p95), retries and traffic.',
'hl.sl.ax.avail': 'Availability', 'hl.sl.ax.apdex': 'Apdex', 'hl.sl.ax.speed': 'Speed', 'hl.sl.ax.retry': 'No retries', 'hl.sl.ax.traffic': 'Traffic',
'hl.sl.err': 'Could not load the services.', 'hl.sl.retry': 'Try again', 'hl.sl.empty': 'Nothing to show for this range.'
'hl.sl.v.ok': 'All services healthy',
'hl.sl.v.ok.sub': '{n} services {range}, all within the 99.5% availability objective. {req} legitimate requests answered.',
'hl.sl.v.bad.1': '1 service burning its error budget',
'hl.sl.v.bad.n': '{n} services burning their error budget',
'hl.sl.v.bad.sub': '{worst} is the most affected: {sli} of requests answered without error {range}, against an objective of 99.5%. Start with the first row below.',
'hl.sl.v.out.1': '1 service broke its objective',
'hl.sl.v.out.n': '{n} services broke their objective',
'hl.sl.v.none': 'No services seen yet',
'hl.sl.v.none.sub': 'No Traefik requests with service data {range}.',
'hl.sl.pill.out': '{n} out of budget', 'hl.sl.pill.burn': '{n} burning', 'hl.sl.pill.ok': '{n} healthy',
'hl.sl.kpi.avail': 'Availability', 'hl.sl.kpi.avail.sub': 'all services · objective 99.5%',
'hl.sl.kpi.err': 'Service errors', 'hl.sl.kpi.err.sub': '{a} blocked attacks are not counted',
'hl.sl.kpi.p95': 'Latency p95', 'hl.sl.kpi.p95.sub': 'typical {p50} · slowest service',
'hl.sl.kpi.req': 'Requests', 'hl.sl.kpi.req.sub': 'peak {rps} req/s',
'hl.sl.list': 'Services, worst first', 'hl.sl.list.hint': 'Click a service to see its detail. The bar is the error budget still left in this window.',
'hl.sl.col.svc': 'Service', 'hl.sl.col.avail': 'Availability', 'hl.sl.col.budget': 'Error budget', 'hl.sl.col.burn': 'Burn 1h / 6h',
'hl.sl.col.apdex': 'Apdex', 'hl.sl.col.lat': 'p95 / p50', 'hl.sl.col.rps': 'Peak req/s', 'hl.sl.col.trend': 'Errors per hour',
'hl.sl.st.ok': 'Healthy', 'hl.sl.st.warn': 'Burning', 'hl.sl.st.danger': 'Out of budget',
'hl.sl.left': '{p} left',
'hl.sl.detail': 'Detail: {s}', 'hl.sl.detail.hint': 'Everything below is about the selected service, {range}.',
'hl.sl.d.series': 'Requests and service errors', 'hl.sl.d.ok': 'Answered', 'hl.sl.d.errors': 'Service errors',
'hl.sl.d.p95': 'Latency p95 per hour', 'hl.sl.d.p95.max': 'Worst hour: {v}.',
'hl.sl.d.mix': 'How requests were answered',
'hl.sl.mix.ok': 'Success', 'hl.sl.mix.app': 'Application error', 'hl.sl.mix.proxy': 'Proxy error', 'hl.sl.mix.blocked': 'Blocked', 'hl.sl.mix.attack': 'Attack answered', 'hl.sl.mix.bot': 'Bot', 'hl.sl.mix.client': 'Client error',
'hl.sl.d.routes': 'Routes that fail',
'hl.sl.g.svc': 'Service errors', 'hl.sl.g.svc.sub': 'The service itself failed: these consume the error budget.',
'hl.sl.g.atk': 'Attacks and bots stopped', 'hl.sl.g.atk.sub': 'Probes and blocked requests: noise, not counted against the objective.',
'hl.sl.g.cli': 'Client mistakes', 'hl.sl.g.cli.sub': 'Broken links and bad requests from legitimate clients.',
'hl.sl.g.none': 'None in this window.',
'hl.sl.err': 'Could not load the services.', 'hl.sl.retry': 'Try again', 'hl.sl.empty': 'Nothing to show for this range.',
'help.term.burn_rate': 'Burn rate: how fast the error budget is being spent. 1 means exactly on pace to use it all by the end of the period; 10 means ten times too fast.',
'help.term.burn_rate.do': 'Above 2 for an hour, look at the service errors now; above 10, treat it as an incident.',
'help.term.p95': 'p95: 95% of the requests were answered within this time; only the slowest 5% took longer. p50 is the typical request.',
'help.term.p95.do': 'A high p95 with a normal p50 points to a few slow routes or a slow dependency.'
},
'pt-BR': {
'hl.sl.title': 'Serviços',
'hl.sl.lead': '{n} serviços, {ok} dentro do objetivo',
'hl.sl.lead.body': 'Objetivo: 99,5% das requisições legítimas sem erro de aplicação ou de proxy. {worst} tem o menor orçamento restante ({budget}) {range}.',
'hl.sl.lead.body.all': 'Objetivo: 99,5% das requisições legítimas sem erro de aplicação ou de proxy, {range}.',
'hl.sl.lead.empty': 'Nenhum serviço visto ainda',
'hl.sl.lead.empty.body': 'Nenhuma requisição do Traefik com dados de serviço {range}.',
'hl.sl.cards': 'Saúde dos serviços', 'hl.sl.cards.hint': 'O SLI é a parcela das requisições legítimas respondidas sem erro de aplicação ou de proxy.',
'hl.sl.sli': 'SLI', 'hl.sl.budget': 'Orçamento restante', 'hl.sl.apdex': 'Apdex', 'hl.sl.p95': 'p95', 'hl.sl.rps': 'pico req/s', 'hl.sl.burn': 'Consumo 1h',
'hl.sl.req': '{n} requisições',
'hl.sl.bands': 'Faixas de latência', 'hl.sl.bands.hint': 'p50, p95 e p99 do tempo total, do tempo no backend e da sobrecarga do proxy (ms), nos serviços mais ocupados.',
'hl.sl.band.total': 'Total', 'hl.sl.band.origin': 'Backend', 'hl.sl.band.overhead': 'Proxy',
'hl.sl.radar': 'Perfil', 'hl.sl.radar.hint': 'Cada eixo é relativo ao melhor serviço: disponibilidade, Apdex, rapidez (p95), retentativas e tráfego.',
'hl.sl.ax.avail': 'Disponibilidade', 'hl.sl.ax.apdex': 'Apdex', 'hl.sl.ax.speed': 'Rapidez', 'hl.sl.ax.retry': 'Sem retentativas', 'hl.sl.ax.traffic': 'Tráfego',
'hl.sl.err': 'Não foi possível carregar os serviços.', 'hl.sl.retry': 'Tentar de novo', 'hl.sl.empty': 'Nada para mostrar neste período.'
'hl.sl.v.ok': 'Todos os serviços saudáveis',
'hl.sl.v.ok.sub': '{n} serviços {range}, todos dentro do objetivo de 99,5% de disponibilidade. {req} requisições legítimas atendidas.',
'hl.sl.v.bad.1': '1 serviço consumindo o orçamento de erro',
'hl.sl.v.bad.n': '{n} serviços consumindo o orçamento de erro',
'hl.sl.v.bad.sub': '{worst} é o mais afetado: {sli} das requisições atendidas sem erro {range}, contra um objetivo de 99,5%. Comece pela primeira linha abaixo.',
'hl.sl.v.out.1': '1 serviço estourou o objetivo',
'hl.sl.v.out.n': '{n} serviços estouraram o objetivo',
'hl.sl.v.none': 'Nenhum serviço visto ainda',
'hl.sl.v.none.sub': 'Nenhuma requisição do Traefik com dados de serviço {range}.',
'hl.sl.pill.out': '{n} sem orçamento', 'hl.sl.pill.burn': '{n} consumindo', 'hl.sl.pill.ok': '{n} saudáveis',
'hl.sl.kpi.avail': 'Disponibilidade', 'hl.sl.kpi.avail.sub': 'todos os serviços · objetivo 99,5%',
'hl.sl.kpi.err': 'Erros do serviço', 'hl.sl.kpi.err.sub': '{a} ataques barrados não contam',
'hl.sl.kpi.p95': 'Latência p95', 'hl.sl.kpi.p95.sub': 'típica {p50} · serviço mais lento',
'hl.sl.kpi.req': 'Requisições', 'hl.sl.kpi.req.sub': 'pico de {rps} req/s',
'hl.sl.list': 'Serviços, dos piores para os melhores', 'hl.sl.list.hint': 'Clique num serviço para ver o detalhe. A barra é o orçamento de erro que ainda resta nesta janela.',
'hl.sl.col.svc': 'Serviço', 'hl.sl.col.avail': 'Disponibilidade', 'hl.sl.col.budget': 'Orçamento de erro', 'hl.sl.col.burn': 'Consumo 1h / 6h',
'hl.sl.col.apdex': 'Apdex', 'hl.sl.col.lat': 'p95 / p50', 'hl.sl.col.rps': 'Pico req/s', 'hl.sl.col.trend': 'Erros por hora',
'hl.sl.st.ok': 'Saudável', 'hl.sl.st.warn': 'Consumindo', 'hl.sl.st.danger': 'Sem orçamento',
'hl.sl.left': 'restam {p}',
'hl.sl.detail': 'Detalhe: {s}', 'hl.sl.detail.hint': 'Tudo abaixo é sobre o serviço selecionado, {range}.',
'hl.sl.d.series': 'Requisições e erros do serviço', 'hl.sl.d.ok': 'Atendidas', 'hl.sl.d.errors': 'Erros do serviço',
'hl.sl.d.p95': 'Latência p95 por hora', 'hl.sl.d.p95.max': 'Pior hora: {v}.',
'hl.sl.d.mix': 'Como as requisições foram respondidas',
'hl.sl.mix.ok': 'Sucesso', 'hl.sl.mix.app': 'Erro da aplicação', 'hl.sl.mix.proxy': 'Erro do proxy', 'hl.sl.mix.blocked': 'Bloqueada', 'hl.sl.mix.attack': 'Ataque respondido', 'hl.sl.mix.bot': 'Robô', 'hl.sl.mix.client': 'Erro do cliente',
'hl.sl.d.routes': 'Rotas que falham',
'hl.sl.g.svc': 'Erros do serviço', 'hl.sl.g.svc.sub': 'O próprio serviço falhou: estes consomem o orçamento de erro.',
'hl.sl.g.atk': 'Ataques e robôs barrados', 'hl.sl.g.atk.sub': 'Sondagens e pedidos bloqueados: ruído, não contam contra o objetivo.',
'hl.sl.g.cli': 'Enganos do cliente', 'hl.sl.g.cli.sub': 'Links quebrados e pedidos inválidos de clientes legítimos.',
'hl.sl.g.none': 'Nenhuma nesta janela.',
'hl.sl.err': 'Não foi possível carregar os serviços.', 'hl.sl.retry': 'Tentar de novo', 'hl.sl.empty': 'Nada para mostrar neste período.',
'help.term.burn_rate': 'Taxa de consumo: a velocidade com que o orçamento de erro está sendo gasto. 1 é o ritmo exato para gastá-lo todo até o fim do período; 10 é dez vezes rápido demais.',
'help.term.burn_rate.do': 'Acima de 2 por uma hora, olhe já os erros do serviço; acima de 10, trate como incidente.',
'help.term.p95': 'p95: 95% das requisições foram respondidas dentro deste tempo; só as 5% mais lentas demoraram mais. O p50 é a requisição típica.',
'help.term.p95.do': 'Um p95 alto com p50 normal aponta para poucas rotas lentas ou uma dependência lenta.'
}
});
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function ms(v) { return v >= 1000 ? (v / 1000).toFixed(v >= 10000 ? 0 : 1) + ' s' : (v >= 10 ? Math.round(v) : v.toFixed(1)) + ' ms'; }
function pct1(v) { return (v * 100).toFixed(v >= 0.9995 ? 2 : 1) + '%'; }
function tone(s) { return s.budget_left <= 0.1 || s.burn_1h >= 6 ? 'danger' : s.budget_left <= 0.5 || s.burn_1h >= 2 ? 'warn' : 'ok'; }
var MIX = [['ok', '--ok'], ['app', '--danger'], ['proxy', '--warn'], ['blocked', '--info'], ['attack', '--viz-5'], ['bot', '--viz-3'], ['client', '--ink-faint']];
function card(s) {
var tn = tone(s);
var spark = U.charts && U.charts.sparkline && s.spark && s.spark.length > 1 ? U.charts.sparkline(s.spark) : null;
var stat = function (label, value, key) {
var l = el('span', { class: 'hl-sl' }, label);
if (key && U.help && U.glossary && U.glossary.has(key)) U.help(l, key);
return el('div', { class: 'hl-st' }, el('span', { class: 'hl-sv num' }, value), l);
};
return el('article', { class: 'hl-card tone-' + tn },
el('header', null, el('h3', { class: 'hl-name' }, s.alias), el('span', { class: 'hl-svc mono' }, s.svc)),
el('div', { class: 'hl-big num' }, pct1(s.sli), el('small', null, t('hl.sl.sli'))),
el('div', { class: 'hl-bar', role: 'img', 'aria-label': t('hl.sl.budget') + ' ' + U.fmt.pct(s.budget_left) }, el('i', { style: { width: Math.round(s.budget_left * 100) + '%' } })),
el('div', { class: 'hl-stats' }, stat(t('hl.sl.budget'), U.fmt.pct(s.budget_left), 'term.error_budget'), stat(t('hl.sl.apdex'), s.apdex.toFixed(2), 'term.apdex'), stat(t('hl.sl.p95'), ms(s.p95.total)), stat(t('hl.sl.rps'), s.rps_peak.toFixed(2))),
spark ? el('div', { class: 'hl-spark' }, spark) : null,
el('footer', null, t('hl.sl.req', { n: U.fmt.num(s.req) })));
}
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
function nf(v) { return U.fmt.num(v); }
function dec(s) { return LANG === 'en' ? s : s.replace('.', ','); }
function ms(v) { return dec(v >= 1000 ? (v / 1000).toFixed(v >= 10000 ? 0 : 1) + ' s' : (v >= 10 ? Math.round(v) + '' : v.toFixed(1)) + ' ms'); }
function pct(v) { var p = v * 100; return dec(p >= 99.995 ? '100' : p.toFixed(p >= 99 ? 2 : 1)) + '%'; }
function fix(v, d) { return dec(v.toFixed(d)); }
function errs(s) { return (s.mix.app || 0) + (s.mix.proxy || 0); }
function legitOf(s) { return s.req - (s.mix.attack || 0) - (s.mix.blocked || 0) - (s.mix.bot || 0); }
function tone(s) { return s.budget_left <= 0 ? 'danger' : (s.budget_left < 1 || s.burn_1h >= 1) ? 'warn' : 'ok'; }
function rank(s) { return { danger: 0, warn: 1, ok: 2 }[tone(s)]; }
function withHelp(node, key) { if (U.help && U.glossary && U.glossary.has(key)) U.help(node, key); return node; }
function head(label, key) { var n = el('span', null, label); return key ? withHelp(n, key) : n; }
function sumArr(a, b) { var out = a.slice(); (b || []).forEach(function (v, i) { out[i] = (out[i] || 0) + v; }); return out; }
var inst = null;
function create(root, ctx) {
var seq = 0, alive = true, data = null, c = ctx;
var grid = el('div', { class: 'grid-12 hl-page' });
var lead = el('div', { class: 'span-12' });
var pc = U.ui.panel({ title: t('hl.sl.cards'), hint: t('hl.sl.cards.hint'), loading: true, cls: 'span-12' });
var pb = U.ui.panel({ title: t('hl.sl.bands'), hint: t('hl.sl.bands.hint'), variant: 'chart', loading: true, cls: 'span-8' });
var pr = U.ui.panel({ title: t('hl.sl.radar'), hint: t('hl.sl.radar.hint'), variant: 'chart', loading: true, cls: 'span-4' });
[lead, pc, pb, pr].forEach(function (n) { grid.appendChild(n); });
root.appendChild(grid);
var seq = 0, dseq = 0, alive = true, data = null, c = ctx, sel = null;
LANG = c.lang || 'en';
var page = el('div', { class: 'sl-page' });
var top = el('div', { class: 'sl-top' }, el('div', { class: 'skeleton' }));
var listP = U.ui.panel({ title: t('hl.sl.list'), hint: t('hl.sl.list.hint'), variant: 'list', help: 'term.slo' });
var detP = el('div', { class: 'sl-detail-wrap' });
page.appendChild(top); page.appendChild(listP); page.appendChild(detP);
root.appendChild(page);
function bands(list) {
var box = el('div', { class: 'hl-bands' });
var mx = 0; list.slice(0, 8).forEach(function (s) { ['p50', 'p95', 'p99'].forEach(function (q) { ['total', 'origin', 'overhead'].forEach(function (k) { if (s[q][k] > mx) mx = s[q][k]; }); }); });
list.slice(0, 8).forEach(function (s) {
var g = el('div', { class: 'hl-bgrp' }, el('h4', null, s.alias));
['p50', 'p95', 'p99'].forEach(function (q) {
var v = s[q];
var line = el('div', { class: 'hl-brow' }, el('span', { class: 'hl-bq' }, q));
[['total', 'hl.sl.band.total', '--viz-1'], ['origin', 'hl.sl.band.origin', '--viz-3'], ['overhead', 'hl.sl.band.overhead', '--viz-5']].forEach(function (p) {
var w = mx ? Math.max(v[p[0]] > 0 ? 1.5 : 0, v[p[0]] / mx * 100) : 0;
var i = el('i', { style: { width: w + '%', background: 'var(' + p[2] + ')' } });
i.title = t(p[1]) + ' ' + ms(v[p[0]]);
line.appendChild(el('span', { class: 'hl-btrack' }, i, el('b', { class: 'num' }, ms(v[p[0]]))));
});
g.appendChild(line);
function verdict(list, range) {
if (!list.length) return el('section', { class: 'sl-verdict tone-neutral' }, el('span', { class: 'sl-v-ico', 'aria-hidden': 'true' }, '–'),
el('div', { class: 'sl-v-txt' }, el('h2', null, t('hl.sl.v.none')), el('p', null, t('hl.sl.v.none.sub', { range: range }))));
var out = list.filter(function (s) { return tone(s) === 'danger'; }).length, burn = list.filter(function (s) { return tone(s) === 'warn'; }).length;
var bad = out + burn, legit = 0;
list.forEach(function (s) { legit += legitOf(s); });
var tn = out ? 'danger' : burn ? 'warn' : 'ok';
var title = !bad ? t('hl.sl.v.ok') : out ? (out === 1 ? t('hl.sl.v.out.1') : t('hl.sl.v.out.n', { n: out })) : (bad === 1 ? t('hl.sl.v.bad.1') : t('hl.sl.v.bad.n', { n: bad }));
var sub = !bad ? t('hl.sl.v.ok.sub', { n: list.length, range: range, req: nf(legit) }) : t('hl.sl.v.bad.sub', { worst: list[0].alias, sli: pct(list[0].sli), range: range });
var pills = el('div', { class: 'sl-v-pills' });
if (out) pills.appendChild(U.ui.badge(t('hl.sl.pill.out', { n: out }), 'danger'));
if (burn) pills.appendChild(U.ui.badge(t('hl.sl.pill.burn', { n: burn }), 'warn'));
if (list.length - bad) pills.appendChild(U.ui.badge(t('hl.sl.pill.ok', { n: list.length - bad }), 'ok'));
return el('section', { class: 'sl-verdict tone-' + tn }, el('span', { class: 'sl-v-ico', 'aria-hidden': 'true' }, bad ? '!' : '✓'),
el('div', { class: 'sl-v-txt' }, el('h2', null, title), el('p', null, sub), pills));
}
function kpis(list) {
var req = 0, legit = 0, er = 0, atk = 0, peak = 0, p95 = 0, p50 = 0, reqSp = [], errSp = [];
list.forEach(function (s) {
req += s.req; er += errs(s); atk += (s.mix.attack || 0) + (s.mix.blocked || 0); legit += legitOf(s);
if (s.rps_peak > peak) peak = s.rps_peak;
if (s.p95.total > p95) { p95 = s.p95.total; p50 = s.p50.total; }
reqSp = sumArr(reqSp, s.spark); errSp = sumArr(errSp, s.err_spark);
});
var avail = legit ? 1 - er / legit : 1;
var kp = el('div', { class: 'sl-kpis' });
kp.appendChild(U.ui.metric(t('hl.sl.kpi.avail'), pct(avail), { sub: t('hl.sl.kpi.avail.sub'), tone: avail >= SLO ? 'ok' : 'danger', help: 'term.slo' }));
kp.appendChild(U.ui.metric(t('hl.sl.kpi.err'), nf(er), { sub: t('hl.sl.kpi.err.sub', { a: nf(atk) }), tone: er ? 'warn' : 'ok', spark: errSp.length > 1 ? errSp : null, help: 'term.error_budget' }));
kp.appendChild(U.ui.metric(t('hl.sl.kpi.p95'), ms(p95), { sub: t('hl.sl.kpi.p95.sub', { p50: ms(p50) }), help: 'term.p95' }));
kp.appendChild(U.ui.metric(t('hl.sl.kpi.req'), nf(req), { sub: t('hl.sl.kpi.req.sub', { rps: fix(peak, 2) }), spark: reqSp.length > 1 ? reqSp : null }));
return kp;
}
function burnCell(v) { return el('span', { class: 'sl-burn num' + (v >= 6 ? ' is-danger' : v >= 1 ? ' is-warn' : '') }, fix(v, v >= 10 ? 0 : 1) + '×'); }
function cell(lab, kids, cls) { var n = el('div', { class: 'sl-c ' + (cls || '') }, kids); n.setAttribute('data-l', lab); return n; }
function row(s) {
var tn = tone(s), es = s.err_spark || [];
var sp = es.length > 1 && Math.max.apply(null, es) > 0 && U.charts.sparkline ? U.charts.sparkline(es) : el('span', { class: 'sl-flat' });
var left = t('hl.sl.left', { p: U.fmt.pct(s.budget_left) });
var b = el('button', { type: 'button', class: 'sl-row tone-' + tn + (sel === s.svc ? ' is-sel' : ''), 'aria-pressed': sel === s.svc ? 'true' : 'false' },
cell(t('hl.sl.col.svc'), [el('span', { class: 'sl-dot', 'aria-hidden': 'true' }), el('span', { class: 'sl-name' }, el('strong', null, s.alias), el('small', null, t('hl.sl.st.' + tn) + ' · ' + nf(s.req)))], 'sl-c-svc'),
cell(t('hl.sl.col.avail'), [el('strong', { class: 'num' }, pct(s.sli)), el('small', { class: 'num' }, 'SLO ' + pct(s.slo))]),
cell(t('hl.sl.col.budget'), [el('span', { class: 'sl-bar', role: 'img', 'aria-label': left }, el('i', { style: { width: Math.max(s.budget_left > 0 ? 2 : 0, Math.round(s.budget_left * 100)) + '%' } })), el('small', { class: 'num' }, left)], 'sl-c-budget'),
cell(t('hl.sl.col.burn'), [burnCell(s.burn_1h), el('span', { class: 'sl-sep' }, '/'), burnCell(s.burn_6h)], 'sl-c-inline'),
cell(t('hl.sl.col.apdex'), [el('strong', { class: 'num' + (s.apdex < 0.85 ? ' is-warn' : '') }, fix(s.apdex, 2))]),
cell(t('hl.sl.col.lat'), [el('strong', { class: 'num' }, ms(s.p95.total)), el('small', { class: 'num' }, ms(s.p50.total))]),
cell(t('hl.sl.col.rps'), [el('strong', { class: 'num' }, fix(s.rps_peak, 2))]),
cell(t('hl.sl.col.trend'), [sp], 'sl-c-trend'));
b.addEventListener('click', function () { sel = s.svc; paintList(); loadDetail(true); });
return b;
}
function paintList() {
clear(listP.body);
var hd = el('div', { class: 'sl-row sl-head' },
el('div', { class: 'sl-c sl-c-svc' }, head(t('hl.sl.col.svc'))), el('div', { class: 'sl-c' }, head(t('hl.sl.col.avail'), 'term.slo')),
el('div', { class: 'sl-c sl-c-budget' }, head(t('hl.sl.col.budget'), 'term.error_budget')), el('div', { class: 'sl-c' }, head(t('hl.sl.col.burn'), 'term.burn_rate')),
el('div', { class: 'sl-c' }, head(t('hl.sl.col.apdex'), 'term.apdex')), el('div', { class: 'sl-c' }, head(t('hl.sl.col.lat'), 'term.p95')),
el('div', { class: 'sl-c' }, head(t('hl.sl.col.rps'))), el('div', { class: 'sl-c sl-c-trend' }, head(t('hl.sl.col.trend'))));
var box = el('div', { class: 'sl-list' }, hd);
data.forEach(function (s) { box.appendChild(row(s)); });
listP.body.appendChild(box);
}
function p95Chart(vals) {
var n = vals.length, W = 600, H = 120, mx = Math.max.apply(null, [1].concat(vals));
var svg = el('svg', { viewBox: '0 0 ' + W + ' ' + H, preserveAspectRatio: 'none', class: 'sl-p95', role: 'img', 'aria-label': t('hl.sl.d.p95') });
if (n < 2) return svg;
var pts = vals.map(function (v, i) { return (i / (n - 1) * W).toFixed(1) + ',' + (H - 4 - v / mx * (H - 12)).toFixed(1); });
svg.appendChild(el('polygon', { points: '0,' + H + ' ' + pts.join(' ') + ' ' + W + ',' + H, class: 'sl-p95-a' }));
svg.appendChild(el('polyline', { points: pts.join(' '), class: 'sl-p95-l' }));
return svg;
}
function routeGroups(routes) {
var g = { svc: [], atk: [], cli: [] };
(routes || []).forEach(function (r) {
var k = r.class === 'app' || r.class === 'proxy' ? 'svc' : (r.class === 'blocked' || r.class === 'attack' || r.class === 'bot') ? 'atk' : 'cli';
g[k].push(r);
});
var wrap = el('div', { class: 'sl-groups' });
[['svc', 'danger'], ['atk', 'info'], ['cli', 'neutral']].forEach(function (p) {
var rs = g[p[0]].slice(0, 6), mx = rs.length ? rs[0].n : 1;
var ul = el('ul', { class: 'sl-routes' });
rs.forEach(function (r) {
var cls = 'hl.sl.mix.' + (String(r.class).indexOf('client') === 0 ? 'client' : r.class);
ul.appendChild(el('li', null,
el('div', { class: 'sl-rt' }, el('code', { class: 'mono' }, r.route || '/'), el('b', { class: 'num' }, nf(r.n))),
el('span', { class: 'sl-rbar' }, el('i', { style: { width: Math.max(3, r.n / mx * 100) + '%' } })),
el('small', null, t(cls) !== cls ? t(cls) : String(r.class))));
});
box.appendChild(g);
wrap.appendChild(el('section', { class: 'sl-grp sl-grp-' + p[0] },
el('h4', null, U.ui.badge(t('hl.sl.g.' + p[0]), p[1])), el('p', { class: 'hint' }, t('hl.sl.g.' + p[0] + '.sub')),
rs.length ? ul : el('p', { class: 'sl-none' }, t('hl.sl.g.none'))));
});
var lg = el('div', { class: 'hl-legend' });
[['hl.sl.band.total', '--viz-1'], ['hl.sl.band.origin', '--viz-3'], ['hl.sl.band.overhead', '--viz-5']].forEach(function (p) {
lg.appendChild(el('span', null, el('i', { style: { background: 'var(' + p[1] + ')' } }), t(p[0])));
});
box.appendChild(lg);
return box;
return wrap;
}
function radar(list) {
var top = list.slice(0, 5);
if (!(U.charts && U.charts.radar) || top.length < 1) return U.ui.empty(t('hl.sl.empty'));
var maxReq = 0, minP = Infinity;
top.forEach(function (s) { if (s.req > maxReq) maxReq = s.req; if (s.p95.total > 0 && s.p95.total < minP) minP = s.p95.total; });
var axes = [{ key: 'avail', label: t('hl.sl.ax.avail') }, { key: 'apdex', label: t('hl.sl.ax.apdex') }, { key: 'speed', label: t('hl.sl.ax.speed') }, { key: 'retry', label: t('hl.sl.ax.retry') }, { key: 'traffic', label: t('hl.sl.ax.traffic') }];
var series = top.map(function (s) {
return { label: s.alias, values: [s.sli * 100, s.apdex * 100, s.p95.total > 0 ? Math.min(100, minP / s.p95.total * 100) : 100, Math.max(0, 100 - s.retries_pct * 10), maxReq ? s.req / maxReq * 100 : 0] };
});
return U.charts.radar(axes, series, { max: 100, title: t('hl.sl.radar'), format: function (v) { return Math.round(v) + ''; } });
function fact(v, lab, key) { var l = el('small', null, lab); return el('span', null, el('b', { class: 'num' }, v), key ? withHelp(l, key) : l); }
function paintDetail(d) {
clear(detP);
var s = d.summary, tl = d.timeline || {}, range = U.rangeLabel({ inline: true });
var grid = el('div', { class: 'grid-12 sl-dgrid' });
var pS = U.ui.panel({ title: t('hl.sl.d.series'), variant: 'chart', cls: 'span-8' });
var ev = tl.errors || [], okv = (tl.req || []).map(function (v, i) { return Math.max(0, v - (ev[i] || 0)); });
pS.body.appendChild(U.charts.stackedArea([{ label: t('hl.sl.d.ok'), values: okv }, { label: t('hl.sl.d.errors'), values: ev }], 3600,
{ colors: ['--ok', '--danger'], start: tl.hours && tl.hours[0], title: t('hl.sl.d.series') }));
var pM = U.ui.panel({ title: t('hl.sl.d.mix'), variant: 'chart', cls: 'span-4' });
var m = s.mix, cli = (m.client_broken || 0) + (m.client_auth || 0) + (m.client_other || 0);
var mix = MIX.map(function (p) { return { key: p[0], label: t('hl.sl.mix.' + p[0]), value: p[0] === 'client' ? cli : (m[p[0]] || 0), color: p[1] }; })
.filter(function (r) { return r.value > 0; }); // the donut drops empty slices, so the colors must follow
pM.body.appendChild(U.charts.donut(mix, { title: t('hl.sl.d.mix'), colors: mix.map(function (r) { return r.color; }), centerLabel: t('hl.sl.kpi.req') }));
var p95v = tl.p95 || [], mx = Math.max.apply(null, [0].concat(p95v));
var pL = U.ui.panel({ title: t('hl.sl.d.p95'), hint: t('hl.sl.d.p95.max', { v: ms(mx) }), variant: 'chart', cls: 'span-12', help: 'term.p95' });
pL.body.appendChild(p95Chart(p95v));
var pR = U.ui.panel({ title: t('hl.sl.d.routes'), cls: 'span-12' });
pR.body.appendChild(routeGroups(d.top_routes));
[pS, pM, pL, pR].forEach(function (p) { grid.appendChild(p); });
var hd = el('header', { class: 'sl-dhead tone-' + tone(s) }, el('span', { class: 'sl-dot', 'aria-hidden': 'true' }),
el('div', { class: 'sl-dtitle' }, el('h2', null, t('hl.sl.detail', { s: s.alias })), el('p', { class: 'hint' }, t('hl.sl.detail.hint', { range: range }))),
el('div', { class: 'sl-dfacts' }, fact(pct(s.sli), 'SLI', 'term.slo'), fact(U.fmt.pct(s.budget_left), t('hl.sl.col.budget'), 'term.error_budget'),
fact(fix(s.apdex, 2), 'Apdex', 'term.apdex'), fact(ms(s.p99.total), 'p99')));
detP.appendChild(hd); detP.appendChild(grid);
}
function loadDetail(scroll) {
if (!sel) { clear(detP); return; }
var my = ++dseq;
if (!detP.firstChild) detP.appendChild(el('div', { class: 'skeleton' }));
U.api('/api/v1/services/' + encodeURIComponent(sel), params()).then(function (d) {
if (!alive || my !== dseq || !d || !d.summary) return;
paintDetail(d);
if (scroll && detP.scrollIntoView) detP.scrollIntoView({ behavior: 'smooth', block: 'start' });
}, function () {
if (alive && my === dseq) { clear(detP); detP.appendChild(U.ui.empty(t('hl.sl.err'))); }
});
}
function params() { var p = Object.assign({}, U.rangeParams()); if (c.domain && c.domain !== 'all') p.host = c.domain; return p; }
function paint() {
clear(lead); [pc, pb, pr].forEach(function (p) { clear(p.body); });
if (!data) return;
clear(top); clear(listP.body);
var range = U.rangeLabel({ inline: true });
if (!data.length) {
lead.appendChild(U.ui.lead(t('hl.sl.lead.empty'), t('hl.sl.lead.empty.body', { range: range }), 'neutral'));
[pc, pb, pr].forEach(function (p) { p.body.appendChild(U.ui.empty(t('hl.sl.empty'))); });
return;
}
var ok = data.filter(function (s) { return s.budget_left > 0; }).length;
var worst = data.slice().sort(function (a, b) { return a.budget_left - b.budget_left; })[0];
lead.appendChild(U.ui.lead(t('hl.sl.lead', { n: data.length, ok: ok }),
worst.budget_left >= 1 ? t('hl.sl.lead.body.all', { range: range }) : t('hl.sl.lead.body', { worst: worst.alias, budget: U.fmt.pct(worst.budget_left), range: range }),
ok === data.length ? 'ok' : 'warn'));
var cards = el('div', { class: 'hl-cards' });
data.forEach(function (s) { cards.appendChild(card(s)); });
pc.body.appendChild(cards);
pb.body.appendChild(bands(data));
pr.body.appendChild(radar(data));
data.sort(function (a, b) { return rank(a) - rank(b) || a.budget_left - b.budget_left || a.sli - b.sli || b.req - a.req; });
top.appendChild(verdict(data, range));
if (!data.length) { listP.body.appendChild(U.ui.empty(t('hl.sl.empty'))); clear(detP); return; }
top.appendChild(kpis(data));
if (!sel || !data.some(function (s) { return s.svc === sel; })) sel = data[0].svc;
paintList();
loadDetail(false);
}
function load() {
var my = ++seq;
var p = Object.assign({}, U.rangeParams());
if (c.domain && c.domain !== 'all') p.host = c.domain;
U.api('/api/v1/services', p).then(function (r) { if (alive && my === seq) { data = r || []; paint(); } }, function () {
U.api('/api/v1/services', params()).then(function (r) { if (alive && my === seq) { data = r || []; paint(); } }, function () {
if (!alive || my !== seq || data) return;
clear(lead);
clear(top);
var b = el('button', { type: 'button', class: 'btn' }, t('hl.sl.retry'));
b.addEventListener('click', load);
lead.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('hl.sl.err')), b));
top.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('hl.sl.err')), b));
});
}
load();
return { update: function (cx) { c = cx; load(); }, destroy: function () { alive = false; seq++; clear(root); } };
return { update: function (cx) { c = cx; LANG = cx.lang || LANG; load(); }, destroy: function () { alive = false; seq++; dseq++; clear(root); } };
}
U.registerPage({
+2 -2
View File
@@ -353,7 +353,7 @@ td small { display: block; color: var(--ink-muted); font-size: .8125rem; overflo
.host dl { display: grid; grid-template-columns: 1fr auto; gap: 3px 8px; margin: 10px 0 0; font-size: .875rem; }
.host dd { text-align: right; font-variant-numeric: tabular-nums; }
.host dt { color: var(--ink-muted); }
.st-following { color: var(--ok); } .st-waiting, .st-backfill { color: var(--warn); } .st-error { color: var(--danger); } .st-disabled { color: var(--ink-muted); }
.st-following { color: var(--ok); } .st-waiting, .st-backfill { color: var(--warn); } .st-error, .st-degraded { color: var(--danger); font-weight: 600; } .st-disabled { color: var(--ink-muted); }
.kv { display: grid; grid-template-columns: minmax(120px, auto) minmax(0, 1fr); gap: 6px var(--s-4); }
.kv dt { color: var(--ink-muted); } .kv dd { overflow-wrap: anywhere; }
@@ -419,7 +419,7 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
.tab .nav-ico svg { width: 22px; height: 22px; }
.tab span:last-child { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tab[aria-current="page"], .tab[aria-expanded="true"] { background: var(--rail-active); color: #fff; }
.more-sheet { position: fixed; left: 0; right: 0; bottom: 68px; z-index: 31; background: var(--surface-overlay); border-top: 1px solid var(--line-strong); border-radius: 14px 14px 0 0; padding: var(--s-3); box-shadow: var(--shadow); }
.more-sheet { position: fixed; left: 0; right: 0; bottom: 68px; z-index: 31; background: var(--surface-overlay); border-top: 1px solid var(--line-strong); border-radius: 14px 14px 0 0; padding: var(--s-3); box-shadow: var(--shadow); max-height: calc(100dvh - 68px - env(safe-area-inset-top, 0px) - 12px); overflow-y: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
.more-sheet:not([hidden]) { display: block; }
.more-sheet a { display: flex; align-items: center; gap: var(--s-3); min-height: 48px; padding: 8px var(--s-3); color: var(--ink); text-decoration: none; border-radius: var(--radius-sm); }
.more-sheet a[aria-current="page"] { background: var(--accent-soft); }
+5 -1
View File
@@ -294,7 +294,11 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
sg := intel.SignatureFrom(paths, tool)
g := s.GeoOf(ss.IP)
sg.ASN, sg.CC = g.ASN, g.CC
sg.NetType, _ = intel.NetType(g.ASN, g.ASOrg, "")
if a, err := netip.ParseAddr(ss.IP); err == nil {
sg.NetType, _ = intel.NetTypeIP(a, g.ASN, g.ASOrg, "")
} else {
sg.NetType, _ = intel.NetType(g.ASN, g.ASOrg, "")
}
sigs[ss.ID] = sg
if g.ASN != 0 {
asns["AS"+strconv.Itoa(int(g.ASN))+" "+g.ASOrg]++
+102
View File
@@ -0,0 +1,102 @@
package store
import (
"strings"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
)
// RosterRow is one address with malicious activity, as the second firewall needs it.
type RosterRow struct {
IP string
Score float64
Level core.Level
Jails []string
Last int64
}
// Tally24 counts the malicious events of one address in a window.
type Tally24 struct{ SSH, Web int }
// AttackRoster lists the addresses with malicious activity since from (unix).
func (s *Store) AttackRoster(from int64) []RosterRow {
nowU := s.now().Unix()
s.mu.RLock()
defer s.mu.RUnlock()
out := make([]RosterRow, 0, 256)
for ip, r := range s.ips {
if r.Last < from || !isAttacker(r) {
continue
}
strong := r.Strong || attackKinds(r.Counts) >= 2
out = append(out, RosterRow{IP: ip, Score: round1(r.Score), Level: core.LevelOf(r.Score, strong, r.adminAt(nowU)),
Jails: append([]string(nil), r.Jails...), Last: r.Last})
}
return out
}
// Reputation is the verdict of one address as the UI shows it.
func (s *Store) Reputation(ip string) (float64, core.Level, bool) {
ip = KeyOf(ip)
s.mu.RLock()
defer s.mu.RUnlock()
r := s.ips[ip]
if r == nil {
return 0, core.LevelLow, false
}
strong := r.Strong || attackKinds(r.Counts) >= 2
return r.Score, core.LevelOf(r.Score, strong, r.adminAt(s.now().Unix())), true
}
var tallyCats = map[string]bool{string(core.SSHFail): true, string(core.Scanner): true, string(core.Exploit): true, string(core.BruteForce): true}
func tallyAdd(m map[string]*Tally24, r evlog.Rec) {
t := m[r.IP]
if t == nil {
t = &Tally24{}
m[r.IP] = t
}
switch {
case r.Cat == string(core.SSHFail):
t.SSH++
case r.Source == "traefik" && !strings.Contains(r.Flags, "F"):
t.Web++
}
}
// AttackTallies counts, in one pass over the event log, the SSH failures and web
// scan/exploit events of every address since from. Nil without an event log.
func (s *Store) AttackTallies(from int64) map[string]Tally24 {
if s.elog == nil {
return nil
}
m := map[string]*Tally24{}
s.elog.Scan(evlog.Filter{From: from, Cats: tallyCats}, 256<<20, false, func(r evlog.Rec, _ []byte) bool {
tallyAdd(m, r)
return true
})
out := make(map[string]Tally24, len(m))
for k, v := range m {
out[k] = *v
}
return out
}
// AttackTally is AttackTallies for one address.
func (s *Store) AttackTally(ip string, from int64) Tally24 {
if s.elog == nil {
return Tally24{}
}
m := map[string]*Tally24{}
s.elog.Scan(evlog.Filter{From: from, IP: ip, Cats: tallyCats}, 64<<20, false, func(r evlog.Rec, _ []byte) bool {
tallyAdd(m, r)
return true
})
var t Tally24
for _, v := range m {
t.SSH += v.SSH
t.Web += v.Web
}
return t
}
+23 -1
View File
@@ -209,6 +209,8 @@ type traefik struct {
Scheme string `json:"RequestScheme,omitempty"`
TLSVer string `json:"TLSVersion,omitempty"`
TLSCipher string `json:"TLSCipher,omitempty"`
Origin int `json:"OriginStatus,omitempty"` // only on 5xx: the backend itself failed
Router string `json:"RouterName,omitempty"` // only on 5xx: the request reached an application router
}
// protoOf varia o protocolo conforme o cliente: navegadores em HTTP/2 e HTTP/3,
@@ -234,7 +236,11 @@ func protoOf(ip netip.Addr, ua string) (proto, scheme, ver, cipher string) {
func webLine(t time.Time, ip netip.Addr, domain, method, path string, status int, ua, ref string, dur time.Duration, size int64) line {
pr, sc, tv, tc := protoOf(ip, ua)
b, _ := json.Marshal(traefik{ip.String(), domain, method, path, status, t.UTC().Format("2006-01-02T15:04:05.000000000Z"), ua, ref, int64(dur), size, pr, sc, tv, tc})
org, router := 0, ""
if status >= 500 {
org, router = status, domain+"@docker"
}
b, _ := json.Marshal(traefik{ip.String(), domain, method, path, status, t.UTC().Format("2006-01-02T15:04:05.000000000Z"), ua, ref, int64(dur), size, pr, sc, tv, tc, org, router})
return line{t, string(b)}
}
@@ -263,6 +269,22 @@ func (g *gen) visit(v *visitor, t time.Time, domain string) []line {
for i := 0; i < pages; i++ {
p := legitPages[g.rng.Intn(len(legitPages))]
st := 200
// some backend failures (5xx from the origin), more on the first domain and in the last hours
fail := 4
if domain == g.cfg.domains[0].name {
fail = 35
if g.now.Sub(t) < 8*time.Hour {
fail = 140
}
}
if g.rng.Intn(1000) < fail {
bad := []string{"/shop/checkout", "/api/cart", "/login", "/docs/api"}
p = bad[g.rng.Intn(len(bad))]
code := []int{500, 502, 503, 504}[g.rng.Intn(4)]
out = append(out, webLine(t, v.ip, domain, "GET", p, code, v.ua, ref, time.Duration(300+g.rng.Intn(4000))*time.Millisecond, 512))
t = t.Add(time.Duration(4+g.rng.Intn(70)) * time.Second)
continue
}
switch x := g.rng.Intn(100); {
case x < 4:
st = 404