CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.
Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.
Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.
Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
432 lines
11 KiB
Go
432 lines
11 KiB
Go
// Package fed lets one instance aggregate the summaries of other instances.
|
|
package fed
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/netip"
|
|
"net/url"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
|
)
|
|
|
|
// maxBody caps what a hub accepts from one peer response.
|
|
const maxBody = 8 << 20
|
|
|
|
// Peer is a remote Urutau instance.
|
|
type Peer struct {
|
|
Name, URL string
|
|
// Token overrides the hub-wide token for this peer (URUTAU_PEER_TOKEN_<NAME>).
|
|
Token string
|
|
}
|
|
|
|
// ParsePeer parses "name=https://url".
|
|
func ParsePeer(s string) (Peer, error) {
|
|
name, u, ok := strings.Cut(s, "=")
|
|
name, u = strings.TrimSpace(name), strings.TrimRight(strings.TrimSpace(u), "/")
|
|
if !ok || name == "" || u == "" {
|
|
return Peer{}, fmt.Errorf("peer %q: expected name=https://url", s)
|
|
}
|
|
pu, err := url.Parse(u)
|
|
if err != nil || pu.Host == "" || pu.User != nil {
|
|
return Peer{}, fmt.Errorf("peer %q: invalid URL", s)
|
|
}
|
|
switch {
|
|
case pu.Scheme == "https":
|
|
case pu.Scheme == "http" && isLoopbackHost(pu.Hostname()):
|
|
default:
|
|
return Peer{}, fmt.Errorf("peer %q: the URL must be https (plain http only for loopback)", s)
|
|
}
|
|
return Peer{Name: name, URL: u}, nil
|
|
}
|
|
|
|
func isLoopbackHost(h string) bool {
|
|
if h == "localhost" {
|
|
return true
|
|
}
|
|
a, err := netip.ParseAddr(h)
|
|
return err == nil && a.IsLoopback()
|
|
}
|
|
|
|
type peerState struct {
|
|
online bool
|
|
lastOK int64
|
|
err string
|
|
latency int64
|
|
version string
|
|
exports map[string]store.PeerExport
|
|
extra map[string]*extraExport // on-demand windows
|
|
studies map[string]*studyCached
|
|
live bool
|
|
}
|
|
|
|
// extraExport is an export of a window outside the background set.
|
|
type extraExport struct {
|
|
at time.Time
|
|
e store.PeerExport
|
|
}
|
|
|
|
const (
|
|
extraTTL = 15 * time.Second
|
|
extraMax = 12 // cached on-demand exports per peer
|
|
)
|
|
|
|
// Hub polls peers and serves their latest summaries.
|
|
type Hub struct {
|
|
Peers []Peer
|
|
Token string
|
|
Interval time.Duration
|
|
client *http.Client
|
|
stream *http.Client // long-lived SSE: no overall timeout, no redirects
|
|
|
|
swg sync.WaitGroup // live stream goroutines
|
|
lmu sync.Mutex
|
|
live liveState
|
|
|
|
mu sync.RWMutex
|
|
state map[string]*peerState
|
|
|
|
// OnLive, when set, sees every sanitized peer event before it is published
|
|
// (it assigns the local id and registers it in the event log).
|
|
OnLive func(*store.LiveEvent)
|
|
}
|
|
|
|
// NewHub creates a hub; Interval defaults to 15 seconds.
|
|
func NewHub(peers []Peer, token string) *Hub {
|
|
h := &Hub{Peers: peers, Token: token, Interval: 15 * time.Second,
|
|
client: &http.Client{Timeout: 4 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, state: map[string]*peerState{}}
|
|
tr := http.DefaultTransport.(*http.Transport).Clone()
|
|
tr.ResponseHeaderTimeout = 10 * time.Second
|
|
h.stream = &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
|
for _, p := range peers {
|
|
h.state[p.Name] = &peerState{exports: map[string]store.PeerExport{}, extra: map[string]*extraExport{}}
|
|
}
|
|
return h
|
|
}
|
|
|
|
func (h *Hub) get(ctx context.Context, p Peer, path string, out any) (time.Duration, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.URL+path, nil)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
tok := h.Token
|
|
if p.Token != "" {
|
|
tok = p.Token
|
|
}
|
|
if tok != "" {
|
|
req.Header.Set("Authorization", "Bearer "+tok)
|
|
}
|
|
req.Header.Set("Accept", "application/json")
|
|
t := time.Now()
|
|
resp, err := h.client.Do(req)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != 200 {
|
|
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
|
|
return 0, fmt.Errorf("HTTP %d", resp.StatusCode)
|
|
}
|
|
body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if len(body) > maxBody {
|
|
return 0, fmt.Errorf("response larger than %d bytes", maxBody)
|
|
}
|
|
if err := json.Unmarshal(body, out); err != nil {
|
|
return 0, err
|
|
}
|
|
return time.Since(t), nil
|
|
}
|
|
|
|
// Refresh fetches every peer once, concurrently. Failures only mark the peer offline.
|
|
func (h *Hub) Refresh(ctx context.Context) {
|
|
var wg sync.WaitGroup
|
|
for _, p := range h.Peers {
|
|
wg.Add(1)
|
|
go func(p Peer) {
|
|
defer wg.Done()
|
|
exports := map[string]store.PeerExport{}
|
|
var lat time.Duration
|
|
var ferr error
|
|
for _, name := range store.BackgroundRanges {
|
|
var e store.PeerExport
|
|
d, err := h.get(ctx, p, "/api/v1/peer/export?range="+name, &e)
|
|
if err == nil {
|
|
err = e.Sanitize(name)
|
|
}
|
|
if err != nil {
|
|
ferr = err
|
|
break
|
|
}
|
|
lat = d
|
|
e.Summary = rename(e.Summary, p.Name)
|
|
exports[name] = e
|
|
}
|
|
h.mu.Lock()
|
|
st := h.state[p.Name]
|
|
if ferr != nil {
|
|
st.online, st.err = false, ferr.Error()
|
|
if len(st.err) > 160 {
|
|
st.err = st.err[:160]
|
|
}
|
|
} else {
|
|
st.online, st.err, st.lastOK, st.latency, st.exports = true, "", time.Now().Unix(), lat.Milliseconds(), exports
|
|
for _, e := range exports {
|
|
st.version = e.Summary.Version
|
|
}
|
|
}
|
|
h.mu.Unlock()
|
|
}(p)
|
|
}
|
|
wg.Wait()
|
|
}
|
|
|
|
// fetchRange asks a peer for the export of a window and sanitizes it.
|
|
func (h *Hub) fetchRange(ctx context.Context, p Peer, rg store.Range) (store.PeerExport, error) {
|
|
var e store.PeerExport
|
|
path := "/api/v1/peer/export?range=" + url.QueryEscape(rg.Name)
|
|
if rg.Custom() {
|
|
path = fmt.Sprintf("/api/v1/peer/export?from=%d&to=%d", rg.From, rg.To)
|
|
}
|
|
if _, err := h.get(ctx, p, path, &e); err != nil {
|
|
return e, err
|
|
}
|
|
if err := e.SanitizeRange(rg); err != nil {
|
|
return e, err
|
|
}
|
|
e.Summary = rename(e.Summary, p.Name)
|
|
return e, nil
|
|
}
|
|
|
|
// exportsFor returns the exports of the online peers (or one) for a window:
|
|
// the cached background ones, or an on-demand fetch cached for 15 s.
|
|
func (h *Hub) exportsFor(ctx context.Context, rg store.Range, only string) map[string]store.PeerExport {
|
|
out := map[string]store.PeerExport{}
|
|
var mu sync.Mutex
|
|
var wg sync.WaitGroup
|
|
for _, p := range h.Peers {
|
|
if only != "" && only != p.Name {
|
|
continue
|
|
}
|
|
h.mu.RLock()
|
|
st := h.state[p.Name]
|
|
online := st.online
|
|
var cached *store.PeerExport
|
|
if !rg.Custom() {
|
|
if e, ok := st.exports[rg.Name]; ok {
|
|
cached = &e
|
|
}
|
|
}
|
|
if cached == nil {
|
|
if x := st.extra[rg.Key()]; x != nil && time.Since(x.at) < extraTTL {
|
|
e := x.e
|
|
cached = &e
|
|
}
|
|
}
|
|
h.mu.RUnlock()
|
|
if !online {
|
|
continue
|
|
}
|
|
if cached != nil {
|
|
out[p.Name] = *cached
|
|
continue
|
|
}
|
|
wg.Add(1)
|
|
go func(p Peer) {
|
|
defer wg.Done()
|
|
e, err := h.fetchRange(ctx, p, rg)
|
|
if err != nil {
|
|
return
|
|
}
|
|
h.mu.Lock()
|
|
st := h.state[p.Name]
|
|
if len(st.extra) >= extraMax {
|
|
st.extra = map[string]*extraExport{}
|
|
}
|
|
st.extra[rg.Key()] = &extraExport{at: time.Now(), e: e}
|
|
h.mu.Unlock()
|
|
mu.Lock()
|
|
out[p.Name] = e
|
|
mu.Unlock()
|
|
}(p)
|
|
}
|
|
wg.Wait()
|
|
return out
|
|
}
|
|
|
|
// SummariesFor returns the summaries of online peers for any window.
|
|
func (h *Hub) SummariesFor(ctx context.Context, rg store.Range, only string) []store.Summary {
|
|
m := h.exportsFor(ctx, rg, only)
|
|
var out []store.Summary
|
|
for _, p := range h.Peers {
|
|
if e, ok := m[p.Name]; ok {
|
|
out = append(out, e.Summary)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// TrafficFor returns the analytics of online peers for any window and domain.
|
|
func (h *Hub) TrafficFor(ctx context.Context, rg store.Range, domain, only string) []store.TrafficData {
|
|
m := h.exportsFor(ctx, rg, only)
|
|
var out []store.TrafficData
|
|
for _, p := range h.Peers {
|
|
if e, ok := m[p.Name]; ok {
|
|
if t, ok := e.Traffic[domain]; ok {
|
|
t.Host = p.Name
|
|
out = append(out, t)
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// rename forces the configured peer name on every row of a remote summary.
|
|
func rename(s store.Summary, name string) store.Summary {
|
|
s.Host = name
|
|
for i := range s.Hosts {
|
|
s.Hosts[i].Name, s.Hosts[i].Self = name, false
|
|
}
|
|
for i := range s.IPs {
|
|
s.IPs[i].Hosts = []string{name}
|
|
}
|
|
for i := range s.Recent {
|
|
s.Recent[i].Host = name
|
|
}
|
|
for i := range s.Sources {
|
|
s.Sources[i].Host = name
|
|
}
|
|
return s
|
|
}
|
|
|
|
// Run refreshes until ctx is done.
|
|
func (h *Hub) Run(ctx context.Context) {
|
|
if len(h.Peers) == 0 {
|
|
return
|
|
}
|
|
h.Stream(ctx)
|
|
h.Refresh(ctx)
|
|
t := time.NewTicker(h.Interval)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
h.Refresh(ctx)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Hosts lists the status of every peer (online or not).
|
|
func (h *Hub) Hosts() []store.HostInfo {
|
|
h.mu.RLock()
|
|
defer h.mu.RUnlock()
|
|
out := make([]store.HostInfo, 0, len(h.Peers))
|
|
for _, p := range h.Peers {
|
|
st := h.state[p.Name]
|
|
hi := store.HostInfo{Name: p.Name, Online: st.online, Error: st.err, LastSeen: st.lastOK, LatencyMS: st.latency, Version: st.version, Live: st.live && st.online}
|
|
if e, ok := st.exports["24h"]; ok && st.online {
|
|
s := e.Summary
|
|
hi.Requests, hi.Malicious = s.Totals.Requests, s.Totals.Malicious
|
|
hi.HostileIPs, hi.ActiveBans = s.Totals.HostileIPs, s.Totals.ActiveBans
|
|
if len(s.Hosts) > 0 {
|
|
hi.Location = s.Hosts[0].Location
|
|
}
|
|
}
|
|
out = append(out, hi)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Summaries returns the summaries of online peers for a range. When only is
|
|
// not empty just that peer is returned.
|
|
func (h *Hub) Summaries(rangeName, only string) []store.Summary {
|
|
h.mu.RLock()
|
|
defer h.mu.RUnlock()
|
|
var out []store.Summary
|
|
for _, p := range h.Peers {
|
|
if only != "" && only != p.Name {
|
|
continue
|
|
}
|
|
st := h.state[p.Name]
|
|
if e, ok := st.exports[rangeName]; ok && st.online {
|
|
out = append(out, e.Summary)
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Peers lists the configured peer names (nil-safe).
|
|
func (h *Hub) PeerNames() []string {
|
|
if h == nil {
|
|
return nil
|
|
}
|
|
out := make([]string, 0, len(h.Peers))
|
|
for _, p := range h.Peers {
|
|
out = append(out, p.Name)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Has reports whether name is a configured peer.
|
|
func (h *Hub) Has(name string) bool {
|
|
for _, p := range h.Peers {
|
|
if p.Name == name {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// IPDetail looks an address up in the cached exports of the online peers (the
|
|
// 30-day summary, which carries the full row). No request is made to the peer.
|
|
func (h *Hub) IPDetail(ip string) []store.IPSummary {
|
|
h.mu.RLock()
|
|
defer h.mu.RUnlock()
|
|
var out []store.IPSummary
|
|
for _, p := range h.Peers {
|
|
st := h.state[p.Name]
|
|
e, ok := st.exports["30d"]
|
|
if !ok || !st.online {
|
|
continue
|
|
}
|
|
for _, x := range e.Summary.IPs {
|
|
if x.IP == ip {
|
|
out = append(out, x)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Traffic returns the cached analytics of online peers (or only one) for a
|
|
// domain ("all" or a name), from the same export.
|
|
func (h *Hub) Traffic(rangeName, domain, only string) []store.TrafficData {
|
|
h.mu.RLock()
|
|
defer h.mu.RUnlock()
|
|
var out []store.TrafficData
|
|
for _, p := range h.Peers {
|
|
if only != "" && only != p.Name {
|
|
continue
|
|
}
|
|
st := h.state[p.Name]
|
|
if e, ok := st.exports[rangeName]; ok && st.online {
|
|
if t, ok := e.Traffic[domain]; ok {
|
|
t.Host = p.Name
|
|
out = append(out, t)
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|