Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
483 lines
14 KiB
Go
483 lines
14 KiB
Go
package app
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net/netip"
|
|
"os"
|
|
"regexp"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/tail"
|
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/wire"
|
|
)
|
|
|
|
const maxLine = 64 * 1024
|
|
|
|
type source struct {
|
|
name, path string
|
|
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]
|
|
}
|
|
|
|
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"}
|
|
switch f := s.fol.Load(); {
|
|
case s.backfilling.Load():
|
|
st.State = "backfill"
|
|
case f == nil:
|
|
st.State = "waiting"
|
|
default:
|
|
if err := f.Err(); err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
st.State = "waiting"
|
|
} else {
|
|
st.State = "error"
|
|
switch {
|
|
case errors.Is(err, os.ErrPermission):
|
|
st.Error = "permission denied" // never echo the host path
|
|
default:
|
|
st.Error = "read error"
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if st.State == "following" && s.win.degraded() {
|
|
st.State, st.Error = "degraded", degradedMsg
|
|
}
|
|
return st
|
|
}
|
|
|
|
// Runner owns the log sources of one instance.
|
|
type Runner struct {
|
|
St *store.Store
|
|
Ignore []netip.Prefix
|
|
Monitor *regexp.Regexp
|
|
MonitorFrom []netip.Prefix // when set, monitors are only believed from these networks
|
|
Enr core.Enricher // optional geo and User-Agent resolver
|
|
Extra func() []store.SourceStatus
|
|
Sources []*source
|
|
DataDir string
|
|
Log *slog.Logger
|
|
// EgressFeed receives the "egress" lines of a probe (nil: they are only counted).
|
|
EgressFeed func(line []byte)
|
|
|
|
mu sync.Mutex // commit mutex: held while a line is applied and by snapshots
|
|
|
|
remote map[string]store.Offset // hub-committed offsets of the sources fed by a probe
|
|
isRemote bool
|
|
rstatus atomic.Pointer[wire.Status]
|
|
connected atomic.Bool
|
|
egLines atomic.Uint64
|
|
}
|
|
|
|
// NewRunner builds the runner for the enabled sources.
|
|
func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) {
|
|
ign, err := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
r := &Runner{St: st, Ignore: ign, DataDir: c.DataDir, Log: log}
|
|
if r.MonitorFrom, err = core.ParseCIDRs(c.MonitorFrom); err != nil {
|
|
return nil, err
|
|
}
|
|
if c.MonitorUA != "" {
|
|
if r.Monitor, err = regexp.Compile(c.MonitorUA); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
for _, d := range []struct {
|
|
name, path string
|
|
parse func([]byte) (core.Event, error)
|
|
}{{"traefik", c.TraefikLog, traefikParse}, {"ssh", c.AuthLog, authParse}, {"fail2ban", c.Fail2banLog, f2bParse}, {"probe", c.ProbeLog, newProbeParser().parse}} {
|
|
if d.path != "" {
|
|
r.Sources = append(r.Sources, &source{name: d.name, path: d.path, parse: d.parse})
|
|
}
|
|
}
|
|
st.SetSources(r.statuses)
|
|
return r, nil
|
|
}
|
|
|
|
// NewRemoteRunner builds the runner of a node whose sources are fed by a probe
|
|
// through Feed: the four parsed sources exist, none follows a file.
|
|
func NewRemoteRunner(c Config, st *store.Store, log *slog.Logger, dataDir string) (*Runner, error) {
|
|
c.TraefikLog, c.AuthLog, c.Fail2banLog, c.ProbeLog = "", "", "", ""
|
|
r, err := NewRunner(c, st, log)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
r.DataDir, r.isRemote, r.remote = dataDir, true, map[string]store.Offset{}
|
|
for _, name := range []string{"traefik", "ssh", "fail2ban", "probe"} {
|
|
parse := map[string]func([]byte) (core.Event, error){"traefik": traefikParse, "ssh": authParse, "fail2ban": f2bParse, "probe": newProbeParser().parse}[name]
|
|
r.Sources = append(r.Sources, &source{name: name, parse: parse})
|
|
}
|
|
return r, nil
|
|
}
|
|
|
|
// runnerSource maps a wire source name to the runner's (and snapshot's) name.
|
|
func runnerSource(src string) string {
|
|
if src == wire.SrcAuth {
|
|
return "ssh"
|
|
}
|
|
return src
|
|
}
|
|
|
|
// wireSource is the inverse of runnerSource.
|
|
func wireSource(name string) string {
|
|
if name == "ssh" {
|
|
return wire.SrcAuth
|
|
}
|
|
return name
|
|
}
|
|
|
|
func (r *Runner) find(name string) *source {
|
|
for _, s := range r.Sources {
|
|
if s.name == name {
|
|
return s
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// StartRemote sets the committed offsets of a probe-fed runner (from the
|
|
// snapshot); there are no followers to start.
|
|
func (r *Runner) StartRemote(ctx context.Context, offsets map[string]store.Offset) {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
for k, v := range offsets {
|
|
r.remote[k] = v
|
|
}
|
|
}
|
|
|
|
// RemoteOffsets returns the committed positions keyed by wire source name.
|
|
func (r *Runner) RemoteOffsets() map[string]wire.Pos {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
out := map[string]wire.Pos{}
|
|
for k, v := range r.remote {
|
|
out[wireSource(k)] = wire.Pos{Inode: v.Inode, Offset: v.Offset, FP: v.FP, FPLen: v.FPLen}
|
|
}
|
|
return out
|
|
}
|
|
|
|
// Feed applies one line of a probe (src is a wire source name): it is dropped
|
|
// when its end position is not past the committed one in the same file, else
|
|
// handled and committed. It reports whether the line was new.
|
|
func (r *Runner) Feed(src string, text []byte, end store.Offset) bool {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
return r.feedLocked(src, text, end)
|
|
}
|
|
|
|
func (r *Runner) feedLocked(src string, text []byte, end store.Offset) bool {
|
|
name := runnerSource(src)
|
|
if saved, ok := r.remote[name]; ok && end.Inode == saved.Inode && end.Offset <= saved.Offset && sameHead(saved, end) {
|
|
return false
|
|
}
|
|
if src == wire.SrcEgress {
|
|
r.egLines.Add(1)
|
|
if r.EgressFeed != nil {
|
|
func() {
|
|
defer func() { recover() }() // one hostile line must never take the node down
|
|
r.EgressFeed(text)
|
|
}()
|
|
}
|
|
} else if s := r.find(name); s != nil {
|
|
r.handle(s)(text)
|
|
}
|
|
r.remote[name] = end
|
|
return true
|
|
}
|
|
|
|
// sameHead reports whether two positions of one inode belong to the same file
|
|
// generation. A copytruncate rotation (Traefik's log) keeps the inode and
|
|
// restarts the offsets at 0: without comparing the head fingerprint every new
|
|
// line below the old high-water mark would be taken for a duplicate and lost
|
|
// until the file regrew past it. Fingerprints of different lengths cannot be
|
|
// compared and count as the same file.
|
|
func sameHead(a, b store.Offset) bool {
|
|
if a.FPLen > 0 && a.FPLen == b.FPLen {
|
|
return a.FP == b.FP
|
|
}
|
|
return true
|
|
}
|
|
|
|
// ApplyBatch applies the lines of a batch under the commit mutex.
|
|
func (r *Runner) ApplyBatch(lines []wire.Line) (accepted, dup int) {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
for _, l := range lines {
|
|
if r.feedLocked(l.Src, []byte(l.Text), store.Offset{Inode: l.End.Inode, Offset: l.End.Offset, FP: l.End.FP, FPLen: l.End.FPLen}) {
|
|
accepted++
|
|
} else {
|
|
dup++
|
|
}
|
|
}
|
|
return accepted, dup
|
|
}
|
|
|
|
// SetRemoteStatus stores the last status reported by the probe.
|
|
func (r *Runner) SetRemoteStatus(st wire.Status, connected bool) {
|
|
r.rstatus.Store(&st)
|
|
r.connected.Store(connected)
|
|
}
|
|
|
|
func (r *Runner) remoteStatuses() []store.SourceStatus {
|
|
ws := r.rstatus.Load()
|
|
var out []store.SourceStatus
|
|
seen := map[string]bool{}
|
|
if ws != nil {
|
|
for _, w := range ws.Sources {
|
|
name := runnerSource(w.Src)
|
|
seen[name] = true
|
|
row := store.SourceStatus{Name: name, State: w.State, Error: w.Error, Lines: w.Lines, Malformed: w.Oversize, LastEvent: w.LastLine}
|
|
if s := r.find(name); s != nil {
|
|
row.Lines, row.Malformed = max(row.Lines, s.lines.Load()), max(w.Oversize, s.malformed.Load())
|
|
if row.LastEvent == 0 {
|
|
row.LastEvent = s.lastEvent.Load()
|
|
}
|
|
if row.State == "following" && s.win.degraded() {
|
|
row.State, row.Error = "degraded", degradedMsg
|
|
}
|
|
}
|
|
out = append(out, row)
|
|
}
|
|
}
|
|
for _, s := range r.Sources { // sources the probe has not reported
|
|
if !seen[s.name] {
|
|
if ws == nil {
|
|
out = append(out, store.SourceStatus{Name: s.name, State: "waiting", Lines: s.lines.Load(), Malformed: s.malformed.Load(), LastEvent: s.lastEvent.Load()})
|
|
}
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (r *Runner) statuses() []store.SourceStatus {
|
|
var out []store.SourceStatus
|
|
if r.isRemote {
|
|
out = r.remoteStatuses()
|
|
} else {
|
|
out = make([]store.SourceStatus, 0, len(r.Sources))
|
|
for _, s := range r.Sources {
|
|
out = append(out, s.status())
|
|
}
|
|
}
|
|
if r.Extra != nil {
|
|
out = append(out, r.Extra()...)
|
|
}
|
|
return out
|
|
}
|
|
|
|
// monitorTraffic reports whether the event is benign traffic of a monitor.
|
|
func (r *Runner) monitorTraffic(ev *core.Event) bool {
|
|
if r.Monitor == nil || ev.Source != "traefik" || ev.UA == "" || !r.Monitor.MatchString(ev.UA) {
|
|
return false
|
|
}
|
|
if len(r.MonitorFrom) > 0 {
|
|
a, err := netip.ParseAddr(ev.IP)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
ok := false
|
|
for _, p := range r.MonitorFrom {
|
|
ok = ok || p.Contains(a)
|
|
}
|
|
if !ok {
|
|
return false // a monitor User-Agent from a stranger is just a User-Agent
|
|
}
|
|
return ev.Cat == core.OK || ev.Cat == core.NotFound
|
|
}
|
|
return ev.Cat == core.OK // without --monitor-from only successful hits are filtered
|
|
}
|
|
|
|
func (r *Runner) handle(s *source) func([]byte) {
|
|
return func(line []byte) {
|
|
defer func() {
|
|
// one hostile line must never take a source down
|
|
if p := recover(); p != nil {
|
|
s.malformed.Add(1)
|
|
r.Log.Error("recovered from a panic while handling a line", "source", s.name, "panic", p)
|
|
}
|
|
}()
|
|
if len(line) == 0 {
|
|
return
|
|
}
|
|
s.lines.Add(1)
|
|
ev, err := s.parse(line)
|
|
if err != nil {
|
|
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
|
|
}
|
|
if r.monitorTraffic(&ev) {
|
|
s.lastEvent.Store(time.Now().Unix())
|
|
r.St.Monitoring(ev.Time)
|
|
return
|
|
}
|
|
if r.Monitor != nil && ev.Source == "traefik" && ev.UA != "" && r.Monitor.MatchString(ev.UA) && ev.Cat != core.OK && ev.Cat != core.NotFound {
|
|
ev.Forged = true // UA claims to be a monitor but the request is an attack
|
|
}
|
|
s.lastEvent.Store(time.Now().Unix())
|
|
r.enrich(&ev)
|
|
if ev.E.Tool && ev.Weak && (ev.Cat == core.OK || ev.Cat == core.NotFound) {
|
|
// cmd=, |sh, eval( only count together with an attack tool
|
|
ev.Cat, ev.Weak = core.Exploit, false
|
|
ev.Soft, ev.Strong = ev.Status < 400, ev.Status >= 400
|
|
}
|
|
r.St.Ingest(ev)
|
|
r.St.ObserveService(ev)
|
|
if ev.Source == "traefik" && !ev.Forged && (ev.Cat == core.OK || ev.Cat == core.NotFound) {
|
|
r.St.Traffic(ev)
|
|
}
|
|
}
|
|
}
|
|
|
|
// enrich fills the location and User-Agent facts of an event.
|
|
func (r *Runner) enrich(ev *core.Event) {
|
|
if r.Enr == nil {
|
|
return
|
|
}
|
|
g := r.Enr.Geo(ev.IP)
|
|
ev.E.CC, ev.E.City = g.CC, g.City
|
|
if ev.UA != "" {
|
|
u := r.Enr.UA(ev.UA)
|
|
ev.E.Browser, ev.E.OS, ev.E.Device = u.Browser, u.OS, u.Device
|
|
ev.E.Bot, ev.E.BotName = u.Bot, u.BotName
|
|
ev.E.Tool = u.Device == "tool" || u.Tool != ""
|
|
}
|
|
}
|
|
|
|
// Start launches one goroutine per source. offsets are the saved positions.
|
|
func (r *Runner) Start(ctx context.Context, offsets map[string]store.Offset, wg *sync.WaitGroup) {
|
|
for _, s := range r.Sources {
|
|
off := offsets[s.name]
|
|
wg.Add(1)
|
|
go func(s *source, off store.Offset) {
|
|
defer wg.Done()
|
|
defer func() {
|
|
if p := recover(); p != nil {
|
|
r.Log.Error("source stopped by a panic", "source", s.name, "panic", p)
|
|
}
|
|
}()
|
|
h := r.handle(s)
|
|
if off.Inode == 0 && off.Offset == 0 {
|
|
s.backfilling.Store(true)
|
|
for _, b := range tail.Backups(s.path) {
|
|
if ctx.Err() != nil {
|
|
break
|
|
}
|
|
locked := func(l []byte) { r.mu.Lock(); h(l); r.mu.Unlock() }
|
|
if err := tail.ReadAll(b, maxLine, locked, func() { s.malformed.Add(1) }); err != nil {
|
|
r.Log.Warn("backfill failed", "source", s.name, "file", b, "err", err)
|
|
} else {
|
|
r.Log.Info("backfilled", "source", s.name, "file", b)
|
|
}
|
|
}
|
|
s.backfilling.Store(false)
|
|
}
|
|
f := tail.NewFollower(s.path, tail.Pos{Inode: off.Inode, Offset: off.Offset, FP: off.FP, FPLen: off.FPLen})
|
|
f.MaxLine, f.Handle, f.Mu = maxLine, h, &r.mu
|
|
f.Oversize = func() { s.malformed.Add(1) }
|
|
s.fol.Store(f)
|
|
f.Run(ctx)
|
|
}(s, off)
|
|
}
|
|
}
|
|
|
|
// Save writes a snapshot consistent with the file offsets. It refuses while a
|
|
// backfill is running (offsets would be missing and a restart would replay).
|
|
func (r *Runner) Save() error {
|
|
for _, s := range r.Sources {
|
|
if s.backfilling.Load() {
|
|
return errors.New("backfill in progress, snapshot skipped")
|
|
}
|
|
}
|
|
if err := os.MkdirAll(r.DataDir, 0o700); err != nil {
|
|
return err
|
|
}
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
offs := map[string]store.Offset{}
|
|
for k, v := range r.remote {
|
|
offs[k] = v
|
|
}
|
|
for _, s := range r.Sources {
|
|
if f := s.fol.Load(); f != nil {
|
|
p := f.Pos()
|
|
offs[s.name] = store.Offset{Inode: p.Inode, Offset: p.Offset, FP: p.FP, FPLen: p.FPLen}
|
|
}
|
|
}
|
|
return r.St.Save(SnapshotPath(r.DataDir), offs)
|
|
}
|
|
|
|
// SnapshotPath is the state file inside the data directory.
|
|
func SnapshotPath(dir string) string { return dir + "/urutau-state.gob" }
|