feat: 1.4.1 pagination, network probes, survival by blocker, report polish
Backend pagination with one pager for sessions, IPs, campaigns and events; network probe source (port-scan, T1046, second firewall reason port-scan); host kit logs inbound probes; urutau call on the report cover. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f27d8441a9
commit
e98739b06a
40 files changed
+927
-136
No files matched your search
@@ -6,6 +6,20 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.4.1] - 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- Network probes source (`URUTAU_PROBE_LOG`, default `/logs/host/probe.log`): the host kit logs new inbound connections to ports nobody listens on; each becomes a `port-scan` event (MITRE T1046), and 10 distinct ports in 10 minutes make the second firewall ban the address (reason `port-scan`).
|
||||
- Survival: who blocked and how fast, the host fail2ban jails apart from the Urutau second firewall.
|
||||
- Pagination in the backend for sessions, IPs, campaigns and the events of an address, with one pager for every list; event search pages by cursor.
|
||||
|
||||
### Changed
|
||||
|
||||
- Outbound traffic page redesigned: plain-language verdict, evidence cards (beacon rhythm and interval histogram), destination map, activity by hour, compact workloads and the timeline of authorised scans. API: `findings[].samples`, `by_country`.
|
||||
- Reports page: a preview of the HTML report itself, always an A4 sheet scaled to the screen, with only Download and Print; language selector, period and server from the header.
|
||||
- Report: sharp logo (the repository logo at 800 px) and the cover drawing is now the urutau's call, five descending notes.
|
||||
|
||||
## [1.4.0] - 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
@@ -6,6 +6,20 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.4.1] - 2026-11-15
|
||||
|
||||
### Adicionado
|
||||
|
||||
- Fonte de sondagens de rede (`URUTAU_PROBE_LOG`, padrão `/logs/host/probe.log`): o kit do host registra conexões novas de entrada para portas em que nada escuta; cada uma vira um evento `port-scan` (MITRE T1046), e 10 portas distintas em 10 minutos fazem o segundo firewall banir o endereço (motivo `port-scan`).
|
||||
- Sobrevivência: quem bloqueou e com que rapidez, os jails do fail2ban do host separados do segundo firewall do Urutau.
|
||||
- Paginação no backend para sessões, IPs, campanhas e eventos de um endereço, com um paginador único em todas as listas; a busca de eventos pagina por cursor.
|
||||
|
||||
### Alterado
|
||||
|
||||
- Página Tráfego de saída refeita: veredito em linguagem leiga, cartões de evidência (ritmo do beacon e histograma dos intervalos), mapa de destinos, atividade por hora, workloads compactos e a linha do tempo das varreduras autorizadas. API: `findings[].samples`, `by_country`.
|
||||
- Página Relatórios: prévia do próprio relatório HTML, sempre uma folha A4 em escala, só com Baixar e Imprimir; seletor de idioma, período e servidor do topo.
|
||||
- Relatório: logo nítida (a logo do repositório em 800 px) e o desenho da capa agora é o canto do urutau, cinco notas descendentes.
|
||||
|
||||
## [1.4.0] - 2026-11-15
|
||||
|
||||
### Adicionado
|
||||
|
||||
@@ -5,3 +5,10 @@ if ($syslogfacility-text == "kern" and $msg contains "URUTAU-EGRESS: ") then {
|
||||
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
|
||||
stop
|
||||
}
|
||||
|
||||
# inbound probes to closed ports (port scans)
|
||||
if ($syslogfacility-text == "kern" and $msg contains "URUTAU-PROBE: ") then {
|
||||
action(type="omfile" file="/var/log/urutau/probe.log" template="RSYSLOG_FileFormat"
|
||||
fileOwner="syslog" fileGroup="adm" fileCreateMode="0640")
|
||||
stop
|
||||
}
|
||||
@@ -20,3 +20,13 @@ r=/var/log/urutau/resolv.conf
|
||||
awk '/^nameserver/ {print $2}' /run/systemd/resolve/resolv.conf 2>/dev/null || true
|
||||
} | grep -vE '^127\.' | sort -u | sed 's/^/nameserver /' > "$r.tmp"
|
||||
chgrp adm "$r.tmp"; chmod 0640 "$r.tmp"; mv -f "$r.tmp" "$r"
|
||||
|
||||
# Ports this host serves (listening sockets, including the ones Docker
|
||||
# publishes): connections to any other port are logged as probes.
|
||||
if nft list set inet urutau_egress open >/dev/null 2>&1; then
|
||||
{
|
||||
echo "flush set inet urutau_egress open"
|
||||
ss -Hlnt | awk '{print $4}' | sed -n 's/.*:\([0-9][0-9]*\)$/tcp . \1/p'
|
||||
ss -Hlnu | awk '{print $4}' | sed -n 's/.*:\([0-9][0-9]*\)$/udp . \1/p'
|
||||
} | sort -u | awk 'NR==1 {print; next} {e = e (e ? ", " : "") $0} END {if (e) print "add element inet urutau_egress open { " e " }"}' | nft -f -
|
||||
fi
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/sbin/nft -f
|
||||
# Urutau: logs NEW outbound connections (host and containers) so the egress
|
||||
# Urutau: logs NEW outbound connections (host and containers), and inbound
|
||||
# probes to closed ports, so the egress
|
||||
# analysis can spot beaconing, mining, spam and unauthorised scans.
|
||||
# Lives in its own table: it never touches the iptables-nft tables of Docker
|
||||
# or fail2ban, and it only logs (policy accept, no drop).
|
||||
@@ -32,6 +33,24 @@ table inet urutau_egress {
|
||||
meta nfproto ipv6 meta l4proto != { tcp, udp } add @rl6 { ip6 saddr limit rate 20/second burst 100 packets } log prefix "URUTAU-EGRESS: " level info
|
||||
}
|
||||
|
||||
# inbound probes: NEW connections to ports nobody listens on (port scans,
|
||||
# RDP/SMB/database probing). @open is refreshed every minute by
|
||||
# urutau-containers-map from `ss` (it also sees ports Docker publishes).
|
||||
set open { type inet_proto . inet_service; }
|
||||
set prl4 { type ipv4_addr; flags dynamic; timeout 2m; size 65535; }
|
||||
set prl6 { type ipv6_addr; flags dynamic; timeout 2m; size 65535; }
|
||||
|
||||
chain probe_log {
|
||||
type filter hook prerouting priority -150; policy accept;
|
||||
iifname != "@WAN@" return
|
||||
ct state != new return
|
||||
meta l4proto != { tcp, udp } return
|
||||
fib daddr type != local return
|
||||
meta l4proto . th dport @open return
|
||||
meta nfproto ipv4 add @prl4 { ip saddr limit rate 10/second burst 50 packets } log prefix "URUTAU-PROBE: " level info
|
||||
meta nfproto ipv6 add @prl6 { ip6 saddr limit rate 10/second burst 50 packets } log prefix "URUTAU-PROBE: " level info
|
||||
}
|
||||
|
||||
chain forward_log {
|
||||
type filter hook forward priority filter - 10; policy accept;
|
||||
ct state new oifname "@WAN@" iifname != "@WAN@" jump egress
|
||||
|
||||
@@ -7,6 +7,7 @@ Wants=network-online.target
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
ExecStart=/usr/sbin/nft -f /etc/urutau/egress.nft
|
||||
ExecStartPost=-/usr/local/sbin/urutau-containers-map
|
||||
ExecStop=/usr/sbin/nft delete table inet urutau_egress
|
||||
|
||||
[Install]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
/var/log/urutau/egress.log {
|
||||
/var/log/urutau/egress.log /var/log/urutau/probe.log {
|
||||
daily
|
||||
rotate 7
|
||||
maxsize 200M
|
||||
|
||||
@@ -26,6 +26,7 @@ type Config struct {
|
||||
TraefikLog string
|
||||
AuthLog string
|
||||
Fail2banLog string
|
||||
ProbeLog string // kernel log of new connections to unserved ports
|
||||
Ignore string // networks whose events are dropped (--ignore, alias of --trusted)
|
||||
Trusted string // trusted sources, e.g. the servers themselves (--trusted)
|
||||
MonitorUA string // regex of monitoring User-Agents
|
||||
@@ -149,6 +150,7 @@ func ParseFlags(name string, args []string) (Config, error) {
|
||||
fs.StringVar(&c.DataDir, "data-dir", env("URUTAU_DATA_DIR", "/data"), "snapshot directory (URUTAU_DATA_DIR)")
|
||||
fs.StringVar(&c.TraefikLog, "traefik-log", env("URUTAU_TRAEFIK_LOG", "/data/coolify/proxy/access.log"), "Traefik JSON access log, empty disables (URUTAU_TRAEFIK_LOG)")
|
||||
fs.StringVar(&c.AuthLog, "auth-log", env("URUTAU_AUTH_LOG", "/var/log/auth.log"), "sshd auth log, empty disables (URUTAU_AUTH_LOG)")
|
||||
fs.StringVar(&c.ProbeLog, "probe-log", env("URUTAU_PROBE_LOG", "/logs/host/probe.log"), "kernel log of network probes (unserved ports) written by the host kit, empty disables (URUTAU_PROBE_LOG)")
|
||||
fs.StringVar(&c.Fail2banLog, "fail2ban-log", env("URUTAU_FAIL2BAN_LOG", "/var/log/fail2ban.log"), "fail2ban log, empty disables (URUTAU_FAIL2BAN_LOG)")
|
||||
ign := &csvFlag{val: env("URUTAU_IGNORE", DefaultIgnore)}
|
||||
trusted := &csvFlag{val: env("URUTAU_TRUSTED", "")}
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
)
|
||||
|
||||
const probeMarker = "URUTAU-PROBE:"
|
||||
|
||||
// probeMaxKeys bounds the aggregation map; when it is full the entries older
|
||||
// than a minute are dropped.
|
||||
const probeMaxKeys = 100000
|
||||
|
||||
type probeKey struct {
|
||||
ip string
|
||||
port uint16
|
||||
proto string
|
||||
}
|
||||
|
||||
// probeParser turns "URUTAU-PROBE:" kernel lines into scanner events, at most
|
||||
// one per (ip, port, proto) per minute, so a SYN flood does not inflate the store.
|
||||
type probeParser struct {
|
||||
mu sync.Mutex
|
||||
last map[probeKey]int64 // minute of the last event kept
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func newProbeParser() *probeParser {
|
||||
return &probeParser{last: map[probeKey]int64{}, now: time.Now}
|
||||
}
|
||||
|
||||
func (p *probeParser) parse(b []byte) (core.Event, error) {
|
||||
k, err := egress.ParseKernel(b, probeMarker, p.now())
|
||||
if err != nil {
|
||||
return core.Event{}, err
|
||||
}
|
||||
if (k.Proto != "tcp" && k.Proto != "udp") || k.DPort == 0 || !k.Src.IsValid() {
|
||||
return core.Event{}, fmt.Errorf("not a tcp/udp probe")
|
||||
}
|
||||
key := probeKey{k.Src.String(), k.DPort, k.Proto}
|
||||
min := k.Time.Unix() / 60
|
||||
p.mu.Lock()
|
||||
if m, ok := p.last[key]; ok && m >= min {
|
||||
p.mu.Unlock()
|
||||
return core.Event{}, core.ErrIgnored
|
||||
}
|
||||
if len(p.last) >= probeMaxKeys {
|
||||
cut := p.now().Unix()/60 - 1
|
||||
for kk, m := range p.last {
|
||||
if m < cut {
|
||||
delete(p.last, kk)
|
||||
}
|
||||
}
|
||||
if len(p.last) >= probeMaxKeys {
|
||||
p.last = map[probeKey]int64{}
|
||||
}
|
||||
}
|
||||
p.last[key] = min
|
||||
p.mu.Unlock()
|
||||
return core.Event{Time: k.Time, IP: k.Src.String(), Cat: core.Scanner, Source: "probe", Method: upper(k.Proto),
|
||||
Path: k.Proto + "/" + itoa(int(k.DPort)) + serviceSuffix(k.Proto, k.DPort), Proto: k.Proto, Port: k.DPort}, nil
|
||||
}
|
||||
|
||||
func upper(s string) string {
|
||||
if s == "udp" {
|
||||
return "UDP"
|
||||
}
|
||||
return "TCP"
|
||||
}
|
||||
|
||||
func itoa(n int) string { return fmt.Sprint(n) }
|
||||
|
||||
func serviceSuffix(proto string, port uint16) string {
|
||||
if s := core.PortService(proto, port); s != "" {
|
||||
return " " + s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
const probeV4 = `2026-11-15T03:20:01.123456+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= MAC=aa SRC=203.0.113.9 DST=195.200.0.252 LEN=44 TTL=241 ID=1 PROTO=TCP SPT=51234 DPT=3389 WINDOW=1024 SYN URGP=0`
|
||||
|
||||
func TestProbeParse(t *testing.T) {
|
||||
p := newProbeParser()
|
||||
ev, err := p.parse([]byte(probeV4))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ev.IP != "203.0.113.9" || ev.Cat != core.Scanner || ev.Source != "probe" || ev.Port != 3389 || ev.Proto != "tcp" || ev.Path != "tcp/3389 rdp" {
|
||||
t.Fatalf("%+v", ev)
|
||||
}
|
||||
v6 := `2026-11-15T03:20:01+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= SRC=2001:db8::5 DST=2001:db8::1 LEN=60 PROTO=TCP SPT=1 DPT=445 SYN`
|
||||
if ev, err = p.parse([]byte(v6)); err != nil || ev.IP != "2001:db8::5" || ev.Port != 445 {
|
||||
t.Fatalf("%+v %v", ev, err)
|
||||
}
|
||||
udp := `2026-11-15T03:20:01+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= SRC=203.0.113.9 DST=195.200.0.252 LEN=60 PROTO=UDP SPT=1 DPT=161 LEN=40`
|
||||
if ev, err = p.parse([]byte(udp)); err != nil || ev.Proto != "udp" || ev.Path != "udp/161 snmp" {
|
||||
t.Fatalf("%+v %v", ev, err)
|
||||
}
|
||||
for _, bad := range []string{"", "garbage", "kernel: URUTAU-PROBE: nothing", `x URUTAU-PROBE: SRC=bad DST=1.1.1.1 PROTO=TCP DPT=1`,
|
||||
`x URUTAU-PROBE: SRC=1.1.1.1 DST=2.2.2.2 PROTO=ICMP`} {
|
||||
if _, err := newProbeParser().parse([]byte(bad)); err == nil {
|
||||
t.Errorf("accepted %q", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestProbePerMinuteAggregation(t *testing.T) {
|
||||
p := newProbeParser()
|
||||
if _, err := p.parse([]byte(probeV4)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// same ip/port/proto in the same minute: ignored (not malformed)
|
||||
if _, err := p.parse([]byte(probeV4)); !errors.Is(err, core.ErrIgnored) {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
// another port is kept
|
||||
if _, err := p.parse([]byte(probeV4[:len(probeV4)-0])); err == nil {
|
||||
t.Fatal("repeat accepted")
|
||||
}
|
||||
other := `2026-11-15T03:20:02+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= SRC=203.0.113.9 DST=1.2.3.4 PROTO=TCP SPT=1 DPT=22 SYN`
|
||||
if _, err := p.parse([]byte(other)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// next minute: kept again
|
||||
next := `2026-11-15T03:21:01+00:00 srv kernel: URUTAU-PROBE: IN=eth0 OUT= SRC=203.0.113.9 DST=1.2.3.4 PROTO=TCP SPT=1 DPT=3389 SYN`
|
||||
if _, err := p.parse([]byte(next)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProbeFamilyMitre(t *testing.T) {
|
||||
fam, tech, _ := store.IntelClassifier(core.Event{Source: "probe", Cat: core.Scanner, Path: "tcp/23 telnet"})
|
||||
if fam != intel.FamPortScan {
|
||||
t.Fatalf("fam %q", fam)
|
||||
}
|
||||
has := false
|
||||
for _, x := range tech {
|
||||
has = has || x == "T1046"
|
||||
}
|
||||
if !has {
|
||||
t.Fatalf("tech %v", tech)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProbeSourceMissingIsWaiting(t *testing.T) {
|
||||
s := &source{name: "probe", path: t.TempDir() + "/absent.log"}
|
||||
if st := s.status(); st.State != "waiting" || st.Error != "" {
|
||||
t.Fatalf("%+v", st)
|
||||
}
|
||||
_ = time.Now
|
||||
}
|
||||
@@ -91,7 +91,7 @@ func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) {
|
||||
for _, d := range []struct {
|
||||
name, path string
|
||||
parse func([]byte) (core.Event, error)
|
||||
}{{"traefik", c.TraefikLog, traefikParse}, {"ssh", c.AuthLog, authParse}, {"fail2ban", c.Fail2banLog, f2bParse}} {
|
||||
}{{"traefik", c.TraefikLog, traefikParse}, {"ssh", c.AuthLog, authParse}, {"fail2ban", c.Fail2banLog, f2bParse}, {"probe", c.ProbeLog, newProbeParser().parse}} {
|
||||
if d.path != "" {
|
||||
r.Sources = append(r.Sources, &source{name: d.name, path: d.path, parse: d.parse})
|
||||
}
|
||||
|
||||
@@ -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.0"
|
||||
var Version = "1.4.1"
|
||||
@@ -132,6 +132,8 @@ type Event struct {
|
||||
User string
|
||||
Jail string
|
||||
Status int
|
||||
// Port is the destination port probed (Source "probe"); Proto holds tcp/udp.
|
||||
Port uint16
|
||||
// Unban marks a fail2ban unban (Cat is Ban). Restore marks a ban replayed
|
||||
// by fail2ban after a restart: it updates the ban state but is not scored.
|
||||
Unban bool
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package core
|
||||
|
||||
// PortService is the well-known service of a probed port ("" when unknown).
|
||||
func PortService(proto string, port uint16) string {
|
||||
if proto == "udp" {
|
||||
return udpServices[port]
|
||||
}
|
||||
return tcpServices[port]
|
||||
}
|
||||
|
||||
var tcpServices = map[uint16]string{
|
||||
21: "ftp", 22: "ssh", 23: "telnet", 25: "smtp", 53: "dns", 80: "http", 110: "pop3", 111: "rpcbind", 135: "msrpc",
|
||||
139: "netbios", 143: "imap", 389: "ldap", 443: "https", 445: "smb", 465: "smtps", 587: "submission", 993: "imaps",
|
||||
995: "pop3s", 1433: "mssql", 1521: "oracle", 1723: "pptp", 2049: "nfs", 2375: "docker", 3306: "mysql", 3389: "rdp",
|
||||
5432: "postgres", 5900: "vnc", 5901: "vnc", 6379: "redis", 8080: "http-alt", 8443: "https-alt", 9200: "elasticsearch",
|
||||
11211: "memcached", 27017: "mongodb", 2323: "telnet",
|
||||
}
|
||||
|
||||
var udpServices = map[uint16]string{
|
||||
53: "dns", 69: "tftp", 123: "ntp", 161: "snmp", 389: "cldap", 500: "ike", 1900: "ssdp", 5060: "sip", 11211: "memcached",
|
||||
}
|
||||
@@ -34,6 +34,13 @@ var ErrNotEgress = errors.New("not an egress line")
|
||||
// of the "Nov 14 22:01:02" rsyslog format (and as the time of a line whose
|
||||
// timestamp is unreadable).
|
||||
func ParseLine(b []byte, now time.Time) (Event, error) {
|
||||
return ParseKernel(b, marker, now)
|
||||
}
|
||||
|
||||
// ParseKernel parses an nftables log line carrying the given prefix marker
|
||||
// (for instance "URUTAU-EGRESS:" or "URUTAU-PROBE:"). It is shared by every
|
||||
// source that reads kernel log lines.
|
||||
func ParseKernel(b []byte, marker string, now time.Time) (Event, error) {
|
||||
line := string(b)
|
||||
i := strings.Index(line, marker)
|
||||
if i < 0 {
|
||||
|
||||
@@ -95,6 +95,7 @@ type aevt struct {
|
||||
type ipState struct {
|
||||
ev []aevt
|
||||
ssh []int64
|
||||
probes map[uint32]int64 // proto<<16|port -> last seen (unix)
|
||||
legit int64
|
||||
uas []string
|
||||
lastAttack int64
|
||||
@@ -384,6 +385,9 @@ func (e *Engine) process(ev core.Event, fam string) {
|
||||
}
|
||||
return
|
||||
case ev.Cat == core.SSHFail:
|
||||
case ev.Source == "probe" && ev.Cat == core.Scanner:
|
||||
e.processProbe(a, ev, now)
|
||||
return
|
||||
case CountsAsAttack(ev):
|
||||
default:
|
||||
return
|
||||
@@ -721,3 +725,32 @@ func (e *Engine) saveState() {
|
||||
e.dirty = true
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
// processProbe counts the distinct ports a network probe touched in Window; a
|
||||
// scan of PortScanPorts or more is a ban. Probes never count as web attacks.
|
||||
func (e *Engine) processProbe(a netip.Addr, ev core.Event, now time.Time) {
|
||||
ts := ev.Time.Unix()
|
||||
cut := now.Add(-Window).Unix()
|
||||
if ts < cut || ev.Port == 0 {
|
||||
return
|
||||
}
|
||||
st := e.stateOf(a)
|
||||
st.lastAttack = max(st.lastAttack, ts)
|
||||
if st.probes == nil {
|
||||
st.probes = map[uint32]int64{}
|
||||
}
|
||||
var proto uint32
|
||||
if ev.Proto == "udp" {
|
||||
proto = 1
|
||||
}
|
||||
k := proto<<16 | uint32(ev.Port)
|
||||
st.probes[k] = max(st.probes[k], ts)
|
||||
for key, t := range st.probes {
|
||||
if t < cut {
|
||||
delete(st.probes, key)
|
||||
}
|
||||
}
|
||||
in := Input{Now: now, Probes: len(st.probes), Exclude: e.excl.Excluded(a)}
|
||||
e.fill(a, st, &in, now)
|
||||
e.apply(a, st, Decide(in, Params{Threshold: e.cfg.Threshold}), "local", now)
|
||||
}
|
||||
@@ -33,12 +33,14 @@ const (
|
||||
ReasonWebshell = "webshell"
|
||||
ReasonSQLi = "sqli"
|
||||
ReasonLog4Shell = "log4shell"
|
||||
ReasonPortScan = "port-scan"
|
||||
)
|
||||
|
||||
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,
|
||||
}
|
||||
|
||||
// ValidReason reports whether s is one of the fixed slugs.
|
||||
@@ -60,6 +62,8 @@ const (
|
||||
Window = 10 * time.Minute
|
||||
LegitWindow = 24 * time.Hour
|
||||
SSHThreshold = 5
|
||||
// PortScanPorts distinct ports probed in Window justify a ban.
|
||||
PortScanPorts = 10
|
||||
// CritHits is how many critical events of one address (in Window) justify a ban.
|
||||
CritHits = 2
|
||||
)
|
||||
@@ -104,6 +108,7 @@ type Input struct {
|
||||
Attacks int // counted attack events in the window
|
||||
Top string // reason slug of the dominant attack in the window
|
||||
SSHFails int // failed SSH logins in the window
|
||||
Probes int // distinct (proto, port) probed in the window
|
||||
Crit string // reason of a critical family hit just seen, "" if none
|
||||
Crits int // critical events of the address in the window (a single hit is not enough)
|
||||
Legit bool // a document 2xx from a browser within the last 24 h
|
||||
@@ -141,6 +146,8 @@ func Decide(in Input, p Params) Decision {
|
||||
reason, score = in.Crit, 90
|
||||
case in.SSHFails >= sshTh:
|
||||
reason, score = ReasonSSHBrute, min(100, 60+(in.SSHFails-sshTh)*5)
|
||||
case in.Probes >= PortScanPorts:
|
||||
reason, score = ReasonPortScan, min(100, 60+(in.Probes-PortScanPorts)*3)
|
||||
case in.Attacks >= th:
|
||||
reason, score = in.Top, min(100, 55+(in.Attacks-th)*5)
|
||||
if !ValidReason(reason) {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
func probe(ip string, at time.Time, port uint16) core.Event {
|
||||
return core.Event{Time: at, IP: ip, Cat: core.Scanner, Source: "probe", Proto: "tcp", Port: port}
|
||||
}
|
||||
|
||||
func TestPortScanBan(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
for i := 0; i < 9; i++ {
|
||||
r.e.process(probe("203.0.114.60", r.now.Add(-time.Duration(i)*time.Second), uint16(1000+i)), "")
|
||||
}
|
||||
// the same port again does not add up
|
||||
r.e.process(probe("203.0.114.60", r.now, 1000), "")
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("banned below 10 distinct ports")
|
||||
}
|
||||
r.e.process(probe("203.0.114.60", r.now, 3389), "")
|
||||
if l := r.lines(t); len(l) != 1 || !strings.Contains(l[0], "reason=port-scan") {
|
||||
t.Fatalf("%q", l)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPortScanExcludedAndOld(t *testing.T) {
|
||||
r := newRig(t, ModeOn, nil)
|
||||
for i := 0; i < 12; i++ { // trusted network
|
||||
r.e.process(probe("45.1.1.1", r.now, uint16(2000+i)), "")
|
||||
}
|
||||
for i := 0; i < 12; i++ { // outside the window
|
||||
r.e.process(probe("203.0.114.61", r.now.Add(-time.Hour), uint16(2000+i)), "")
|
||||
}
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("excluded or old probes banned")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPortScanReasonValid(t *testing.T) {
|
||||
if !ValidReason(ReasonPortScan) {
|
||||
t.Fatal("port-scan reason not valid")
|
||||
}
|
||||
}
|
||||
@@ -75,6 +75,8 @@ type Rec struct {
|
||||
Bytes int64 `json:"bytes"`
|
||||
DurMS int64 `json:"dur_ms"`
|
||||
Flags string `json:"flags"`
|
||||
Port int `json:"port,omitempty"`
|
||||
Proto string `json:"proto,omitempty"`
|
||||
}
|
||||
|
||||
// Item is a parsed line with its raw JSON.
|
||||
|
||||
@@ -28,6 +28,7 @@ const (
|
||||
FamIoTCGI = "iot-cgi"
|
||||
FamAdminPanel = "admin-panel"
|
||||
FamGeneric404 = "generic-404"
|
||||
FamPortScan = "port-scan"
|
||||
maxPathScan = 8192
|
||||
maxPathScanTop = maxPathScan / 2
|
||||
)
|
||||
|
||||
@@ -102,6 +102,9 @@ func Techniques(cat, fam string, ctx TechCtx) []string {
|
||||
switch core.Category(cat) {
|
||||
case core.Scanner:
|
||||
switch {
|
||||
case fam == FamPortScan:
|
||||
set["T1595.001"] = true
|
||||
set["T1046"] = true
|
||||
case hasTool(tool, vulnTools):
|
||||
set["T1595.002"] = true
|
||||
case hasTool(tool, wordTools):
|
||||
|
||||
@@ -18,7 +18,14 @@ func init() {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, store.CampaignsOf(p))
|
||||
out := store.CampaignsOf(p)
|
||||
page, per := pageParams(r.URL.Query())
|
||||
from, to := window(len(out.Campaigns), page, per)
|
||||
out.Campaigns = out.Campaigns[from:to]
|
||||
writeJSON(w, 200, struct {
|
||||
store.CampaignsOut
|
||||
pageMeta
|
||||
}{out, metaOf(out.Total, page, per)})
|
||||
}
|
||||
})
|
||||
registerUserRoute("GET /api/v1/campaigns/{id}", func(s *Server) http.HandlerFunc {
|
||||
|
||||
@@ -2,9 +2,13 @@ package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/intel"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
@@ -30,7 +34,58 @@ func init() {
|
||||
counts = &c
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, store.FunnelOf(p, counts))
|
||||
writeJSON(w, 200, pagedFunnel(store.FunnelOf(p, counts), r.URL.Query()))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// funnelPage is the funnel with its session list cut to one page; hosts and
|
||||
// fams list every value of the (unfiltered) study for the filter menus.
|
||||
type funnelPage struct {
|
||||
store.FunnelOut
|
||||
Hosts []string `json:"hosts"`
|
||||
Fams []string `json:"fams"`
|
||||
pageTotal
|
||||
}
|
||||
|
||||
// pagedFunnel filters (stage, host, fam) and paginates the session list after
|
||||
// the peers were merged; the funnel counts always cover the whole study.
|
||||
func pagedFunnel(f store.FunnelOut, q url.Values) funnelPage {
|
||||
hosts, fams := map[string]bool{}, map[string]bool{}
|
||||
for _, x := range f.Sessions {
|
||||
for _, h := range x.Hosts {
|
||||
hosts[h] = true
|
||||
}
|
||||
for k := range x.Fams {
|
||||
fams[k] = true
|
||||
}
|
||||
}
|
||||
stage, host, fam := q.Get("stage"), q.Get("host_f"), q.Get("fam")
|
||||
list := make([]intel.Session, 0, len(f.Sessions))
|
||||
for _, x := range f.Sessions {
|
||||
st := x.Stage
|
||||
if st == "" {
|
||||
st = "recon"
|
||||
}
|
||||
if (stage != "" && st != stage) || (fam != "" && x.Fams[fam] == 0) {
|
||||
continue
|
||||
}
|
||||
if host != "" && !slices.Contains(x.Hosts, host) {
|
||||
continue
|
||||
}
|
||||
list = append(list, x)
|
||||
}
|
||||
page, per := pageParams(q)
|
||||
from, to := window(len(list), page, per)
|
||||
f.Sessions = list[from:to]
|
||||
return funnelPage{f, sortedKeys(hosts), sortedKeys(fams), pageTotal{metaOf(len(list), page, per), len(list)}}
|
||||
}
|
||||
|
||||
func sortedKeys(m map[string]bool) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
@@ -109,6 +109,10 @@ func (s *Server) eventsPage(w http.ResponseWriter, r *http.Request, desc bool) {
|
||||
badRequest(w, "invalid cursor")
|
||||
return
|
||||
}
|
||||
if q.Get("page") != "" {
|
||||
s.eventsNumbered(w, q, eq)
|
||||
return
|
||||
}
|
||||
page, err := s.opt.Store.QueryEvents(eq)
|
||||
if errors.Is(err, evlog.ErrBusy) {
|
||||
w.Header().Set("Retry-After", "5")
|
||||
@@ -122,6 +126,60 @@ func (s *Server) eventsPage(w http.ResponseWriter, r *http.Request, desc bool) {
|
||||
writeJSON(w, 200, page)
|
||||
}
|
||||
|
||||
// eventsNumbered answers /api/v1/events?page=N&per_page=M: the Nth page of the
|
||||
// same ordered log. The log is cursor-addressed, so the first (N-1)*M rows are
|
||||
// walked to find the cursor (at most evlog.MaxLimit of them: deeper pages are
|
||||
// empty and the client narrows the filter). total is the log's estimate.
|
||||
func (s *Server) eventsNumbered(w http.ResponseWriter, q url.Values, eq store.EventsQuery) {
|
||||
page, per := pageParams(q)
|
||||
eq.Cursor = ""
|
||||
skip := (page - 1) * per
|
||||
fail := func(err error) {
|
||||
if errors.Is(err, evlog.ErrBusy) {
|
||||
w.Header().Set("Retry-After", "5")
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "busy"})
|
||||
return
|
||||
}
|
||||
badRequest(w, "invalid cursor")
|
||||
}
|
||||
var out store.EventsPage
|
||||
if skip <= evlog.MaxLimit {
|
||||
cur := ""
|
||||
if skip > 0 {
|
||||
eq.Limit = skip
|
||||
head, err := s.opt.Store.QueryEvents(eq)
|
||||
if err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
out.TotalEstimate = head.TotalEstimate
|
||||
out.Enabled = head.Enabled
|
||||
if len(head.Events) >= skip && head.Next != "" {
|
||||
cur = head.Next
|
||||
}
|
||||
}
|
||||
if skip == 0 || cur != "" {
|
||||
eq.Limit, eq.Cursor = per, cur
|
||||
var err error
|
||||
if out, err = s.opt.Store.QueryEvents(eq); err != nil {
|
||||
fail(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.Events == nil {
|
||||
out.Events = []json.RawMessage{}
|
||||
}
|
||||
total := int(max(out.TotalEstimate, 0))
|
||||
if !out.Truncated && total < skip+len(out.Events) {
|
||||
total = skip + len(out.Events)
|
||||
}
|
||||
writeJSON(w, 200, struct {
|
||||
store.EventsPage
|
||||
pageTotal
|
||||
}{out, pageTotal{metaOf(total, page, per), total}})
|
||||
}
|
||||
|
||||
// sessionsAPI: GET /api/v1/events/sessions?from&to&host&gap=900
|
||||
func (s *Server) sessionsAPI(w http.ResponseWriter, r *http.Request) {
|
||||
eq, ok := s.eventFilter(w, r, 24*time.Hour)
|
||||
@@ -138,7 +196,25 @@ func (s *Server) sessionsAPI(w http.ResponseWriter, r *http.Request) {
|
||||
gap = n
|
||||
}
|
||||
list, trunc := s.opt.Store.Sessions(eq.From, eq.To, eq.Host, eq.IP, gap)
|
||||
writeJSON(w, 200, map[string]any{"sessions": list, "gap": gap, "truncated": trunc, "enabled": s.opt.Store.EventLog() != nil})
|
||||
sort.SliceStable(list, func(i, j int) bool {
|
||||
a, b := list[i], list[j]
|
||||
if a.Start != b.Start {
|
||||
return a.Start < b.Start
|
||||
}
|
||||
if a.IP != b.IP {
|
||||
return a.IP < b.IP
|
||||
}
|
||||
return a.End < b.End
|
||||
})
|
||||
page, per := pageParams(r.URL.Query())
|
||||
from, to := window(len(list), page, per)
|
||||
writeJSON(w, 200, struct {
|
||||
Sessions []store.Session `json:"sessions"`
|
||||
Gap int64 `json:"gap"`
|
||||
Truncated bool `json:"truncated"`
|
||||
Enabled bool `json:"enabled"`
|
||||
pageTotal
|
||||
}{list[from:to], gap, trunc, s.opt.Store.EventLog() != nil, pageTotal{metaOf(len(list), page, per), len(list)}})
|
||||
}
|
||||
|
||||
// studyHosts resolves the host selection of period and metrics: whether the
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Backend pagination shared by the list endpoints: `page` (1-based) and
|
||||
// `per_page` (default 25, at most 100). Out-of-range values are clamped and a
|
||||
// page past the end is an empty slice with the true total.
|
||||
const (
|
||||
defaultPerPage = 25
|
||||
maxPerPage = 100
|
||||
maxPageNo = 100000
|
||||
)
|
||||
|
||||
// pageParams reads page and per_page ("per" is the older spelling the IP list
|
||||
// used). Missing, zero or negative values fall back to page 1 / 25 per page.
|
||||
func pageParams(q url.Values) (page, per int) {
|
||||
page, _ = strconv.Atoi(q.Get("page"))
|
||||
page = min(max(page, 1), maxPageNo)
|
||||
v := q.Get("per_page")
|
||||
if v == "" {
|
||||
v = q.Get("per")
|
||||
}
|
||||
per, _ = strconv.Atoi(v)
|
||||
if per < 1 {
|
||||
per = defaultPerPage
|
||||
}
|
||||
return page, min(per, maxPerPage)
|
||||
}
|
||||
|
||||
// pageMeta is the metadata block every paginated response carries.
|
||||
type pageMeta struct {
|
||||
Page int `json:"page"`
|
||||
PerPage int `json:"per_page"`
|
||||
Pages int `json:"pages"`
|
||||
}
|
||||
|
||||
// pageTotal adds the exact (or, for the event log, estimated) item count.
|
||||
type pageTotal struct {
|
||||
pageMeta
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
func metaOf(total, page, per int) pageMeta {
|
||||
return pageMeta{Page: page, PerPage: per, Pages: max(1, (total+per-1)/per)}
|
||||
}
|
||||
|
||||
// window returns the bounds of the page inside a list of n items.
|
||||
func window(n, page, per int) (from, to int) {
|
||||
from = min((page-1)*per, n)
|
||||
return from, min(from+per, n)
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"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/intel"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func TestPageParamsLimits(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
q string
|
||||
page, per int
|
||||
}{
|
||||
{"", 1, 25}, {"page=0", 1, 25}, {"page=-4&per_page=-1", 1, 25}, {"page=x&per_page=y", 1, 25},
|
||||
{"page=3&per_page=500", 3, 100}, {"per=40", 1, 40}, {"per_page=10&per=40", 1, 10}, {"page=999999999", maxPageNo, 25},
|
||||
} {
|
||||
v, _ := url.ParseQuery(c.q)
|
||||
if p, n := pageParams(v); p != c.page || n != c.per {
|
||||
t.Errorf("%q: got %d/%d want %d/%d", c.q, p, n, c.page, c.per)
|
||||
}
|
||||
}
|
||||
if m := metaOf(0, 1, 25); m.Pages != 1 {
|
||||
t.Errorf("empty list has one page: %+v", m)
|
||||
}
|
||||
if m := metaOf(51, 1, 25); m.Pages != 3 {
|
||||
t.Errorf("pages: %+v", m)
|
||||
}
|
||||
if f, to := window(10, 9, 25); f != 10 || to != 10 {
|
||||
t.Errorf("past the end: %d %d", f, to)
|
||||
}
|
||||
}
|
||||
|
||||
// the funnel list is filtered and cut after the (federated) merge: totals and
|
||||
// pages describe the merged list, and the order is the same on every call.
|
||||
func TestPagedFunnelMerged(t *testing.T) {
|
||||
base := time.Unix(1_800_000_000, 0).UTC()
|
||||
mk := func(host string, n int) []intel.Session {
|
||||
var out []intel.Session
|
||||
for i := 0; i < n; i++ {
|
||||
out = append(out, intel.Session{IP: fmt.Sprintf("10.%s.0.%d", host, i), Start: base, End: base.Add(time.Minute), Stage: "probe", Hosts: []string{host}, Fams: map[string]int{"wp": 1}})
|
||||
}
|
||||
return out
|
||||
}
|
||||
merged := store.MergePeriods([]store.PeriodOut{{Sessions: mk("1", 30)}, {Sessions: mk("2", 30)}})
|
||||
f := store.FunnelOf(merged, nil)
|
||||
q := func(s string) url.Values { v, _ := url.ParseQuery(s); return v }
|
||||
p1 := pagedFunnel(f, q("page=1&per_page=25"))
|
||||
if p1.Total != 60 || p1.Pages != 3 || len(p1.Sessions) != 25 || len(p1.Hosts) != 2 {
|
||||
t.Fatalf("page1: total=%d pages=%d n=%d hosts=%v", p1.Total, p1.Pages, len(p1.Sessions), p1.Hosts)
|
||||
}
|
||||
p3 := pagedFunnel(f, q("page=3&per_page=25"))
|
||||
if len(p3.Sessions) != 10 {
|
||||
t.Fatalf("page3: %d", len(p3.Sessions))
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, p := range []funnelPage{p1, pagedFunnel(f, q("page=2&per_page=25")), p3} {
|
||||
for _, s := range p.Sessions {
|
||||
if seen[s.IP] {
|
||||
t.Fatalf("%s appears on two pages", s.IP)
|
||||
}
|
||||
seen[s.IP] = true
|
||||
}
|
||||
}
|
||||
if len(seen) != 60 {
|
||||
t.Fatalf("pages cover %d of 60", len(seen))
|
||||
}
|
||||
if again := pagedFunnel(f, q("page=1&per_page=25")); again.Sessions[0].IP != p1.Sessions[0].IP || again.Sessions[24].IP != p1.Sessions[24].IP {
|
||||
t.Fatal("order must be stable")
|
||||
}
|
||||
if far := pagedFunnel(f, q("page=50")); len(far.Sessions) != 0 || far.Total != 60 {
|
||||
t.Fatalf("beyond the end: %d items, total %d", len(far.Sessions), far.Total)
|
||||
}
|
||||
if h := pagedFunnel(f, q("host_f=2")); h.Total != 30 || h.Pages != 2 {
|
||||
t.Fatalf("host filter: %d/%d", h.Total, h.Pages)
|
||||
}
|
||||
if h := pagedFunnel(f, q("stage=exploit")); h.Total != 0 || h.Pages != 1 {
|
||||
t.Fatalf("stage filter: %d/%d", h.Total, h.Pages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaginatedEndpoints(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
|
||||
l, _ := evlog.Open(evlog.Options{Dir: filepath.Join(t.TempDir(), "events")})
|
||||
st.SetEventLog(l)
|
||||
now := time.Now()
|
||||
for i := 0; i < 60; i++ {
|
||||
st.Ingest(core.Event{Time: now.Add(-time.Hour), IP: fmt.Sprintf("20.0.%d.%d", i/250, i%250+1), Cat: core.Scanner, Source: "traefik", Method: "GET", Path: "/a", Status: 404, UA: "x"})
|
||||
}
|
||||
var h http.Handler = New(Options{Token: userTok, Version: "t", Store: st})
|
||||
auth := map[string]string{"Authorization": "Bearer " + userTok}
|
||||
|
||||
m := getJSON(t, h, "/api/v1/ips?range=24h", auth)
|
||||
if m["total"].(float64) != 60 || m["per_page"].(float64) != 25 || m["pages"].(float64) != 3 || len(m["items"].([]any)) != 25 {
|
||||
t.Fatalf("ips defaults: %v %v %v", m["total"], m["per_page"], m["pages"])
|
||||
}
|
||||
if m = getJSON(t, h, "/api/v1/ips?range=24h&per_page=1000&page=-2", auth); m["per_page"].(float64) != 100 || m["page"].(float64) != 1 || len(m["items"].([]any)) != 60 {
|
||||
t.Fatalf("ips clamp: %v %v", m["per_page"], m["page"])
|
||||
}
|
||||
if m = getJSON(t, h, "/api/v1/ips?range=24h&page=9", auth); len(m["items"].([]any)) != 0 || m["total"].(float64) != 60 {
|
||||
t.Fatalf("ips beyond the end: %v", m)
|
||||
}
|
||||
a := getJSON(t, h, "/api/v1/ips?range=24h&page=2&sort=score", auth)["items"].([]any)
|
||||
b := getJSON(t, h, "/api/v1/ips?range=24h&page=2&sort=score", auth)["items"].([]any)
|
||||
for i := range a {
|
||||
if a[i].(map[string]any)["ip"] != b[i].(map[string]any)["ip"] {
|
||||
t.Fatal("ips order unstable")
|
||||
}
|
||||
}
|
||||
|
||||
e := getJSON(t, h, "/api/v1/events?range=24h&page=2&per_page=25", auth)
|
||||
if len(e["events"].([]any)) != 25 || e["page"].(float64) != 2 || e["total"].(float64) < 60 {
|
||||
t.Fatalf("events page 2: n=%d page=%v total=%v", len(e["events"].([]any)), e["page"], e["total"])
|
||||
}
|
||||
if e = getJSON(t, h, "/api/v1/events?range=24h&page=3&per_page=25", auth); len(e["events"].([]any)) != 10 {
|
||||
t.Fatalf("events last page: %d", len(e["events"].([]any)))
|
||||
}
|
||||
if e = getJSON(t, h, "/api/v1/events?range=24h&page=40&per_page=25", auth); len(e["events"].([]any)) != 0 || e["total"].(float64) < 60 {
|
||||
t.Fatalf("events beyond the end: %v", e)
|
||||
}
|
||||
s := getJSON(t, h, "/api/v1/events/sessions?range=24h&per_page=10", auth)
|
||||
if len(s["sessions"].([]any)) != 10 || s["total"].(float64) != 60 || s["pages"].(float64) != 6 {
|
||||
t.Fatalf("event sessions: %v %v", s["total"], s["pages"])
|
||||
}
|
||||
f := getJSON(t, h, "/api/v1/sessions/funnel?range=24h&per_page=10&page=2", auth)
|
||||
if len(f["sessions"].([]any)) != 10 || f["page"].(float64) != 2 || f["total"].(float64) < 60 {
|
||||
t.Fatalf("funnel page: %v", f["total"])
|
||||
}
|
||||
c := getJSON(t, h, "/api/v1/campaigns?range=24h&page=0&per_page=500", auth)
|
||||
if c["per_page"].(float64) != 100 || c["page"].(float64) != 1 || c["pages"] == nil {
|
||||
t.Fatalf("campaigns meta: %v", c)
|
||||
}
|
||||
}
|
||||
@@ -154,29 +154,28 @@ func svgDonut(items []chartItem, title string) string {
|
||||
return sb.String()
|
||||
}
|
||||
|
||||
// svgMotif is the faint decoration of the cover, built from the attack series.
|
||||
func svgMotif(vals []uint32) string {
|
||||
// svgMotif is the cover decoration: a stylised waveform of the urutau's call,
|
||||
// five whistled notes that descend in pitch and fade, the way the bird sings
|
||||
// at night. It does not depend on the data, so it never turns into a flat comb.
|
||||
func svgMotif(_ []uint32) string {
|
||||
var sb strings.Builder
|
||||
sb.WriteString(`<svg class="motif" viewBox="0 0 210 120" preserveAspectRatio="none" aria-hidden="true">`)
|
||||
for i := 1; i <= 7; i++ {
|
||||
fmt.Fprintf(&sb, `<line x1="0" y1="%d" x2="210" y2="%d" stroke="#45d6b0" stroke-opacity="0.12" stroke-width="0.25"/>`, i*15, i*15)
|
||||
fmt.Fprintf(&sb, `<line x1="0" y1="%d" x2="210" y2="%d" stroke="#45d6b0" stroke-opacity="0.10" stroke-width="0.25"/>`, i*15, i*15)
|
||||
}
|
||||
n := len(vals)
|
||||
if n > 1 {
|
||||
var mx uint32 = 1
|
||||
for _, v := range vals {
|
||||
if v > mx {
|
||||
mx = v
|
||||
}
|
||||
}
|
||||
step := 1
|
||||
if n > 120 {
|
||||
step = n / 120
|
||||
}
|
||||
for i := 0; i < n; i += step {
|
||||
x := 210 * float64(i) / float64(n-1)
|
||||
hgt := 4 + 38*float64(vals[i])/float64(mx)
|
||||
fmt.Fprintf(&sb, `<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="#f0b35b" stroke-opacity="0.55" stroke-width="0.7" stroke-linecap="round"/>`, x, 60-hgt/2, x, 60+hgt/2)
|
||||
type note struct{ x0, w, peak, y float64 }
|
||||
notes := []note{{14, 30, 46, 54}, {52, 28, 40, 57}, {88, 27, 34, 60}, {123, 25, 27, 63}, {156, 23, 20, 66}}
|
||||
for _, n := range notes {
|
||||
lines := int(n.w / 1.3)
|
||||
for k := 0; k <= lines; k++ {
|
||||
t := float64(k) / float64(lines)
|
||||
env := math.Pow(math.Sin(math.Pi*t), 1.6) * (0.78 + 0.22*math.Sin(23*t+n.x0))
|
||||
h := 1.2 + n.peak*env
|
||||
x := n.x0 + n.w*t
|
||||
// fade toward the page edges so the call sits behind the bird
|
||||
fade := 1 - math.Min(1, math.Abs(x-105)/115)
|
||||
fmt.Fprintf(&sb, `<line x1="%.1f" y1="%.1f" x2="%.1f" y2="%.1f" stroke="#f0b35b" stroke-opacity="%.2f" stroke-width="0.75" stroke-linecap="round"/>`,
|
||||
x, n.y-h/2, x, n.y+h/2, 0.18+0.5*fade)
|
||||
}
|
||||
}
|
||||
sb.WriteString(`</svg>`)
|
||||
|
||||
@@ -555,25 +555,8 @@ func (s *Server) ips(w http.ResponseWriter, r *http.Request) {
|
||||
case "score", "last", "first", "events", "ip":
|
||||
store.SortIPs(filtered, q.Get("sort"), q.Get("order") != "asc")
|
||||
}
|
||||
per, _ := strconv.Atoi(q.Get("per"))
|
||||
if per < 1 || per > 200 {
|
||||
per = 50
|
||||
}
|
||||
page, _ := strconv.Atoi(q.Get("page"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if page > 100000 {
|
||||
page = 100000
|
||||
}
|
||||
from := (page - 1) * per
|
||||
if from > len(filtered) {
|
||||
from = len(filtered)
|
||||
}
|
||||
to := from + per
|
||||
if to > len(filtered) {
|
||||
to = len(filtered)
|
||||
}
|
||||
page, per := pageParams(q)
|
||||
from, to := window(len(filtered), page, per)
|
||||
items := filtered[from:to]
|
||||
for i := range items {
|
||||
s.opt.Store.Enrich(&items[i])
|
||||
@@ -581,7 +564,7 @@ func (s *Server) ips(w http.ResponseWriter, r *http.Request) {
|
||||
items[i].RDNS = s.opt.Store.RDNSOf(items[i].IP)
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"range": rg.Info(s.opt.Now().Unix()), "total": len(filtered), "page": page, "per": per, "items": items})
|
||||
writeJSON(w, 200, map[string]any{"range": rg.Info(s.opt.Now().Unix()), "total": len(filtered), "page": page, "per": per, "per_page": per, "pages": metaOf(len(filtered), page, per).Pages, "items": items})
|
||||
}
|
||||
|
||||
func (s *Server) ipDetail(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
+85
-20
@@ -68,7 +68,7 @@
|
||||
* heatmap(matrix[row][col], xLabels[], yLabels[], {format, title}) cells use --seq-1..5
|
||||
* sparkline(values[]) gauge(value, max, thresholds[{at,tone:'ok|warn|danger|info'}], {label, format})
|
||||
* colors are CSS token names ("--viz-1"); the default palette is --viz-1..8 in order.
|
||||
* Urutau.ui = { panel, stat, metric, lead, empty, badge, bars, chart, sparkline } shared primitives
|
||||
* Urutau.ui = { panel, stat, metric, lead, empty, badge, bars, chart, sparkline, pager } shared primitives
|
||||
* (the same ones the core pages use; see their definitions below)
|
||||
*
|
||||
* Security rule of this file: log data is hostile. Dynamic text goes through
|
||||
@@ -644,10 +644,47 @@
|
||||
return function () { off(); clearTimeout(timer); timer = 0; };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- pager
|
||||
// pager({page, pages, total, onPage, hasNext, label}): numbered pages (first/prev/next/last, ellipses) when the
|
||||
// page count is known; with only hasNext (cursor lists) just previous/next and "page N". Returns null when
|
||||
// there is nothing to page through.
|
||||
function pager(o) {
|
||||
var page = Math.max(1, o.page || 1), known = typeof o.pages === 'number', pages = known ? Math.max(1, o.pages) : 0;
|
||||
if (known && pages <= 1) return null;
|
||||
if (!known && page <= 1 && !o.hasNext) return null;
|
||||
var nav = el('nav', { class: 'pgr', 'aria-label': o.label || t('pager.nav') });
|
||||
function go(n) { return function () { if (o.onPage) o.onPage(n); }; }
|
||||
function btn(txt, aria, n, off, cls) {
|
||||
var b = el('button', { type: 'button', class: 'btn pgr-b ' + (cls || ''), 'aria-label': aria, title: aria, disabled: off }, txt);
|
||||
if (!off) b.addEventListener('click', go(n));
|
||||
return b;
|
||||
}
|
||||
var atEnd = known ? page >= pages : !o.hasNext;
|
||||
var list = h('div', 'pgr-l');
|
||||
if (known) list.appendChild(btn('\u00ab', t('pager.first'), 1, page <= 1, 'pgr-edge'));
|
||||
list.appendChild(btn('\u2039', t('pager.prev'), page - 1, page <= 1));
|
||||
if (known) {
|
||||
var seq = [], last = 0;
|
||||
for (var i = 1; i <= pages; i++) if (i === 1 || i === pages || Math.abs(i - page) <= 1) seq.push(i);
|
||||
seq.forEach(function (n) {
|
||||
if (last && n - last > 1) list.appendChild(h('span', 'pgr-gap', n - last === 2 ? String(last + 1) : '\u2026'));
|
||||
var b = el('button', { type: 'button', class: 'btn pgr-b pgr-n' + (n === page ? ' on' : ''), 'aria-label': t('pager.goto', { n: nf(n) }) }, nf(n));
|
||||
if (n === page) b.setAttribute('aria-current', 'page'); else b.addEventListener('click', go(n));
|
||||
list.appendChild(b); last = n;
|
||||
});
|
||||
}
|
||||
list.appendChild(btn('\u203a', t('pager.next'), page + 1, atEnd));
|
||||
if (known) list.appendChild(btn('\u00bb', t('pager.last'), pages, atEnd, 'pgr-edge'));
|
||||
var info = known ? t('pager.page', { n: nf(page), m: nf(pages) }) + (o.total !== undefined && o.total !== null ? ' \u00b7 ' + (o.totalText || nf(o.total)) : '') : t('pager.pageN', { n: nf(page) });
|
||||
nav.appendChild(h('span', 'pgr-i', info));
|
||||
nav.appendChild(list);
|
||||
return nav;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- IP table
|
||||
function sumCounts(c) { var s = 0; for (var k in c) s += c[k]; return s; }
|
||||
function ipTable(full) {
|
||||
var st = { sort: 'score', order: 'desc', page: 1, per: window.innerWidth < 768 ? 25 : (full ? 50 : 25), q: '', level: '', banned: false, total: 0, sig: '', ctxKey: '', multi: false, headSig: '' };
|
||||
var st = { sort: 'score', order: 'desc', page: 1, per: 25, q: '', level: '', banned: false, total: 0, sig: '', ctxKey: '', multi: false, headSig: '' };
|
||||
var timer = 0, alive = true, onTotal = null;
|
||||
var search = el('input', { type: 'search', autocomplete: 'off', placeholder: t('ips.search'), 'aria-label': t('ips.search') });
|
||||
var levelSel = el('select', { 'aria-label': t('ips.level') });
|
||||
@@ -657,15 +694,14 @@
|
||||
var perSel = null;
|
||||
if (full) {
|
||||
perSel = el('select', { 'aria-label': t('ips.perPage') });
|
||||
[25, 50, 100, 200].forEach(function (n) { perSel.appendChild(el('option', { value: String(n) }, String(n))); });
|
||||
[25, 50, 100].forEach(function (n) { perSel.appendChild(el('option', { value: String(n) }, String(n))); });
|
||||
perSel.value = String(st.per);
|
||||
toolbar.appendChild(perSel);
|
||||
}
|
||||
var thead = h('thead'), tbody = h('tbody');
|
||||
var table = h('table', 'stack tbl-cards', thead, tbody);
|
||||
var count = h('span'), page = h('span'), prev = el('button', { type: 'button', class: 'btn' }, t('pager.prev')), next = el('button', { type: 'button', class: 'btn' }, t('pager.next'));
|
||||
var pager = h('div', 'pager', count, h('div', 'btns', page, prev, next));
|
||||
var node = h('div', null, toolbar, h('div', 'tbl-wrap', table), pager);
|
||||
var pagerBox = h('div', 'pgr-box');
|
||||
var node = h('div', null, toolbar, h('div', 'tbl-wrap', table), pagerBox);
|
||||
|
||||
function cols() {
|
||||
var c = [{ k: 'ip', s: 'ip' }, { k: 'score', s: 'score' }, { k: 'level' }, { k: 'cats' }, { k: 'origin' }];
|
||||
@@ -690,7 +726,7 @@
|
||||
var b = el('button', { type: 'button' }, colLabel(x.k));
|
||||
b.addEventListener('click', function () {
|
||||
if (st.sort === x.s) st.order = st.order === 'desc' ? 'asc' : 'desc'; else { st.sort = x.s; st.order = 'desc'; }
|
||||
st.page = 1; load();
|
||||
reset();
|
||||
});
|
||||
th.appendChild(b);
|
||||
} else th.textContent = colLabel(x.k);
|
||||
@@ -755,20 +791,30 @@
|
||||
tr.addEventListener('keydown', function (ev) { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); openIP(x.ip); } });
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
drawPager();
|
||||
}
|
||||
function drawPager() {
|
||||
clear(pagerBox);
|
||||
var pages = Math.max(1, Math.ceil(st.total / st.per));
|
||||
count.textContent = pl('pager.count', st.total, { n: nf(st.total) });
|
||||
page.textContent = full ? t('pager.page', { n: nf(st.page), m: nf(pages) }) : '';
|
||||
prev.disabled = st.page <= 1;
|
||||
next.disabled = st.page >= pages;
|
||||
var pg = pager({ page: st.page, pages: pages, total: st.total, totalText: pl('pager.count', st.total, { n: nf(st.total) }), onPage: goPage });
|
||||
if (pg) pagerBox.appendChild(pg); else pagerBox.appendChild(h('p', 'note', pl('pager.count', st.total, { n: nf(st.total) })));
|
||||
}
|
||||
// the full page keeps its page number in the URL (&p=3); the overview widget keeps it locally
|
||||
function goPage(n) {
|
||||
st.page = n;
|
||||
if (full) setParam('p', n);
|
||||
load();
|
||||
}
|
||||
function load() {
|
||||
var c = ctx(), key = ctxKey(c);
|
||||
if (key !== st.ctxKey) { st.ctxKey = key; st.page = 1; }
|
||||
if (key !== st.ctxKey) { st.ctxKey = key; if (!full) st.page = 1; }
|
||||
if (full) st.page = pageParam();
|
||||
buildHead();
|
||||
var params = qs({ sort: st.sort, order: st.order, page: st.page, per: st.per, q: st.q, level: st.level, banned: st.banned ? '1' : '0' });
|
||||
var params = qs({ sort: st.sort, order: st.order, page: st.page, per_page: st.per, q: st.q, level: st.level, banned: st.banned ? '1' : '0' });
|
||||
return api('/api/v1/ips', params).then(function (r) {
|
||||
if (!alive) return;
|
||||
st.total = r.total;
|
||||
if (st.page > 1 && !r.items.length && r.total) { goPage(Math.max(1, r.pages || 1)); return; } // the list shrank under the page
|
||||
if (onTotal) onTotal(r.total);
|
||||
var sig = JSON.stringify([lang, st.multi, st.page, st.per, r.items.map(function (x) { return [x.ip, x.score, x.last, x.banned, x.level]; })]);
|
||||
if (sig === st.sig) return;
|
||||
@@ -776,18 +822,18 @@
|
||||
renderRows(r.items);
|
||||
}).catch(function () { /* banner already shown by api() */ });
|
||||
}
|
||||
function reset() { st.page = 1; return load(); }
|
||||
function reset() { st.page = 1; if (full) setParam('p', 1); return load(); }
|
||||
function onHash() { if (full && alive && pageParam() !== st.page) load(); }
|
||||
window.addEventListener('hashchange', onHash); // back/forward between pages (route() runs first)
|
||||
search.addEventListener('input', function () { clearTimeout(timer); timer = setTimeout(function () { st.q = search.value.trim(); reset(); }, 300); });
|
||||
levelSel.addEventListener('change', function () { st.level = levelSel.value; reset(); });
|
||||
bannedChk.addEventListener('change', function () { st.banned = bannedChk.checked; reset(); });
|
||||
if (perSel) perSel.addEventListener('change', function () { st.per = parseInt(perSel.value, 10) || 50; reset(); });
|
||||
prev.addEventListener('click', function () { if (st.page > 1) { st.page--; load(); } });
|
||||
next.addEventListener('click', function () { st.page++; load(); });
|
||||
return {
|
||||
node: node, load: load, reset: reset,
|
||||
setMulti: function (b) { if (st.multi !== b) { st.multi = b; st.sig = ''; } },
|
||||
onTotal: function (cb) { onTotal = cb; },
|
||||
dispose: function () { alive = false; clearTimeout(timer); }
|
||||
dispose: function () { alive = false; clearTimeout(timer); window.removeEventListener('hashchange', onHash); }
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1689,7 +1735,8 @@
|
||||
function setShell(over) {
|
||||
var sl = { range: state.range, from: state.from, to: state.to, host: state.host };
|
||||
Object.keys(over).forEach(function (k) { sl[k] = over[k]; });
|
||||
var id = current ? current.id : 'overview', hash = buildHash(id, state.params.segments, state.params.query, sl);
|
||||
var q = Object.assign({}, state.params.query); delete q.p; // a new period or host starts at page 1
|
||||
var id = current ? current.id : 'overview', hash = buildHash(id, state.params.segments, q, sl);
|
||||
if (hash !== location.hash) history.pushState(null, '', hash);
|
||||
route();
|
||||
}
|
||||
@@ -1850,6 +1897,23 @@
|
||||
if (b) b.setAttribute('aria-expanded', open ? 'true' : 'false');
|
||||
}
|
||||
|
||||
function mkParams(segments, extra) {
|
||||
return { segments: segments, path: segments, query: extra, get: function (n) { return Object.prototype.hasOwnProperty.call(extra, n) ? extra[n] : null; } };
|
||||
}
|
||||
// one query parameter of the current page (e.g. p, the page number); null when absent
|
||||
function param(name) { return state.params.get(name); }
|
||||
// set or drop one query parameter in the hash without re-routing: the caller reloads its own data.
|
||||
// p=1 is the default and never written, so the first page keeps a clean link.
|
||||
function setParam(name, val) {
|
||||
var q = Object.assign({}, state.params.query);
|
||||
if (val === '' || val === null || val === undefined || (name === 'p' && String(val) === '1')) delete q[name]; else q[name] = String(val);
|
||||
state.params = mkParams(state.params.segments, q);
|
||||
var hash = buildHash(current ? current.id : 'overview', state.params.segments, q);
|
||||
if (hash !== location.hash) history.pushState(null, '', hash);
|
||||
if (current) current.sig = pageSig();
|
||||
}
|
||||
// page number of the URL (>= 1)
|
||||
function pageParam() { var n = parseInt(param('p'), 10); return n >= 1 ? Math.min(n, 100000) : 1; }
|
||||
function pageSig() { var c = ctx(); return ctxKey(c) + '|' + JSON.stringify(state.params.segments) + '|' + JSON.stringify(state.params.query); }
|
||||
function route() {
|
||||
var u = parseHash(), id = u.page;
|
||||
@@ -1861,7 +1925,7 @@
|
||||
readSlice(u.query);
|
||||
var extra = {};
|
||||
u.query.forEach(function (v, k) { if (['r', 'range', 'from', 'to', 'host'].indexOf(k) < 0) extra[k] = v; });
|
||||
state.params = { segments: u.segments, path: u.segments, query: extra, get: function (n) { return Object.prototype.hasOwnProperty.call(extra, n) ? extra[n] : null; } };
|
||||
state.params = mkParams(u.segments, extra);
|
||||
var norm = buildHash(id, u.segments, extra);
|
||||
if (norm !== location.hash) history.replaceState(null, '', norm);
|
||||
setMore(false); closeRangePicker(false);
|
||||
@@ -1996,7 +2060,8 @@
|
||||
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,
|
||||
ui: { panel: panel, stat: stat, metric: metric, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart, sparkline: sparkline }
|
||||
param: param, setParam: setParam, pageParam: pageParam,
|
||||
ui: { panel: panel, stat: stat, metric: metric, lead: lead, empty: empty, badge: badge, bars: bars, chart: chart, sparkline: sparkline, pager: pager }
|
||||
};
|
||||
|
||||
// page scripts are listed in /pages.json ({"pages":[{"name":"geo","css":true}, ...]}); only files that exist
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
var NS = 'http://www.w3.org/2000/svg';
|
||||
var PER = 12;
|
||||
var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned'];
|
||||
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"><circle cx="12" cy="5" r="2.5"/><circle cx="5" cy="18" r="2.5"/><circle cx="19" cy="18" r="2.5"/><path d="M11 7.5L6 15.5M13 7.5l5 8M7.5 18h9"/></svg>';
|
||||
var ID_OK = /^[A-Za-z0-9_-]{1,64}$/;
|
||||
@@ -56,6 +57,8 @@
|
||||
'cp.stage.exploit': 'Exploit',
|
||||
'cp.stage.access': 'Access',
|
||||
'cp.stage.banned': 'Banned',
|
||||
'cp.n.one': '{n} campaign',
|
||||
'cp.n.other': '{n} campaigns',
|
||||
'cp.more': '+{n} more'
|
||||
},
|
||||
'pt-BR': {
|
||||
@@ -100,6 +103,8 @@
|
||||
'cp.stage.exploit': 'Exploração',
|
||||
'cp.stage.access': 'Acesso',
|
||||
'cp.stage.banned': 'Banido',
|
||||
'cp.n.one': '{n} campanha',
|
||||
'cp.n.other': '{n} campanhas',
|
||||
'cp.more': '+{n} mais'
|
||||
}
|
||||
});
|
||||
@@ -169,8 +174,10 @@
|
||||
function load() {
|
||||
var my = ++seq, cid = id(), path = cid ? '/api/v1/campaigns/' + encodeURIComponent(cid) : '/api/v1/campaigns';
|
||||
if (cid && !ID_OK.test(cid)) { data = { missing: true }; paint(); return; }
|
||||
U.api(path, Object.assign({ host: self.ctx.host }, U.rangeParams())).then(function (d) {
|
||||
if (!alive || my !== seq) return; data = d; key = cid; paint();
|
||||
U.api(path, Object.assign({ host: self.ctx.host }, cid ? {} : { page: U.pageParam(), per_page: PER }, U.rangeParams())).then(function (d) {
|
||||
if (!alive || my !== seq) return;
|
||||
if (!cid && d.page > 1 && !(d.campaigns || []).length && d.total) { U.setParam('p', d.pages); load(); return; }
|
||||
data = d; key = cid; paint();
|
||||
}).catch(function (e) {
|
||||
if (!alive || my !== seq) return;
|
||||
if (e && e.status === 404 && cid) { data = { missing: true }; key = cid; paint(); return; }
|
||||
@@ -191,7 +198,7 @@
|
||||
if (data.truncated) wrap.appendChild(h('p', { class: 'note', text: t('cp.truncated') }));
|
||||
if (!cs.length) return;
|
||||
var grid = h('div', 'cp-cards');
|
||||
cs.slice(0, 60).forEach(function (c) {
|
||||
cs.forEach(function (c) {
|
||||
var sg = c.signature || {};
|
||||
grid.appendChild(h('article', 'cp-card',
|
||||
h('header', null, h('a', { class: 'cp-id mono', href: '#/campaigns/' + encodeURIComponent(c.id), text: short(c.id) }),
|
||||
@@ -204,7 +211,8 @@
|
||||
h('footer', null, h('a', { class: 'btn', href: '#/campaigns/' + encodeURIComponent(c.id), text: t('cp.open') }),
|
||||
h('a', { class: 'btn', href: replayHref(c), text: t('cp.replay') }))));
|
||||
});
|
||||
wrap.appendChild(U.ui.panel({ title: t('cp.cards'), help: 'term.campaign' }, grid));
|
||||
wrap.appendChild(U.ui.panel({ title: t('cp.cards'), help: 'term.campaign' }, grid,
|
||||
U.ui.pager({ page: data.page, pages: data.pages, total: data.total, totalText: U.pl('cp.n', data.total, { n: nf(data.total) }), onPage: function (n) { U.setParam('p', n); load(); } })));
|
||||
var top = cs.slice(0, 15), mn = Infinity, mx = 0;
|
||||
top.forEach(function (c) { mn = Math.min(mn, sec(c.first)); mx = Math.max(mx, sec(c.last)); });
|
||||
wrap.appendChild(U.ui.panel({ title: t('cp.gantt'), hint: t('cp.gantt.hint') },
|
||||
|
||||
@@ -113,6 +113,7 @@
|
||||
'df.en.reason.webshell': 'Looking for or uploading a backdoor (webshell)',
|
||||
'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.error': 'Could not load the second firewall data.'
|
||||
},
|
||||
'pt-BR': {
|
||||
@@ -217,6 +218,7 @@
|
||||
'df.en.reason.webshell': 'Procura ou envio de porta dos fundos (webshell)',
|
||||
'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.error': 'Não foi possível carregar os dados do segundo firewall.'
|
||||
}
|
||||
});
|
||||
|
||||
@@ -187,8 +187,13 @@ window.URUTAU_I18N = {
|
||||
'col.lines': 'Lines',
|
||||
'col.malformed': 'Malformed',
|
||||
'col.lastEvent': 'Last event',
|
||||
'pager.prev': 'Previous',
|
||||
'pager.next': 'Next',
|
||||
'pager.nav': 'Pagination',
|
||||
'pager.first': 'First page',
|
||||
'pager.last': 'Last page',
|
||||
'pager.goto': 'Go to page {n}',
|
||||
'pager.pageN': 'Page {n}',
|
||||
'pager.prev': 'Previous page',
|
||||
'pager.next': 'Next page',
|
||||
'pager.count.one': '{n} IP',
|
||||
'pager.count.other': '{n} IPs',
|
||||
'pager.page': 'Page {n} of {m}',
|
||||
@@ -681,8 +686,13 @@ window.URUTAU_I18N = {
|
||||
'col.lines': 'Linhas',
|
||||
'col.malformed': 'Malformadas',
|
||||
'col.lastEvent': 'Último evento',
|
||||
'pager.prev': 'Anterior',
|
||||
'pager.next': 'Próxima',
|
||||
'pager.nav': 'Paginação',
|
||||
'pager.first': 'Primeira página',
|
||||
'pager.last': 'Última página',
|
||||
'pager.goto': 'Ir para a página {n}',
|
||||
'pager.pageN': 'Página {n}',
|
||||
'pager.prev': 'Página anterior',
|
||||
'pager.next': 'Próxima página',
|
||||
'pager.count.one': '{n} IP',
|
||||
'pager.count.other': '{n} IPs',
|
||||
'pager.page': 'Página {n} de {m}',
|
||||
|
||||
+14
-17
@@ -225,6 +225,7 @@
|
||||
'ip.fam.iot-cgi': 'IoT and CGI',
|
||||
'ip.fam.admin-panel': 'Admin panels',
|
||||
'ip.fam.generic-404': 'Generic probing',
|
||||
'ip.fam.port-scan': 'Network port scan',
|
||||
'ip.ses.title': 'Sessions',
|
||||
'ip.ses.hint': 'Bursts of activity separated by quiet gaps.',
|
||||
'ip.ses.empty': 'No session found in this period.',
|
||||
@@ -256,7 +257,6 @@
|
||||
'ip.ev.request': 'Request',
|
||||
'ip.ev.status': 'Status',
|
||||
'ip.ev.bytes': 'Bytes',
|
||||
'ip.ev.more': 'Load more',
|
||||
'ip.ev.loading': 'Loading events.',
|
||||
'ip.ev.empty': 'No raw events returned for this period.',
|
||||
'ip.ev.unavailable': 'Raw events are not available right now.',
|
||||
@@ -525,6 +525,7 @@
|
||||
'ip.fam.iot-cgi': 'IoT e CGI',
|
||||
'ip.fam.admin-panel': 'Painéis de administração',
|
||||
'ip.fam.generic-404': 'Sondagem genérica',
|
||||
'ip.fam.port-scan': 'Varredura de portas de rede',
|
||||
'ip.ses.title': 'Sessões',
|
||||
'ip.ses.hint': 'Rajadas de atividade separadas por intervalos quietos.',
|
||||
'ip.ses.empty': 'Nenhuma sessão encontrada neste período.',
|
||||
@@ -556,7 +557,6 @@
|
||||
'ip.ev.request': 'Requisição',
|
||||
'ip.ev.status': 'Status',
|
||||
'ip.ev.bytes': 'Bytes',
|
||||
'ip.ev.more': 'Carregar mais',
|
||||
'ip.ev.loading': 'Carregando eventos.',
|
||||
'ip.ev.empty': 'Nenhum evento bruto retornado para este período.',
|
||||
'ip.ev.unavailable': 'Os eventos brutos não estão disponíveis agora.',
|
||||
@@ -721,7 +721,7 @@
|
||||
var LEVELS = ['hostile', 'suspicious', 'low'];
|
||||
var LEVEL_TONE = { hostile: 'danger', suspicious: 'warn', low: 'info' };
|
||||
var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned'];
|
||||
var FAMS = ['traversal', 'log4shell', 'sqli', 'xss', 'rce-injection', 'webshell', 'env-credentials', 'vcs', 'backup', 'wordpress', 'phpmyadmin-db', 'actuator-debug', 'iot-cgi', 'admin-panel', 'generic-404'];
|
||||
var FAMS = ['traversal', 'log4shell', 'sqli', 'xss', 'rce-injection', 'webshell', 'env-credentials', 'vcs', 'backup', 'wordpress', 'phpmyadmin-db', 'actuator-debug', 'iot-cgi', 'admin-panel', 'generic-404', 'port-scan'];
|
||||
var SENSITIVE = ['traversal', 'webshell', 'env-credentials', 'vcs', 'backup', 'phpmyadmin-db', 'actuator-debug'];
|
||||
var NETTYPES = ['tor', 'vpn', 'research-scanner', 'isp-cn', 'hosting', 'mobile', 'isp/mobile', 'residential', 'unknown'];
|
||||
var NT_TONE = { tor: 'danger', vpn: 'warn', 'research-scanner': 'info', 'isp-cn': 'warn', hosting: 'warn', mobile: 'info', 'isp/mobile': 'info', residential: 'info', unknown: 'neutral' };
|
||||
@@ -1466,29 +1466,25 @@
|
||||
h('th', null, t('ip.ev.status')), h('th', null, t('ip.ev.bytes')))), tb);
|
||||
box.appendChild(h('div', 'ipx-tbl-w', table));
|
||||
var foot = h('div', 'ipx-ev-f', h('span', 'ipx-faint ipx-num', t('ip.ev.shown', { n: N(ev.rows.length) })));
|
||||
if (ev.cursor) {
|
||||
var more = h('button', 'ipx-btn sm', { type: 'button' }, t(ev.loading ? 'ip.ev.loading' : 'ip.ev.more'));
|
||||
if (ev.loading) more.disabled = true;
|
||||
more.addEventListener('click', function () { loadEvents(s, true); });
|
||||
foot.appendChild(more);
|
||||
}
|
||||
box.appendChild(foot);
|
||||
var pg = U.ui.pager({ page: ev.page, pages: ev.pages, total: ev.total, onPage: function (n) { U.setParam('p', n); ev.page = n; loadEvents(s); } });
|
||||
if (pg) box.appendChild(pg);
|
||||
}
|
||||
function loadEvents(s, more) {
|
||||
function loadEvents(s) {
|
||||
var ev = s.ev;
|
||||
if (ev.loading) return;
|
||||
ev.loading = true; ev.failed = false;
|
||||
var my = ++ev.seq;
|
||||
var p = rParams(s.ctx);
|
||||
var q = { ip: s.ip, limit: 25, order: 'desc' };
|
||||
var q = { ip: s.ip, per_page: 25, page: ev.page || 1, order: 'desc' };
|
||||
Object.keys(p).forEach(function (k) { q[k] = p[k]; });
|
||||
if (more && ev.cursor) q.cursor = ev.cursor;
|
||||
paintEvents(s);
|
||||
U.api('/api/v1/events', q).then(function (r) {
|
||||
if (!s.alive || my !== ev.seq) return;
|
||||
var rows = Array.isArray(r) ? r : arr(r && (r.events || r.items || r.rows)), cur = isObj(r) ? (r.next || r.next_cursor || r.cursor || '') : '';
|
||||
ev.rows = more ? ev.rows.concat(rows.filter(isObj)) : rows.filter(isObj);
|
||||
ev.cursor = rows.length ? str(cur) : '';
|
||||
var rows = Array.isArray(r) ? r : arr(r && (r.events || r.items || r.rows));
|
||||
if (isObj(r) && r.page > 1 && !rows.length && r.total) { ev.loading = false; ev.page = r.pages || 1; U.setParam('p', ev.page); loadEvents(s); return; } // stale link past the last page
|
||||
ev.rows = rows.filter(isObj);
|
||||
ev.total = isObj(r) ? num(r.total) : 0; ev.pages = isObj(r) && r.pages ? num(r.pages) : 1;
|
||||
if (isObj(r) && r.enabled === false) ev.disabled = true;
|
||||
if (s.statusPaint) s.statusPaint();
|
||||
ev.loaded = true; ev.loading = false;
|
||||
@@ -1845,7 +1841,7 @@
|
||||
var my = ++s.seq;
|
||||
s.ip = ipFromCtx(s.ctx);
|
||||
s.key = ctxKey(s.ctx);
|
||||
s.ev = { rows: [], cursor: '', loading: false, failed: false, loaded: false, disabled: !!(isObj(s.data && s.data.log) && s.data.log.available === false), seq: s.ev.seq + 1 };
|
||||
s.ev = { rows: [], page: U.pageParam(), pages: 1, total: 0, loading: false, failed: false, loaded: false, disabled: !!(isObj(s.data && s.data.log) && s.data.log.available === false), seq: s.ev.seq + 1 };
|
||||
if (!validIP(s.ip)) { showState(s, errorNode(s, 'ip.invalid', false)); return; }
|
||||
document.title = s.ip + ' · ' + t('ip.title') + ' · Urutau';
|
||||
if (!s.data) showState(s, loadingNode());
|
||||
@@ -1855,7 +1851,7 @@
|
||||
s.data = d;
|
||||
s.ev.disabled = !!(isObj(d.log) && d.log.available === false);
|
||||
render(s);
|
||||
if (!s.ev.disabled) loadEvents(s, false);
|
||||
if (!s.ev.disabled) loadEvents(s);
|
||||
}).catch(function (e) {
|
||||
if (!s.alive || my !== s.seq) return;
|
||||
if (e && e.message === 'unauthorized') return;
|
||||
@@ -1881,6 +1877,7 @@
|
||||
S.ctx = ctx; S.lang = ctx.lang;
|
||||
if (ctxKey(ctx) !== S.key) { S.data = S.data && ipFromCtx(ctx) === S.ip ? S.data : null; load(S); return; }
|
||||
if (ctx.lang !== prevLang && S.data) { render(S); paintEvents(S); }
|
||||
else if (S.data && !S.ev.disabled && S.ev.page !== U.pageParam()) { S.ev.page = U.pageParam(); loadEvents(S); } // back/forward
|
||||
},
|
||||
unmount: function () {
|
||||
if (!S) return;
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
var CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban'];
|
||||
var CAT_OK = {}; CATS.concat(['ok']).forEach(function (c) { CAT_OK[c] = 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"><circle cx="11" cy="11" r="6.5"/><path d="M16 16l5 5"/></svg>';
|
||||
var PAGE = 100, MAXROWS = 5000;
|
||||
var PAGE = 100;
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
@@ -17,7 +17,7 @@
|
||||
'sr.title': 'Event search',
|
||||
'sr.lead.one': '{n} event found',
|
||||
'sr.lead.other': '{n} events found',
|
||||
'sr.lead.more': 'More events match; load more to continue.',
|
||||
'sr.lead.more': 'More events match; use Next page to continue.',
|
||||
'sr.lead.body': 'Events {range}, newest first.',
|
||||
'sr.lead.empty': 'No event matches',
|
||||
'sr.lead.emptyBody': 'Nothing {range} fits these filters, or the event registry is off.',
|
||||
@@ -35,7 +35,6 @@
|
||||
'sr.f.s5': '5xx',
|
||||
'sr.search': 'Search',
|
||||
'sr.clear': 'Clear',
|
||||
'sr.more': 'Load more',
|
||||
'sr.csv': 'Export CSV',
|
||||
'sr.csv.done': 'CSV saved',
|
||||
'sr.c.time': 'Time',
|
||||
@@ -46,7 +45,6 @@
|
||||
'sr.c.status': 'Status',
|
||||
'sr.c.fam': 'Family',
|
||||
'sr.statusnote': 'The status filter applies to the rows already loaded.',
|
||||
'sr.cap': 'Row limit reached ({n}); narrow the search.',
|
||||
'sr.err': 'Search failed.',
|
||||
'sr.retry': 'Try again',
|
||||
'sr.busy': 'The server is busy; try again in a few seconds.',
|
||||
@@ -56,7 +54,7 @@
|
||||
'sr.title': 'Busca de eventos',
|
||||
'sr.lead.one': '{n} evento encontrado',
|
||||
'sr.lead.other': '{n} eventos encontrados',
|
||||
'sr.lead.more': 'Há mais eventos; carregue mais para continuar.',
|
||||
'sr.lead.more': 'Há mais eventos; use Próxima página para continuar.',
|
||||
'sr.lead.body': 'Eventos {range}, do mais novo ao mais antigo.',
|
||||
'sr.lead.empty': 'Nenhum evento encontrado',
|
||||
'sr.lead.emptyBody': 'Nada {range} combina com estes filtros, ou o registro de eventos está desligado.',
|
||||
@@ -74,7 +72,6 @@
|
||||
'sr.f.s5': '5xx',
|
||||
'sr.search': 'Buscar',
|
||||
'sr.clear': 'Limpar',
|
||||
'sr.more': 'Carregar mais',
|
||||
'sr.csv': 'Exportar CSV',
|
||||
'sr.csv.done': 'CSV salvo',
|
||||
'sr.c.time': 'Hora',
|
||||
@@ -85,7 +82,6 @@
|
||||
'sr.c.status': 'Status',
|
||||
'sr.c.fam': 'Família',
|
||||
'sr.statusnote': 'O filtro de status vale para as linhas já carregadas.',
|
||||
'sr.cap': 'Limite de linhas atingido ({n}); restrinja a busca.',
|
||||
'sr.err': 'A busca falhou.',
|
||||
'sr.retry': 'Tentar de novo',
|
||||
'sr.busy': 'O servidor está ocupado; tente de novo em alguns segundos.',
|
||||
@@ -103,7 +99,7 @@
|
||||
|
||||
var inst = null;
|
||||
function Page(root, ctx) {
|
||||
var self = this, alive = true, seq = 0, rows = [], next = '', total = 0, loaded = false, busy = false, err = '', capped = false;
|
||||
var self = this, alive = true, seq = 0, rows = [], next = '', total = 0, loaded = false, busy = false, err = '', stack = [''];
|
||||
this.ctx = ctx;
|
||||
var q0 = (ctx.params && ctx.params.query) || {};
|
||||
var F = { ip: q0.ip || '', q: q0.q || '', fam: q0.fam || '', cat: CATS.indexOf(q0.cat) >= 0 ? q0.cat : '', status: '', host: '' };
|
||||
@@ -141,20 +137,27 @@
|
||||
if (cursor) p.cursor = cursor;
|
||||
return p;
|
||||
}
|
||||
function run() { rows = []; next = ''; total = 0; loaded = false; err = ''; capped = false; fetchPage(''); }
|
||||
function fetchPage(cursor) {
|
||||
// stack[i] is the cursor that opens page i+1; going back is popping, going forward pushes the `next` of the page shown
|
||||
function run() { rows = []; next = ''; total = 0; loaded = false; err = ''; stack = ['']; fetchPage(0); }
|
||||
function fetchPage(idx) {
|
||||
var my = ++seq; busy = true; paint();
|
||||
U.api('/api/v1/events', params(cursor)).then(function (d) {
|
||||
U.api('/api/v1/events', params(stack[idx])).then(function (d) {
|
||||
if (!alive || my !== seq) return;
|
||||
busy = false; loaded = true; err = '';
|
||||
rows = rows.concat(d.events || []); total = d.total_estimate || rows.length; next = d.next || '';
|
||||
if (rows.length >= MAXROWS) { capped = true; next = ''; }
|
||||
rows = d.events || []; total = d.total_estimate || rows.length; next = (d.events || []).length ? d.next || '' : '';
|
||||
stack.length = idx + 1; cur = idx;
|
||||
paint();
|
||||
}).catch(function (e) {
|
||||
if (!alive || my !== seq) return;
|
||||
busy = false; loaded = true; err = e && e.status === 503 ? 'sr.busy' : e && e.status === 400 ? 'sr.badq' : 'sr.err'; paint();
|
||||
});
|
||||
}
|
||||
var cur = 0;
|
||||
function goto(n) { // n is the 0-based index of the page asked for
|
||||
if (n === cur + 1 && next) stack[n] = next;
|
||||
if (n < 0 || !stack[n] && n > 0) return;
|
||||
fetchPage(n);
|
||||
}
|
||||
function visible() { return rows.filter(function (r) { return statusOk(F.status, r.status); }); }
|
||||
function exportCsv() {
|
||||
var cols = ['t', 'ip', 'cat', 'host', 'domain', 'method', 'path', 'status', 'fam', 'cc'];
|
||||
@@ -175,7 +178,7 @@
|
||||
if (!loaded) { out.appendChild(h('div', 'skeleton')); return; }
|
||||
leadBox.appendChild(vis.length ? U.ui.lead(U.pl('sr.lead', vis.length, { n: nf(vis.length) + (next ? '+' : '') }), t('sr.lead.body', { range: range }) + (next ? ' ' + t('sr.lead.more') : ''), 'ok')
|
||||
: U.ui.lead(t('sr.lead.empty'), t('sr.lead.emptyBody', { range: range }), 'neutral'));
|
||||
if (!vis.length) { if (next) out.appendChild(moreBtn()); return; }
|
||||
if (!vis.length) { var pe = pagerNode(); if (pe) out.appendChild(pe); return; }
|
||||
var tb = h('tbody');
|
||||
vis.forEach(function (r) {
|
||||
function td(l, k, c) { return h('td', { 'data-label': l, class: c || null }, k); }
|
||||
@@ -192,10 +195,9 @@
|
||||
var th = h('tr'); ['time', 'ip', 'cat', 'host', 'path', 'status', 'fam'].forEach(function (k) { th.appendChild(h('th', { text: t('sr.c.' + k) })); });
|
||||
var csv = h('button', { type: 'button', class: 'btn', text: t('sr.csv') }); csv.addEventListener('click', exportCsv);
|
||||
out.appendChild(U.ui.panel({ title: t('sr.title'), help: 'cat.scanner', actions: [csv] }, h('table', 'stack sr-table', h('thead', null, th), tb)));
|
||||
if (capped) out.appendChild(h('p', { class: 'note', text: t('sr.cap', { n: nf(MAXROWS) }) }));
|
||||
if (next) out.appendChild(moreBtn());
|
||||
var pn = pagerNode(); if (pn) out.appendChild(pn);
|
||||
}
|
||||
function moreBtn() { var b = h('button', { type: 'button', class: 'btn sr-more', text: t('sr.more') }); b.disabled = busy; b.addEventListener('click', function () { fetchPage(next); }); return b; }
|
||||
function pagerNode() { return U.ui.pager({ page: cur + 1, hasNext: !!next, onPage: function (n) { goto(n - 1); } }); }
|
||||
buildForm();
|
||||
this.update = function (c) {
|
||||
var lang = self.ctx.lang; self.ctx = c;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
'use strict';
|
||||
var STAGES = ['recon', 'probe', 'exploit', 'access', 'banned'];
|
||||
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="M3 5h18l-7 8v6l-4 2v-8z"/></svg>';
|
||||
var SHOW = 100;
|
||||
var SHOW = 25;
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
@@ -41,7 +41,8 @@
|
||||
'ss.c.fam': 'Family',
|
||||
'ss.c.replay': 'Replay',
|
||||
'ss.replay': 'Replay',
|
||||
'ss.more': 'Show more',
|
||||
'ss.n.one': '{n} session',
|
||||
'ss.n.other': '{n} sessions',
|
||||
'ss.none': 'No session matches these filters',
|
||||
'ss.esc': 'Escalation chains',
|
||||
'ss.esc.hint': 'The steps of the most serious sessions.',
|
||||
@@ -80,7 +81,8 @@
|
||||
'ss.c.fam': 'Família',
|
||||
'ss.c.replay': 'Reprodução',
|
||||
'ss.replay': 'Reproduzir',
|
||||
'ss.more': 'Mostrar mais',
|
||||
'ss.n.one': '{n} sessão',
|
||||
'ss.n.other': '{n} sessões',
|
||||
'ss.none': 'Nenhuma sessão combina com estes filtros',
|
||||
'ss.esc': 'Cadeias de escalada',
|
||||
'ss.esc.hint': 'Os passos das sessões mais graves.',
|
||||
@@ -100,14 +102,16 @@
|
||||
|
||||
var inst = null;
|
||||
function Page(root, ctx) {
|
||||
var self = this, data = null, seq = 0, alive = true, st = { stage: '', host: '', fam: '', shown: SHOW };
|
||||
var self = this, data = null, seq = 0, alive = true, st = { stage: '', host: '', fam: '' };
|
||||
this.ctx = ctx;
|
||||
var wrap = h('div', 'ss');
|
||||
root.appendChild(wrap);
|
||||
function load() {
|
||||
var my = ++seq;
|
||||
U.api('/api/v1/sessions/funnel', Object.assign({ host: self.ctx.host }, U.rangeParams())).then(function (d) {
|
||||
if (!alive || my !== seq) return; data = d; paint();
|
||||
U.api('/api/v1/sessions/funnel', Object.assign({ host: self.ctx.host, page: U.pageParam(), per_page: SHOW, stage: st.stage, host_f: st.host, fam: st.fam }, U.rangeParams())).then(function (d) {
|
||||
if (!alive || my !== seq) return;
|
||||
if (d.page > 1 && !(d.sessions || []).length && d.total) { U.setParam('p', d.pages); load(); return; } // stale link past the last page
|
||||
data = d; paint();
|
||||
}).catch(function () {
|
||||
if (!alive || my !== seq || data) return;
|
||||
var b = h('button', { type: 'button', class: 'btn', text: t('ss.retry') });
|
||||
@@ -116,6 +120,7 @@
|
||||
wrap.appendChild(h('div', 'state-error', h('strong', { text: t('ss.err') }), b));
|
||||
});
|
||||
}
|
||||
function refilter() { U.setParam('p', 1); load(); }
|
||||
function paint() {
|
||||
wrap.textContent = '';
|
||||
var d = data, n = d.sessions_n || 0, k = d.exploited || 0, range = U.rangeLabel({ inline: true });
|
||||
@@ -132,36 +137,32 @@
|
||||
bar.appendChild(i);
|
||||
b.appendChild(bar);
|
||||
b.appendChild(h('span', { class: 'ss-fn num', text: nf(v) }));
|
||||
b.addEventListener('click', function () { st.stage = st.stage === g ? '' : g; st.shown = SHOW; paint(); });
|
||||
b.addEventListener('click', function () { st.stage = st.stage === g ? '' : g; refilter(); });
|
||||
fb.appendChild(b);
|
||||
});
|
||||
wrap.appendChild(U.ui.panel({ title: t('ss.funnel'), help: 'term.session', hint: t('ss.funnel.hint') }, fb));
|
||||
// filters
|
||||
var hosts = {}, fams = {};
|
||||
d.sessions.forEach(function (s) { (s.hosts || []).forEach(function (x) { hosts[x] = 1; }); Object.keys(s.fams || {}).forEach(function (x) { fams[x] = 1; }); });
|
||||
var f = h('div', 'ss-filters');
|
||||
function sel(label, key, values, labeler) {
|
||||
var s = h('select', { 'aria-label': label });
|
||||
opt(s, '', label + ': ' + t('ss.f.all'));
|
||||
values.forEach(function (v) { opt(s, v, labeler ? labeler(v) : v); });
|
||||
s.value = values.indexOf(st[key]) >= 0 ? st[key] : '';
|
||||
s.addEventListener('change', function () { st[key] = s.value; st.shown = SHOW; paint(); });
|
||||
s.addEventListener('change', function () { st[key] = s.value; refilter(); });
|
||||
f.appendChild(s);
|
||||
}
|
||||
sel(t('ss.f.stage'), 'stage', STAGES, function (g) { return t('ss.stage.' + g); });
|
||||
sel(t('ss.f.host'), 'host', Object.keys(hosts).sort());
|
||||
sel(t('ss.f.fam'), 'fam', Object.keys(fams).sort());
|
||||
sel(t('ss.f.host'), 'host', d.hosts || []);
|
||||
sel(t('ss.f.fam'), 'fam', d.fams || []);
|
||||
// list
|
||||
var rows = d.sessions.filter(function (s) {
|
||||
return (!st.stage || stg(s.stage) === st.stage) && (!st.host || (s.hosts || []).indexOf(st.host) >= 0) && (!st.fam || (s.fams || {})[st.fam]);
|
||||
});
|
||||
var rows = d.sessions || [];
|
||||
var body = h('div');
|
||||
if (d.sampled) body.appendChild(h('p', { class: 'note', text: t('ss.sampled', { n: nf(d.sessions.length), m: nf(n) }) }));
|
||||
if (d.sampled && !st.stage && !st.host && !st.fam) body.appendChild(h('p', { class: 'note', text: t('ss.sampled', { n: nf(d.total), m: nf(n) }) }));
|
||||
body.appendChild(f);
|
||||
if (!rows.length) body.appendChild(U.ui.empty(t('ss.none')));
|
||||
else {
|
||||
var tb = h('tbody');
|
||||
rows.slice(0, st.shown).forEach(function (s) {
|
||||
rows.forEach(function (s) {
|
||||
var a = Math.floor(Date.parse(s.start) / 1000), b = Math.floor(Date.parse(s.end) / 1000);
|
||||
var rp = h('a', { class: 'btn ss-rp', href: '#/replay?ip=' + encodeURIComponent(s.ip) + '&from=' + encodeURIComponent(iso(a - 60)) + '&to=' + encodeURIComponent(iso(b + 60)), text: t('ss.replay') });
|
||||
function td(label, kid, cls) { return h('td', { 'data-label': label, class: cls || null }, kid); }
|
||||
@@ -178,11 +179,8 @@
|
||||
var th = h('tr');
|
||||
['ip', 'stage', 'start', 'dur', 'events', 'hosts', 'fam', 'replay'].forEach(function (c) { th.appendChild(h('th', { text: t('ss.c.' + c) })); });
|
||||
body.appendChild(h('table', 'stack ss-table', h('thead', null, th), tb));
|
||||
if (rows.length > st.shown) {
|
||||
var more = h('button', { type: 'button', class: 'btn', text: t('ss.more') });
|
||||
more.addEventListener('click', function () { st.shown += SHOW; paint(); });
|
||||
body.appendChild(more);
|
||||
}
|
||||
var pg = U.ui.pager({ page: d.page, pages: d.pages, total: d.total, totalText: U.pl('ss.n', d.total, { n: nf(d.total) }), onPage: function (n) { U.setParam('p', n); load(); } });
|
||||
if (pg) body.appendChild(pg);
|
||||
}
|
||||
wrap.appendChild(U.ui.panel({ title: t('ss.list') }, body));
|
||||
// escalation chains
|
||||
|
||||
@@ -325,6 +325,17 @@ td small { display: block; color: var(--ink-muted); font-size: .8125rem; overflo
|
||||
.toolbar input[type="number"] { width: 90px; }
|
||||
.pager { display: flex; justify-content: space-between; align-items: center; gap: var(--s-2); margin-top: var(--s-3); color: var(--ink-muted); font-size: .875rem; flex-wrap: wrap; }
|
||||
.pager .btns { display: flex; gap: var(--s-2); align-items: center; }
|
||||
.pgr { display: flex; justify-content: space-between; align-items: center; gap: var(--s-2) var(--s-3); margin-top: var(--s-3); flex-wrap: wrap; color: var(--ink-muted); font-size: .875rem; }
|
||||
.pgr-l { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
|
||||
.pgr-b { min-width: 36px; padding: 2px 8px; justify-content: center; }
|
||||
.pgr-n.on { background: var(--accent); color: var(--on-accent); border-color: transparent; font-weight: 600; }
|
||||
.pgr-gap { min-width: 20px; text-align: center; }
|
||||
.pgr-b:disabled { opacity: .45; cursor: default; }
|
||||
@media (max-width: 560px) {
|
||||
.pgr { justify-content: center; }
|
||||
.pgr-n:not(.on), .pgr-gap { display: none; }
|
||||
.pgr-b { min-width: 44px; min-height: 44px; }
|
||||
}
|
||||
|
||||
/* feed */
|
||||
.feed { list-style: none; padding: 0; max-height: 420px; overflow-y: auto; }
|
||||
|
||||
@@ -55,7 +55,10 @@ func CampaignsOf(p PeriodOut) CampaignsOut {
|
||||
if list[i].IPsN != list[j].IPsN {
|
||||
return list[i].IPsN > list[j].IPsN
|
||||
}
|
||||
return list[i].First.Before(list[j].First)
|
||||
if !list[i].First.Equal(list[j].First) {
|
||||
return list[i].First.Before(list[j].First)
|
||||
}
|
||||
return list[i].ID < list[j].ID
|
||||
})
|
||||
out := CampaignsOut{Range: p.Range, Enabled: p.Enabled, Truncated: p.Truncated, Total: len(list)}
|
||||
seen := map[string]bool{}
|
||||
@@ -74,6 +77,7 @@ func CampaignsOf(p PeriodOut) CampaignsOut {
|
||||
list = list[:MaxCampaignsOut]
|
||||
}
|
||||
out.Campaigns = list
|
||||
out.Total = len(list) // what can be paged through (the cap above applies)
|
||||
if out.Campaigns == nil {
|
||||
out.Campaigns = []intel.Campaign{}
|
||||
}
|
||||
@@ -257,7 +261,14 @@ func FunnelOf(p PeriodOut, counts *StageCounts) FunnelOut {
|
||||
if a != b {
|
||||
return a > b
|
||||
}
|
||||
return f.Sessions[i].Start.After(f.Sessions[j].Start)
|
||||
x, y := f.Sessions[i], f.Sessions[j]
|
||||
if !x.Start.Equal(y.Start) {
|
||||
return x.Start.After(y.Start)
|
||||
}
|
||||
if x.IP != y.IP {
|
||||
return x.IP < y.IP
|
||||
}
|
||||
return x.End.After(y.End)
|
||||
})
|
||||
return f
|
||||
}
|
||||
@@ -23,6 +23,9 @@ func IntelClassifier(ev core.Event) (string, []string, string) {
|
||||
marker = intel.Marker(ev.Path)
|
||||
}
|
||||
}
|
||||
if ev.Source == "probe" {
|
||||
fam = intel.FamPortScan
|
||||
}
|
||||
tech := intel.Techniques(string(ev.Cat), fam, intel.TechCtx{Tool: ev.UA, Path: ev.Path})
|
||||
return fam, tech, marker
|
||||
}
|
||||
|
||||
+13
-1
@@ -162,6 +162,9 @@ type FeedEvent struct {
|
||||
Bytes int64 `json:"bytes,omitempty"`
|
||||
DurMS int64 `json:"dur_ms,omitempty"`
|
||||
Flags string `json:"flags,omitempty"` // S strong, W weak, G forged, F framed, X soft
|
||||
// Network probe (Source "probe"): destination port and transport.
|
||||
Port int `json:"port,omitempty"`
|
||||
Proto string `json:"proto,omitempty"`
|
||||
}
|
||||
|
||||
// SetAttribution sets the credit line shown in the dashboard footer (geo data licence).
|
||||
@@ -574,7 +577,7 @@ func (s *Store) feedOf(ev core.Event, ts int64, fam string, tech []string, marke
|
||||
return FeedEvent{T: ts, IP: ev.IP, Cat: string(ev.Cat), Source: ev.Source, Host: s.cfg.Name, Domain: ev.Domain,
|
||||
Method: ev.Method, Path: ev.Path, User: ev.User, Jail: ev.Jail, Status: ev.Status, Unban: ev.Unban, Forged: ev.Forged, CC: ev.E.CC,
|
||||
UA: clipS(ev.UA, 200), ID: s.ids.Add(1), Fam: clipS(fam, 40), Tech: tech, Marker: clipS(marker, 80),
|
||||
Bytes: ev.Bytes, DurMS: ev.DurationNS / 1e6, Flags: flags}
|
||||
Bytes: ev.Bytes, DurMS: ev.DurationNS / 1e6, Flags: flags, Port: int(ev.Port), Proto: probeProto(ev)}
|
||||
}
|
||||
|
||||
// listedRule is the blocklist rule: score of 50, a strong signal and not an admin.
|
||||
@@ -979,3 +982,12 @@ func (s *Store) Monitoring(t time.Time) {
|
||||
hs.Mon++
|
||||
s.mu.Unlock()
|
||||
}
|
||||
|
||||
// probeProto is the transport of a network probe; the Proto of an HTTP event
|
||||
// (HTTP/1.1...) is not exported.
|
||||
func probeProto(ev core.Event) string {
|
||||
if ev.Source == "probe" {
|
||||
return ev.Proto
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -221,10 +221,11 @@ func SortIPs(l []IPSummary, key string, desc bool) {
|
||||
return a.Last < b.Last
|
||||
}
|
||||
sort.SliceStable(l, func(i, j int) bool {
|
||||
if desc {
|
||||
return less(l[j], l[i])
|
||||
a, b := l[i], l[j]
|
||||
if lt, gt := less(a, b), less(b, a); lt || gt { // equal keys fall back to the address: pages never shuffle
|
||||
return lt != desc
|
||||
}
|
||||
return less(l[i], l[j])
|
||||
return a.IP < b.IP
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user