Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
873219416f | ||
|
|
da333d70f1 | ||
|
|
1ef5a0ce9f | ||
|
|
0dc3268b29 | ||
|
|
50cd2bd3ce | ||
|
|
045ed53e43 |
No files matched your search
@@ -6,6 +6,43 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.4.7] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- The unban file now defaults to `unban.log` next to `--enforce-log` (the default was lost, so the Unban button reported the file as not writable).
|
||||
- Second firewall: the 24 h rules also count from the persistent day counters, so they work when the event registry does not cover the whole day (after a reset or upgrade).
|
||||
|
||||
## [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
|
||||
|
||||
- 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
|
||||
|
||||
- Tor network: the official exit and relay lists are downloaded every 6 hours (`URUTAU_TOR_AUTO`, cached in the data directory). Requests from Tor exits are marked `tor`; a workload talking to a Tor relay is a high outbound finding.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Outbound traffic: the servers themselves (trusted addresses, peers, local public addresses) never raise findings; regular connections of the host to its own provider (`URUTAU_EGRESS_PROVIDER_ASN` or the provider of its address) are shown as provider services, outside the verdict; regular connections to large CDNs and clouds are low severity unless the destination attacked the server.
|
||||
|
||||
## [1.4.2] - 2026-11-15
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -6,6 +6,43 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.4.7] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- O arquivo de desban agora tem como padrão `unban.log` ao lado de `--enforce-log` (o padrão se perdia, e o botão Desbanir dizia que o arquivo não era gravável).
|
||||
- Segundo firewall: as regras de 24 h também contam pelos contadores diários persistentes, então funcionam quando o registro de eventos não cobre o dia inteiro (após um reset ou atualização).
|
||||
|
||||
## [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
|
||||
|
||||
- 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
|
||||
|
||||
- Rede Tor: as listas oficiais de saídas e relays são baixadas a cada 6 horas (`URUTAU_TOR_AUTO`, com cache no diretório de dados). Requisições vindas de saídas Tor são marcadas `tor`; um workload falando com um relay Tor é um achado de saída de gravidade alta.
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Tráfego de saída: os próprios servidores (endereços confiáveis, peers, endereços públicos locais) nunca geram achados; conexões regulares do host com o próprio provedor (`URUTAU_EGRESS_PROVIDER_ASN` ou o provedor do seu endereço) aparecem como serviços do provedor, fora do veredito; conexões regulares com grandes CDNs e nuvens têm gravidade baixa, salvo se o destino atacou o servidor.
|
||||
|
||||
## [1.4.2] - 2026-11-15
|
||||
|
||||
### Alterado
|
||||
|
||||
@@ -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"
|
||||
|
||||
Executable
+31
@@ -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"
|
||||
@@ -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
|
||||
@@ -0,0 +1,6 @@
|
||||
[Unit]
|
||||
Description=Urutau: apply the operator's unban requests
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/urutau-unban
|
||||
@@ -44,12 +44,14 @@ type Config struct {
|
||||
PeerAllow string // CIDRs allowed to call /api/v1/peer/export (empty: any source with the token)
|
||||
TrustedProxy string // proxies whose X-Forwarded-For is believed
|
||||
Retention time.Duration
|
||||
TorAuto string // on (default) or off: download the official Tor lists every 6 h
|
||||
TorExits string // file with Tor exit addresses, one per line; empty disables the check
|
||||
EventsMax string // size cap of the event registry ("512MB", "0" disables it)
|
||||
NoAuth bool
|
||||
// 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
|
||||
@@ -174,10 +176,12 @@ func ParseFlags(name string, args []string) (Config, error) {
|
||||
fs.StringVar(&c.Location, "location", env("URUTAU_LOCATION", ""), `where this instance lives, "lat,lon" or "lat,lon,label"; shown as the destination of live arcs (URUTAU_LOCATION)`)
|
||||
fs.StringVar(&c.PeerBlocklist, "peer-blocklist", env("URUTAU_PEER_BLOCKLIST", "on"), "on: the blocklist also lists strong hostile IPs seen only by peers; off: local IPs only (URUTAU_PEER_BLOCKLIST)")
|
||||
fs.DurationVar(&c.Retention, "retention", store.DefaultRetention, "how long data is kept, at most 720h (URUTAU_RETENTION)")
|
||||
fs.StringVar(&c.TorAuto, "tor-auto", env("URUTAU_TOR_AUTO", "on"), "download the official Tor exit and relay lists every 6 h into <data-dir>/tor: on or off (URUTAU_TOR_AUTO)")
|
||||
fs.StringVar(&c.TorExits, "tor-exits", env("URUTAU_TOR_EXITS", ""), "file with Tor exit node addresses, one per line, reloaded every 24 h when it changes; empty disables (URUTAU_TOR_EXITS)")
|
||||
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)")
|
||||
@@ -268,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{}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+93
-11
@@ -2,11 +2,13 @@ package app
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
@@ -28,20 +30,24 @@ func newEgress(c Config, st *store.Store, log *slog.Logger) (*egress.Source, err
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
var allow []netip.Prefix
|
||||
if nets, err := core.ParseCIDRs(c.Trusted); err == nil {
|
||||
for _, n := range nets {
|
||||
if p, err := netip.ParsePrefix(n.String()); err == nil {
|
||||
allow = append(allow, p)
|
||||
}
|
||||
allow := egressAllow(c)
|
||||
var provMu sync.Mutex
|
||||
var provCache []string
|
||||
provider := func() []string {
|
||||
provMu.Lock()
|
||||
defer provMu.Unlock()
|
||||
if provCache == nil {
|
||||
provCache = providerASNs(os.Getenv("URUTAU_EGRESS_PROVIDER_ASN"), func(ip string) uint32 { return st.GeoOf(ip).ASN })
|
||||
}
|
||||
return provCache
|
||||
}
|
||||
allow = append(allow, egressExtraAllow(c)...)
|
||||
eng, err := egress.New(egress.Config{
|
||||
Workloads: c.EgressWorkloads,
|
||||
Resolvers: c.EgressResolvers,
|
||||
Allow: allow,
|
||||
Containers: c.EgressContainers,
|
||||
Workloads: c.EgressWorkloads,
|
||||
Resolvers: c.EgressResolvers,
|
||||
Allow: allow,
|
||||
Containers: c.EgressContainers,
|
||||
TorRelay: func(a netip.Addr) bool { return intel.IsTorRelay(a) && !intel.IsTorExit(a) },
|
||||
ProviderASNs: provider,
|
||||
Geo: func(ip string) (string, string, string) {
|
||||
g := st.GeoOf(ip)
|
||||
asn := ""
|
||||
@@ -96,3 +102,79 @@ func egressExtraAllow(c Config) []netip.Prefix {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ownPublicPrefixes returns the global unicast addresses of the local
|
||||
// interfaces: the server's own addresses never produce a finding.
|
||||
func ownPublicPrefixes() []netip.Prefix {
|
||||
var out []netip.Prefix
|
||||
for _, a := range localPublicAddrs() {
|
||||
out = append(out, netip.PrefixFrom(a, a.BitLen()))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func localPublicAddrs() []netip.Addr {
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []netip.Addr
|
||||
for _, ad := range addrs {
|
||||
ipn, ok := ad.(*net.IPNet)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
a, ok := netip.AddrFromSlice(ipn.IP)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
a = a.Unmap()
|
||||
if a.IsGlobalUnicast() && !a.IsPrivate() && !a.IsLoopback() && !a.IsLinkLocalUnicast() && !(a.Is4() && netip.MustParsePrefix("100.64.0.0/10").Contains(a)) {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// providerASNs lists the hosting provider's ASNs ("AS31898"): the explicit
|
||||
// list (env, "31898,AS47583") wins, otherwise the ASN of the server's public
|
||||
// interface addresses. nil (retried later) when none is known yet.
|
||||
func providerASNs(explicit string, asnOf func(ip string) uint32) []string {
|
||||
var out []string
|
||||
seen := map[string]bool{}
|
||||
add := func(n uint64) {
|
||||
k := "AS" + strconv.FormatUint(n, 10)
|
||||
if n != 0 && !seen[k] {
|
||||
seen[k] = true
|
||||
out = append(out, k)
|
||||
}
|
||||
}
|
||||
for _, s := range strings.Split(explicit, ",") {
|
||||
s = strings.TrimPrefix(strings.ToUpper(strings.TrimSpace(s)), "AS")
|
||||
if n, err := strconv.ParseUint(s, 10, 32); err == nil {
|
||||
add(n)
|
||||
}
|
||||
}
|
||||
if len(out) > 0 {
|
||||
return out
|
||||
}
|
||||
for _, a := range localPublicAddrs() {
|
||||
add(uint64(asnOf(a.String())))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// egressAllow is the list of destinations that never produce a finding: the
|
||||
// trusted origins (our own servers, an invalid item does not discard the
|
||||
// others), the federation peers, URUTAU_EGRESS_ALLOW and the local public
|
||||
// addresses.
|
||||
func egressAllow(c Config) []netip.Prefix {
|
||||
var allow []netip.Prefix
|
||||
for _, part := range strings.Split(c.Trusted, ",") {
|
||||
if nets, err := core.ParseCIDRs(part); err == nil {
|
||||
allow = append(allow, nets...)
|
||||
}
|
||||
}
|
||||
allow = append(allow, egressExtraAllow(c)...)
|
||||
return append(allow, ownPublicPrefixes()...)
|
||||
}
|
||||
+43
-2
@@ -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
|
||||
@@ -35,10 +35,29 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher) *enfor
|
||||
}
|
||||
}
|
||||
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: unbanLogPath(c), 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 },
|
||||
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, Est: enforce.Tally{SSH: r.Est.SSH, Web: r.Est.Web}}
|
||||
}
|
||||
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, ""
|
||||
@@ -71,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 {
|
||||
@@ -93,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
|
||||
@@ -162,3 +192,14 @@ func cloudflareClients(path string) (cf, total int) {
|
||||
}
|
||||
return cf, total
|
||||
}
|
||||
|
||||
// unbanLogPath is --enforce-unban-log, or unban.log next to --enforce-log.
|
||||
func unbanLogPath(c Config) string {
|
||||
if c.EnforceUnbanLog != "" {
|
||||
return c.EnforceUnbanLog
|
||||
}
|
||||
if c.EnforceLog == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
|
||||
}
|
||||
+11
-1
@@ -46,6 +46,9 @@ func Serve(c Config) error {
|
||||
st := store.New(store.Config{Name: c.Name, Version: Version, Retention: c.Retention, AdminUsers: c.AdminUserList(), Location: loc})
|
||||
st.SetDomains(splitList(c.Domains))
|
||||
watchTorExits(ctx, c.TorExits, 24*time.Hour, log)
|
||||
if !strings.EqualFold(c.TorAuto, "off") {
|
||||
watchTorLists(ctx, filepath.Join(c.DataDir, "tor"), torExitURL, torRelayURL, 6*time.Hour, log)
|
||||
}
|
||||
var elog *evlog.Log
|
||||
if max, err := ParseSize(orDefault(c.EventsMax, DefaultEventsMax)); err == nil && max > 0 {
|
||||
if elog, err = evlog.Open(evlog.Options{Dir: filepath.Join(c.DataDir, "events"), MaxBytes: max, Retention: c.Retention, Log: log}); err != nil {
|
||||
@@ -106,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
|
||||
}
|
||||
|
||||
+182
-1
@@ -3,12 +3,17 @@ package app
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
@@ -69,7 +74,7 @@ func watchTorExits(ctx context.Context, path string, every time.Duration, log *s
|
||||
log.Warn("tor exit list unreadable", "err", err)
|
||||
return
|
||||
}
|
||||
intel.SetTorExits(addrs)
|
||||
torLists.setManual(addrs)
|
||||
lastMod, lastSize = st.ModTime(), st.Size()
|
||||
log.Info("tor exit list loaded", "n", len(addrs))
|
||||
}
|
||||
@@ -87,3 +92,179 @@ func watchTorExits(ctx context.Context, path string, every time.Duration, log *s
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
const (
|
||||
torExitURL = "https://check.torproject.org/torbulkexitlist"
|
||||
torRelayURL = "https://onionoo.torproject.org/details?running=true&fields=or_addresses,exit_addresses"
|
||||
maxTorList = 32 << 20
|
||||
torFetchTO = 60 * time.Second
|
||||
torUserAgent = "urutau"
|
||||
maxTorRelays = 400000
|
||||
torExitCache = "exits.txt"
|
||||
torRelayCache = "relays.json"
|
||||
)
|
||||
|
||||
// torLists merges the manual exit file (URUTAU_TOR_EXITS) with the downloaded
|
||||
// lists into the intel package.
|
||||
var torLists = &torSource{}
|
||||
|
||||
type torSource struct {
|
||||
mu sync.Mutex
|
||||
manual, auto, rels []netip.Addr
|
||||
}
|
||||
|
||||
func (t *torSource) apply() {
|
||||
all := append(append([]netip.Addr(nil), t.manual...), t.auto...)
|
||||
intel.SetTorExits(all)
|
||||
intel.SetTorRelays(append(all, t.rels...))
|
||||
}
|
||||
|
||||
func (t *torSource) setManual(a []netip.Addr) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
t.manual = a
|
||||
t.apply()
|
||||
}
|
||||
|
||||
func (t *torSource) setAuto(exits, relays []netip.Addr) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if exits != nil {
|
||||
t.auto = exits
|
||||
}
|
||||
if relays != nil {
|
||||
t.rels = relays
|
||||
}
|
||||
t.apply()
|
||||
}
|
||||
|
||||
func torAddr(s string) (netip.Addr, bool) {
|
||||
s = strings.TrimSpace(s)
|
||||
if ap, err := netip.ParseAddrPort(s); err == nil {
|
||||
s = ap.Addr().String()
|
||||
}
|
||||
a, err := netip.ParseAddr(strings.Trim(s, "[]"))
|
||||
if err != nil || a.Zone() != "" {
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
return a.Unmap(), true
|
||||
}
|
||||
|
||||
// ParseTorExitList parses the plain-text exit list (one address per line,
|
||||
// junk and # comments ignored, at most maxTorExits addresses, input limited to
|
||||
// 32 MB).
|
||||
func ParseTorExitList(r io.Reader) []netip.Addr {
|
||||
var out []netip.Addr
|
||||
sc := bufio.NewScanner(io.LimitReader(r, maxTorList))
|
||||
sc.Buffer(make([]byte, 0, 4096), 4096)
|
||||
for sc.Scan() && len(out) < maxTorExits {
|
||||
l := sc.Text()
|
||||
if i := strings.IndexByte(l, '#'); i >= 0 {
|
||||
l = l[:i]
|
||||
}
|
||||
if a, ok := torAddr(l); ok {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ParseOnionoo extracts the relay and exit addresses (v4 and v6) of an Onionoo
|
||||
// "details" document (input limited to 32 MB, at most 400000 addresses).
|
||||
func ParseOnionoo(r io.Reader) ([]netip.Addr, error) {
|
||||
var doc struct {
|
||||
Relays []struct {
|
||||
OR []string `json:"or_addresses"`
|
||||
Exit []string `json:"exit_addresses"`
|
||||
} `json:"relays"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(r, maxTorList)).Decode(&doc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []netip.Addr
|
||||
for _, rl := range doc.Relays {
|
||||
for _, s := range append(rl.OR, rl.Exit...) {
|
||||
if a, ok := torAddr(s); ok && len(out) < maxTorRelays {
|
||||
out = append(out, a)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func fetchTor(ctx context.Context, url string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, torFetchTO)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", torUserAgent)
|
||||
resp, err := (&http.Client{Timeout: torFetchTO}).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("status %d", resp.StatusCode)
|
||||
}
|
||||
b, err := io.ReadAll(io.LimitReader(resp.Body, maxTorList+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(b) > maxTorList {
|
||||
return nil, errors.New("list larger than 32 MB")
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// refreshTorLists reads the cache in dir and, when force or the cache is older
|
||||
// than maxAge, downloads the lists again. A failed download keeps the cache.
|
||||
func refreshTorLists(ctx context.Context, dir, exitURL, relayURL string, maxAge time.Duration, log *slog.Logger) {
|
||||
_ = os.MkdirAll(dir, 0o750)
|
||||
one := func(name, url string, parse func([]byte) ([]netip.Addr, error)) []netip.Addr {
|
||||
path := filepath.Join(dir, name)
|
||||
st, statErr := os.Stat(path)
|
||||
if statErr != nil || time.Since(st.ModTime()) >= maxAge {
|
||||
if b, err := fetchTor(ctx, url); err != nil {
|
||||
log.Warn("tor list download failed", "list", name, "err", err)
|
||||
} else if a, err := parse(b); err != nil || len(a) == 0 {
|
||||
log.Warn("tor list invalid, kept the cache", "list", name, "err", err)
|
||||
} else if err := os.WriteFile(path+".tmp", b, 0o640); err == nil && os.Rename(path+".tmp", path) == nil {
|
||||
return a
|
||||
}
|
||||
}
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil || len(b) > maxTorList {
|
||||
return nil
|
||||
}
|
||||
a, _ := parse(b)
|
||||
return a
|
||||
}
|
||||
exits := one(torExitCache, exitURL, func(b []byte) ([]netip.Addr, error) {
|
||||
return ParseTorExitList(strings.NewReader(string(b))), nil
|
||||
})
|
||||
relays := one(torRelayCache, relayURL, func(b []byte) ([]netip.Addr, error) {
|
||||
return ParseOnionoo(strings.NewReader(string(b)))
|
||||
})
|
||||
torLists.setAuto(exits, relays)
|
||||
log.Info("tor lists", "exits", len(exits), "relays", len(relays))
|
||||
}
|
||||
|
||||
// watchTorLists refreshes the official lists now (in the background, so
|
||||
// startup is not blocked) and every interval.
|
||||
func watchTorLists(ctx context.Context, dir, exitURL, relayURL string, every time.Duration, log *slog.Logger) {
|
||||
go func() {
|
||||
refreshTorLists(ctx, dir, exitURL, relayURL, every*9/10, log)
|
||||
t := time.NewTicker(every)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
refreshTorLists(ctx, dir, exitURL, relayURL, every*9/10, log)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
)
|
||||
|
||||
func TestParseTorLists(t *testing.T) {
|
||||
got := ParseTorExitList(strings.NewReader("1.2.3.4\n# c\nlixo\n2001:db8::1 # x\n999.1.1.1\n::ffff:5.6.7.8\n"))
|
||||
if len(got) != 3 || got[2].String() != "5.6.7.8" {
|
||||
t.Fatalf("exits: %v", got)
|
||||
}
|
||||
js := `{"relays":[{"or_addresses":["10.1.1.1:9001","[2001:db8::2]:443","junk"],"exit_addresses":["10.1.1.2"]},{"or_addresses":[]}]}`
|
||||
a, err := ParseOnionoo(strings.NewReader(js))
|
||||
if err != nil || len(a) != 3 || a[1].String() != "2001:db8::2" {
|
||||
t.Fatalf("onionoo: %v %v", a, err)
|
||||
}
|
||||
if _, err := ParseOnionoo(strings.NewReader("<html>")); err == nil {
|
||||
t.Fatal("garbage must fail")
|
||||
}
|
||||
// the size limit truncates the input: broken JSON, an error
|
||||
if _, err := ParseOnionoo(strings.NewReader(`{"relays":[{"or_addresses":["1.1.1.1:1"]}` + strings.Repeat(" ", maxTorList+10) + `]}`)); err == nil {
|
||||
t.Fatal("oversize must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshTorListsCache(t *testing.T) {
|
||||
hits := 0
|
||||
fail := false
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits++
|
||||
if fail || r.Header.Get("User-Agent") != "urutau" {
|
||||
http.Error(w, "x", 500)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/exit" {
|
||||
w.Write([]byte("198.51.100.1\n"))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"relays":[{"or_addresses":["198.51.100.2:9001"]}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
defer torLists.setManual(nil)
|
||||
defer torLists.setAuto([]netip.Addr{}, []netip.Addr{})
|
||||
dir := filepath.Join(t.TempDir(), "tor")
|
||||
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
|
||||
ctx := context.Background()
|
||||
refreshTorLists(ctx, dir, srv.URL+"/exit", srv.URL+"/relays", time.Hour, log)
|
||||
if !intel.IsTorExit(netip.MustParseAddr("198.51.100.1")) || !intel.IsTorRelay(netip.MustParseAddr("198.51.100.2")) || hits != 2 {
|
||||
t.Fatalf("lists not loaded, hits=%d", hits)
|
||||
}
|
||||
refreshTorLists(ctx, dir, srv.URL+"/exit", srv.URL+"/relays", time.Hour, log) // fresh cache: no download
|
||||
if hits != 2 {
|
||||
t.Fatalf("cache ignored: %d", hits)
|
||||
}
|
||||
torLists.setAuto([]netip.Addr{}, []netip.Addr{})
|
||||
fail = true
|
||||
refreshTorLists(ctx, dir, srv.URL+"/exit", srv.URL+"/relays", 0, log) // stale + failing: the cache serves
|
||||
if !intel.IsTorExit(netip.MustParseAddr("198.51.100.1")) || !intel.IsTorRelay(netip.MustParseAddr("198.51.100.2")) {
|
||||
t.Fatal("fallback to cache failed")
|
||||
}
|
||||
// the manual list coexists
|
||||
torLists.setManual([]netip.Addr{netip.MustParseAddr("203.0.113.9")})
|
||||
if !intel.IsTorExit(netip.MustParseAddr("203.0.113.9")) || !intel.IsTorExit(netip.MustParseAddr("198.51.100.1")) {
|
||||
t.Fatal("manual + auto merge failed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetTypeTorEntry(t *testing.T) {
|
||||
a := netip.MustParseAddr("198.51.100.5")
|
||||
intel.SetTorExits([]netip.Addr{a})
|
||||
defer intel.SetTorExits(nil)
|
||||
if typ, _ := intel.NetTypeIP(a, 0, "", ""); typ != "tor" {
|
||||
t.Fatal(typ)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEgressOwnAllowAndProvider(t *testing.T) {
|
||||
if got := providerASNs("31898, AS47583,x", nil); len(got) != 2 || got[0] != "AS31898" || got[1] != "AS47583" {
|
||||
t.Fatalf("%v", got)
|
||||
}
|
||||
ps := ownPublicPrefixes()
|
||||
for _, p := range ps {
|
||||
if p.Addr().IsPrivate() || p.Addr().IsLoopback() {
|
||||
t.Fatal(p)
|
||||
}
|
||||
}
|
||||
// the peer has no URUTAU_PEERS: URUTAU_TRUSTED carries both servers, and a
|
||||
// bad item does not discard the others
|
||||
al := egressAllow(Config{Trusted: "136.248.78.83,lixo,195.200.0.252/32"})
|
||||
for _, ipS := range []string{"136.248.78.83", "195.200.0.252"} {
|
||||
ok := false
|
||||
for _, p := range al {
|
||||
ok = ok || p.Contains(netip.MustParseAddr(ipS))
|
||||
}
|
||||
if !ok {
|
||||
t.Fatal("not allowed: ", ipS)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -257,3 +257,34 @@ 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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnbanLogPathDefault(t *testing.T) {
|
||||
if got := unbanLogPath(Config{EnforceLog: "/logs/enforce/decisions.log"}); got != "/logs/enforce/unban.log" {
|
||||
t.Fatalf("default unban log = %q", got)
|
||||
}
|
||||
if got := unbanLogPath(Config{EnforceLog: "/a/d.log", EnforceUnbanLog: "/b/u.log"}); got != "/b/u.log" {
|
||||
t.Fatalf("explicit unban log = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -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.2"
|
||||
var Version = "1.4.7"
|
||||
@@ -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
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
@@ -548,3 +549,59 @@ func TestBeaconDuringContinuousScan(t *testing.T) {
|
||||
t.Fatal("fanSeen unbounded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconProviderAndCDN(t *testing.T) {
|
||||
geo := func(s string) (string, string, string) {
|
||||
switch s {
|
||||
case "192.0.2.10":
|
||||
return "US", "AS31898", "Oracle Corporation"
|
||||
case "192.0.2.20":
|
||||
return "US", "AS13335", "Cloudflare"
|
||||
}
|
||||
return "BR", "AS2", "y"
|
||||
}
|
||||
bad := func(a netip.Addr) (bool, string) { return a == ip("192.0.2.30"), "known attacker" }
|
||||
e := newEng(t, Config{Geo: geo, BadDst: bad, ProviderASNs: func() []string { return []string{"AS31898"} }})
|
||||
rnd := rand.New(rand.NewSource(2))
|
||||
for _, src := range []string{"10.0.3.5"} {
|
||||
feedBeacon(e, src, "192.0.2.10", 443, t0, 50, 60*time.Second, 0.05, rnd)
|
||||
feedBeacon(e, src, "192.0.2.20", 443, t0, 50, 60*time.Second, 0.05, rnd)
|
||||
}
|
||||
// the host itself towards the provider network
|
||||
for i := 0; i < 50; i++ {
|
||||
ev := mk(t0.Add(time.Duration(i)*60*time.Second), "10.0.3.5", "192.0.2.10", "tcp", 8443)
|
||||
ev.Host = true
|
||||
e.IngestEvent(ev)
|
||||
ev2 := mk(t0.Add(time.Duration(i)*60*time.Second), "10.0.3.5", "192.0.2.30", "tcp", 8443)
|
||||
ev2.Host = true
|
||||
e.IngestEvent(ev2)
|
||||
}
|
||||
r := rep(e)
|
||||
var inf, cont, cdn, hi bool
|
||||
for _, f := range r.Findings {
|
||||
switch {
|
||||
case f.Kind == "infra" && f.Dst == "192.0.2.10" && f.Workload == "host" && f.Severity == "info" && strings.Contains(f.Detail, "provider service (Oracle Corporation)"):
|
||||
inf = true
|
||||
case f.Kind == "beacon" && f.Dst == "192.0.2.10" && f.Severity == "medium":
|
||||
cont = true // container to the provider ASN: evaluated normally
|
||||
case f.Kind == "beacon" && f.Dst == "192.0.2.20" && f.Severity == "low" && strings.Contains(f.Detail, "API"):
|
||||
cdn = true
|
||||
case f.Kind == "beacon" && f.Dst == "192.0.2.30" && f.Severity == "high":
|
||||
hi = true
|
||||
}
|
||||
}
|
||||
if !inf || !cont || !cdn || !hi {
|
||||
t.Fatalf("infra=%v container=%v cdn=%v bad=%v: %+v", inf, cont, cdn, hi, r.Findings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTorRelayFinding(t *testing.T) {
|
||||
e := newEng(t, Config{Workloads: "sc=10.0.5.0/24:scanner", TorRelay: func(a netip.Addr) bool { return a == ip("192.0.2.77") }})
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "192.0.2.77", "tcp", 443))
|
||||
e.IngestEvent(mk(t0, "10.0.5.2", "192.0.2.77", "tcp", 443)) // scanner outside a burst
|
||||
e.IngestEvent(mk(t0, "10.0.3.5", "192.0.2.78", "tcp", 443))
|
||||
f := kinds(rep(e), "tor")
|
||||
if len(f) != 2 || f[0].Severity != "high" || f[0].Dst != "192.0.2.77" {
|
||||
t.Fatalf("tor: %+v", f)
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,13 @@ type Config struct {
|
||||
// destination is a known attacker or Tor exit (and why).
|
||||
Geo func(ip string) (cc, asn, org string)
|
||||
BadDst func(netip.Addr) (bool, string)
|
||||
Now func() time.Time
|
||||
// TorRelay says whether an address is a Tor relay (a connection to one is
|
||||
// a "tor" finding).
|
||||
TorRelay func(netip.Addr) bool
|
||||
// ProviderASNs ("AS31898") are the hosting provider's own networks: a
|
||||
// beacon from the host itself to them is informational ("infra").
|
||||
ProviderASNs func() []string
|
||||
Now func() time.Time
|
||||
// Learn is the per-workload learning time before new_geo (default 24h).
|
||||
Learn time.Duration
|
||||
// ResolvConf lists resolv.conf files whose nameservers are allowed resolvers
|
||||
@@ -700,6 +706,9 @@ func (e *Engine) checks(ws *wstate, ev Event, dport uint16, t int64, ds *dstStat
|
||||
e.addFinding("bad_dst", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
|
||||
}
|
||||
}
|
||||
if e.cfg.TorRelay != nil && e.cfg.TorRelay(ev.Dst) {
|
||||
e.addFinding("tor", "high", ws.name, dst, dport, ev.Proto, t, 0, 0, "connection to a Tor relay", 1)
|
||||
}
|
||||
if ev.Proto == "tcp" {
|
||||
if sev, why := suspiciousPort(dport, ws.role); why != "" {
|
||||
e.addFinding("port", sev, ws.name, dst, dport, ev.Proto, t, 0, 0, why, 1)
|
||||
@@ -744,7 +753,15 @@ func suspiciousPort(port uint16, role string) (sev, why string) {
|
||||
|
||||
func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairState, ds *dstStat) {
|
||||
if p.flagged {
|
||||
if f := e.addFinding("beacon", "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1); f != nil {
|
||||
kind := "beacon"
|
||||
if ev.Host && e.cfg.Geo != nil {
|
||||
if _, asn, _ := e.cfg.Geo(ev.Dst.String()); e.providerASN(asn) {
|
||||
if _, ok := e.findings[fmt.Sprintf("infra|%s|%s|%d", ws.name, ev.Dst, dport)]; ok {
|
||||
kind = "infra"
|
||||
}
|
||||
}
|
||||
}
|
||||
if f := e.addFinding(kind, "", ws.name, ev.Dst.String(), dport, ev.Proto, p.last, p.interval, p.cv, "", 1); f != nil {
|
||||
if n := len(f.Samples); n == 0 || f.Samples[n-1] != p.last {
|
||||
if n >= MaxSamples {
|
||||
f.Samples = append(f.Samples[:0], f.Samples[1:]...)
|
||||
@@ -802,15 +819,27 @@ func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairSta
|
||||
if mad < cv {
|
||||
jit = mad
|
||||
}
|
||||
sev := "medium"
|
||||
sev, kind := "medium", "beacon"
|
||||
why := fmt.Sprintf("regular connections every %.0f s (jitter %.0f%%)", med, jit*100)
|
||||
bad := false
|
||||
if e.cfg.BadDst != nil {
|
||||
if bad, r := e.cfg.BadDst(ev.Dst); bad {
|
||||
sev, why = "high", why+"; destination: "+r
|
||||
if b, r := e.cfg.BadDst(ev.Dst); b {
|
||||
bad, sev, why = true, "high", why+"; destination: "+r
|
||||
}
|
||||
}
|
||||
if !bad && e.cfg.Geo != nil {
|
||||
_, asn, org := e.cfg.Geo(ev.Dst.String())
|
||||
switch {
|
||||
case ev.Host && e.providerASN(asn):
|
||||
sev, kind = "info", "infra"
|
||||
why = fmt.Sprintf("%s; provider service (%s)", why, org)
|
||||
case commonCloudASNs[asn]:
|
||||
sev = "low"
|
||||
why += "; large CDN/cloud network: regular connections are common for API calls"
|
||||
}
|
||||
}
|
||||
p.flagged, p.interval, p.cv = true, med, jit
|
||||
f := e.addFinding("beacon", sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
|
||||
f := e.addFinding(kind, sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
|
||||
if f != nil {
|
||||
f.Count, f.First = int(p.total), p.first
|
||||
f.Samples = make([]int64, 0, MaxSamples)
|
||||
@@ -820,6 +849,25 @@ func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairSta
|
||||
}
|
||||
}
|
||||
|
||||
// commonCloudASNs are large CDNs/clouds whose regular connections usually are
|
||||
// API calls.
|
||||
var commonCloudASNs = map[string]bool{"AS13335": true, "AS15169": true, "AS14618": true, "AS16509": true, "AS8075": true, "AS20940": true, "AS54113": true}
|
||||
|
||||
func (e *Engine) providerASN(asn string) bool {
|
||||
if asn == "" {
|
||||
return false
|
||||
}
|
||||
if e.cfg.ProviderASNs == nil {
|
||||
return false
|
||||
}
|
||||
for _, a := range e.cfg.ProviderASNs() {
|
||||
if strings.EqualFold(a, asn) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func median(v []float64) float64 {
|
||||
s := append([]float64(nil), v...)
|
||||
sort.Float64s(s)
|
||||
@@ -833,7 +881,7 @@ func median(v []float64) float64 {
|
||||
return (s[n/2-1] + s[n/2]) / 2
|
||||
}
|
||||
|
||||
var sevRank = map[string]int{"low": 1, "medium": 2, "high": 3}
|
||||
var sevRank = map[string]int{"info": 0, "low": 1, "medium": 2, "high": 3}
|
||||
|
||||
func (e *Engine) addFinding(kind, sev, wl, dst string, dport uint16, proto string, t int64, iv, jit float64, detail string, inc int) *Finding {
|
||||
key := fmt.Sprintf("%s|%s|%s|%d", kind, wl, dst, dport)
|
||||
|
||||
+100
-13
@@ -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
|
||||
@@ -31,6 +32,37 @@ 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
|
||||
Est Tally // estimate from per-day counters, used when the registry holds less
|
||||
}
|
||||
|
||||
// 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.
|
||||
@@ -132,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
|
||||
@@ -151,6 +185,10 @@ type Engine struct {
|
||||
dirty bool
|
||||
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
|
||||
}
|
||||
|
||||
// New builds an engine and loads its state.
|
||||
@@ -174,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{}}}
|
||||
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()
|
||||
@@ -223,15 +262,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 {
|
||||
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
|
||||
go e.Sweep()
|
||||
}
|
||||
e.drain()
|
||||
case <-peers.C:
|
||||
e.refreshPeers()
|
||||
}
|
||||
@@ -431,6 +483,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] {
|
||||
@@ -438,10 +500,13 @@ 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
|
||||
}
|
||||
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) {
|
||||
@@ -610,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
|
||||
}
|
||||
@@ -627,10 +692,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
|
||||
}
|
||||
@@ -647,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
|
||||
}
|
||||
@@ -662,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() {
|
||||
@@ -684,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.
|
||||
@@ -706,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)
|
||||
@@ -750,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)
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
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
|
||||
}
|
||||
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)
|
||||
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()]
|
||||
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)
|
||||
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,233 @@
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"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
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
+37
-19
@@ -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.
|
||||
@@ -84,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"
|
||||
)
|
||||
@@ -116,6 +125,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 +165,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{}
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -11,8 +11,29 @@ import (
|
||||
var (
|
||||
torMu sync.RWMutex
|
||||
torExits map[netip.Addr]struct{}
|
||||
torRelay map[netip.Addr]struct{}
|
||||
)
|
||||
|
||||
// SetTorRelays loads (or clears) the list of running Tor relays.
|
||||
func SetTorRelays(addrs []netip.Addr) {
|
||||
m := make(map[netip.Addr]struct{}, len(addrs))
|
||||
for _, a := range addrs {
|
||||
m[a.Unmap()] = struct{}{}
|
||||
}
|
||||
torMu.Lock()
|
||||
torRelay = m
|
||||
torMu.Unlock()
|
||||
}
|
||||
|
||||
// IsTorRelay reports whether ip is a running Tor relay (exits included when the
|
||||
// relay list carries them).
|
||||
func IsTorRelay(ip netip.Addr) bool {
|
||||
torMu.RLock()
|
||||
defer torMu.RUnlock()
|
||||
_, ok := torRelay[ip.Unmap()]
|
||||
return ok
|
||||
}
|
||||
|
||||
// SetTorExits loads (or clears, with nil/empty) the Tor exit list. It is off
|
||||
// by default; the caller decides where the list comes from.
|
||||
func SetTorExits(addrs []netip.Addr) {
|
||||
|
||||
@@ -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})
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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'];
|
||||
@@ -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,
|
||||
|
||||
@@ -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)',
|
||||
@@ -114,6 +124,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': {
|
||||
@@ -199,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)',
|
||||
@@ -219,6 +240,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.'
|
||||
}
|
||||
});
|
||||
@@ -385,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)));
|
||||
});
|
||||
@@ -399,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));
|
||||
@@ -412,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() {
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
var SEV = { high: 0, medium: 1, low: 2 };
|
||||
var SEV_NAME = ['high', 'medium', 'low'];
|
||||
var SEV_TONE = { high: 'danger', medium: 'warn', low: 'info' };
|
||||
var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', 'new_geo'];
|
||||
var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.eg_baddst', dns_bypass: 'term.dot', new_geo: 'term.new_geo' };
|
||||
var KINDS = ['beacon', 'scan', 'port', 'bad_dst', 'dns_bypass', 'new_geo', 'tor'];
|
||||
var KIND_HELP = { beacon: 'term.beaconing', scan: 'term.fanout', port: 'term.stratum', bad_dst: 'term.eg_baddst', dns_bypass: 'term.dot', new_geo: 'term.new_geo', tor: 'term.tor' };
|
||||
var LAT_TOP = 84, LAT_SPAN = 142;
|
||||
|
||||
function boot() {
|
||||
@@ -58,6 +58,11 @@
|
||||
'eg.kind.bad_dst': 'Known-bad destination',
|
||||
'eg.kind.dns_bypass': 'DNS outside the resolver',
|
||||
'eg.kind.new_geo': 'New country',
|
||||
'eg.kind.tor': 'Talking to the Tor network',
|
||||
'eg.why.tor': 'The workload connected to a relay of the Tor network (anonymous routing). On a server this is common in malware, command-and-control and data exfiltration.',
|
||||
'eg.do.tor': 'Find the process that opened the connection. Unless Tor is intended on this server, treat it as compromised and rebuild it from a clean image.',
|
||||
'eg.infra': 'Regular connections with provider services ({n})',
|
||||
'eg.infra.hint': 'Not counted as findings: the host talking to its own cloud provider (agents, metadata, updates).',
|
||||
'eg.why.beacon': 'The workload talks to the same destination at regular intervals, like a clock. This is the typical pattern of malware checking in with its controller.',
|
||||
'eg.why.scan': 'The workload tried to connect to many different addresses in a short time. A server that scans the internet usually means it was taken over.',
|
||||
'eg.why.port': 'Connection to a port used by mining pools or remote-control tools, which normal software on this server does not use.',
|
||||
@@ -167,6 +172,11 @@
|
||||
'eg.kind.bad_dst': 'Destino sabidamente ruim',
|
||||
'eg.kind.dns_bypass': 'DNS fora do resolvedor',
|
||||
'eg.kind.new_geo': 'País novo',
|
||||
'eg.kind.tor': 'Conversa com a rede Tor',
|
||||
'eg.why.tor': 'O workload conectou a um relay da rede Tor (roteamento anônimo). Em um servidor isso é comum em malware, comando e controle e exfiltração de dados.',
|
||||
'eg.do.tor': 'Descubra o processo que abriu a conexão. Se o Tor não é esperado neste servidor, trate-o como comprometido e reconstrua a partir de uma imagem limpa.',
|
||||
'eg.infra': 'Conexões regulares com serviços do provedor ({n})',
|
||||
'eg.infra.hint': 'Não contam como achados: o servidor falando com a própria nuvem (agentes, metadados, atualizações).',
|
||||
'eg.why.beacon': 'O workload fala com o mesmo destino em intervalos regulares, como um relógio. É o padrão típico de um malware avisando seu controlador que está vivo.',
|
||||
'eg.why.scan': 'O workload tentou conectar a muitos endereços diferentes em pouco tempo. Um servidor que varre a internet costuma ter sido invadido.',
|
||||
'eg.why.port': 'Conexão a uma porta usada por mineração de criptomoeda ou ferramentas de controle remoto, que os programas normais deste servidor não usam.',
|
||||
@@ -274,6 +284,18 @@
|
||||
el('div', { class: 'eg-v-txt' }, el('h2', null, title), el('p', null, sub), pills.firstChild ? pills : null, srcLine));
|
||||
}
|
||||
|
||||
function infraLine(st) {
|
||||
var box = el('details', { class: 'eg-infra hint' }, el('summary', { title: t('eg.infra.hint') }, t('eg.infra', { n: nf(st.infra.length) })));
|
||||
var ul = el('ul', null);
|
||||
st.infra.slice(0, 50).forEach(function (f) {
|
||||
var li = el('li', { class: 'mono' }, (f.workload || '-') + ' → ' + (f.dst || '-') + (f.dport ? ':' + f.dport : ''));
|
||||
if (f.detail) li.appendChild(el('span', null, ' · ' + f.detail));
|
||||
ul.appendChild(li);
|
||||
});
|
||||
box.appendChild(ul);
|
||||
return box;
|
||||
}
|
||||
|
||||
function kpis(st) {
|
||||
var kp = el('div', { class: 'eg-kpis' });
|
||||
kp.appendChild(U.ui.metric(t('eg.kpi.conns'), nf(st.conns), { sub: t('eg.kpi.conns.sub'), spark: st.total }));
|
||||
@@ -482,6 +504,8 @@
|
||||
// ------------------------------------------------------------ paint
|
||||
function stats(d) {
|
||||
var st = { wls: d.workloads || [], fnd: (d.findings || []).slice(), dsts: d.top_dst || [], bursts: (d.scanner && d.scanner.bursts) || [], tl: d.timeline || {} };
|
||||
st.infra = st.fnd.filter(function (f) { return f.severity === 'info' || f.kind === 'infra'; });
|
||||
st.fnd = st.fnd.filter(function (f) { return f.severity !== 'info' && f.kind !== 'infra'; });
|
||||
st.fnd.sort(function (a, b) { return SEV[sevOf(a)] - SEV[sevOf(b)] || (b.last || 0) - (a.last || 0); });
|
||||
st.ser = st.tl.series || {};
|
||||
st.conns = 0; st.active = 0; st.sev = { high: 0, medium: 0, low: 0 };
|
||||
@@ -516,6 +540,7 @@
|
||||
var st = stats(data), range = U.rangeLabel({ inline: true });
|
||||
root.appendChild(verdict(data, st, range));
|
||||
root.appendChild(kpis(st));
|
||||
if (st.infra.length) root.appendChild(infraLine(st));
|
||||
|
||||
var grid = el('div', { class: 'grid-12' });
|
||||
var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12' });
|
||||
|
||||
@@ -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',
|
||||
@@ -243,6 +256,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)',
|
||||
@@ -468,6 +482,8 @@ window.URUTAU_I18N = {
|
||||
'help.term.authorized_scanner.do': 'Make sure it only aims at targets you own or may test.',
|
||||
'help.term.ban_ttl': 'Block duration (TTL): how long an address stays blocked before being released. Repeat offenders get longer blocks.',
|
||||
'help.term.ban_ttl.do': 'Short blocks are safer against mistakes; long ones stop persistent attackers.',
|
||||
'help.term.tor': 'Tor is a network that hides who is connecting. Some visitors use it for privacy, but attackers also use it to hide. An origin marked Tor is a Tor exit; a server of yours talking to Tor relays is suspicious.',
|
||||
'help.term.tor.do': 'Treat requests from Tor with caution (do not trust them for sensitive actions). If one of your servers connects to Tor and you did not set that up, investigate it.',
|
||||
'help.term.new_geo': 'New country: the workload connected to a country it had not reached before in this window.',
|
||||
'help.term.new_geo.do': 'Check whether the destination is a service you use.',
|
||||
'help.term.error_class.app': 'Errors caused by your own application (5xx coming from the app).',
|
||||
@@ -543,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',
|
||||
@@ -742,6 +771,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)',
|
||||
@@ -967,6 +997,8 @@ window.URUTAU_I18N = {
|
||||
'help.term.authorized_scanner.do': 'Garanta que ele só mire alvos seus ou que você pode testar.',
|
||||
'help.term.ban_ttl': 'Duração do bloqueio (TTL): por quanto tempo o endereço fica bloqueado antes de ser liberado. Reincidentes recebem bloqueios mais longos.',
|
||||
'help.term.ban_ttl.do': 'Bloqueios curtos são mais seguros contra enganos; longos barram atacantes persistentes.',
|
||||
'help.term.tor': 'Tor é uma rede que esconde quem está conectando. Algumas pessoas usam por privacidade, mas atacantes também usam para se esconder. Origem marcada como Tor é uma saída Tor; um servidor seu falando com relays Tor é suspeito.',
|
||||
'help.term.tor.do': 'Trate requisições vindas do Tor com cautela (não confie nelas em ações sensíveis). Se um servidor seu conecta ao Tor e você não configurou isso, investigue.',
|
||||
'help.term.new_geo': 'País novo: o workload conectou a um país que ainda não tinha alcançado nesta janela.',
|
||||
'help.term.new_geo.do': 'Confira se o destino é um serviço que você usa.',
|
||||
'help.term.error_class.app': 'Erros causados pela sua própria aplicação (5xx vindos do app).',
|
||||
|
||||
@@ -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')));
|
||||
|
||||
@@ -124,7 +124,7 @@
|
||||
'ip.ntr.asn': 'known ASN {v}',
|
||||
'ip.ntr.asorg': 'organization name contains "{v}"',
|
||||
'ip.ntr.rdns': 'reverse DNS contains "{v}"',
|
||||
'ip.ntr.tor': 'listed as a Tor exit node',
|
||||
'ip.ntr.tor': 'listed as a Tor exit node (official list)',
|
||||
'ip.untrusted': 'text sent by the attacker',
|
||||
'ip.act.copy': 'Copy IP',
|
||||
'ip.act.ioc': 'Copy as IOC',
|
||||
@@ -1010,7 +1010,9 @@
|
||||
box.appendChild(chip('ip.id.rdns', rv));
|
||||
if (id.net_type) {
|
||||
var nt = pick(NETTYPES, id.net_type, 'unknown'), why = ntReason(id.net_type_reason);
|
||||
box.appendChild(chip('ip.id.nettype', h('span', null, badge(t('ip.nt.' + nt.replace('/', '-')), NT_TONE[nt]), why ? h('small', 'ipx-faint ipx-why', ' ' + why) : null)));
|
||||
var ntw = h('span', null, badge(t('ip.nt.' + nt.replace('/', '-')), NT_TONE[nt]), why ? h('small', 'ipx-faint ipx-why', ' ' + why) : null);
|
||||
if (nt === 'tor' && U.help) U.help(ntw, 'term.tor');
|
||||
box.appendChild(chip('ip.id.nettype', ntw));
|
||||
}
|
||||
if (id.prefix) box.appendChild(chip('ip.id.prefix', h('span', 'ipx-mono', clip(id.prefix, 50))));
|
||||
return box;
|
||||
@@ -1286,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) {
|
||||
|
||||
@@ -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); }
|
||||
@@ -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; }
|
||||
@@ -294,7 +294,11 @@ func (s *Store) period(q PeriodQuery) PeriodOut {
|
||||
sg := intel.SignatureFrom(paths, tool)
|
||||
g := s.GeoOf(ss.IP)
|
||||
sg.ASN, sg.CC = g.ASN, g.CC
|
||||
sg.NetType, _ = intel.NetType(g.ASN, g.ASOrg, "")
|
||||
if a, err := netip.ParseAddr(ss.IP); err == nil {
|
||||
sg.NetType, _ = intel.NetTypeIP(a, g.ASN, g.ASOrg, "")
|
||||
} else {
|
||||
sg.NetType, _ = intel.NetType(g.ASN, g.ASOrg, "")
|
||||
}
|
||||
sigs[ss.ID] = sg
|
||||
if g.ASN != 0 {
|
||||
asns["AS"+strconv.Itoa(int(g.ASN))+" "+g.ASOrg]++
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
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
|
||||
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.
|
||||
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, Est: dayEstimate(r, nowU)})
|
||||
}
|
||||
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}, 4<<30, 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 {
|
||||
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 est
|
||||
}
|
||||
m := map[string]*Tally24{}
|
||||
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
|
||||
})
|
||||
var t Tally24
|
||||
for _, v := range m {
|
||||
t.SSH += v.SSH
|
||||
t.Web += v.Web
|
||||
}
|
||||
t.SSH, t.Web = max(t.SSH, est.SSH), max(t.Web, est.Web)
|
||||
return t
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user