Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1ef5a0ce9f | ||
|
|
0dc3268b29 | ||
|
|
50cd2bd3ce |
No files matched your search
@@ -6,6 +6,20 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.4.5] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Second firewall: it now uses the history. An address whose verdict is hostile (or suspicious with score 100 or more) is banned on its first new malicious event (`known-attacker`); 10 SSH failures or 20 web scan/exploit events in 24 h also ban (slow attackers); a sweep every 10 minutes (and after the start-up backfill) bans the addresses active in the last 24 h that nothing blocks yet, at most `--enforce-max-per-min` per minute, with every exclusion kept. Coverage in `/api/v1/enforce` is computed from the store, so it survives restarts.
|
||||
|
||||
## [1.4.4] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Traefik access logs in the default text format are now read too (fewer fields than JSON: no host or service), so a proxy that loses its JSON setting no longer silently drops the web traffic.
|
||||
- A source with more than 20% unreadable lines in its last 1000 is shown as degraded (red) in Integrity and Sources, logged once an hour, and checked by `urutau doctor`.
|
||||
- Mobile: the More menu scrolls when it is taller than the screen.
|
||||
|
||||
## [1.4.3] - 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
@@ -6,6 +6,20 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.4.5] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Segundo firewall: agora usa o histórico. Endereço com veredito hostil (ou suspeito com score 100 ou mais) é banido no primeiro evento malicioso novo (`known-attacker`); 10 falhas SSH ou 20 eventos de varredura/exploração web em 24 h também banem (atacantes lentos); uma varredura a cada 10 minutos (e após o backfill da partida) bane os endereços ativos nas últimas 24 h que nada bloqueia ainda, no máximo `--enforce-max-per-min` por minuto, mantidas todas as exclusões. A cobertura de `/api/v1/enforce` sai do store e sobrevive a reinícios.
|
||||
|
||||
## [1.4.4] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- O log de acesso do Traefik no formato texto padrão agora também é lido (menos campos que o JSON: sem host nem serviço), então um proxy que perde a configuração JSON não descarta mais o tráfego web em silêncio.
|
||||
- Uma fonte com mais de 20% de linhas ilegíveis nas últimas 1000 aparece como degradada (vermelho) em Integridade e Fontes, é registrada no log uma vez por hora e é verificada pelo `urutau doctor`.
|
||||
- Celular: o menu Mais rola quando é maior que a tela.
|
||||
|
||||
## [1.4.3] - 2026-11-15
|
||||
|
||||
### Adicionado
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
"io"
|
||||
@@ -46,6 +49,11 @@ func Doctor(c Config, w io.Writer, asJSON bool) bool {
|
||||
fi, _ := f.Stat()
|
||||
f.Close()
|
||||
add("source "+s.name, "ok", fmt.Sprintf("%s readable (%d bytes)", s.path, fi.Size()))
|
||||
if s.name == "traefik" {
|
||||
if bad, n := sampleMalformed(s.path); n >= winMin && bad*5 > n {
|
||||
add("source traefik format", "warn", fmt.Sprintf("degraded: %d of the last %d lines are malformed: %s", bad, n, degradedMsg))
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(c.DataDir, 0o700); err != nil {
|
||||
add("data-dir", "fail", err.Error())
|
||||
@@ -134,3 +142,45 @@ func doctorState(c Config, add func(name, status, detail string)) map[string]any
|
||||
add("state", "ok", fmt.Sprintf("%d IPs, %d domains, %d requests in 7 days", st.IPCount(), len(tr.Domains), tr.Requests))
|
||||
return info
|
||||
}
|
||||
|
||||
// sampleMalformed parses up to the last winSize lines of a Traefik log and
|
||||
// counts the malformed ones.
|
||||
func sampleMalformed(path string) (bad, n int) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return 0, 0
|
||||
}
|
||||
defer f.Close()
|
||||
const tailBytes = 512 << 10
|
||||
off := int64(0)
|
||||
if fi, err := f.Stat(); err == nil && fi.Size() > tailBytes {
|
||||
off = fi.Size() - tailBytes
|
||||
}
|
||||
if _, err := f.Seek(off, io.SeekStart); err != nil {
|
||||
return 0, 0
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(f, tailBytes))
|
||||
if err != nil {
|
||||
return 0, 0
|
||||
}
|
||||
lines := bytes.Split(b, []byte("\n"))
|
||||
if off > 0 && len(lines) > 0 {
|
||||
lines = lines[1:] // first line is cut
|
||||
}
|
||||
if len(lines) > 0 && len(lines[len(lines)-1]) == 0 {
|
||||
lines = lines[:len(lines)-1]
|
||||
}
|
||||
if len(lines) > winSize {
|
||||
lines = lines[len(lines)-winSize:]
|
||||
}
|
||||
for _, l := range lines {
|
||||
if len(bytes.TrimSpace(l)) == 0 {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
if _, err := core.ParseTraefik(l); err != nil && !errors.Is(err, core.ErrIgnored) {
|
||||
bad++
|
||||
}
|
||||
}
|
||||
return bad, n
|
||||
}
|
||||
+20
-1
@@ -22,7 +22,7 @@ import (
|
||||
)
|
||||
|
||||
// newEnforce builds the second firewall and hooks it into the store; nil when off.
|
||||
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enforce.Engine {
|
||||
func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready func() bool) *enforce.Engine {
|
||||
mode := strings.ToLower(c.Enforce)
|
||||
if mode != enforce.ModeObserve && mode != enforce.ModeOn {
|
||||
return nil
|
||||
@@ -39,6 +39,25 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enfor
|
||||
Threshold: c.EnforceThreshold, MaxPerMin: c.EnforceMaxPerMin, Share: strings.EqualFold(c.EnforceShare, "on"),
|
||||
Trusted: trusted, PeerHosts: hosts, InfraHosts: hosts, Resolve: resolveHost,
|
||||
Crawler: func(ip string, uas []string) bool { v := st.FCrDNS(ip, uas); return v != nil && *v },
|
||||
Rep: st.Reputation,
|
||||
Tally: func(ip string, from int64) (int, int) { t := st.AttackTally(ip, from); return t.SSH, t.Web },
|
||||
Roster: func(from int64) []enforce.Seen {
|
||||
rows := st.AttackRoster(from)
|
||||
out := make([]enforce.Seen, len(rows))
|
||||
for i, r := range rows {
|
||||
out[i] = enforce.Seen{IP: r.IP, Score: r.Score, Level: r.Level, Jails: r.Jails}
|
||||
}
|
||||
return out
|
||||
},
|
||||
Tallies: func(from int64) map[string]enforce.Tally {
|
||||
m := st.AttackTallies(from)
|
||||
out := make(map[string]enforce.Tally, len(m))
|
||||
for k, v := range m {
|
||||
out[k] = enforce.Tally{SSH: v.SSH, Web: v.Web}
|
||||
}
|
||||
return out
|
||||
},
|
||||
Ready: ready,
|
||||
Geo: func(ip string) (string, uint32, string) {
|
||||
if en.g == nil {
|
||||
return "", 0, ""
|
||||
|
||||
@@ -109,7 +109,14 @@ func Serve(c Config) error {
|
||||
extra := runner.Extra
|
||||
runner.Extra = func() []store.SourceStatus { return append(extra(), egressSrc.Status()) }
|
||||
}
|
||||
eng := newEnforce(c, st, peers, en)
|
||||
eng := newEnforce(c, st, peers, en, func() bool {
|
||||
for _, s := range runner.Sources {
|
||||
if s.backfilling.Load() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
})
|
||||
if eng != nil {
|
||||
server.SetEnforce(eng)
|
||||
}
|
||||
|
||||
+53
-1
@@ -23,6 +23,8 @@ type source struct {
|
||||
parse func([]byte) (core.Event, error)
|
||||
|
||||
lines, malformed atomic.Uint64
|
||||
win window
|
||||
lastWarn atomic.Int64
|
||||
lastEvent atomic.Int64
|
||||
backfilling atomic.Bool
|
||||
fol atomic.Pointer[tail.Follower]
|
||||
@@ -32,6 +34,44 @@ func traefikParse(b []byte) (core.Event, error) { return core.ParseTraefik(b) }
|
||||
func authParse(b []byte) (core.Event, error) { return core.ParseAuth(string(b)) }
|
||||
func f2bParse(b []byte) (core.Event, error) { return core.ParseFail2ban(string(b)) }
|
||||
|
||||
const (
|
||||
winSize = 1000
|
||||
winMin = 50 // fewer samples than this never mark a source degraded
|
||||
degradedMsg = "formato inesperado (JSON esperado?)"
|
||||
)
|
||||
|
||||
// window remembers whether each of the last winSize lines was malformed.
|
||||
type window struct {
|
||||
mu sync.Mutex
|
||||
ring [winSize]bool
|
||||
n int // lines recorded so far, capped at winSize
|
||||
pos int
|
||||
bad int
|
||||
}
|
||||
|
||||
func (w *window) add(bad bool) {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
if w.n == winSize && w.ring[w.pos] {
|
||||
w.bad--
|
||||
}
|
||||
w.ring[w.pos] = bad
|
||||
if bad {
|
||||
w.bad++
|
||||
}
|
||||
w.pos = (w.pos + 1) % winSize
|
||||
if w.n < winSize {
|
||||
w.n++
|
||||
}
|
||||
}
|
||||
|
||||
// degraded reports whether more than 20% of the recent lines were malformed.
|
||||
func (w *window) degraded() bool {
|
||||
w.mu.Lock()
|
||||
defer w.mu.Unlock()
|
||||
return w.n >= winMin && w.bad*5 > w.n
|
||||
}
|
||||
|
||||
func (s *source) status() store.SourceStatus {
|
||||
st := store.SourceStatus{Name: s.name, Path: s.path, Lines: s.lines.Load(), Malformed: s.malformed.Load(),
|
||||
LastEvent: s.lastEvent.Load(), State: "following"}
|
||||
@@ -55,6 +95,9 @@ func (s *source) status() store.SourceStatus {
|
||||
}
|
||||
}
|
||||
}
|
||||
if st.State == "following" && s.win.degraded() {
|
||||
st.State, st.Error = "degraded", degradedMsg
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
@@ -148,11 +191,20 @@ func (r *Runner) handle(s *source) func([]byte) {
|
||||
s.lines.Add(1)
|
||||
ev, err := s.parse(line)
|
||||
if err != nil {
|
||||
if !errors.Is(err, core.ErrIgnored) {
|
||||
bad := !errors.Is(err, core.ErrIgnored)
|
||||
if bad {
|
||||
s.malformed.Add(1)
|
||||
}
|
||||
s.win.add(bad)
|
||||
if bad && s.win.degraded() {
|
||||
now := time.Now().Unix()
|
||||
if last := s.lastWarn.Load(); now-last >= 3600 && s.lastWarn.CompareAndSwap(last, now) {
|
||||
r.Log.Warn("many lines of this source are malformed", "source", s.name, "detail", degradedMsg)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
s.win.add(false)
|
||||
if core.Ignored(r.Ignore, ev.IP) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -257,3 +257,25 @@ func TestEgressExtraAllow(t *testing.T) {
|
||||
t.Fatalf("%v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceDegradedWindow(t *testing.T) {
|
||||
var w window
|
||||
for i := 0; i < 100; i++ {
|
||||
w.add(i%10 == 0)
|
||||
}
|
||||
if w.degraded() {
|
||||
t.Fatal("10% must not degrade")
|
||||
}
|
||||
for i := 0; i < 400; i++ {
|
||||
w.add(true)
|
||||
}
|
||||
if !w.degraded() {
|
||||
t.Fatal("expected degraded")
|
||||
}
|
||||
for i := 0; i < winSize; i++ {
|
||||
w.add(false)
|
||||
}
|
||||
if w.degraded() {
|
||||
t.Fatal("window must recover")
|
||||
}
|
||||
}
|
||||
@@ -2,4 +2,4 @@ package app
|
||||
|
||||
// Version is the release version (SemVer). Release builds may override it with
|
||||
// -ldflags "-X .../internal/app.Version=...".
|
||||
var Version = "1.4.3"
|
||||
var Version = "1.4.5"
|
||||
@@ -266,3 +266,25 @@ func TestZonesAreRejectedEverywhere(t *testing.T) {
|
||||
}
|
||||
_ = strings.ToLower
|
||||
}
|
||||
|
||||
func TestParseTraefikText(t *testing.T) {
|
||||
ev, err := ParseTraefik([]byte(`10.0.15.1 - - [15/Nov/2026:04:10:51 +0000] "GET /wp-content/uploads/2026/08/IMG.jpg HTTP/2.0" 200 252131 "-" "-" 22219 "https-0-fwl1r20xzp8uf2g48log9q49-wordpress-1870@docker" "http://10.0.5.2:80" 3ms`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ev.IP != "10.0.15.1" || ev.Method != "GET" || ev.Path != "/wp-content/uploads/2026/08/IMG.jpg" || ev.Proto != "HTTP/2.0" ||
|
||||
ev.Status != 200 || ev.Bytes != 252131 || ev.UA != "" || ev.Referer != "" || ev.OriginStatus != 200 ||
|
||||
ev.DurationNS != 3e6 || ev.Domain != "" || ev.Router != "https-0-fwl1r20xzp8uf2g48log9q49-wordpress-1870@docker" ||
|
||||
ev.Time.Format("2006-01-02T15:04:05Z") != "2026-11-15T04:10:51Z" {
|
||||
t.Fatalf("%+v", ev)
|
||||
}
|
||||
ev, err = ParseTraefik([]byte(`203.0.113.9 - - [15/Nov/2026:04:10:52 +0000] "POST /wp-login.php HTTP/1.1" 404 19 "https://x/\"y" "Mozilla \"q\" 5.0" 1 "web@docker" "-" 12ms`))
|
||||
if err != nil || ev.Method != "POST" || ev.Status != 404 || ev.UA != `Mozilla "q" 5.0` || ev.Referer != `https://x/"y` || ev.OriginStatus != 0 {
|
||||
t.Fatalf("%+v %v", ev, err)
|
||||
}
|
||||
for _, bad := range []string{"garbage", `1.2.3.4 - - [bad] "GET / HTTP/1.1" 200 1 "-" "-" 1`, `1.2.3.4 - - [15/Nov/2026:04:10:52 +0000] "GET / HTTP/1.1" 200 1 "-" "-`, `nope - - [15/Nov/2026:04:10:52 +0000] "GET / HTTP/1.1" 200 1 "-" "-" 1`} {
|
||||
if _, err := ParseTraefik([]byte(bad)); err == nil {
|
||||
t.Errorf("accepted %q", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/netip"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -72,6 +74,9 @@ type traefikLine struct {
|
||||
|
||||
// ParseTraefik parses one Traefik JSON access log line.
|
||||
func ParseTraefik(line []byte) (Event, error) {
|
||||
if t := bytes.TrimLeft(line, " \t"); len(t) > 0 && t[0] != '{' {
|
||||
return parseTraefikText(string(t))
|
||||
}
|
||||
var l traefikLine
|
||||
if err := json.Unmarshal(line, &l); err != nil {
|
||||
return Event{}, err
|
||||
@@ -213,3 +218,119 @@ func ParseFail2ban(line string) (Event, error) {
|
||||
Unban: m[3] == "Unban", Restore: m[3] == "Restore Ban",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// textFields splits a Traefik text (extended CLF) access log line into its
|
||||
// fields. Quoted fields may carry backslash escapes, the [time] field is read
|
||||
// up to the closing bracket.
|
||||
func textFields(s string) ([]string, bool) {
|
||||
var out []string
|
||||
i := 0
|
||||
for i < len(s) {
|
||||
switch c := s[i]; {
|
||||
case c == ' ' || c == '\t':
|
||||
i++
|
||||
case c == '"':
|
||||
var b strings.Builder
|
||||
i++
|
||||
closed := false
|
||||
for i < len(s) {
|
||||
if s[i] == '\\' && i+1 < len(s) {
|
||||
b.WriteByte(s[i+1])
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if s[i] == '"' {
|
||||
closed = true
|
||||
i++
|
||||
break
|
||||
}
|
||||
b.WriteByte(s[i])
|
||||
i++
|
||||
}
|
||||
if !closed {
|
||||
return nil, false
|
||||
}
|
||||
out = append(out, b.String())
|
||||
case c == '[':
|
||||
j := strings.IndexByte(s[i:], ']')
|
||||
if j < 0 {
|
||||
return nil, false
|
||||
}
|
||||
out = append(out, s[i+1:i+j])
|
||||
i += j + 1
|
||||
default:
|
||||
j := i
|
||||
for j < len(s) && s[j] != ' ' && s[j] != '\t' {
|
||||
j++
|
||||
}
|
||||
out = append(out, s[i:j])
|
||||
i = j
|
||||
}
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func dash(s string) string {
|
||||
if s == "-" {
|
||||
return ""
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// parseTraefikText parses the default Traefik access log format:
|
||||
// host ident user [time] "METHOD path PROTO" status size "referer" "ua" count "router" "backend" Nms
|
||||
// The format carries no Host header, so Domain stays empty.
|
||||
func parseTraefikText(line string) (Event, error) {
|
||||
f, ok := textFields(line)
|
||||
if !ok || len(f) < 9 {
|
||||
return Event{}, errors.New("not a traefik text line")
|
||||
}
|
||||
ip, ok := cleanIP(f[0])
|
||||
if !ok {
|
||||
if _, err := netip.ParseAddr(strings.TrimSpace(f[0])); err != nil {
|
||||
return Event{}, errors.New("bad client address")
|
||||
}
|
||||
return Event{}, ErrIgnored
|
||||
}
|
||||
t, err := time.Parse("02/Jan/2006:15:04:05 -0700", f[3])
|
||||
if err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
rl := strings.Fields(f[4])
|
||||
if len(rl) < 2 {
|
||||
return Event{}, errors.New("bad request line")
|
||||
}
|
||||
method, path, proto := rl[0], rl[1], ""
|
||||
if len(rl) >= 3 {
|
||||
proto = rl[len(rl)-1]
|
||||
}
|
||||
status, err := strconv.Atoi(f[5])
|
||||
if err != nil || status < 100 || status > 999 {
|
||||
return Event{}, errors.New("bad status")
|
||||
}
|
||||
var size int64
|
||||
if f[6] != "-" {
|
||||
if size, err = strconv.ParseInt(f[6], 10, 64); err != nil {
|
||||
return Event{}, err
|
||||
}
|
||||
}
|
||||
ev := Event{
|
||||
Time: t.UTC(), IP: ip, Source: "traefik", Status: status,
|
||||
Method: clip(method, 12), Path: clip(path, maxPath), Proto: clip(proto, 12),
|
||||
Bytes: size, Referer: clip(dash(f[7]), 300), UA: clip(dash(f[8]), maxUA),
|
||||
}
|
||||
if len(f) > 10 {
|
||||
ev.Router = clip(dash(f[10]), 64)
|
||||
}
|
||||
if len(f) > 11 && dash(f[11]) != "" {
|
||||
ev.OriginStatus = status
|
||||
}
|
||||
if len(f) > 12 {
|
||||
if d, err := time.ParseDuration(strings.TrimSpace(f[12])); err == nil {
|
||||
ev.DurationNS = d.Nanoseconds()
|
||||
}
|
||||
}
|
||||
c := Classify(method, path, status)
|
||||
ev.Cat, ev.Soft, ev.Strong, ev.Weak = c.Cat, c.Soft, c.Strong, c.Weak
|
||||
return ev, nil
|
||||
}
|
||||
@@ -31,6 +31,36 @@ type Config struct {
|
||||
Crawler func(ip string, uas []string) bool // FCrDNS verified crawler
|
||||
Geo func(ip string) (string, uint32, string) // cc, asn, org
|
||||
Now func() time.Time
|
||||
|
||||
// History hooks (all optional, supplied by the store).
|
||||
Rep func(ip string) (score float64, level core.Level, ok bool) // verdict of an address
|
||||
Tally func(ip string, from int64) (ssh, web int) // 24 h counts of one address
|
||||
Roster func(from int64) []Seen // addresses with malicious activity since from
|
||||
Tallies func(from int64) map[string]Tally // 24 h counts of every address, one pass
|
||||
Ready func() bool // false while sources still backfill
|
||||
}
|
||||
|
||||
// Seen is one address with malicious activity, as listed by Config.Roster.
|
||||
type Seen struct {
|
||||
IP string
|
||||
Score float64
|
||||
Level core.Level
|
||||
Jails []string
|
||||
}
|
||||
|
||||
// Tally counts malicious events of one address in LongWindow.
|
||||
type Tally struct{ SSH, Web int }
|
||||
|
||||
type longRec struct {
|
||||
ssh, web int
|
||||
at int64 // when loaded from the registry
|
||||
known bool
|
||||
fresh bool // just loaded: the current event is already counted
|
||||
}
|
||||
|
||||
type cand struct {
|
||||
a netip.Addr
|
||||
d Decision
|
||||
}
|
||||
|
||||
// Wire is a decision as exchanged between peers.
|
||||
@@ -151,6 +181,8 @@ type Engine struct {
|
||||
dirty bool
|
||||
lastSave time.Time
|
||||
hostIPs map[string][]netip.Addr // last good resolution per host
|
||||
long map[netip.Addr]*longRec
|
||||
queue []cand
|
||||
}
|
||||
|
||||
// New builds an engine and loads its state.
|
||||
@@ -174,7 +206,7 @@ func New(c Config) *Engine {
|
||||
}
|
||||
e := &Engine{cfg: c, log: &logFile{path: c.Path}, ch: make(chan item, 4096), ips: map[netip.Addr]*ipState{},
|
||||
bans: map[netip.Addr]banRec{}, would: map[netip.Addr]int64{}, skipSeen: map[netip.Addr]int64{},
|
||||
counts: Counts{Skipped: map[string]int{}}}
|
||||
counts: Counts{Skipped: map[string]int{}}, long: map[netip.Addr]*longRec{}}
|
||||
e.hostIPs = map[string][]netip.Addr{}
|
||||
e.excl = Exclusions{Trusted: c.Trusted, Peers: map[netip.Addr]bool{}, Infra: map[netip.Addr]bool{}}
|
||||
e.refreshPeers()
|
||||
@@ -223,15 +255,28 @@ func (e *Engine) Run(ctx context.Context) {
|
||||
defer flush.Stop()
|
||||
defer peers.Stop()
|
||||
defer e.log.close()
|
||||
sweepT := time.NewTicker(SweepEvery)
|
||||
defer sweepT.Stop()
|
||||
started := e.cfg.Now()
|
||||
swept := false
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
e.saveState()
|
||||
return
|
||||
case it := <-e.ch:
|
||||
e.process(it.ev, it.fam)
|
||||
e.handle(it.ev, it.fam)
|
||||
case <-sweepT.C:
|
||||
if swept {
|
||||
e.Sweep()
|
||||
}
|
||||
case <-flush.C:
|
||||
e.maybeSave()
|
||||
if !swept && e.cfg.Now().Sub(started) >= 20*time.Second && (e.cfg.Ready == nil || e.cfg.Ready()) {
|
||||
swept = true
|
||||
e.Sweep()
|
||||
}
|
||||
e.drain()
|
||||
case <-peers.C:
|
||||
e.refreshPeers()
|
||||
}
|
||||
@@ -431,6 +476,16 @@ func (e *Engine) process(ev core.Event, fam string) {
|
||||
st.uas = append(st.uas, ua)
|
||||
}
|
||||
}
|
||||
lr := e.long[a]
|
||||
if lr != nil {
|
||||
if lr.fresh {
|
||||
lr.fresh = false
|
||||
} else if ev.Cat == core.SSHFail {
|
||||
lr.ssh++
|
||||
} else {
|
||||
lr.web++
|
||||
}
|
||||
}
|
||||
crits := 0
|
||||
for _, x := range st.ev {
|
||||
if criticalReasons[x.slug] {
|
||||
@@ -442,6 +497,9 @@ func (e *Engine) process(ev core.Event, fam string) {
|
||||
if crit {
|
||||
in.Crit = slug
|
||||
}
|
||||
if lr != nil {
|
||||
in.Known, in.SSH24, in.Web24 = lr.known, lr.ssh, lr.web
|
||||
}
|
||||
e.fill(a, st, &in, now)
|
||||
d := Decide(in, Params{Threshold: e.cfg.Threshold})
|
||||
if d.Action == ActBan && e.cfg.Crawler != nil && len(st.uas) > 0 && e.cfg.Crawler(a.String(), st.uas) {
|
||||
@@ -627,10 +685,20 @@ func (e *Engine) AcceptPeer(name string, in []Wire) (accepted, invalid int) {
|
||||
|
||||
// Report summarizes the activity since the unix time from.
|
||||
func (e *Engine) Report(from int64) Report {
|
||||
var roster []Seen
|
||||
if e.cfg.Roster != nil {
|
||||
roster = e.cfg.Roster(from) // outside the lock: it walks the store
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
var cv Coverage
|
||||
if e.cfg.Roster != nil {
|
||||
cv = e.coverageOf(roster, from)
|
||||
}
|
||||
for _, st := range e.ips {
|
||||
if e.cfg.Roster != nil {
|
||||
break
|
||||
}
|
||||
if st.lastAttack < from {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
// SweepEvery is the period of the proactive sweep.
|
||||
const SweepEvery = 10 * time.Minute
|
||||
|
||||
const (
|
||||
longTTL = 10 * time.Minute // a loaded 24 h count is trusted this long, then reloaded
|
||||
maxLong = 20000
|
||||
jailOurs = "urutau"
|
||||
)
|
||||
|
||||
// IsKnown reports whether a verdict alone justifies a ban.
|
||||
func IsKnown(score float64, level core.Level) bool {
|
||||
return level == core.LevelHostile || (level == core.LevelSuspicious && score >= KnownSuspiciousScore)
|
||||
}
|
||||
|
||||
// handle is the live path of one event: it loads the history of a malicious
|
||||
// address (outside the lock, at most once per longTTL) and then decides.
|
||||
func (e *Engine) handle(ev core.Event, fam string) {
|
||||
e.prefetch(ev)
|
||||
e.process(ev, fam)
|
||||
}
|
||||
|
||||
func (e *Engine) prefetch(ev core.Event) {
|
||||
if e.cfg.Rep == nil && e.cfg.Tally == nil {
|
||||
return
|
||||
}
|
||||
if ev.Cat != core.SSHFail && !CountsAsAttack(ev) {
|
||||
return
|
||||
}
|
||||
a, err := netip.ParseAddr(ev.IP)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
a = a.Unmap().WithZone("")
|
||||
now := e.cfg.Now()
|
||||
if ev.Time.Unix() < now.Add(-Window).Unix() { // replayed history: no decision, no query
|
||||
return
|
||||
}
|
||||
e.mu.Lock()
|
||||
skip := e.excl.Excluded(a) != ""
|
||||
lr := e.long[a]
|
||||
stale := lr == nil || now.Unix()-lr.at > int64(longTTL/time.Second)
|
||||
e.mu.Unlock()
|
||||
if skip {
|
||||
return
|
||||
}
|
||||
var known bool
|
||||
if e.cfg.Rep != nil {
|
||||
if sc, lv, ok := e.cfg.Rep(a.String()); ok {
|
||||
known = IsKnown(sc, lv)
|
||||
}
|
||||
}
|
||||
var ssh, web int
|
||||
if stale && e.cfg.Tally != nil {
|
||||
ssh, web = e.cfg.Tally(a.String(), now.Add(-LongWindow).Unix())
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if len(e.long) >= maxLong {
|
||||
cut := now.Add(-LongWindow).Unix()
|
||||
for k, v := range e.long {
|
||||
if v.at < cut {
|
||||
delete(e.long, k)
|
||||
}
|
||||
}
|
||||
if len(e.long) >= maxLong {
|
||||
e.long = map[netip.Addr]*longRec{}
|
||||
}
|
||||
}
|
||||
lr = e.long[a]
|
||||
if lr == nil {
|
||||
lr = &longRec{}
|
||||
e.long[a] = lr
|
||||
}
|
||||
lr.known = known
|
||||
if stale {
|
||||
lr.ssh, lr.web, lr.at, lr.fresh = ssh, web, now.Unix(), true
|
||||
}
|
||||
}
|
||||
|
||||
// Sweep evaluates the addresses with malicious activity in the last 24 h that
|
||||
// nothing blocks yet and queues a ban for those the long rules justify. The
|
||||
// queue is drained at most MaxPerMin per minute by Run.
|
||||
func (e *Engine) Sweep() {
|
||||
if e.cfg.Roster == nil {
|
||||
return
|
||||
}
|
||||
now := e.cfg.Now()
|
||||
from := now.Add(-LongWindow).Unix()
|
||||
roster := e.cfg.Roster(from)
|
||||
var tallies map[string]Tally
|
||||
if e.cfg.Tallies != nil {
|
||||
tallies = e.cfg.Tallies(from)
|
||||
}
|
||||
sort.SliceStable(roster, func(i, j int) bool { return roster[i].Score > roster[j].Score })
|
||||
var q []cand
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
for _, r := range roster {
|
||||
if len(r.Jails) > 0 {
|
||||
continue // fail2ban or our own jail holds it
|
||||
}
|
||||
a, err := netip.ParseAddr(r.IP)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
a = a.Unmap().WithZone("")
|
||||
st := e.stateOf(a)
|
||||
t := tallies[a.String()]
|
||||
in := Input{Now: now, Known: IsKnown(r.Score, r.Level), SSH24: t.SSH, Web24: t.Web,
|
||||
Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.excl.Excluded(a)}
|
||||
e.fill(a, st, &in, now)
|
||||
d := Decide(in, Params{Threshold: e.cfg.Threshold})
|
||||
if d.Action == ActBan && e.cfg.Crawler != nil && len(st.uas) > 0 && e.cfg.Crawler(a.String(), st.uas) {
|
||||
in.Exclude = SkipCrawler
|
||||
d = Decide(in, Params{Threshold: e.cfg.Threshold})
|
||||
}
|
||||
switch d.Action {
|
||||
case ActBan:
|
||||
q = append(q, cand{a, d})
|
||||
case ActSkip:
|
||||
e.apply(a, st, d, "sweep", now)
|
||||
}
|
||||
}
|
||||
e.queue = q
|
||||
}
|
||||
|
||||
// drain applies queued sweep bans while this minute has budget left.
|
||||
func (e *Engine) drain() {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
now := e.cfg.Now()
|
||||
for len(e.queue) > 0 {
|
||||
if m := now.Unix() / 60; m != e.minute {
|
||||
e.minute, e.inMinute = m, 0
|
||||
}
|
||||
if e.inMinute >= e.cfg.MaxPerMin {
|
||||
return
|
||||
}
|
||||
c := e.queue[0]
|
||||
e.queue = e.queue[1:]
|
||||
st := e.stateOf(c.a)
|
||||
if st.banned > now.Unix() {
|
||||
continue
|
||||
}
|
||||
in := Input{Now: now}
|
||||
e.fill(c.a, st, &in, now)
|
||||
if in.Active {
|
||||
continue
|
||||
}
|
||||
c.d.TTL = TTLFor(in.Offences)
|
||||
e.apply(c.a, st, c.d, "local", now)
|
||||
}
|
||||
}
|
||||
|
||||
// coverageOf computes the coverage from the registry's roster plus the engine's
|
||||
// durable decisions; the lock is held.
|
||||
func (e *Engine) coverageOf(roster []Seen, from int64) Coverage {
|
||||
var cv Coverage
|
||||
for _, r := range roster {
|
||||
cv.AttackIPs++
|
||||
a, _ := netip.ParseAddr(r.IP)
|
||||
a = a.Unmap().WithZone("")
|
||||
f2b, ours := false, false
|
||||
for _, j := range r.Jails {
|
||||
if j == jailOurs {
|
||||
ours = true
|
||||
} else {
|
||||
f2b = true
|
||||
}
|
||||
}
|
||||
if b, ok := e.bans[a]; ok && b.Last >= from {
|
||||
ours = true
|
||||
}
|
||||
st := e.ips[a]
|
||||
switch {
|
||||
case f2b:
|
||||
cv.BlockedByFirewall++
|
||||
case ours || (st != nil && st.urutauAt >= from && st.urutauAt > 0):
|
||||
cv.BlockedByUrutau++
|
||||
case e.would[a] > 0 || (st != nil && st.wouldAt >= from && st.wouldAt > 0):
|
||||
cv.WouldBlock++
|
||||
default:
|
||||
cv.Unblocked++
|
||||
}
|
||||
}
|
||||
return cv
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
func sshEv(ip string, at time.Time) core.Event {
|
||||
return core.Event{Time: at, IP: ip, Cat: core.SSHFail, Source: "ssh", User: "root"}
|
||||
}
|
||||
|
||||
func histRig(t *testing.T, mod func(*Config)) *rig {
|
||||
return newRig(t, ModeOn, func(c *Config) {
|
||||
c.Trusted = append(c.Trusted, netip.MustParsePrefix("168.196.85.0/24"))
|
||||
if mod != nil {
|
||||
mod(c)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestKnownAttackerBansOnFirstEvent(t *testing.T) {
|
||||
lv := map[string]core.Level{"203.0.114.50": core.LevelHostile, "203.0.114.51": core.LevelSuspicious}
|
||||
sc := map[string]float64{"203.0.114.50": 80, "203.0.114.51": 40, "203.0.114.52": 120}
|
||||
lv["203.0.114.52"] = core.LevelSuspicious
|
||||
r := histRig(t, func(c *Config) {
|
||||
c.Rep = func(ip string) (float64, core.Level, bool) { l, ok := lv[ip]; return sc[ip], l, ok }
|
||||
})
|
||||
for _, ip := range []string{"203.0.114.50", "203.0.114.51", "203.0.114.52"} {
|
||||
r.e.handle(atk(ip, r.now, "/x", 404), "")
|
||||
}
|
||||
got := map[string]bool{}
|
||||
for _, l := range r.lines(t) {
|
||||
for _, ip := range []string{"203.0.114.50", "203.0.114.51", "203.0.114.52"} {
|
||||
if len(l) > 0 && contains(l, ip) {
|
||||
got[ip] = true
|
||||
if !contains(l, "known-attacker") {
|
||||
t.Errorf("reason: %s", l)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !got["203.0.114.50"] || got["203.0.114.51"] || !got["203.0.114.52"] {
|
||||
t.Fatalf("bans: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, sub string) bool {
|
||||
for i := 0; i+len(sub) <= len(s); i++ {
|
||||
if s[i:i+len(sub)] == sub {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestSlowSSH24h(t *testing.T) {
|
||||
r := histRig(t, func(c *Config) {
|
||||
c.Tally = func(ip string, from int64) (int, int) { return 9, 0 } // 9 already in the registry
|
||||
})
|
||||
r.e.handle(sshEv("203.0.114.60", r.now), "")
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("9 in 24h must not ban")
|
||||
}
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.e.handle(sshEv("203.0.114.60", r.now), "") // the 10th
|
||||
if l := r.lines(t); len(l) != 1 || !contains(l[0], "ssh-bruteforce") {
|
||||
t.Fatalf("lines: %v", l)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrustedNeverBannedByHistory(t *testing.T) {
|
||||
r := histRig(t, func(c *Config) {
|
||||
c.Rep = func(string) (float64, core.Level, bool) { return 200, core.LevelHostile, true }
|
||||
c.Tally = func(string, int64) (int, int) { return 500, 500 }
|
||||
c.Roster = func(int64) []Seen {
|
||||
return []Seen{{IP: "168.196.85.9", Score: 200, Level: core.LevelHostile}}
|
||||
}
|
||||
})
|
||||
r.e.handle(sshEv("168.196.85.9", r.now), "")
|
||||
r.e.Sweep()
|
||||
r.e.drain()
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatalf("trusted banned: %v", r.lines(t))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSweepRespectsExclusionsAndCap(t *testing.T) {
|
||||
var roster []Seen
|
||||
tal := map[string]Tally{}
|
||||
for i := 1; i <= 5; i++ {
|
||||
ip := "203.0.114." + itoa(100+i)
|
||||
roster = append(roster, Seen{IP: ip, Score: float64(60 - i), Level: core.LevelHostile})
|
||||
}
|
||||
roster = append(roster,
|
||||
Seen{IP: "168.196.85.7", Score: 90, Level: core.LevelHostile}, // trusted
|
||||
Seen{IP: "10.0.0.5", Score: 90, Level: core.LevelHostile}, // private
|
||||
Seen{IP: "203.0.114.120", Score: 90, Level: core.LevelHostile, Jails: []string{"sshd"}}, // already
|
||||
Seen{IP: "203.0.114.121", Score: 20, Level: core.LevelSuspicious}, // slow web
|
||||
)
|
||||
tal["203.0.114.121"] = Tally{Web: 25}
|
||||
r := histRig(t, func(c *Config) {
|
||||
c.MaxPerMin = 2
|
||||
c.Roster = func(int64) []Seen { return roster }
|
||||
c.Tallies = func(int64) map[string]Tally { return tal }
|
||||
})
|
||||
r.e.Sweep()
|
||||
r.e.drain()
|
||||
if n := len(r.lines(t)); n != 2 {
|
||||
t.Fatalf("minute 1: %d lines", n)
|
||||
}
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.e.drain()
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.e.drain()
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.e.drain()
|
||||
ls := r.lines(t)
|
||||
if len(ls) != 6 {
|
||||
t.Fatalf("total %d: %v", len(ls), ls)
|
||||
}
|
||||
for _, l := range ls {
|
||||
for _, bad := range []string{"168.196.85.7", "10.0.0.5", "203.0.114.120"} {
|
||||
if contains(l, bad) {
|
||||
t.Errorf("banned %s", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !contains(ls[len(ls)-1], "203.0.114.121") || !contains(ls[len(ls)-1], "scanner-flood") {
|
||||
t.Errorf("last: %s", ls[len(ls)-1])
|
||||
}
|
||||
if r.e.counts.DroppedRate != 0 {
|
||||
t.Errorf("cap must defer, not drop: %d", r.e.counts.DroppedRate)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageSurvivesRestart(t *testing.T) {
|
||||
roster := []Seen{
|
||||
{IP: "203.0.114.70", Jails: []string{"sshd"}},
|
||||
{IP: "203.0.114.71", Jails: []string{"urutau"}},
|
||||
{IP: "203.0.114.72"},
|
||||
{IP: "203.0.114.73"},
|
||||
}
|
||||
cfg := func(c *Config) { c.Roster = func(int64) []Seen { return roster } }
|
||||
r := histRig(t, cfg)
|
||||
r.e.AcceptPeer("x", nil)
|
||||
r.e.process(atk("203.0.114.72", r.now, "/.env", 200), "env-credentials")
|
||||
// 72 gets banned by the engine (written decision), 73 stays unblocked.
|
||||
r.e.mu.Lock()
|
||||
r.e.bans[netip.MustParseAddr("203.0.114.72")] = banRec{Until: r.now.Add(time.Hour).Unix(), Last: r.now.Unix(), Offences: 1}
|
||||
r.e.dirty = true
|
||||
r.e.mu.Unlock()
|
||||
r.e.saveState()
|
||||
from := r.now.Add(-24 * time.Hour).Unix()
|
||||
want := r.e.Report(from).Coverage
|
||||
if want.AttackIPs != 4 || want.BlockedByFirewall != 1 || want.BlockedByUrutau != 2 || want.Unblocked != 1 {
|
||||
t.Fatalf("coverage: %+v", want)
|
||||
}
|
||||
// restart: a new engine over the same state file and the same store
|
||||
c := Config{Mode: ModeOn, Path: r.log, StatePath: r.e.cfg.StatePath, Host: "oracle", Now: func() time.Time { return r.now }}
|
||||
cfg(&c)
|
||||
e2 := New(c)
|
||||
if got := e2.Report(from).Coverage; got != want {
|
||||
t.Fatalf("after restart %+v want %+v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func itoa(n int) string {
|
||||
if n == 0 {
|
||||
return "0"
|
||||
}
|
||||
s := ""
|
||||
for ; n > 0; n /= 10 {
|
||||
s = string(rune('0'+n%10)) + s
|
||||
}
|
||||
return s
|
||||
}
|
||||
+31
-14
@@ -21,26 +21,27 @@ const (
|
||||
|
||||
// Fixed reason slugs. Anything else is refused (also from peers).
|
||||
const (
|
||||
ReasonScannerFlood = "scanner-flood"
|
||||
ReasonExploitFlood = "exploit-flood"
|
||||
ReasonWebBrute = "web-bruteforce"
|
||||
ReasonWPBrute = "wp-bruteforce"
|
||||
ReasonSSHBrute = "ssh-bruteforce"
|
||||
ReasonRCE = "rce"
|
||||
ReasonTraversal = "path-traversal"
|
||||
ReasonEnvProbe = "env-probe"
|
||||
ReasonVCSProbe = "vcs-probe"
|
||||
ReasonWebshell = "webshell"
|
||||
ReasonSQLi = "sqli"
|
||||
ReasonLog4Shell = "log4shell"
|
||||
ReasonPortScan = "port-scan"
|
||||
ReasonScannerFlood = "scanner-flood"
|
||||
ReasonExploitFlood = "exploit-flood"
|
||||
ReasonWebBrute = "web-bruteforce"
|
||||
ReasonWPBrute = "wp-bruteforce"
|
||||
ReasonSSHBrute = "ssh-bruteforce"
|
||||
ReasonRCE = "rce"
|
||||
ReasonTraversal = "path-traversal"
|
||||
ReasonEnvProbe = "env-probe"
|
||||
ReasonVCSProbe = "vcs-probe"
|
||||
ReasonWebshell = "webshell"
|
||||
ReasonSQLi = "sqli"
|
||||
ReasonLog4Shell = "log4shell"
|
||||
ReasonPortScan = "port-scan"
|
||||
ReasonKnownAttacker = "known-attacker"
|
||||
)
|
||||
|
||||
var reasons = map[string]bool{
|
||||
ReasonScannerFlood: true, ReasonExploitFlood: true, ReasonWebBrute: true, ReasonWPBrute: true,
|
||||
ReasonSSHBrute: true, ReasonRCE: true, ReasonTraversal: true, ReasonEnvProbe: true,
|
||||
ReasonVCSProbe: true, ReasonWebshell: true, ReasonSQLi: true, ReasonLog4Shell: true,
|
||||
ReasonPortScan: true,
|
||||
ReasonPortScan: true, ReasonKnownAttacker: true,
|
||||
}
|
||||
|
||||
// ValidReason reports whether s is one of the fixed slugs.
|
||||
@@ -66,6 +67,13 @@ const (
|
||||
PortScanPorts = 10
|
||||
// CritHits is how many critical events of one address (in Window) justify a ban.
|
||||
CritHits = 2
|
||||
// SSH24Threshold SSH failures, or Web24Threshold web scan/exploit events, in
|
||||
// LongWindow justify a ban (slow attackers never cross the 10 minute rules).
|
||||
SSH24Threshold = 10
|
||||
Web24Threshold = 20
|
||||
LongWindow = 24 * time.Hour
|
||||
// KnownSuspiciousScore: a "suspicious" address at or above this score counts as a known attacker.
|
||||
KnownSuspiciousScore = 100
|
||||
)
|
||||
|
||||
// ttls is the advisory duration by number of previous bans.
|
||||
@@ -116,6 +124,9 @@ type Input struct {
|
||||
Banned bool // fail2ban already blocks it
|
||||
Active bool // an advisory ban is still valid
|
||||
Offences int
|
||||
Known bool // the store's verdict is hostile (or suspicious with a high score)
|
||||
SSH24 int // failed SSH logins in LongWindow
|
||||
Web24 int // web scan/exploit events in LongWindow
|
||||
}
|
||||
|
||||
// Params are the thresholds.
|
||||
@@ -153,6 +164,12 @@ func Decide(in Input, p Params) Decision {
|
||||
if !ValidReason(reason) {
|
||||
reason = ReasonScannerFlood
|
||||
}
|
||||
case in.Known:
|
||||
reason, score = ReasonKnownAttacker, 80
|
||||
case in.SSH24 >= SSH24Threshold:
|
||||
reason, score = ReasonSSHBrute, min(100, 60+(in.SSH24-SSH24Threshold))
|
||||
case in.Web24 >= Web24Threshold:
|
||||
reason, score = ReasonScannerFlood, min(100, 55+(in.Web24-Web24Threshold)/2)
|
||||
default:
|
||||
return Decision{}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ type integritySource struct {
|
||||
Lines uint64 `json:"lines"`
|
||||
Malformed uint64 `json:"malformed"`
|
||||
Last int64 `json:"last"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type integrityHost struct {
|
||||
@@ -97,7 +98,7 @@ func (s *Server) integrity(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
continue
|
||||
}
|
||||
hh.Sources = append(hh.Sources, integritySource{Name: src.Name, State: src.State, Lines: src.Lines, Malformed: src.Malformed, Last: src.LastEvent})
|
||||
hh.Sources = append(hh.Sources, integritySource{Name: src.Name, State: src.State, Lines: src.Lines, Malformed: src.Malformed, Last: src.LastEvent, Error: src.Error})
|
||||
lines += src.Lines
|
||||
bad += src.Malformed
|
||||
if src.LastEvent > hh.LastEvent {
|
||||
|
||||
@@ -224,7 +224,7 @@
|
||||
function countryLabel(cc) { return (flag(cc) + ' ' + countryName(cc)).trim(); }
|
||||
|
||||
var KNOWN_CATS = ['ok', 'notfound', 'scanner', 'exploit', 'bruteforce', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban'];
|
||||
var KNOWN_STATES = ['following', 'waiting', 'backfill', 'error', 'disabled'];
|
||||
var KNOWN_STATES = ['following', 'waiting', 'backfill', 'error', 'degraded', 'disabled'];
|
||||
var KNOWN_LEVELS = ['hostile', 'suspicious', 'low'];
|
||||
var KNOWN_TONES = ['neutral', 'ok', 'warn', 'danger', 'info'];
|
||||
var CHART_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban'];
|
||||
|
||||
@@ -114,6 +114,7 @@
|
||||
'df.en.reason.sqli': 'Attempt to tamper with the database (SQL injection)',
|
||||
'df.en.reason.log4shell': 'Log4Shell exploit attempt',
|
||||
'df.en.reason.port-scan': 'Scanning many network ports on the server',
|
||||
'df.en.reason.known-attacker': 'Known attacker returning (hostile verdict)',
|
||||
'df.en.error': 'Could not load the second firewall data.'
|
||||
},
|
||||
'pt-BR': {
|
||||
@@ -219,6 +220,7 @@
|
||||
'df.en.reason.sqli': 'Tentativa de adulterar o banco de dados (injeção de SQL)',
|
||||
'df.en.reason.log4shell': 'Tentativa de explorar o Log4Shell',
|
||||
'df.en.reason.port-scan': 'Varredura de muitas portas de rede do servidor',
|
||||
'df.en.reason.known-attacker': 'Atacante conhecido voltando (veredito hostil)',
|
||||
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.'
|
||||
}
|
||||
});
|
||||
|
||||
@@ -243,6 +243,7 @@ window.URUTAU_I18N = {
|
||||
'state.waiting': 'waiting for file',
|
||||
'state.backfill': 'reading history',
|
||||
'state.error': 'error',
|
||||
'state.degraded': 'degraded',
|
||||
'state.disabled': 'disabled',
|
||||
'cat.ok': 'ok',
|
||||
'cat.notfound': 'Nonexistent page (404)',
|
||||
@@ -744,6 +745,7 @@ window.URUTAU_I18N = {
|
||||
'state.waiting': 'aguardando arquivo',
|
||||
'state.backfill': 'lendo histórico',
|
||||
'state.error': 'erro',
|
||||
'state.degraded': 'degradada',
|
||||
'state.disabled': 'desativada',
|
||||
'cat.ok': 'ok',
|
||||
'cat.notfound': 'Página inexistente (404)',
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var STATES = { following: 1, waiting: 1, backfill: 1, error: 1, disabled: 1 };
|
||||
var STATES = { following: 1, waiting: 1, backfill: 1, error: 1, degraded: 1, disabled: 1 };
|
||||
var ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 3 4 6v6c0 4.5 3.2 7.8 8 9 4.8-1.2 8-4.5 8-9V6l-8-3z"/><path d="m9 12 2 2 4-4"/></svg>';
|
||||
|
||||
function boot() {
|
||||
@@ -44,6 +44,7 @@
|
||||
'ig.state.waiting': 'waiting',
|
||||
'ig.state.backfill': 'catching up',
|
||||
'ig.state.error': 'error',
|
||||
'ig.state.degraded': 'degraded',
|
||||
'ig.state.disabled': 'disabled',
|
||||
'ig.peers.title': 'Peers',
|
||||
'ig.peers.none': 'No peers configured.',
|
||||
@@ -96,6 +97,7 @@
|
||||
'ig.state.waiting': 'aguardando',
|
||||
'ig.state.backfill': 'recuperando',
|
||||
'ig.state.error': 'erro',
|
||||
'ig.state.degraded': 'degradada',
|
||||
'ig.state.disabled': 'desativada',
|
||||
'ig.peers.title': 'Peers',
|
||||
'ig.peers.none': 'Nenhum peer configurado.',
|
||||
@@ -172,7 +174,7 @@
|
||||
hosts.forEach(function (x) {
|
||||
gaps += (x.gaps || []).length;
|
||||
if (x.online) onlineN++;
|
||||
(x.sources || []).forEach(function (s) { lines += s.lines; bad += s.malformed; if (s.state === 'error') errors++; });
|
||||
(x.sources || []).forEach(function (s) { lines += s.lines; bad += s.malformed; if (s.state === 'error' || s.state === 'degraded') errors++; });
|
||||
});
|
||||
var offline = peers.filter(function (p) { return !p.online; }).length;
|
||||
var rate = lines + bad > 0 ? bad / (lines + bad) : 0;
|
||||
@@ -233,8 +235,8 @@
|
||||
var rows = [];
|
||||
hosts.forEach(function (x) {
|
||||
(x.sources || []).forEach(function (s) {
|
||||
var tone = s.state === 'error' ? 'danger' : s.state === 'following' ? 'ok' : 'neutral';
|
||||
rows.push([x.name, s.name, U.ui.badge(STATES[s.state] ? t('ig.state.' + s.state) : String(s.state || ''), tone), nf(s.lines), nf(s.malformed), s.last ? U.fmt.ago(s.last) : '-']);
|
||||
var tone = (s.state === 'error' || s.state === 'degraded') ? 'danger' : s.state === 'following' ? 'ok' : 'neutral';
|
||||
rows.push([x.name, s.name, U.ui.badge(STATES[s.state] ? t('ig.state.' + s.state) + (s.state === 'degraded' && s.error ? ' (' + s.error + ')' : '') : String(s.state || ''), tone), nf(s.lines), nf(s.malformed), s.last ? U.fmt.ago(s.last) : '-']);
|
||||
});
|
||||
});
|
||||
sp2.body.appendChild(rows.length ? table([t('ig.src.host'), t('ig.src.name'), t('ig.src.state'), t('ig.src.lines'), t('ig.src.bad'), t('ig.src.last')], rows) : U.ui.empty(t('ig.src.none')));
|
||||
|
||||
@@ -353,7 +353,7 @@ td small { display: block; color: var(--ink-muted); font-size: .8125rem; overflo
|
||||
.host dl { display: grid; grid-template-columns: 1fr auto; gap: 3px 8px; margin: 10px 0 0; font-size: .875rem; }
|
||||
.host dd { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
.host dt { color: var(--ink-muted); }
|
||||
.st-following { color: var(--ok); } .st-waiting, .st-backfill { color: var(--warn); } .st-error { color: var(--danger); } .st-disabled { color: var(--ink-muted); }
|
||||
.st-following { color: var(--ok); } .st-waiting, .st-backfill { color: var(--warn); } .st-error, .st-degraded { color: var(--danger); font-weight: 600; } .st-disabled { color: var(--ink-muted); }
|
||||
.kv { display: grid; grid-template-columns: minmax(120px, auto) minmax(0, 1fr); gap: 6px var(--s-4); }
|
||||
.kv dt { color: var(--ink-muted); } .kv dd { overflow-wrap: anywhere; }
|
||||
|
||||
@@ -419,7 +419,7 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
|
||||
.tab .nav-ico svg { width: 22px; height: 22px; }
|
||||
.tab span:last-child { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.tab[aria-current="page"], .tab[aria-expanded="true"] { background: var(--rail-active); color: #fff; }
|
||||
.more-sheet { position: fixed; left: 0; right: 0; bottom: 68px; z-index: 31; background: var(--surface-overlay); border-top: 1px solid var(--line-strong); border-radius: 14px 14px 0 0; padding: var(--s-3); box-shadow: var(--shadow); }
|
||||
.more-sheet { position: fixed; left: 0; right: 0; bottom: 68px; z-index: 31; background: var(--surface-overlay); border-top: 1px solid var(--line-strong); border-radius: 14px 14px 0 0; padding: var(--s-3); box-shadow: var(--shadow); max-height: calc(100dvh - 68px - env(safe-area-inset-top, 0px) - 12px); overflow-y: auto; overscroll-behavior: contain; -webkit-overflow-scrolling: touch; }
|
||||
.more-sheet:not([hidden]) { display: block; }
|
||||
.more-sheet a { display: flex; align-items: center; gap: var(--s-3); min-height: 48px; padding: 8px var(--s-3); color: var(--ink); text-decoration: none; border-radius: var(--radius-sm); }
|
||||
.more-sheet a[aria-current="page"] { background: var(--accent-soft); }
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
)
|
||||
|
||||
// RosterRow is one address with malicious activity, as the second firewall needs it.
|
||||
type RosterRow struct {
|
||||
IP string
|
||||
Score float64
|
||||
Level core.Level
|
||||
Jails []string
|
||||
Last int64
|
||||
}
|
||||
|
||||
// Tally24 counts the malicious events of one address in a window.
|
||||
type Tally24 struct{ SSH, Web int }
|
||||
|
||||
// AttackRoster lists the addresses with malicious activity since from (unix).
|
||||
func (s *Store) AttackRoster(from int64) []RosterRow {
|
||||
nowU := s.now().Unix()
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
out := make([]RosterRow, 0, 256)
|
||||
for ip, r := range s.ips {
|
||||
if r.Last < from || !isAttacker(r) {
|
||||
continue
|
||||
}
|
||||
strong := r.Strong || attackKinds(r.Counts) >= 2
|
||||
out = append(out, RosterRow{IP: ip, Score: round1(r.Score), Level: core.LevelOf(r.Score, strong, r.adminAt(nowU)),
|
||||
Jails: append([]string(nil), r.Jails...), Last: r.Last})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Reputation is the verdict of one address as the UI shows it.
|
||||
func (s *Store) Reputation(ip string) (float64, core.Level, bool) {
|
||||
ip = KeyOf(ip)
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
r := s.ips[ip]
|
||||
if r == nil {
|
||||
return 0, core.LevelLow, false
|
||||
}
|
||||
strong := r.Strong || attackKinds(r.Counts) >= 2
|
||||
return r.Score, core.LevelOf(r.Score, strong, r.adminAt(s.now().Unix())), true
|
||||
}
|
||||
|
||||
var tallyCats = map[string]bool{string(core.SSHFail): true, string(core.Scanner): true, string(core.Exploit): true, string(core.BruteForce): true}
|
||||
|
||||
func tallyAdd(m map[string]*Tally24, r evlog.Rec) {
|
||||
t := m[r.IP]
|
||||
if t == nil {
|
||||
t = &Tally24{}
|
||||
m[r.IP] = t
|
||||
}
|
||||
switch {
|
||||
case r.Cat == string(core.SSHFail):
|
||||
t.SSH++
|
||||
case r.Source == "traefik" && !strings.Contains(r.Flags, "F"):
|
||||
t.Web++
|
||||
}
|
||||
}
|
||||
|
||||
// AttackTallies counts, in one pass over the event log, the SSH failures and web
|
||||
// scan/exploit events of every address since from. Nil without an event log.
|
||||
func (s *Store) AttackTallies(from int64) map[string]Tally24 {
|
||||
if s.elog == nil {
|
||||
return nil
|
||||
}
|
||||
m := map[string]*Tally24{}
|
||||
s.elog.Scan(evlog.Filter{From: from, Cats: tallyCats}, 256<<20, false, func(r evlog.Rec, _ []byte) bool {
|
||||
tallyAdd(m, r)
|
||||
return true
|
||||
})
|
||||
out := make(map[string]Tally24, len(m))
|
||||
for k, v := range m {
|
||||
out[k] = *v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AttackTally is AttackTallies for one address.
|
||||
func (s *Store) AttackTally(ip string, from int64) Tally24 {
|
||||
if s.elog == nil {
|
||||
return Tally24{}
|
||||
}
|
||||
m := map[string]*Tally24{}
|
||||
s.elog.Scan(evlog.Filter{From: from, IP: ip, Cats: tallyCats}, 64<<20, false, func(r evlog.Rec, _ []byte) bool {
|
||||
tallyAdd(m, r)
|
||||
return true
|
||||
})
|
||||
var t Tally24
|
||||
for _, v := range m {
|
||||
t.SSH += v.SSH
|
||||
t.Web += v.Web
|
||||
}
|
||||
return t
|
||||
}
|
||||
Reference in new issue
Block a user