Compare commits

...
3 Commits
Author SHA1 Message Date
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
24 changed files with 875 additions and 28 deletions

No files matched your search

+18
View File
@@ -6,6 +6,24 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased] ## [Unreleased]
## [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 ## [1.4.2] - 2026-11-15
### Changed ### Changed
+18
View File
@@ -6,6 +6,24 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Unreleased] ## [Unreleased]
## [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 ## [1.4.2] - 2026-11-15
### Alterado ### Alterado
+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) 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 TrustedProxy string // proxies whose X-Forwarded-For is believed
Retention time.Duration 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 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) EventsMax string // size cap of the event registry ("512MB", "0" disables it)
NoAuth bool 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.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.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.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.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.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)") 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 package app
import ( import (
"bytes"
"errors"
"time" "time"
"encoding/json" "encoding/json"
"fmt" "fmt"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
"io" "io"
@@ -46,6 +49,11 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
fi, _ := f.Stat() fi, _ := f.Stat()
f.Close() f.Close()
add("source "+s.name, "ok", fmt.Sprintf("%s readable (%d bytes)", s.path, fi.Size())) 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 { if err := os.MkdirAll(c.DataDir, 0o700); err != nil {
add("data-dir", "fail", err.Error()) 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)) add("state", "ok", fmt.Sprintf("%d IPs, %d domains, %d requests in 7 days", st.IPCount(), len(tr.Domains), tr.Requests))
return info 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
}
+89 -7
View File
@@ -2,11 +2,13 @@ package app
import ( import (
"log/slog" "log/slog"
"net"
"net/netip" "net/netip"
"net/url" "net/url"
"os" "os"
"strconv" "strconv"
"strings" "strings"
"sync"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress" "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 return nil, nil
} }
} }
var allow []netip.Prefix allow := egressAllow(c)
if nets, err := core.ParseCIDRs(c.Trusted); err == nil { var provMu sync.Mutex
for _, n := range nets { var provCache []string
if p, err := netip.ParsePrefix(n.String()); err == nil { provider := func() []string {
allow = append(allow, p) 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{ eng, err := egress.New(egress.Config{
Workloads: c.EgressWorkloads, Workloads: c.EgressWorkloads,
Resolvers: c.EgressResolvers, Resolvers: c.EgressResolvers,
Allow: allow, Allow: allow,
Containers: c.EgressContainers, 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) { Geo: func(ip string) (string, string, string) {
g := st.GeoOf(ip) g := st.GeoOf(ip)
asn := "" asn := ""
@@ -96,3 +102,79 @@ func egressExtraAllow(c Config) []netip.Prefix {
} }
return out 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()...)
}
+3
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 := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
st.SetDomains(splitList(c.Domains)) st.SetDomains(splitList(c.Domains))
watchTorExits(ctx, c.TorExits, 24*time.Hour, log) 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 var elog *evlog.Log
if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 { 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 { if elog, err = evlog.Open(evlog.Options{Dir: filepath.Join(c.DataDir, "events"), MaxBytes: max, Retention: c.Retention, Log: log}); err != nil {
+53 -1
View File
@@ -23,6 +23,8 @@ type source struct {
parse func([]byte) (core.Event, error) parse func([]byte) (core.Event, error)
lines, malformed atomic.Uint64 lines, malformed atomic.Uint64
win window
lastWarn atomic.Int64
lastEvent atomic.Int64 lastEvent atomic.Int64
backfilling atomic.Bool backfilling atomic.Bool
fol atomic.Pointer[tail.Follower] 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 authParse(b []byte) (core.Event, error) { return core.ParseAuth(string(b)) }
func f2bParse(b []byte) (core.Event, error) { return core.ParseFail2ban(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 { func (s *source) status() store.SourceStatus {
st := store.SourceStatus{Name: s.name, Path: s.path, Lines: s.lines.Load(), Malformed: s.malformed.Load(), st := store.SourceStatus{Name: s.name, Path: s.path, Lines: s.lines.Load(), Malformed: s.malformed.Load(),
LastEvent: s.lastEvent.Load(), State: "following"} 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 return st
} }
@@ -148,11 +191,20 @@ func (r *Runner) handle(s *source) func([]byte) {
s.lines.Add(1) s.lines.Add(1)
ev, err := s.parse(line) ev, err := s.parse(line)
if err != nil { if err != nil {
if !errors.Is(err, core.ErrIgnored) { bad := !errors.Is(err, core.ErrIgnored)
if bad {
s.malformed.Add(1) 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 return
} }
s.win.add(false)
if core.Ignored(r.Ignore, ev.IP) { if core.Ignored(r.Ignore, ev.IP) {
return return
} }
+182 -1
View File
@@ -3,12 +3,17 @@ package app
import ( import (
"bufio" "bufio"
"context" "context"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"io"
"log/slog" "log/slog"
"net/http"
"net/netip" "net/netip"
"os" "os"
"path/filepath"
"strings" "strings"
"sync"
"time" "time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel" "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) log.Warn("tor exit list unreadable", "err", err)
return return
} }
intel.SetTorExits(addrs) torLists.setManual(addrs)
lastMod, lastSize = st.ModTime(), st.Size() lastMod, lastSize = st.ModTime(), st.Size()
log.Info("tor exit list loaded", "n", len(addrs)) 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) 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 // Version is the release version (SemVer). Release builds may override it with
// -ldflags "-X .../internal/app.Version=...". // -ldflags "-X .../internal/app.Version=...".
var Version = "1.4.2" var Version = "1.4.4"
+22
View File
@@ -266,3 +266,25 @@ func TestZonesAreRejectedEverywhere(t *testing.T) {
} }
_ = strings.ToLower _ = 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 package core
import ( import (
"bytes"
"encoding/json" "encoding/json"
"errors" "errors"
"net/netip" "net/netip"
"regexp" "regexp"
"strconv"
"strings" "strings"
"time" "time"
) )
@@ -72,6 +74,9 @@ type traefikLine struct {
// ParseTraefik parses one Traefik JSON access log line. // ParseTraefik parses one Traefik JSON access log line.
func ParseTraefik(line []byte) (Event, error) { func ParseTraefik(line []byte) (Event, error) {
if t := bytes.TrimLeft(line, " \t"); len(t) > 0 && t[0] != '{' {
return parseTraefikText(string(t))
}
var l traefikLine var l traefikLine
if err := json.Unmarshal(line, &l); err != nil { if err := json.Unmarshal(line, &l); err != nil {
return Event{}, err return Event{}, err
@@ -213,3 +218,119 @@ func ParseFail2ban(line string) (Event, error) {
Unban: m[3] == "Unban", Restore: m[3] == "Restore Ban", Unban: m[3] == "Unban", Restore: m[3] == "Restore Ban",
}, nil }, 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" "os"
"path/filepath" "path/filepath"
"sort" "sort"
"strings"
"testing" "testing"
"time" "time"
) )
@@ -548,3 +549,59 @@ func TestBeaconDuringContinuousScan(t *testing.T) {
t.Fatal("fanSeen unbounded") 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)
}
}
+54 -6
View File
@@ -61,6 +61,12 @@ type Config struct {
// destination is a known attacker or Tor exit (and why). // destination is a known attacker or Tor exit (and why).
Geo func(ip string) (cc, asn, org string) Geo func(ip string) (cc, asn, org string)
BadDst func(netip.Addr) (bool, string) BadDst func(netip.Addr) (bool, string)
// 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 Now func() time.Time
// Learn is the per-workload learning time before new_geo (default 24h). // Learn is the per-workload learning time before new_geo (default 24h).
Learn time.Duration Learn time.Duration
@@ -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) 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 ev.Proto == "tcp" {
if sev, why := suspiciousPort(dport, ws.role); why != "" { if sev, why := suspiciousPort(dport, ws.role); why != "" {
e.addFinding("port", sev, ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1) 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) { func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairState, ds *dstStat) {
if p.flagged { 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 := len(f.Samples); n == 0 || f.Samples[n-1] != p.last {
if n >= MaxSamples { if n >= MaxSamples {
f.Samples = append(f.Samples[:0], f.Samples[1:]...) 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 { if mad < cv {
jit = mad jit = mad
} }
sev := "medium" sev, kind := "medium", "beacon"
why := fmt.Sprintf("regular connections every %.0f s (jitter %.0f%%)", med, jit*100) why := fmt.Sprintf("regular connections every %.0f s (jitter %.0f%%)", med, jit*100)
bad := false
if e.cfg.BadDst != nil { if e.cfg.BadDst != nil {
if bad, r := e.cfg.BadDst(ev.Dst); bad { if b, r := e.cfg.BadDst(ev.Dst); b {
sev, why = "high", why+"; destination: "+r 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 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 { if f != nil {
f.Count, f.First = int(p.total), p.first f.Count, f.First = int(p.total), p.first
f.Samples = make([]int64, 0, MaxSamples) 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 { func median(v []float64) float64 {
s := append([]float64(nil), v...) s := append([]float64(nil), v...)
sort.Float64s(s) sort.Float64s(s)
@@ -833,7 +881,7 @@ func median(v []float64) float64 {
return (s[n/2-1] + s[n/2]) / 2 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 { 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) key := fmt.Sprintf("%s|%s|%s|%d", kind, wl, dst, dport)
+21
View File
@@ -11,8 +11,29 @@ import (
var ( var (
torMu sync.RWMutex torMu sync.RWMutex
torExits map[netip.Addr]struct{} 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 // SetTorExits loads (or clears, with nil/empty) the Tor exit list. It is off
// by default; the caller decides where the list comes from. // by default; the caller decides where the list comes from.
func SetTorExits(addrs []netip.Addr) { func SetTorExits(addrs []netip.Addr) {
+2 -1
View File
@@ -13,6 +13,7 @@ type integritySource struct {
Lines uint64 `json:"lines"` Lines uint64 `json:"lines"`
Malformed uint64 `json:"malformed"` Malformed uint64 `json:"malformed"`
Last int64 `json:"last"` Last int64 `json:"last"`
Error string `json:"error,omitempty"`
} }
type integrityHost struct { type integrityHost struct {
@@ -97,7 +98,7 @@ func (s *Server) integrity(w http.ResponseWriter, r *http.Request) {
} }
continue 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 lines += src.Lines
bad += src.Malformed bad += src.Malformed
if src.LastEvent > hh.LastEvent { if src.LastEvent > hh.LastEvent {
+1 -1
View File
@@ -224,7 +224,7 @@
function countryLabel(cc) { return (flag(cc) + ' ' + countryName(cc)).trim(); } 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_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_LEVELS = ['hostile', 'suspicious', 'low'];
var KNOWN_TONES = ['neutral', 'ok', 'warn', 'danger', 'info']; var KNOWN_TONES = ['neutral', 'ok', 'warn', 'danger', 'info'];
var CHART_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban']; var CHART_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban'];
+27 -2
View File
@@ -11,8 +11,8 @@
var SEV = { high: 0, medium: 1, low: 2 }; var SEV = { high: 0, medium: 1, low: 2 };
var SEV_NAME = ['high', 'medium', 'low']; var SEV_NAME = ['high', 'medium', 'low'];
var SEV_TONE = { high: 'danger', medium: 'warn', low: 'info' }; var SEV_TONE = { high: 'danger', medium: 'warn', low: 'info' };
var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', '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' }; 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; var LAT_TOP = 84, LAT_SPAN = 142;
function boot() { function boot() {
@@ -58,6 +58,11 @@
'eg.kind.bad_dst': 'Known-bad destination', 'eg.kind.bad_dst': 'Known-bad destination',
'eg.kind.dns_bypass': 'DNS outside the resolver', 'eg.kind.dns_bypass': 'DNS outside the resolver',
'eg.kind.new_geo': 'New country', '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.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.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.', '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.bad_dst': 'Destino sabidamente ruim',
'eg.kind.dns_bypass': 'DNS fora do resolvedor', 'eg.kind.dns_bypass': 'DNS fora do resolvedor',
'eg.kind.new_geo': 'País novo', '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.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.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.', '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)); 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) { function kpis(st) {
var kp = el('div', { class: 'eg-kpis' }); 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 })); 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 // ------------------------------------------------------------ paint
function stats(d) { 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 || {} }; 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.fnd.sort(function (a, b) { return SEV[sevOf(a)] - SEV[sevOf(b)] || (b.last || 0) - (a.last || 0); });
st.ser = st.tl.series || {}; st.ser = st.tl.series || {};
st.conns = 0; st.active = 0; st.sev = { high: 0, medium: 0, low: 0 }; 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 }); var st = stats(data), range = U.rangeLabel({ inline: true });
root.appendChild(verdict(data, st, range)); root.appendChild(verdict(data, st, range));
root.appendChild(kpis(st)); root.appendChild(kpis(st));
if (st.infra.length) root.appendChild(infraLine(st));
var grid = el('div', { class: 'grid-12' }); var grid = el('div', { class: 'grid-12' });
var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-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.waiting': 'waiting for file',
'state.backfill': 'reading history', 'state.backfill': 'reading history',
'state.error': 'error', 'state.error': 'error',
'state.degraded': 'degraded',
'state.disabled': 'disabled', 'state.disabled': 'disabled',
'cat.ok': 'ok', 'cat.ok': 'ok',
'cat.notfound': 'Nonexistent page (404)', '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.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': '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.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': '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.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).', '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.waiting': 'aguardando arquivo',
'state.backfill': 'lendo histórico', 'state.backfill': 'lendo histórico',
'state.error': 'erro', 'state.error': 'erro',
'state.degraded': 'degradada',
'state.disabled': 'desativada', 'state.disabled': 'desativada',
'cat.ok': 'ok', 'cat.ok': 'ok',
'cat.notfound': 'Página inexistente (404)', '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.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': '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.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': '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.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).', '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 () { (function () {
'use strict'; '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>'; 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() { function boot() {
@@ -44,6 +44,7 @@
'ig.state.waiting': 'waiting', 'ig.state.waiting': 'waiting',
'ig.state.backfill': 'catching up', 'ig.state.backfill': 'catching up',
'ig.state.error': 'error', 'ig.state.error': 'error',
'ig.state.degraded': 'degraded',
'ig.state.disabled': 'disabled', 'ig.state.disabled': 'disabled',
'ig.peers.title': 'Peers', 'ig.peers.title': 'Peers',
'ig.peers.none': 'No peers configured.', 'ig.peers.none': 'No peers configured.',
@@ -96,6 +97,7 @@
'ig.state.waiting': 'aguardando', 'ig.state.waiting': 'aguardando',
'ig.state.backfill': 'recuperando', 'ig.state.backfill': 'recuperando',
'ig.state.error': 'erro', 'ig.state.error': 'erro',
'ig.state.degraded': 'degradada',
'ig.state.disabled': 'desativada', 'ig.state.disabled': 'desativada',
'ig.peers.title': 'Peers', 'ig.peers.title': 'Peers',
'ig.peers.none': 'Nenhum peer configurado.', 'ig.peers.none': 'Nenhum peer configurado.',
@@ -172,7 +174,7 @@
hosts.forEach(function (x) { hosts.forEach(function (x) {
gaps += (x.gaps || []).length; gaps += (x.gaps || []).length;
if (x.online) onlineN++; 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 offline = peers.filter(function (p) { return !p.online; }).length;
var rate = lines + bad > 0 ? bad / (lines + bad) : 0; var rate = lines + bad > 0 ? bad / (lines + bad) : 0;
@@ -233,8 +235,8 @@
var rows = []; var rows = [];
hosts.forEach(function (x) { hosts.forEach(function (x) {
(x.sources || []).forEach(function (s) { (x.sources || []).forEach(function (s) {
var tone = s.state === 'error' ? 'danger' : s.state === 'following' ? 'ok' : 'neutral'; 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) : String(s.state || ''), tone), nf(s.lines), nf(s.malformed), s.last ? U.fmt.ago(s.last) : '-']); 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'))); 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.asn': 'known ASN {v}',
'ip.ntr.asorg': 'organization name contains "{v}"', 'ip.ntr.asorg': 'organization name contains "{v}"',
'ip.ntr.rdns': 'reverse DNS 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.untrusted': 'text sent by the attacker',
'ip.act.copy': 'Copy IP', 'ip.act.copy': 'Copy IP',
'ip.act.ioc': 'Copy as IOC', 'ip.act.ioc': 'Copy as IOC',
@@ -1010,7 +1010,9 @@
box.appendChild(chip('ip.id.rdns', rv)); box.appendChild(chip('ip.id.rdns', rv));
if (id.net_type) { if (id.net_type) {
var nt = pick(NETTYPES, id.net_type, 'unknown'), why = ntReason(id.net_type_reason); 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)))); if (id.prefix) box.appendChild(chip('ip.id.prefix', h('span', 'ipx-mono', clip(id.prefix, 50))));
return box; return box;
+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 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 dd { text-align: right; font-variant-numeric: tabular-nums; }
.host dt { color: var(--ink-muted); } .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 { 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; } .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 .nav-ico svg { width: 22px; height: 22px; }
.tab span:last-child { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .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; } .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: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 { 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); } .more-sheet a[aria-current="page"] { background: var(--accent-soft); }
+4
View File
@@ -294,7 +294,11 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
sg := intel.SignatureFrom(paths, tool) sg := intel.SignatureFrom(paths, tool)
g := s.GeoOf(ss.IP) g := s.GeoOf(ss.IP)
sg.ASN, sg.CC = g.ASN, g.CC sg.ASN, sg.CC = g.ASN, g.CC
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, "") sg.NetType, _ = intel.NetType(g.ASN, g.ASOrg, "")
}
sigs[ss.ID] = sg sigs[ss.ID] = sg
if g.ASN != 0 { if g.ASN != 0 {
asns["AS"+strconv.Itoa(int(g.ASN))+" "+g.ASOrg]++ asns["AS"+strconv.Itoa(int(g.ASN))+" "+g.ASOrg]++