Compare commits

...
1 Commits
Author SHA1 Message Date
Lucas RayanandClaude Opus 5.5 da333d70f1 feat: 1.4.6 unban from the UI, operator allows, day-counter fallback for long windows
Release / Publish tags (push) Successful in 16s
Release / ci (push) Successful in 1m47s
Release / Build image (amd64) (push) Successful in 21s
Release / Build image (arm64) (push) Successful in 23s
CI / Format and vet (push) Successful in 27s
CI / Tests (Linux, race detector) (push) Successful in 1m20s
CI / Dependency audit (push) Successful in 31s
CI / Docker image (build and smoke test) (push) Skipped
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / Gitea release (push) Successful in 5s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 01:53:24 -03:00
25 changed files with 841 additions and 33 deletions

No files matched your search

+6
View File
@@ -6,6 +6,12 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
## [Unreleased]
## [1.4.6] - 2026-11-15
### Added
- Unban from the interface: an "Unban" button on recent decisions and on the address page asks the host (through `unban.log` next to `--enforce-log`, flag `--enforce-unban-log`) to lift the fail2ban block, and can keep the second firewall from banning the address again for 1 h, 24 h or 7 days (operator releases, listed and endable in Defense; shared with peers when sharing is on). API: `POST /api/v1/enforce/unban`, `DELETE /api/v1/enforce/allow`, `allows` in `GET /api/v1/enforce`.
## [1.4.5] - 2026-11-15
### Fixed
+6
View File
@@ -6,6 +6,12 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
## [Unreleased]
## [1.4.6] - 2026-11-15
### Adicionado
- Desbanir pela interface: botão "Desbanir" nas decisões recentes e na página do endereço pede ao host (por `unban.log` ao lado de `--enforce-log`, flag `--enforce-unban-log`) que libere o bloqueio do fail2ban, e pode impedir o segundo firewall de banir de novo por 1 h, 24 h ou 7 dias (liberações do operador, listadas e encerráveis em Defesa; compartilhadas com os parceiros quando o compartilhamento está ligado). API: `POST /api/v1/enforce/unban`, `DELETE /api/v1/enforce/allow`, `allows` em `GET /api/v1/enforce`.
## [1.4.5] - 2026-11-15
### Corrigido
+8 -2
View File
@@ -15,12 +15,13 @@ uid=${URUTAU_UID:-10001}
[ "$(id -u)" = 0 ] || { echo "run as root" >&2; exit 1; }
if [ "${1:-}" = "--remove" ]; then
systemctl disable --now urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer 2>/dev/null || true
systemctl disable --now urutau-egress.service urutau-containers-map.timer urutau-logrotate.timer urutau-unban.path 2>/dev/null || true
rm -f /etc/systemd/system/urutau-egress.service /etc/systemd/system/urutau-containers-map.service \
/etc/systemd/system/urutau-containers-map.timer /usr/local/sbin/urutau-containers-map \
/etc/rsyslog.d/41-urutau-egress.conf /etc/logrotate.d/urutau-egress \
/etc/fail2ban/jail.d/urutau.local /etc/fail2ban/filter.d/urutau.conf /etc/fail2ban/action.d/urutau-allports.conf \
/etc/systemd/system/urutau-logrotate.service /etc/systemd/system/urutau-logrotate.timer
/etc/systemd/system/urutau-logrotate.service /etc/systemd/system/urutau-logrotate.timer \
/etc/systemd/system/urutau-unban.path /etc/systemd/system/urutau-unban.service /usr/local/sbin/urutau-unban
rm -rf /etc/urutau
systemctl daemon-reload
systemctl restart rsyslog
@@ -57,6 +58,11 @@ if [ "${1:-}" = "--enforce" ]; then
install -m 0644 "$here/fail2ban-filter-urutau.conf" /etc/fail2ban/filter.d/urutau.conf
install -m 0644 "$here/fail2ban-action-urutau.conf" /etc/fail2ban/action.d/urutau-allports.conf
install -m 0644 "$here/fail2ban-jail-urutau.local" /etc/fail2ban/jail.d/urutau.local
[ -e /var/log/urutau-enforce/unban.log ] || install -m 0640 -o "$uid" -g adm /dev/null /var/log/urutau-enforce/unban.log
install -m 0755 "$here/urutau-unban" /usr/local/sbin/urutau-unban
install -m 0644 "$here/urutau-unban.path" "$here/urutau-unban.service" /etc/systemd/system/
systemctl daemon-reload
systemctl enable --now urutau-unban.path >/dev/null
fail2ban-client -t >/dev/null
fail2ban-client reload
echo "fail2ban jail 'urutau' on; mount /var/log/urutau-enforce:/logs/enforce (rw) in the container"
+31
View File
@@ -0,0 +1,31 @@
#!/bin/sh
# Urutau: applies the operator's unban requests written by Urutau (UI button)
# to /var/log/urutau-enforce/unban.log. One line per request:
# 2026-11-15T05:00:00Z urutau unban ip=203.0.113.7 allow=86400
# The address is validated strictly; fail2ban unbans it from every jail and,
# with allow>0, ignores it in every jail for that many seconds (pentests).
set -eu
log=/var/log/urutau-enforce/unban.log
state=/var/lib/urutau/unban.offset
[ -f "$log" ] || exit 0
mkdir -p /var/lib/urutau
off=$(cat "$state" 2>/dev/null || echo 0)
size=$(stat -c %s "$log")
[ "$size" -lt "$off" ] && off=0 # rotated or truncated
tail -c +"$((off + 1))" "$log" | head -n 1000 | while IFS= read -r line; do
ip=$(printf '%s\n' "$line" | sed -n 's/^[0-9TZ:-]* urutau unban ip=\([0-9a-fA-F.:]\{2,45\}\) allow=\([0-9]\{1,7\}\)$/\1/p')
allow=$(printf '%s\n' "$line" | sed -n 's/^.* allow=\([0-9]\{1,7\}\)$/\1/p')
[ -n "$ip" ] || continue
# only literal IPv4 / IPv6 addresses (no CIDR, no names)
python3 -c 'import ipaddress,sys; ipaddress.ip_address(sys.argv[1])' "$ip" 2>/dev/null || continue
fail2ban-client unban "$ip" >/dev/null 2>&1 || true
logger -t urutau-unban "unban $ip allow=${allow:-0}"
if [ "${allow:-0}" -gt 0 ]; then
for j in $(fail2ban-client status | sed -n 's/.*Jail list:[[:space:]]*//p' | tr ',' ' '); do
fail2ban-client set "$j" addignoreip "$ip" >/dev/null 2>&1 || true
done
systemd-run --quiet --on-active="${allow}s" --unit="urutau-allow-end-$(printf '%s' "$ip" | tr ':.' '--')" \
/bin/sh -c "for j in \$(fail2ban-client status | sed -n 's/.*Jail list:[[:space:]]*//p' | tr ',' ' '); do fail2ban-client set \$j delignoreip $ip; done" 2>/dev/null || true
fi
done
echo "$size" > "$state"
+8
View File
@@ -0,0 +1,8 @@
[Unit]
Description=Urutau: watch the operator's unban requests
[Path]
PathModified=/var/log/urutau-enforce/unban.log
[Install]
WantedBy=multi-user.target
+6
View File
@@ -0,0 +1,6 @@
[Unit]
Description=Urutau: apply the operator's unban requests
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/urutau-unban
+5
View File
@@ -51,6 +51,7 @@ type Config struct {
// Second firewall (see internal/enforce).
Enforce string // off (default), observe or on
EnforceLog string // decision file read by the host fail2ban
EnforceUnbanLog string // unban requests (UI button) read by the host; default: unban.log next to --enforce-log
EnforceShare string // off (default) or on: exchange decisions with peers
EnforceThreshold int // attack events in 10 minutes that justify a ban
EnforceMaxPerMin int // decisions per minute; the excess is dropped
@@ -180,6 +181,7 @@ func ParseFlags(name string, args []string) (Config, error) {
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.EnforceLog, "enforce-log", env("URUTAU_ENFORCE_LOG", "/logs/enforce/decisions.log"), "decision file appended in --enforce=on (URUTAU_ENFORCE_LOG)")
fs.StringVar(&c.EnforceUnbanLog, "enforce-unban-log", env("URUTAU_ENFORCE_UNBAN_LOG", ""), "unban request file written by the Unban button (URUTAU_ENFORCE_UNBAN_LOG); default unban.log next to --enforce-log")
fs.StringVar(&c.EnforceShare, "enforce-share", env("URUTAU_ENFORCE_SHARE", "off"), "on: exchange decisions with peers, each side applies its own exclusions (URUTAU_ENFORCE_SHARE)")
fs.IntVar(&c.EnforceThreshold, "enforce-threshold", envInt("URUTAU_ENFORCE_THRESHOLD", 5), "attack events in 10 minutes that justify a ban (URUTAU_ENFORCE_THRESHOLD)")
fs.StringVar(&c.Egress, "egress", env("URUTAU_EGRESS", "auto"), "egress analysis: auto (on when --egress-log exists), on or off (URUTAU_EGRESS)")
@@ -270,6 +272,9 @@ func (c Config) Validate(token string) ([]fed.Peer, error) {
if strings.EqualFold(c.Enforce, "on") && c.EnforceLog == "" {
return nil, fmt.Errorf("--enforce=on needs --enforce-log")
}
if c.EnforceUnbanLog == "" && c.EnforceLog != "" {
c.EnforceUnbanLog = filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
}
var peers []fed.Peer
seen := map[string]bool{}
envSeen := map[string]string{}
+13 -2
View File
@@ -35,7 +35,7 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready
}
}
e := enforce.New(enforce.Config{
Mode: mode, Path: c.EnforceLog, StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
Mode: mode, Path: c.EnforceLog, UnbanPath: c.EnforceUnbanLog, StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
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 },
@@ -45,7 +45,7 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready
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}
out[i] = enforce.Seen{IP: r.IP, Score: r.Score, Level: r.Level, Jails: r.Jails, Est: enforce.Tally{SSH: r.Est.SSH, Web: r.Est.Web}}
}
return out
},
@@ -90,6 +90,7 @@ func resolveHost(h string) []netip.Addr {
func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) {
pulled := map[string]int64{}
pushed := map[string]int64{}
pushedUn := map[string]int64{}
t := time.NewTicker(30 * time.Second)
defer t.Stop()
for {
@@ -112,6 +113,16 @@ func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *s
}
}
}
for _, p := range hub.Peers {
if mine := e.UnbansSince(pushedUn[p.Name]); len(mine) > 0 {
start := time.Now().Unix()
if err := hub.PostJSON(ctx, p, "/api/v1/peer/unban?from="+url.QueryEscape(e.Host()), map[string]any{"unbans": mine}); err == nil {
pushedUn[p.Name] = start
} else if ctx.Err() == nil {
log.Debug("enforce: unban push failed", "peer", p.Name, "err", err)
}
}
}
select {
case <-ctx.Done():
return
+1 -1
View File
@@ -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.5"
var Version = "1.4.6"
+33 -14
View File
@@ -18,6 +18,7 @@ import (
type Config struct {
Mode string
Path string // decision file
UnbanPath string // unban requests read by the host (empty: unbanning is unavailable)
StatePath string // enforce.json, empty: no persistence
Host string // name of this instance, written in every line
Threshold int // attack events in Window
@@ -46,6 +47,7 @@ type Seen struct {
Score float64
Level core.Level
Jails []string
Est Tally // estimate from per-day counters, used when the registry holds less
}
// Tally counts malicious events of one address in LongWindow.
@@ -162,10 +164,12 @@ const (
// Engine is the second firewall.
type Engine struct {
cfg Config
log *logFile
ch chan item
dropQ atomic.Int64
cfg Config
log *logFile
ch chan item
dropQ atomic.Int64
sweeping atomic.Bool
unlog *logFile
mu sync.Mutex
ips map[netip.Addr]*ipState
@@ -182,6 +186,8 @@ type Engine struct {
lastSave time.Time
hostIPs map[string][]netip.Addr // last good resolution per host
long map[netip.Addr]*longRec
allows map[netip.Addr]int64 // operator allowances: address -> until (unix)
unbans []UnbanWire
queue []cand
}
@@ -206,7 +212,8 @@ 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{}}, long: map[netip.Addr]*longRec{}}
counts: Counts{Skipped: map[string]int{}}, long: map[netip.Addr]*longRec{}, allows: map[netip.Addr]int64{}}
e.unlog = &logFile{path: c.UnbanPath}
e.hostIPs = map[string][]netip.Addr{}
e.excl = Exclusions{Trusted: c.Trusted, Peers: map[netip.Addr]bool{}, Infra: map[netip.Addr]bool{}}
e.refreshPeers()
@@ -268,13 +275,13 @@ func (e *Engine) Run(ctx context.Context) {
e.handle(it.ev, it.fam)
case <-sweepT.C:
if swept {
e.Sweep()
go 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()
go e.Sweep()
}
e.drain()
case <-peers.C:
@@ -493,7 +500,7 @@ func (e *Engine) process(ev core.Event, fam string) {
}
}
in := Input{Now: now, Attacks: len(st.ev), Top: topSlug(st.ev), SSHFails: len(st.ssh), Crits: crits,
Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.excl.Excluded(a)}
Legit: st.legit >= now.Add(-LegitWindow).Unix(), Exclude: e.exclude(a, now)}
if crit {
in.Crit = slug
}
@@ -668,7 +675,7 @@ func (e *Engine) AcceptPeer(name string, in []Wire) (accepted, invalid int) {
continue // already expired
}
st := e.stateOf(a)
in := Input{Now: now, Crit: w.Reason, Crits: CritHits, Exclude: e.excl.Excluded(a)}
in := Input{Now: now, Crit: w.Reason, Crits: CritHits, Exclude: e.exclude(a, now)}
if in.Exclude == "" && st.lastAttack < now.Add(-peerConfirmAge).Unix() {
in.Exclude = SkipUnconfirmed // a peer's word alone never bans: this node must have seen the address attack
}
@@ -715,7 +722,7 @@ func (e *Engine) Report(from int64) Report {
}
}
c := e.counts
c.Skipped = map[string]int{SkipTrusted: 0, SkipPrivate: 0, SkipCrawler: 0, SkipLegit: 0, SkipPeer: 0, SkipInfra: 0, SkipUnconfirmed: 0}
c.Skipped = map[string]int{SkipOperator: 0, SkipTrusted: 0, SkipPrivate: 0, SkipCrawler: 0, SkipLegit: 0, SkipPeer: 0, SkipInfra: 0, SkipUnconfirmed: 0}
for k, v := range e.counts.Skipped {
c.Skipped[k] = v
}
@@ -730,8 +737,9 @@ func (e *Engine) Report(from int64) Report {
}
type stateFile struct {
V int `json:"v"`
Bans map[string]banRec `json:"bans"`
V int `json:"v"`
Bans map[string]banRec `json:"bans"`
Allows map[string]int64 `json:"allows,omitempty"`
}
func (e *Engine) loadState() {
@@ -752,6 +760,12 @@ func (e *Engine) loadState() {
e.bans[a.Unmap()] = v
}
}
nowU := e.cfg.Now().Unix()
for k, u := range sf.Allows {
if a, err := netip.ParseAddr(k); err == nil && u > nowU && u <= nowU+MaxAllow {
e.allows[a.Unmap()] = u
}
}
}
// maybeSave writes the state at most every saveEvery.
@@ -774,10 +788,15 @@ func (e *Engine) saveState() {
}
e.lastSave = e.cfg.Now()
e.trimMaps(e.lastSave)
sf := stateFile{V: 1, Bans: map[string]banRec{}}
sf := stateFile{V: 1, Bans: map[string]banRec{}, Allows: map[string]int64{}}
for a, b := range e.bans {
sf.Bans[a.String()] = b
}
for a, u := range e.allows {
if u > e.lastSave.Unix() {
sf.Allows[a.String()] = u
}
}
e.dirty = false
e.mu.Unlock()
b, _ := json.Marshal(sf)
@@ -818,7 +837,7 @@ func (e *Engine) processProbe(a netip.Addr, ev core.Event, now time.Time) {
delete(st.probes, key)
}
}
in := Input{Now: now, Probes: len(st.probes), Exclude: e.excl.Excluded(a)}
in := Input{Now: now, Probes: len(st.probes), Exclude: e.exclude(a, now)}
e.fill(a, st, &in, now)
e.apply(a, st, Decide(in, Params{Threshold: e.cfg.Threshold}), "local", now)
}
+5
View File
@@ -94,6 +94,10 @@ func (e *Engine) Sweep() {
if e.cfg.Roster == nil {
return
}
if !e.sweeping.CompareAndSwap(false, true) {
return
}
defer e.sweeping.Store(false)
now := e.cfg.Now()
from := now.Add(-LongWindow).Unix()
roster := e.cfg.Roster(from)
@@ -116,6 +120,7 @@ func (e *Engine) Sweep() {
a = a.Unmap().WithZone("")
st := e.stateOf(a)
t := tallies[a.String()]
t.SSH, t.Web = max(t.SSH, r.Est.SSH), max(t.Web, r.Est.Web)
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)
+54
View File
@@ -2,6 +2,9 @@ package enforce
import (
"net/netip"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -177,3 +180,54 @@ func itoa(n int) string {
}
return s
}
func TestOperatorAllowBlocksBansAndExpires(t *testing.T) {
r := histRig(t, func(c *Config) { c.UnbanPath = filepath.Join(t.TempDir(), "u", "unban.log") })
ip := netip.MustParseAddr("203.0.114.80")
r.hits(ip.String(), 5, "/x", 404)
if len(r.lines(t)) != 1 {
t.Fatalf("expected a ban: %v", r.lines(t))
}
if err := r.e.Unban(ip, 3600, "local"); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(r.e.UnbanLogPath()); !strings.HasSuffix(string(b), " urutau unban ip=203.0.114.80 allow=3600\n") {
t.Fatalf("file %q", b)
}
r.now = r.now.Add(time.Minute)
r.hits(ip.String(), 8, "/y", 404)
if len(r.lines(t)) != 1 {
t.Fatalf("allowed address was banned: %v", r.lines(t))
}
if r.e.counts.Skipped[SkipOperator] == 0 {
t.Fatal("skip not counted")
}
// survives a restart
e2 := New(Config{Mode: ModeOn, Path: r.log, StatePath: r.e.cfg.StatePath, Now: func() time.Time { return r.now }})
if len(e2.Allows()) != 1 {
t.Fatal("allow not persisted")
}
// expires by itself
r.now = r.now.Add(2 * time.Hour)
if len(r.e.Allows()) != 0 {
t.Fatal("allow did not expire")
}
r.hits(ip.String(), 8, "/z", 404)
if len(r.lines(t)) != 2 {
t.Fatalf("not banned after expiry: %v", r.lines(t))
}
// ending early lets the engine decide again
r.e.Unban(ip, 3600, "local")
if !r.e.EndAllow(ip) || r.e.EndAllow(ip) {
t.Fatal("EndAllow")
}
if got := r.e.UnbansSince(0); len(got) != 2 || got[0].IP != ip.String() {
t.Fatalf("unbans for peers: %v", got)
}
if rep := r.e.Report(0); rep.Recent[0].Action != "unban" {
t.Fatalf("recent: %+v", rep.Recent[0])
}
if err := New(Config{Mode: ModeOn, Path: r.log}).Unban(ip, 0, "local"); err != ErrNoUnbanLog {
t.Fatalf("no file: %v", err)
}
}
+6 -5
View File
@@ -92,11 +92,12 @@ func TTLFor(offences int) time.Duration {
// Skip reasons, also the keys of Counts.Skipped.
const (
SkipTrusted = "trusted"
SkipPrivate = "private"
SkipCrawler = "crawler"
SkipLegit = "legit_visitor"
SkipPeer = "peer"
SkipTrusted = "trusted"
SkipPrivate = "private"
SkipCrawler = "crawler"
SkipLegit = "legit_visitor"
SkipOperator = "operator_allow"
SkipPeer = "peer"
// SkipUnconfirmed: a peer's decision about an address this node never saw attacking.
SkipUnconfirmed = "peer_unconfirmed"
)
+103
View File
@@ -0,0 +1,103 @@
package enforce
import (
"path/filepath"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func TestSweepWithRealStoreAndRegistry(t *testing.T) {
now := time.Now()
s := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
l, err := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "ev")})
if err != nil {
t.Fatal(err)
}
s.SetEventLog(l)
for i := 0; i < 41; i++ {
s.Ingest(core.Event{Time: now.Add(-time.Duration(20+i) * time.Minute), IP: "43.139.48.108", Cat: core.SSHFail, Source: "ssh", User: "root"})
}
for i := 0; i < 30; i++ {
s.Ingest(core.Event{Time: now.Add(-time.Duration(30+i) * time.Minute), IP: "129.213.151.234", Cat: core.Scanner, Source: "traefik",
Domain: "a.example", Method: "GET", Path: "/.env", Status: 404, UA: "curl/8"})
}
l.Flush()
r := newRig(t, ModeOn, func(c *Config) {
c.Now = time.Now
c.Rep = s.Reputation
c.Roster = func(from int64) []Seen {
var out []Seen
for _, x := range s.AttackRoster(from) {
out = append(out, Seen{IP: x.IP, Score: x.Score, Level: x.Level, Jails: x.Jails})
}
return out
}
c.Tallies = func(from int64) map[string]Tally {
out := map[string]Tally{}
for k, v := range s.AttackTallies(from) {
out[k] = Tally{SSH: v.SSH, Web: v.Web}
}
return out
}
})
r.e.Sweep()
r.e.drain()
if n := len(r.lines(t)); n != 2 {
t.Fatalf("lines %d: %v / roster %+v / tallies %+v", n, r.lines(t), s.AttackRoster(0), s.AttackTallies(0))
}
}
func TestTalliesAfterCompression(t *testing.T) {
real := time.Now()
shift := time.Duration(0)
s := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
l, err := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "ev"), Now: func() time.Time { return real.Add(shift) }})
if err != nil {
t.Fatal(err)
}
s.SetEventLog(l)
for i := 0; i < 41; i++ {
s.Ingest(core.Event{Time: real.Add(-time.Duration(20+i) * time.Minute), IP: "43.139.48.108", Cat: core.SSHFail, Source: "ssh", User: "root"})
}
l.Flush()
shift = 36 * time.Hour // the day ends; Maintain compresses it
l.Maintain()
shift = 0
m := s.AttackTallies(real.Add(-24 * time.Hour).Unix())
if m["43.139.48.108"].SSH != 41 {
t.Fatalf("tallies: %+v", m)
}
}
// The registry may hold less than the store knows (it only records live events):
// the per-day counters must still justify the long-window ban.
func TestSweepWithoutRegistryUsesDayCounters(t *testing.T) {
now := time.Now()
s := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
for i := 0; i < 41; i++ {
s.Ingest(core.Event{Time: now.Add(-time.Duration(20+i) * time.Minute), IP: "43.139.48.108", Cat: core.SSHFail, Source: "ssh", User: "root"})
}
for i := 0; i < 30; i++ {
s.Ingest(core.Event{Time: now.Add(-time.Duration(30+i) * time.Minute), IP: "129.213.151.234", Cat: core.Scanner, Source: "traefik",
Domain: "a.example", Method: "GET", Path: "/.env", Status: 404, UA: "curl/8"})
}
r := newRig(t, ModeOn, func(c *Config) {
c.Now = time.Now
c.Roster = func(from int64) []Seen {
var out []Seen
for _, x := range s.AttackRoster(from) {
out = append(out, Seen{IP: x.IP, Score: x.Score, Level: x.Level, Jails: x.Jails, Est: Tally{SSH: x.Est.SSH, Web: x.Est.Web}})
}
return out
}
})
r.e.Sweep()
r.e.drain()
if n := len(r.lines(t)); n != 2 {
t.Fatalf("lines %d: %v", n, r.lines(t))
}
}
+148
View File
@@ -0,0 +1,148 @@
package enforce
import (
"errors"
"fmt"
"net/netip"
"sort"
"time"
)
// MaxAllow is the longest operator allowance in seconds (30 days).
const MaxAllow = 30 * 24 * 3600
// ErrNoUnbanLog means unbanning is not configured.
var ErrNoUnbanLog = errors.New("unban file not configured")
// UnbanWire is an unban as exchanged between peers.
type UnbanWire struct {
T int64 `json:"t"`
IP string `json:"ip"`
Allow int `json:"allow"`
}
// Allow is an operator allowance: the engine does not ban the address until it ends.
type Allow struct {
IP string `json:"ip"`
Until int64 `json:"until"`
By string `json:"by"`
}
// exclude is Excluded plus the operator allowances; the lock is held.
func (e *Engine) exclude(a netip.Addr, now time.Time) string {
if u, ok := e.allows[a.Unmap()]; ok && u > now.Unix() {
return SkipOperator
}
return e.excl.Excluded(a)
}
// UnbanLogPath is the file the host reads unban requests from.
func (e *Engine) UnbanLogPath() string { return e.cfg.UnbanPath }
// UnbanLine formats one request of the unban file (exact host contract).
func UnbanLine(t time.Time, a netip.Addr, allow int) string {
return fmt.Sprintf("%s urutau unban ip=%s allow=%d\n", t.UTC().Format("2006-01-02T15:04:05Z"), a.Unmap().WithZone("").String(), allow)
}
// Unban writes the request for the host, drops the active ban of the address
// and, when allowS > 0, keeps the engine from banning it for that long.
func (e *Engine) Unban(a netip.Addr, allowS int, src string) error {
if e.cfg.UnbanPath == "" {
return ErrNoUnbanLog
}
if allowS < 0 || allowS > MaxAllow {
return fmt.Errorf("allow out of range")
}
a = a.Unmap().WithZone("")
now := e.cfg.Now()
if err := e.unlog.write(UnbanLine(now, a, allowS)); err != nil {
return err
}
e.mu.Lock()
delete(e.bans, a)
delete(e.would, a)
delete(e.skipSeen, a)
if st := e.ips[a]; st != nil {
st.banned, st.urutauAt, st.wouldAt, st.f2bAt = 0, 0, 0, 0
st.ev, st.ssh = nil, nil
}
delete(e.long, a)
if allowS > 0 {
e.allows[a] = now.Add(time.Duration(allowS) * time.Second).Unix()
}
e.addRecent(a, Recent{T: now.Unix(), IP: a.String(), Action: "unban", TTL: allowS, Src: src, SkipReason: ""})
if src == "local" {
e.unbans = append(e.unbans, UnbanWire{T: now.Unix(), IP: a.String(), Allow: allowS})
if len(e.unbans) > MaxWire {
e.unbans = e.unbans[len(e.unbans)-MaxWire:]
}
}
e.dirty = true
e.mu.Unlock()
e.saveState()
return nil
}
// EndAllow ends an operator allowance early; it reports whether there was one.
func (e *Engine) EndAllow(a netip.Addr) bool {
a = a.Unmap().WithZone("")
e.mu.Lock()
_, ok := e.allows[a]
delete(e.allows, a)
if ok {
e.dirty = true
}
e.mu.Unlock()
if ok {
e.saveState()
}
return ok
}
// Allows lists the active operator allowances, soonest to end first.
func (e *Engine) Allows() []Allow {
now := e.cfg.Now().Unix()
e.mu.Lock()
defer e.mu.Unlock()
out := []Allow{}
for a, u := range e.allows {
if u > now {
out = append(out, Allow{IP: a.String(), Until: u, By: "operator"})
} else {
delete(e.allows, a)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Until < out[j].Until })
return out
}
// UnbansSince returns the local unbans since the unix time, for peers.
func (e *Engine) UnbansSince(since int64) []UnbanWire {
e.mu.Lock()
defer e.mu.Unlock()
out := []UnbanWire{}
for _, w := range e.unbans {
if w.T >= since {
out = append(out, w)
}
}
return out
}
// AcceptPeerUnban applies unbans of a peer (same effect as a local one, so the
// shared decision is not re-applied here); it returns how many were accepted.
func (e *Engine) AcceptPeerUnban(name string, in []UnbanWire) (accepted int) {
if len(in) > MaxWire {
in = in[:MaxWire]
}
for _, w := range in {
a, err := netip.ParseAddr(w.IP)
if err != nil || w.Allow < 0 || w.Allow > MaxAllow {
continue
}
if e.Unban(a, w.Allow, "peer:"+token(name, "peer")) == nil {
accepted++
}
}
return accepted
}
+82 -1
View File
@@ -5,7 +5,9 @@ import (
"errors"
"io"
"net/http"
"net/netip"
"strconv"
"strings"
"sync/atomic"
"time"
@@ -41,7 +43,7 @@ func init() {
from = rg.From
}
out := map[string]any{"mode": enforce.ModeOff, "share": "off", "threshold": 0, "log_writable": false,
"coverage": enforce.Coverage{}, "counts": enforce.Counts{Skipped: map[string]int{}}, "recent": []enforce.Recent{}}
"allows": []enforce.Allow{}, "unban_log_writable": false, "coverage": enforce.Coverage{}, "counts": enforce.Counts{Skipped: map[string]int{}}, "recent": []enforce.Recent{}}
if e := enforceEngine.Load(); e != nil {
rep := e.Report(from)
share := "off"
@@ -50,12 +52,36 @@ func init() {
}
out["mode"], out["share"], out["threshold"] = e.Mode(), share, e.Threshold()
out["log_writable"] = enforce.Writable(e.LogPath())
out["unban_log_writable"] = enforce.Writable(e.UnbanLogPath())
out["allows"] = e.Allows()
out["coverage"], out["counts"], out["recent"] = rep.Coverage, rep.Counts, rep.Recent
}
writeJSON(w, http.StatusOK, out)
}
})
registerUserRoute("POST /api/v1/enforce/unban", func(s *Server) http.HandlerFunc { return s.enforceUnban })
registerUserRoute("DELETE /api/v1/enforce/allow", func(s *Server) http.HandlerFunc { return s.enforceEndAllow })
peerRoutes = append(peerRoutes,
peerRoute{"POST /api/v1/peer/unban", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
e := enforceEngine.Load()
if !s.peerGate(w, r) {
return
}
if e == nil || !e.Share() {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "decision sharing is not enabled"})
return
}
var in struct {
Unbans []enforce.UnbanWire `json:"unbans"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxDecisionBody)).Decode(&in); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
writeJSON(w, http.StatusOK, map[string]int{"accepted": e.AcceptPeerUnban(r.URL.Query().Get("from"), in.Unbans)})
}
}},
peerRoute{"GET /api/v1/peer/decisions", func(s *Server) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
e := enforceEngine.Load()
@@ -110,3 +136,58 @@ func init() {
}},
)
}
const maxUnbanBody = 1 << 10
func (s *Server) enforceUnban(w http.ResponseWriter, r *http.Request) {
if !sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
return
}
e := enforceEngine.Load()
if e == nil {
writeJSON(w, http.StatusConflict, map[string]string{"error": "the second firewall is off"})
return
}
var in struct {
IP string `json:"ip"`
AllowS int `json:"allow_s"`
}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxUnbanBody))
dec.DisallowUnknownFields()
if err := dec.Decode(&in); err != nil || dec.More() {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
return
}
a, err := netip.ParseAddr(strings.TrimSpace(in.IP))
if err != nil || a.Zone() != "" || in.AllowS < 0 || in.AllowS > enforce.MaxAllow {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip or allow_s"})
return
}
switch err := e.Unban(a, in.AllowS, "local"); {
case errors.Is(err, enforce.ErrNoUnbanLog):
writeJSON(w, http.StatusConflict, map[string]string{"error": "unban file not configured"})
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not write the unban request"})
default:
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "ip": a.Unmap().String(), "allow_s": in.AllowS})
}
}
func (s *Server) enforceEndAllow(w http.ResponseWriter, r *http.Request) {
if !sameOrigin(r) {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
return
}
e := enforceEngine.Load()
a, err := netip.ParseAddr(r.URL.Query().Get("ip"))
if e == nil || err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"})
return
}
if !e.EndAllow(a) {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "no allowance for this address"})
return
}
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
+1 -1
View File
@@ -39,7 +39,7 @@ func TestEnforceAPI(t *testing.T) {
t.Fatalf("missing %s: %v", k, d)
}
}
if sk := d["counts"].(map[string]any)["skipped"].(map[string]any); len(sk) != 7 {
if sk := d["counts"].(map[string]any)["skipped"].(map[string]any); len(sk) != 8 {
t.Fatalf("skipped %v", sk)
}
// feed events through the store hook and the engine worker
+119
View File
@@ -0,0 +1,119 @@
package server
import (
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/enforce"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
)
func unbanRig(t *testing.T) (http.Handler, *enforce.Engine, string) {
t.Helper()
dir := t.TempDir()
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
e := enforce.New(enforce.Config{Mode: enforce.ModeOn, Path: filepath.Join(dir, "decisions.log"), UnbanPath: filepath.Join(dir, "unban.log"),
Host: "oracle", Threshold: 3, Share: true})
SetEnforce(e)
t.Cleanup(func() { SetEnforce(nil) })
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st}), e, filepath.Join(dir, "unban.log")
}
func req(h http.Handler, method, path, body string, hdr map[string]string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, path, strings.NewReader(body))
r.RemoteAddr = "198.51.100.1:1234"
for k, v := range hdr {
r.Header.Set(k, v)
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
func TestUnbanRoute(t *testing.T) {
h, e, file := unbanRig(t)
auth := map[string]string{"Authorization": "Bearer " + userTok}
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7","allow_s":60}`, nil); w.Code != 401 {
t.Fatalf("no auth: %d", w.Code)
}
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7"}`, map[string]string{"Authorization": "Bearer " + peerTok}); w.Code != 403 {
t.Fatalf("peer token: %d", w.Code)
}
cross := map[string]string{"Authorization": "Bearer " + userTok, "Sec-Fetch-Site": "cross-site"}
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7"}`, cross); w.Code != 403 {
t.Fatalf("cross-site: %d", w.Code)
}
for _, b := range []string{`nope`, `{"ip":"203.0.113.7","x":1}`, `{"ip":"203.0.113.7\nroot","allow_s":1}`, `{"ip":"1.2.3.4 allow=9","allow_s":0}`,
`{"ip":"fe80::1%eth0"}`, `{"ip":"203.0.113.7","allow_s":-1}`, `{"ip":"203.0.113.7","allow_s":2592001}`, `{"ip":"999.1.1.1"}`,
`{"ip":"203.0.113.7"}{"ip":"1.1.1.1"}`, `{"ip":"` + strings.Repeat("a", 2000) + `"}`} {
if w := req(h, "POST", "/api/v1/enforce/unban", b, auth); w.Code != 400 {
t.Errorf("%.40q: %d", b, w.Code)
}
}
if b, _ := os.ReadFile(file); len(b) != 0 {
t.Fatalf("invalid requests wrote: %q", b)
}
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"203.0.113.7","allow_s":86400}`, auth); w.Code != 200 {
t.Fatalf("ok: %d %s", w.Code, w.Body)
}
if w := req(h, "POST", "/api/v1/enforce/unban", `{"ip":"::ffff:198.51.100.9"}`, auth); w.Code != 200 {
t.Fatalf("mapped: %d", w.Code)
}
b, _ := os.ReadFile(file)
lines := strings.Split(strings.TrimSpace(string(b)), "\n")
re := regexp.MustCompile(`^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ urutau unban ip=203\.0\.113\.7 allow=86400$`)
if len(lines) != 2 || !re.MatchString(lines[0]) || !strings.HasSuffix(lines[1], " urutau unban ip=198.51.100.9 allow=0") {
t.Fatalf("file: %q", b)
}
d := getJSON(t, h, "/api/v1/enforce?range=24h", auth)
al := d["allows"].([]any)
if len(al) != 1 || al[0].(map[string]any)["ip"] != "203.0.113.7" || al[0].(map[string]any)["by"] != "operator" || d["unban_log_writable"] != true {
t.Fatalf("allows: %v", d)
}
// DELETE
if w := req(h, "DELETE", "/api/v1/enforce/allow?ip=bad", "", auth); w.Code != 400 {
t.Fatalf("bad ip: %d", w.Code)
}
if w := req(h, "DELETE", "/api/v1/enforce/allow?ip=203.0.113.7", "", cross); w.Code != 403 {
t.Fatalf("delete cross-site: %d", w.Code)
}
if w := req(h, "DELETE", "/api/v1/enforce/allow?ip=203.0.113.7", "", auth); w.Code != 200 {
t.Fatalf("delete: %d", w.Code)
}
if w := req(h, "DELETE", "/api/v1/enforce/allow?ip=203.0.113.7", "", auth); w.Code != 404 {
t.Fatalf("delete again: %d", w.Code)
}
if len(e.Allows()) != 0 {
t.Fatal("allow remains")
}
if after, _ := os.ReadFile(file); string(after) != string(b) {
t.Fatal("DELETE wrote to the host file")
}
}
func TestPeerUnbanRoute(t *testing.T) {
h, e, file := unbanRig(t)
peer := map[string]string{"Authorization": "Bearer " + peerTok}
if w := req(h, "POST", "/api/v1/peer/unban?from=hostinger", `{"unbans":[{"ip":"203.0.113.7","allow":3600},{"ip":"bad","allow":1}]}`, map[string]string{"Authorization": "Bearer " + userTok}); w.Code == 200 {
t.Fatalf("user token accepted on peer route")
}
w := req(h, "POST", "/api/v1/peer/unban?from=hostinger", `{"unbans":[{"ip":"203.0.113.7","allow":3600},{"ip":"bad","allow":1}]}`, peer)
if w.Code != 200 || !strings.Contains(w.Body.String(), `"accepted":1`) {
t.Fatalf("%d %s", w.Code, w.Body)
}
if len(e.Allows()) != 1 {
t.Fatal("peer allow not applied")
}
if b, _ := os.ReadFile(file); !strings.Contains(string(b), "ip=203.0.113.7 allow=3600") {
t.Fatalf("file: %q", b)
}
if len(e.UnbansSince(0)) != 0 {
t.Fatal("peer unban must not be echoed back")
}
}
+56 -1
View File
@@ -989,6 +989,61 @@
setTimeout(function () { if (n.parentNode) n.parentNode.removeChild(n); }, 2600);
}
// POST/DELETE with a JSON body (same-origin cookie session); resolves with the parsed answer or rejects with its status.
function apiSend(method, path, body) {
var o = { method: method, credentials: 'same-origin', headers: { Accept: 'application/json' } };
if (body !== undefined) { o.body = JSON.stringify(body); o.headers['Content-Type'] = 'application/json'; }
return fetch(path, o).then(function (r) {
if (r.status === 401) { location.href = '/login'; throw mkErr('unauthorized', 401); }
if (!r.ok) throw mkErr('HTTP ' + r.status, r.status);
return r.json();
});
}
// Unban dialog: native <dialog> (focus trap, Esc), a radio group for how long the address stays protected, confirm.
var UNBAN_CHOICES = [['0', 'unban.keep.none'], ['3600', 'unban.keep.1h'], ['86400', 'unban.keep.24h'], ['604800', 'unban.keep.7d']];
function unbanDialog(ip, onDone) {
var prev = document.activeElement;
var dlg = el('dialog', { class: 'unban-dlg', 'aria-labelledby': 'unban-h', 'aria-describedby': 'unban-p' });
var err = el('p', { class: 'unban-err', role: 'alert', hidden: true });
var fs = el('fieldset', { class: 'unban-opts' }, el('legend', null, t('unban.keep')));
UNBAN_CHOICES.forEach(function (c, i) {
var id = 'unban-o' + i;
var inp = el('input', { type: 'radio', name: 'unban-keep', id: id, value: c[0] });
if (i === 0) inp.checked = true;
fs.appendChild(el('div', { class: 'unban-opt' }, inp, el('label', { for: id }, t(c[1]))));
});
var ok = el('button', { type: 'button', class: 'btn btn-primary' }, t('unban.confirm'));
var cancel = el('button', { type: 'button', class: 'btn' }, t('unban.cancel'));
dlg.appendChild(el('h2', { id: 'unban-h' }, t('unban.title', { ip: ip })));
dlg.appendChild(el('p', { id: 'unban-p' }, t('unban.explain')));
dlg.appendChild(fs);
dlg.appendChild(err);
dlg.appendChild(el('div', { class: 'unban-btns' }, cancel, ok));
function close() { dlg.close(); }
cancel.addEventListener('click', close);
dlg.addEventListener('close', function () {
if (dlg.parentNode) dlg.parentNode.removeChild(dlg);
if (prev && prev.focus && document.contains(prev)) prev.focus();
});
ok.addEventListener('click', function () {
var sel = dlg.querySelector('input[name="unban-keep"]:checked');
ok.disabled = true;
apiSend('POST', '/api/v1/enforce/unban', { ip: ip, allow_s: parseInt(sel ? sel.value : '0', 10) || 0 }).then(function () {
close();
toast(t('unban.done', { ip: ip }));
if (onDone) onDone();
}, function (e) {
ok.disabled = false;
err.textContent = t(e && e.status === 409 ? 'unban.err.off' : 'unban.err');
err.hidden = false;
});
});
document.body.appendChild(dlg);
if (dlg.showModal) dlg.showModal(); else dlg.setAttribute('open', '');
ok.focus();
}
// ---------------------------------------------------------------- charts library (own SVG, no dependencies)
var VIZ = ['--viz-1', '--viz-2', '--viz-3', '--viz-4', '--viz-5', '--viz-6', '--viz-7', '--viz-8'];
function vizColor(i, colors) { return 'var(' + ((colors && colors[i % colors.length]) || VIZ[i % VIZ.length]) + ')'; }
@@ -2056,7 +2111,7 @@
window.Urutau = {
registerPage: registerPage, registerI18n: registerI18n, t: t, pl: pl, api: api, onEvent: onEvent, openIP: openIP,
rangeParams: rangeParams, rangeLabel: rangeLabel, href: hrefFor, toast: toast,
rangeParams: rangeParams, rangeLabel: rangeLabel, href: hrefFor, toast: toast, apiSend: apiSend, unbanDialog: unbanDialog,
fmt: { num: nf, pct: pct, ago: ago, bytes: fmtBytes, flag: flag, country: countryName, clock: clock, date: dateTime },
world: world, el: el, css: cssVar, setSliceNote: setSliceNote,
charts: charts, help: help, glossary: glossary,
+37 -2
View File
@@ -94,6 +94,16 @@
'df.en.act.ban': 'Blocked',
'df.en.act.would_ban': 'Would block',
'df.en.act.skip': 'Not blocked',
'df.en.act.unban': 'Unbanned',
'df.en.skip.operator_allow': 'Released by you',
'df.en.allows': 'Operator releases',
'df.en.allows.hint': 'Addresses you unbanned and asked not to block again for a while. The system will not block them until the time ends.',
'df.en.allows.none': 'No active releases.',
'df.en.allows.until': 'Until',
'df.en.allows.end': 'End release',
'df.en.allows.ended': 'Release ended',
'df.en.allows.err': 'Could not end the release.',
'df.en.allows.unwritable': 'The unban file is not writable, so unbanning will fail.',
'df.en.src.local': 'this server',
'df.en.src.peer': 'peer {n}',
'df.en.skip.trusted': 'Trusted address (your own list)',
@@ -200,6 +210,16 @@
'df.en.act.ban': 'Bloqueado',
'df.en.act.would_ban': 'Bloquearia',
'df.en.act.skip': 'Não bloqueado',
'df.en.act.unban': 'Desbanido',
'df.en.skip.operator_allow': 'Liberado por você',
'df.en.allows': 'Liberações do operador',
'df.en.allows.hint': 'Endereços que você desbaniu e pediu para não bloquear de novo por um tempo. O sistema não os bloqueia até o prazo acabar.',
'df.en.allows.none': 'Nenhuma liberação ativa.',
'df.en.allows.until': 'Até',
'df.en.allows.end': 'Encerrar',
'df.en.allows.ended': 'Liberação encerrada',
'df.en.allows.err': 'Não foi possível encerrar a liberação.',
'df.en.allows.unwritable': 'O arquivo de desban não é gravável, então desbanir vai falhar.',
'df.en.src.local': 'este servidor',
'df.en.src.peer': 'parceiro {n}',
'df.en.skip.trusted': 'Endereço confiável (sua própria lista)',
@@ -387,7 +407,7 @@
k(U.ui.metric(t('df.en.c.already'), nf(cn.already_blocked || 0)));
np.body.appendChild(kp);
var skl = el('ul', { class: 'df-skips' });
['trusted', 'private', 'crawler', 'legit_visitor', 'peer'].forEach(function (key) {
['trusted', 'private', 'crawler', 'legit_visitor', 'peer', 'operator_allow'].forEach(function (key) {
if (!sk[key]) return;
skl.appendChild(el('li', null, el('span', { class: 'num' }, nf(sk[key])), ' ' + t('df.en.skip.' + key)));
});
@@ -401,8 +421,9 @@
var cols = [{ label: t('df.en.col.time') }, { label: t('df.en.col.ip'), cls: 'mono' }, { label: t('df.en.col.cc') }, { label: t('df.en.col.reason') },
{ label: t('df.en.col.score'), cls: 'num' }, { label: t('df.en.col.ttl'), cls: 'num' }, { label: t('df.en.col.action') }, { label: t('df.en.col.src') }];
rp.body.appendChild(tbl(cols, rec.map(function (r) {
var act = /^(ban|would_ban|skip)$/.test(r.action) ? r.action : 'skip';
var act = /^(ban|would_ban|skip|unban)$/.test(r.action) ? r.action : 'skip';
var actNode = el('span', { class: 'df-act' }, U.ui.badge(t('df.en.act.' + act), act === 'ban' ? 'ok' : act === 'would_ban' ? 'warn' : 'neutral'));
if (act === 'ban') actNode.appendChild(el('button', { type: 'button', class: 'btn btn-sm df-unban', onclick: function () { U.unbanDialog(r.ip, loadEnforce); } }, t('unban.btn')));
if (act === 'skip' && r.skip_reason) {
var sk2 = 'df.en.skip.' + r.skip_reason;
actNode.appendChild(el('small', { class: 'df-skipwhy' }, t(sk2) !== sk2 ? t(sk2) : r.skip_reason));
@@ -414,6 +435,20 @@
})));
}
grid.appendChild(rp);
var ap = U.ui.panel({ title: t('df.en.allows'), hint: t('df.en.allows.hint'), cls: 'span-12', variant: 'list' });
var als = e.allows || [];
if (e.unban_log_writable === false) ap.body.appendChild(el('p', { class: 'state-warn' }, t('df.en.allows.unwritable')));
if (!als.length) ap.body.appendChild(U.ui.empty(t('df.en.allows.none')));
else {
ap.body.appendChild(tbl([{ label: t('df.en.col.ip'), cls: 'mono' }, { label: t('df.en.allows.until') }, { label: '' }], als.map(function (a) {
return [el('a', { href: U.href('ip', [a.ip]) }, a.ip), U.fmt.date ? U.fmt.date(a.until) : String(a.until),
el('button', { type: 'button', class: 'btn btn-sm', onclick: function () {
U.apiSend('DELETE', '/api/v1/enforce/allow?ip=' + encodeURIComponent(a.ip)).then(function () { U.toast(t('df.en.allows.ended')); loadEnforce(); },
function () { U.toast(t('df.en.allows.err')); });
} }, t('df.en.allows.end'))];
})));
}
grid.appendChild(ap);
enBox.appendChild(grid);
}
function loadEnforce() {
+26
View File
@@ -44,6 +44,19 @@ window.URUTAU_I18N = {
'range.widen': 'Choose another period',
'timeline.bucket': '{n}-minute buckets',
'toast.copied': 'Copied',
'unban.btn': 'Unban',
'unban.title': 'Unban {ip}',
'unban.explain': 'This lifts the block on this address in the server firewall (fail2ban) right away. Use it when the block was a mistake or when you are testing your own system.',
'unban.keep': 'Do not block it again for:',
'unban.keep.none': 'Do not keep (it can be blocked again)',
'unban.keep.1h': '1 hour',
'unban.keep.24h': '24 hours',
'unban.keep.7d': '7 days',
'unban.confirm': 'Unban',
'unban.cancel': 'Cancel',
'unban.done': '{ip} unbanned',
'unban.err': 'Could not unban. Try again.',
'unban.err.off': 'The second firewall is off, so there is nothing to unban from here.',
'state.retry': 'Try again',
'top.empty.title': 'No data',
'ips.empty.title': 'No IPs found',
@@ -546,6 +559,19 @@ window.URUTAU_I18N = {
'range.widen': 'Escolher outro período',
'timeline.bucket': 'caixas de {n} min',
'toast.copied': 'Copiado',
'unban.btn': 'Desbanir',
'unban.title': 'Desbanir {ip}',
'unban.explain': 'Isto libera agora o bloqueio deste endereço no firewall do servidor (fail2ban). Use quando o bloqueio foi um engano ou quando você está testando o seu próprio sistema.',
'unban.keep': 'Não bloquear de novo por:',
'unban.keep.none': 'Não manter (pode ser bloqueado de novo)',
'unban.keep.1h': '1 hora',
'unban.keep.24h': '24 horas',
'unban.keep.7d': '7 dias',
'unban.confirm': 'Desbanir',
'unban.cancel': 'Cancelar',
'unban.done': '{ip} desbanido',
'unban.err': 'Não foi possível desbanir. Tente de novo.',
'unban.err.off': 'O segundo firewall está desligado, então não há o que desbanir por aqui.',
'state.retry': 'Tentar novamente',
'top.empty.title': 'Sem dados',
'ips.empty.title': 'Nenhum IP encontrado',
+3
View File
@@ -1288,6 +1288,9 @@
});
b.appendChild(ol);
}
if (banned && window.Urutau && Urutau.unbanDialog) {
b.appendChild(Urutau.el('button', { type: 'button', class: 'btn btn-sm ipx-unban', onclick: function () { Urutau.unbanDialog(d.ip, function () { location.reload(); }); } }, t('unban.btn')));
}
c.body.appendChild(b);
var f = h('dl', 'ipx-facts');
if (has(ttb) || list.length) {
+9
View File
@@ -656,3 +656,12 @@ input[type="datetime-local"] { background: var(--surface-raised); border: 1px so
.more-sheet .nav-group { color: var(--ink-muted); padding: 6px var(--s-3) 0; }
@media (max-width: 1199px) { .nav-group { font-size: 0; height: 1px; background: var(--rail-line); margin: 8px 6px; padding: 0; } }
@media (max-width: 767px) { .more-sheet .nav-group { font-size: 11px; height: auto; background: none; margin: 6px 0 0; padding: 6px var(--s-3) 0; } }
.unban-dlg { max-width: min(30rem, calc(100vw - 32px)); padding: var(--s-4, 16px); border: 1px solid var(--line-strong); border-radius: var(--radius-sm); background: var(--surface-overlay); color: var(--ink); }
.unban-dlg::backdrop { background: rgba(0, 0, 0, .5); }
.unban-dlg h2 { margin: 0 0 8px; font-size: 1.125rem; }
.unban-opts { border: 0; padding: 0; margin: 12px 0; display: grid; gap: 6px; }
.unban-opts legend { padding: 0; margin-bottom: 6px; font-weight: 600; }
.unban-opt { display: flex; align-items: center; gap: 8px; }
.unban-err { color: var(--bad, #b3261e); margin: 8px 0 0; }
.unban-btns { display: flex; justify-content: flex-end; gap: 8px; margin-top: 16px; }
+37 -4
View File
@@ -14,6 +14,32 @@ type RosterRow struct {
Level core.Level
Jails []string
Last int64
Est Tally24 // 24 h estimate from the per-day counters (the registry may not cover the whole window)
}
// dayEstimate estimates the SSH and web malicious events of the last 24 h from
// the per-day counters: today plus the share of yesterday still inside the window.
func dayEstimate(r *IPRec, nowU int64) Tally24 {
if len(r.DayCats) == 0 {
return Tally24{}
}
today := nowU / 86400
frac := 1 - float64(nowU%86400)/86400
var t Tally24
for k := int64(0); k <= 1; k++ {
i := int(r.DayBase - (today - k))
if i < 0 || i >= len(r.DayCats) {
continue
}
w := 1.0
if k == 1 {
w = frac
}
c := r.DayCats[i]
t.SSH += int(float64(c[core.SSHFail.Index()])*w + 0.999)
t.Web += int(float64(c[core.Scanner.Index()]+c[core.Exploit.Index()]+c[core.BruteForce.Index()])*w + 0.999)
}
return t
}
// Tally24 counts the malicious events of one address in a window.
@@ -31,7 +57,7 @@ func (s *Store) AttackRoster(from int64) []RosterRow {
}
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})
Jails: append([]string(nil), r.Jails...), Last: r.Last, Est: dayEstimate(r, nowU)})
}
return out
}
@@ -72,7 +98,7 @@ func (s *Store) AttackTallies(from int64) map[string]Tally24 {
return nil
}
m := map[string]*Tally24{}
s.elog.Scan(evlog.Filter{From: from, Cats: tallyCats}, 256<<20, false, func(r evlog.Rec, _ []byte) bool {
s.elog.Scan(evlog.Filter{From: from, Cats: tallyCats}, 4<<30, false, func(r evlog.Rec, _ []byte) bool {
tallyAdd(m, r)
return true
})
@@ -85,11 +111,17 @@ func (s *Store) AttackTallies(from int64) map[string]Tally24 {
// AttackTally is AttackTallies for one address.
func (s *Store) AttackTally(ip string, from int64) Tally24 {
var est Tally24
s.mu.RLock()
if r := s.ips[KeyOf(ip)]; r != nil {
est = dayEstimate(r, s.now().Unix())
}
s.mu.RUnlock()
if s.elog == nil {
return Tally24{}
return est
}
m := map[string]*Tally24{}
s.elog.Scan(evlog.Filter{From: from, IP: ip, Cats: tallyCats}, 64<<20, false, func(r evlog.Rec, _ []byte) bool {
s.elog.Scan(evlog.Filter{From: from, IP: ip, Cats: tallyCats}, 1<<30, false, func(r evlog.Rec, _ []byte) bool {
tallyAdd(m, r)
return true
})
@@ -98,5 +130,6 @@ func (s *Store) AttackTally(ip string, from int64) Tally24 {
t.SSH += v.SSH
t.Web += v.Web
}
t.SSH, t.Web = max(t.SSH, est.SSH), max(t.Web, est.Web)
return t
}
+38
View File
@@ -0,0 +1,38 @@
package store
import (
"testing"
"time"
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
)
func TestTalliesFromRealRegistry(t *testing.T) {
s := store30("oracle")
l := openLog(t)
s.SetEventLog(l)
for i := 0; i < 41; i++ {
s.Ingest(core.Event{Time: t0.Add(-time.Duration(20+i) * time.Minute), IP: "43.139.48.108", Cat: core.SSHFail, Source: "ssh", User: "root"})
}
for i := 0; i < 30; i++ {
s.Ingest(core.Event{Time: t0.Add(-time.Duration(30+i) * time.Minute), IP: "129.213.151.234", Cat: core.Scanner, Source: "traefik",
Domain: "a.example", Method: "GET", Path: "/.env", Status: 404, UA: "curl/8"})
}
l.Flush()
from := t0.Add(-24 * time.Hour).Unix()
m := s.AttackTallies(from)
if m["43.139.48.108"].SSH != 41 || m["129.213.151.234"].Web != 30 {
t.Fatalf("tallies: %+v", m)
}
if x := s.AttackTally("43.139.48.108", from); x.SSH != 41 {
t.Fatalf("one: %+v", x)
}
rows := s.AttackRoster(from)
got := map[string]bool{}
for _, r := range rows {
got[r.IP] = true
}
if !got["43.139.48.108"] || !got["129.213.151.234"] {
t.Fatalf("roster: %+v", rows)
}
}