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" ) 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 mu sync.Mutex // commit mutex: held while a line is applied and by snapshots } // 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 } func (r *Runner) statuses() []store.SourceStatus { 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 _, 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" }