Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22ccde539b | ||
|
|
bc3ce09088 | ||
|
|
54b9ae65cd | ||
|
|
393a31cebe | ||
|
|
2a14924ed9 | ||
|
|
7e1f70bf40 | ||
|
|
a689dd8824 | ||
|
|
804d2c6e8d | ||
|
|
612516db76 | ||
|
|
3c7caef0c8 | ||
|
|
e5058968e2 | ||
|
|
3ae72e27d6 | ||
|
|
873219416f | ||
|
|
da333d70f1 |
No files matched your search
+92
-1
@@ -4,7 +4,98 @@
|
||||
|
||||
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer.
|
||||
|
||||
## [Unreleased]
|
||||
## [1.6.0] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Code forge browsing is no longer an attack: crawlers (a Alibaba range and Googlebot) reading `/owner/repo/src/commit/<sha>/.gitignore`, `/raw/commit/...`, `/blame/...`, `/commits/...`, `.env.example` and similar repository files on a public Gitea (also GitHub and GitLab style `blob`/`tree`/`raw` paths) were classified as scanner, env-probe and vcs-probe, about 58% of the "attackers". Real probes (`/.env`, `/.git/config`, `/app/.env`, traversal) are unchanged.
|
||||
- The second firewall excluded crawlers only when the User-Agent claimed to be one, so a verified Googlebot ("GoogleOther") got banned. A forward-confirmed reverse DNS (googlebot.com, google.com, search.msn.com, applebot.apple.com) now excludes the address whatever the User-Agent says; more crawler User-Agents (GoogleOther, Google-InspectionTool, AdsBot, Apple) are recognized.
|
||||
- Feedback loop: bans of the `urutau` jail (our own decisions) and of `recidive` (which only repeats bans) no longer count as evidence: no score, no strong signal, no blocklist listing. Bans of independent jails (sshd, traefik...) still count.
|
||||
- The blocklist coverage was misleading (3%): it counted only listed attackers.
|
||||
|
||||
### Changed
|
||||
|
||||
- Coverage (`blocklist.coverage_pct`, `blocklist_coverage`) now counts an attacker as protected when it is listed or banned by any jail. New fields, additive: `blocklist.attackers`, `covered`, `one_shot`, `repeat_ips`, `repeat_covered`, `repeat_coverage_pct` in `/api/v1/defense`, and `one_shot`, `repeat_ips`, `repeat_unblocked` in the enforce `coverage`.
|
||||
- Enforce policy for slow attackers: `ssh-probe` events count half a failure in the SSH rules; a 7-day window bans at 10 SSH failures (probes count half) or 10 web scan/exploit events without a legitimate visit (bounded memory); new reason `neighbor-campaign`: when 3 or more distinct addresses of a /24 (IPv4) or /64 (IPv6) were banned in the last 24 h, one attack event of another address of the prefix is enough. All exclusions (trusted, private, crawler, infrastructure, legitimate visitor, operator) still apply, and peers accept the new reason.
|
||||
|
||||
## [1.5.8] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Phones: plain data tables (Concentration ranking, Errors routes, MITRE techniques, Defense, Integrity sources, and any other table without its own phone layout) rendered as squeezed columns with IPs broken letter by letter or sideways scrolling. Under 768 px their rows now become stacked cards with the column name as label, right-aligned numbers and long text wrapping; desktop is unchanged. One shared rule in `style.css` plus `cardTables()` in `app.js` covers all of them. `TABLES_ONLY=1 scripts/screenshots.sh` captures every table page at 375x812 and checks for horizontal overflow.
|
||||
|
||||
## [1.5.7] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Protocols & TLS: the class legend under the stacked bars had no styles (words glued together, no color swatches, overflowing on phones); the Methods panel no longer reserves a fixed 280 px height with empty space; cipher suite names break at underscores instead of mid-word; on phones the per-class breakdown of each method moves under the method name; an invalid CSS selector disabled the page's mobile one-column rule.
|
||||
|
||||
## [1.5.6] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Phones: the hidden accessible data table of the charts (`table.sr-only`, ~1300 px wide because tables ignore `width: 1px`) widened the mobile layout viewport on the egress page, dragging the fixed bottom menu sideways. The table is now fixed-layout at 1 px, and `html`/`body` use `overflow-x: clip` so nothing can widen the page again.
|
||||
|
||||
## [1.5.5] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Incidents on phones: quick actions wrap instead of being cut, filters share the row evenly, and the workload line is no longer indented.
|
||||
|
||||
## [1.5.4] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Incidents list: egress tickets show the pattern on the first line and the workload below, instead of a long auto title cut in the middle; the status tabs are compact and fit in one line at 1280 px.
|
||||
|
||||
## [1.5.3] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Incidents: the Copy button of the fingerprint no longer wraps letter by letter; the list shows one tag per row and a wider host/destination column, so titles and IPs stop being cut.
|
||||
|
||||
## [1.5.2] - 2026-11-15
|
||||
|
||||
### Changed
|
||||
|
||||
- Incidents redesigned after a UX review: ticket page with a sticky header and quick actions, a main column (summary + unified activity timeline of comments and changes) and a sidebar with inline-saved properties and compact technical data; the list is a dense table with one-line underlined tabs, and the empty state offers "See all". No more empty gaps between panels.
|
||||
|
||||
## [1.5.1] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Incidents: the list accepts `?status=` in the link (alias of `?s=`), so `#/incidents?status=benign` opens filtered.
|
||||
- Incidents: the ticket creation entry in the history reads "urutau opened the ticket (severity: …)" instead of "changed created".
|
||||
|
||||
## [1.5.0] - 2026-11-15
|
||||
|
||||
### Added
|
||||
|
||||
- Incident management: every egress finding (severity above info) becomes a ticket `INC-<n>` keyed by `host|kind|workload|dst|dport|proto`, created by a sync on each merged egress report and every 60 s. Tickets have status (`open`, `investigating`, `true_positive`, `false_positive`, `benign`, `resolved`), severity, assignee, tags, verdict, comments and a change history; a resolved ticket reopens when the finding reappears. Stored in `<data-dir>/incidents.json` (atomic write, 0600; a corrupt file is moved to `.corrupt`); limits of 5000 tickets, 200 comments and 500 history entries each. Every write is also logged (id, field, author).
|
||||
- A ticket in `false_positive` or `benign` can suppress the findings with exactly its key: they leave `/api/v1/egress` (and the egress report) unless `?suppressed=1`. Findings now carry `ticket_id`, `ticket_status` and `suppressed`, and the response has `suppressed_count`.
|
||||
- API: `GET /api/v1/incidents`, `GET /api/v1/incidents/{id}`, `POST /api/v1/incidents`, `PATCH /api/v1/incidents/{id}`, `POST /api/v1/incidents/{id}/comments` and `GET /api/v1/incidents/export.csv` (not open to the peer token; writes refuse cross-site requests).
|
||||
|
||||
## [1.4.8] - 2026-11-15
|
||||
|
||||
### Fixed
|
||||
|
||||
- Egress analysis, false positives: the nftables kit now logs only TCP connection attempts (SYN without ACK), so replies of banned clients (conntrack recreated mid-flow) no longer show up as `bad_dst` "attacked us". **Re-run `deploy/host/install.sh --enforce` on the host to apply the new nft rules.**
|
||||
- Hosts with the old kit: the parser drops TCP lines without a pure SYN and counts them as `non_syn_dropped` in the egress source (not as `malformed`).
|
||||
- Cloud metadata services (169.254.169.254, `fd00:c1::a9fe:a9fe`, `fd00:ec2::254`, link-local) polled by the host itself are `infra` (info), not beacon; a container reaching them stays a finding (SSRF/credential theft).
|
||||
- Regular connections to Akamai (AS20940/AS16625 and its main ranges) and Telegram (AS62041, 149.154.160.0/20, 91.108.0.0/16) are `low` ("large CDN/cloud network"). Hetzner (e.g. SURBL updates) stays `medium`: there is no name correlation, and no IP is hardcoded.
|
||||
|
||||
## [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
|
||||
|
||||
|
||||
+92
-1
@@ -4,7 +4,98 @@
|
||||
|
||||
Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versionamento segue SemVer.
|
||||
|
||||
## [Unreleased]
|
||||
## [1.6.0] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Navegar em forja de código não é mais ataque: crawlers (uma faixa da Alibaba e o Googlebot) lendo `/dono/repo/src/commit/<sha>/.gitignore`, `/raw/commit/...`, `/blame/...`, `/commits/...`, `.env.example` e arquivos parecidos de repositório num Gitea público (também caminhos `blob`/`tree`/`raw` no estilo GitHub e GitLab) eram classificados como scanner, env-probe e vcs-probe, cerca de 58% dos "atacantes". Sondagens reais (`/.env`, `/.git/config`, `/app/.env`, traversal) não mudam.
|
||||
- O segundo firewall só excluía crawler quando o User-Agent dizia ser um, então um Googlebot verificado ("GoogleOther") foi banido. Um DNS reverso confirmado nos dois sentidos (googlebot.com, google.com, search.msn.com, applebot.apple.com) agora exclui o endereço qualquer que seja o User-Agent; mais User-Agents de crawler são reconhecidos (GoogleOther, Google-InspectionTool, AdsBot, Apple).
|
||||
- Laço de retroalimentação: banimentos do jail `urutau` (decisões nossas) e do `recidive` (que só repete bans) deixam de contar como evidência: sem pontuação, sem sinal forte, sem entrar na lista de bloqueio. Bans de jails independentes (sshd, traefik...) continuam valendo.
|
||||
- A cobertura da lista de bloqueio enganava (3%): contava só os atacantes listados.
|
||||
|
||||
### Alterado
|
||||
|
||||
- A cobertura (`blocklist.coverage_pct`, `blocklist_coverage`) passa a contar como protegido o atacante listado ou banido por qualquer jail. Campos novos, só adicionados: `blocklist.attackers`, `covered`, `one_shot`, `repeat_ips`, `repeat_covered`, `repeat_coverage_pct` em `/api/v1/defense`, e `one_shot`, `repeat_ips`, `repeat_unblocked` na `coverage` do enforce.
|
||||
- Política do enforce para atacantes lentos: eventos `ssh-probe` valem meia falha nas regras de SSH; uma janela de 7 dias bane com 10 falhas de SSH (probes valem metade) ou 10 eventos de scan/exploit web sem visita legítima (memória limitada); novo motivo `neighbor-campaign`: com 3 ou mais endereços distintos de um /24 (IPv4) ou /64 (IPv6) banidos nas últimas 24 h, basta um evento de ataque de outro endereço do prefixo. Todas as exclusões (confiável, privado, crawler, infraestrutura, visitante legítimo, operador) seguem valendo, e os peers aceitam o novo motivo.
|
||||
|
||||
## [1.5.8] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Celular: tabelas de dados comuns (ranking da Concentração, rotas de Erros, técnicas MITRE, Defesa, fontes da Integridade e qualquer outra sem layout próprio para celular) apareciam com colunas espremidas, IPs quebrados letra por letra ou rolagem lateral. Abaixo de 768 px as linhas agora viram cartões empilhados com o nome da coluna como rótulo, números alinhados à direita e texto longo quebrando; o desktop não muda. Uma regra única em `style.css` e `cardTables()` em `app.js` cobre todas. `TABLES_ONLY=1 scripts/screenshots.sh` captura todas as páginas com tabela em 375x812 e verifica estouro horizontal.
|
||||
|
||||
## [1.5.7] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Protocolos e TLS: a legenda das classes sob as barras empilhadas não tinha estilo (palavras grudadas, sem as cores e estourando no celular); o painel Métodos não reserva mais 280 px fixos com espaço vazio; os nomes das suítes de cifra quebram nos sublinhados em vez de no meio da palavra; no celular o detalhamento por classe de cada método vai para baixo do nome; um seletor CSS inválido desligava a regra de uma coluna no celular.
|
||||
|
||||
## [1.5.6] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Celular: a tabela acessível oculta dos gráficos (`table.sr-only`, ~1300 px porque tabelas ignoram `width: 1px`) alargava o layout na página de tráfego de saída e arrastava o menu inferior fixo para o lado. A tabela agora tem layout fixo de 1 px, e `html`/`body` usam `overflow-x: clip`, para nada mais alargar a página.
|
||||
|
||||
## [1.5.5] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Incidentes no celular: as ações rápidas quebram linha em vez de ficarem cortadas, os filtros dividem a linha por igual e a linha da carga de trabalho não fica mais recuada.
|
||||
|
||||
## [1.5.4] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Lista de incidentes: chamados de egress mostram o padrão na primeira linha e a carga de trabalho embaixo, em vez de um título automático longo cortado no meio; as abas de status ficaram compactas e cabem numa linha em 1280 px.
|
||||
|
||||
## [1.5.3] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Incidentes: o botão Copiar da impressão digital não quebra mais letra por letra; a lista mostra uma etiqueta por linha e coluna de servidor/destino mais larga, então títulos e IPs deixam de ser cortados.
|
||||
|
||||
## [1.5.2] - 2026-11-15
|
||||
|
||||
### Alterado
|
||||
|
||||
- Incidentes redesenhados após revisão de UX: página do chamado com cabeçalho fixo e ações rápidas, coluna principal (resumo + linha do tempo única de comentários e alterações) e barra lateral com propriedades salvas na hora e dados técnicos compactos; a lista virou tabela densa com abas numa linha e o estado vazio oferece "Ver todos". Acabaram os vazios entre painéis.
|
||||
|
||||
## [1.5.1] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Incidentes: a lista aceita `?status=` no link (sinônimo de `?s=`), então `#/incidents?status=benign` abre filtrado.
|
||||
- Incidentes: a criação do chamado no histórico aparece como "urutau abriu o chamado (severidade: …)" em vez de "alterou created".
|
||||
|
||||
## [1.5.0] - 2026-11-15
|
||||
|
||||
### Adicionado
|
||||
|
||||
- Gestão de incidentes: cada achado de egress (severidade acima de info) vira um chamado `INC-<n>` com chave `host|kind|workload|dst|dport|proto`, criado por uma sincronização a cada relatório de egress mesclado e a cada 60 s. O chamado tem status (`open`, `investigating`, `true_positive`, `false_positive`, `benign`, `resolved`), severidade, responsável, etiquetas, conclusão, comentários e histórico de mudanças; um chamado resolvido reabre quando o achado reaparece. Fica em `<data-dir>/incidents.json` (escrita atômica, 0600; arquivo corrompido vai para `.corrupt`); limites de 5000 chamados, 200 comentários e 500 entradas de histórico cada. Toda escrita também vai para o log (id, campo, autor).
|
||||
- Um chamado em `false_positive` ou `benign` pode suprimir os achados com exatamente a sua chave: eles saem de `/api/v1/egress` (e do relatório de egress), salvo com `?suppressed=1`. Os achados agora trazem `ticket_id`, `ticket_status` e `suppressed`, e a resposta tem `suppressed_count`.
|
||||
- API: `GET /api/v1/incidents`, `GET /api/v1/incidents/{id}`, `POST /api/v1/incidents`, `PATCH /api/v1/incidents/{id}`, `POST /api/v1/incidents/{id}/comments` e `GET /api/v1/incidents/export.csv` (fechada ao token de peer; escritas recusam requisições cross-site).
|
||||
|
||||
## [1.4.8] - 2026-11-15
|
||||
|
||||
### Corrigido
|
||||
|
||||
- Análise de egress, falsos positivos: o kit nftables agora registra só tentativas de conexão TCP (SYN sem ACK), então respostas a clientes banidos (conntrack recriado no meio do fluxo) não aparecem mais como `bad_dst` "nos atacou". **Rode `deploy/host/install.sh --enforce` de novo no host para aplicar o nft novo.**
|
||||
- Hosts com o kit antigo: o parser descarta linhas TCP sem SYN puro e as conta como `non_syn_dropped` na fonte de egress (não como `malformed`).
|
||||
- Serviços de metadados de nuvem (169.254.169.254, `fd00:c1::a9fe:a9fe`, `fd00:ec2::254`, link-local) consultados pelo próprio host são `infra` (info), não beacon; container acessando continua alerta (SSRF/roubo de credencial).
|
||||
- Conexões regulares para Akamai (AS20940/AS16625 e faixas principais) e Telegram (AS62041, 149.154.160.0/20, 91.108.0.0/16) ficam `low` ("rede grande de CDN/nuvem"). Hetzner (ex.: atualização do SURBL) continua `medium`: não há correlação por nome e nenhum IP foi fixado no código.
|
||||
|
||||
## [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
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -22,6 +22,10 @@ table inet urutau_egress {
|
||||
set seen6 { type ipv6_addr . ipv6_addr . inet_proto . inet_service; flags dynamic, timeout; timeout 2h; size 131072; }
|
||||
|
||||
chain egress {
|
||||
# only real connection attempts (SYN without ACK): replies of flows whose
|
||||
# conntrack entry was recreated mid-flow (nf_conntrack_tcp_loose=1, e.g.
|
||||
# after fail2ban drops only the original direction) are not egress
|
||||
meta l4proto tcp tcp flags & (syn | ack) != syn return
|
||||
# known pair: always log, refresh its timer
|
||||
meta nfproto ipv4 meta l4proto { tcp, udp } ip saddr . ip daddr . meta l4proto . th dport @seen4 update @seen4 { ip saddr . ip daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
|
||||
meta nfproto ipv6 meta l4proto { tcp, udp } ip6 saddr . ip6 daddr . meta l4proto . th dport @seen6 update @seen6 { ip6 saddr . ip6 daddr . meta l4proto . th dport } log prefix "URUTAU-EGRESS: " level info return
|
||||
|
||||
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
|
||||
@@ -163,7 +163,7 @@ The investigation layer is computed from the IP table and the registry, with no
|
||||
| `exploits_refused_pct` | exploit requests answered 4xx or 5xx / exploit requests with a status, in percent |
|
||||
| `mttb` | median and 90th percentile of the time from first sighting to ban |
|
||||
| `ban_coverage` | hostile IPs banned / hostile IPs, in percent |
|
||||
| `blocklist_coverage` | hostile IPs that are listable (global addresses) / hostile IPs, in percent |
|
||||
| `blocklist_coverage` | hostile IPs that are protected (on the published blocklist or banned by any jail) / hostile IPs, in percent; `GET /api/v1/defense` also gives `blocklist.attackers`, `covered`, `one_shot` (single-event attackers, impossible to block reactively), `repeat_ips`, `repeat_covered` and `repeat_coverage_pct` |
|
||||
| `blocklist_leak` | hostile IPs neither banned nor listable (a count) |
|
||||
| `ssh.fails_24h`, `ssh.users_distinct`, `ssh.ok_after_fail` | SSH failures in 24 h, distinct users tried in 24 h, sessions with a failure and then a successful login |
|
||||
| `concentration.top10_ips`, `top5_asns` | share of malicious events from the 10 busiest IPs and the 5 busiest ASNs, in percent |
|
||||
|
||||
@@ -138,6 +138,12 @@ State and city boundaries on the Geography page are from [Natural Earth](https:/
|
||||
| `GET /api/v1/events/stream` | session or bearer | Server-Sent Events, event `ev`, a ping every 20 s. With `visits=1` it also sends anonymous `visit` events (no address, at most 20 per second) |
|
||||
| `GET /api/v1/blocklist.txt` | session or bearer | one IP per line. Query: `min_score` (default 50), `range` (default `7d`), `host`, `family` (`4`, `6`; default both; `4` suits `ipset hash:ip`), `download=1` |
|
||||
| `GET /api/v1/blocklist.json` | session or bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; the `ip` of an IPv6 entry is a `/64` prefix |
|
||||
| `GET /api/v1/incidents` | session or bearer | incident tickets (no comments or history, with `comment_count`). Query: `status` (comma list), `severity`, `host`, `q`, `sort` (`updated`, `severity`, `last_seen`), `page`, `per_page` (max 200). Returns `{items,total,counts}` |
|
||||
| `GET /api/v1/incidents/{id}` | session or bearer | full ticket with `comments` and `history` |
|
||||
| `GET /api/v1/incidents/export.csv` | session or bearer | the filtered list as CSV |
|
||||
| `POST /api/v1/incidents` | session or bearer | opens a manual ticket `{title,detail,severity,host,tags,author}` (body up to 64 KiB, unknown fields refused; cross-site refused) |
|
||||
| `PATCH /api/v1/incidents/{id}` | session or bearer | partial update `{status,severity,assignee,tags,title,verdict,suppress,author}`; each change is a history entry. `suppress` only in `false_positive` or `benign`, and hides findings with the exact same key in `/api/v1/egress` (add `suppressed=1` to see them) |
|
||||
| `POST /api/v1/incidents/{id}/comments` | session or bearer | adds a comment `{text,author}` |
|
||||
|
||||
An invalid `range` or period answers 400, and `range` in the responses is an object `{name,from,to,step,clipped}` (`step` is the timeline granularity in seconds).
|
||||
|
||||
|
||||
@@ -163,7 +163,7 @@ A camada de investigação é calculada a partir da tabela de IPs e do registro,
|
||||
| `exploits_refused_pct` | requisições de exploit respondidas 4xx ou 5xx / requisições de exploit com status, em percentual |
|
||||
| `mttb` | mediana e percentil 90 do tempo entre o primeiro avistamento e o ban |
|
||||
| `ban_coverage` | IPs hostis banidos / IPs hostis, em percentual |
|
||||
| `blocklist_coverage` | IPs hostis listáveis (endereços globais) / IPs hostis, em percentual |
|
||||
| `blocklist_coverage` | IPs hostis protegidos (na lista de bloqueio publicada ou banidos por algum jail) / IPs hostis, em percentual; `GET /api/v1/defense` também traz `blocklist.attackers`, `covered`, `one_shot` (atacantes de um só evento, impossíveis de bloquear de forma reativa), `repeat_ips`, `repeat_covered` e `repeat_coverage_pct` |
|
||||
| `blocklist_leak` | IPs hostis nem banidos nem listáveis (uma contagem) |
|
||||
| `ssh.fails_24h`, `ssh.users_distinct`, `ssh.ok_after_fail` | falhas SSH em 24 h, usuários distintos tentados em 24 h, sessões com falha e depois login bem-sucedido |
|
||||
| `concentration.top10_ips`, `top5_asns` | parcela dos eventos maliciosos dos 10 IPs mais ativos e dos 5 ASNs mais ativos, em percentual |
|
||||
|
||||
@@ -135,6 +135,12 @@ Os limites de estados e cidades da página Geografia são do [Natural Earth](htt
|
||||
| `GET /api/v1/events/stream` | sessão ou bearer | Server-Sent Events, evento `ev`, um ping a cada 20 s. Com `visits=1` também envia eventos `visit` anônimos (sem endereço, no máximo 20 por segundo) |
|
||||
| `GET /api/v1/blocklist.txt` | sessão ou bearer | um IP por linha. Query: `min_score` (padrão 50), `range` (padrão `7d`), `host`, `family` (`4`, `6`; padrão ambos; `4` serve ao `ipset hash:ip`), `download=1` |
|
||||
| `GET /api/v1/blocklist.json` | sessão ou bearer | `{"generated","min_score","count","ips":[{"ip","score","last","hosts"}]}`; o `ip` de uma entrada IPv6 é um prefixo `/64` |
|
||||
| `GET /api/v1/incidents` | sessão ou bearer | chamados de incidente (sem comentários e histórico, com `comment_count`). Query: `status` (lista separada por vírgula), `severity`, `host`, `q`, `sort` (`updated`, `severity`, `last_seen`), `page`, `per_page` (máx. 200). Devolve `{items,total,counts}` |
|
||||
| `GET /api/v1/incidents/{id}` | sessão ou bearer | chamado completo, com `comments` e `history` |
|
||||
| `GET /api/v1/incidents/export.csv` | sessão ou bearer | a lista filtrada em CSV |
|
||||
| `POST /api/v1/incidents` | sessão ou bearer | abre um chamado manual `{title,detail,severity,host,tags,author}` (corpo até 64 KiB, campos desconhecidos recusados; cross-site recusado) |
|
||||
| `PATCH /api/v1/incidents/{id}` | sessão ou bearer | atualização parcial `{status,severity,assignee,tags,title,verdict,suppress,author}`; cada mudança vira uma entrada no histórico. `suppress` só em `false_positive` ou `benign`, e esconde de `/api/v1/egress` os achados com exatamente a mesma chave (use `suppressed=1` para vê-los) |
|
||||
| `POST /api/v1/incidents/{id}/comments` | sessão ou bearer | adiciona um comentário `{text,author}` |
|
||||
|
||||
Um `range` ou período inválido responde 400, e `range` nas respostas é um objeto `{name,from,to,step,clipped}` (`step` é a granularidade da linha do tempo em segundos).
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@ type Config struct {
|
||||
// Second firewall (see internal/enforce).
|
||||
Enforce string // off (default), observe or on
|
||||
EnforceLog string // decision file read by the host fail2ban
|
||||
EnforceUnbanLog string // unban requests (UI button) read by the host; default: unban.log next to --enforce-log
|
||||
EnforceShare string // off (default) or on: exchange decisions with peers
|
||||
EnforceThreshold int // attack events in 10 minutes that justify a ban
|
||||
EnforceMaxPerMin int // decisions per minute; the excess is dropped
|
||||
@@ -180,6 +181,7 @@ func ParseFlags(name string, args []string) (Config, error) {
|
||||
fs.StringVar(&c.EventsMax, "events-max", env("URUTAU_EVENTS_MAX", DefaultEventsMax), "size cap of the event registry in <data-dir>/events, 0 disables it (URUTAU_EVENTS_MAX)")
|
||||
fs.StringVar(&c.Enforce, "enforce", env("URUTAU_ENFORCE", "off"), "second firewall: off, observe (decide in memory only) or on (write decisions for the host fail2ban) (URUTAU_ENFORCE)")
|
||||
fs.StringVar(&c.EnforceLog, "enforce-log", env("URUTAU_ENFORCE_LOG", "/logs/enforce/decisions.log"), "decision file appended in --enforce=on (URUTAU_ENFORCE_LOG)")
|
||||
fs.StringVar(&c.EnforceUnbanLog, "enforce-unban-log", env("URUTAU_ENFORCE_UNBAN_LOG", ""), "unban request file written by the Unban button (URUTAU_ENFORCE_UNBAN_LOG); default unban.log next to --enforce-log")
|
||||
fs.StringVar(&c.EnforceShare, "enforce-share", env("URUTAU_ENFORCE_SHARE", "off"), "on: exchange decisions with peers, each side applies its own exclusions (URUTAU_ENFORCE_SHARE)")
|
||||
fs.IntVar(&c.EnforceThreshold, "enforce-threshold", envInt("URUTAU_ENFORCE_THRESHOLD", 5), "attack events in 10 minutes that justify a ban (URUTAU_ENFORCE_THRESHOLD)")
|
||||
fs.StringVar(&c.Egress, "egress", env("URUTAU_EGRESS", "auto"), "egress analysis: auto (on when --egress-log exists), on or off (URUTAU_EGRESS)")
|
||||
@@ -270,6 +272,9 @@ func (c Config) Validate(token string) ([]fed.Peer, error) {
|
||||
if strings.EqualFold(c.Enforce, "on") && c.EnforceLog == "" {
|
||||
return nil, fmt.Errorf("--enforce=on needs --enforce-log")
|
||||
}
|
||||
if c.EnforceUnbanLog == "" && c.EnforceLog != "" {
|
||||
c.EnforceUnbanLog = filepath.Join(filepath.Dir(c.EnforceLog), "unban.log")
|
||||
}
|
||||
var peers []fed.Peer
|
||||
seen := map[string]bool{}
|
||||
envSeen := map[string]string{}
|
||||
|
||||
+37
-6
@@ -35,17 +35,22 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready
|
||||
}
|
||||
}
|
||||
e := enforce.New(enforce.Config{
|
||||
Mode: mode, Path: c.EnforceLog, StatePath: filepath.Join(c.DataDir, "enforce.json"), Host: c.Name,
|
||||
Mode: mode, Path: c.EnforceLog, UnbanPath: 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 },
|
||||
Crawler: func(ip string, uas []string) bool {
|
||||
if v := st.FCrDNS(ip, uas); v != nil && *v {
|
||||
return true
|
||||
}
|
||||
return st.VerifiedCrawler(ip) // forward-confirmed rDNS excludes it whatever the User-Agent says
|
||||
},
|
||||
Rep: st.Reputation,
|
||||
Tally: func(ip string, from int64) enforce.Tally { return tallyOf(st.AttackTally(ip, from)) },
|
||||
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}
|
||||
out[i] = enforce.Seen{IP: r.IP, Score: r.Score, Level: r.Level, Jails: r.Jails, Events: r.Events, Last: r.Last, Est: tallyOf(r.Est)}
|
||||
}
|
||||
return out
|
||||
},
|
||||
@@ -53,7 +58,7 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready
|
||||
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}
|
||||
out[k] = tallyOf(v)
|
||||
}
|
||||
return out
|
||||
},
|
||||
@@ -90,6 +95,7 @@ func resolveHost(h string) []netip.Addr {
|
||||
func shareDecisions(ctx context.Context, hub *fed.Hub, e *enforce.Engine, log *slog.Logger) {
|
||||
pulled := map[string]int64{}
|
||||
pushed := map[string]int64{}
|
||||
pushedUn := map[string]int64{}
|
||||
t := time.NewTicker(30 * time.Second)
|
||||
defer t.Stop()
|
||||
for {
|
||||
@@ -112,6 +118,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
|
||||
@@ -181,3 +197,18 @@ 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")
|
||||
}
|
||||
|
||||
func tallyOf(t store.Tally24) enforce.Tally {
|
||||
return enforce.Tally{SSH: t.SSH, Web: t.Web, Probe: t.Probe, SSH7: t.SSH7, Web7: t.Web7, Probe7: t.Probe7}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/geo"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/rdns"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/server"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
@@ -99,8 +100,13 @@ func Serve(c Config) error {
|
||||
tproxy, _ := core.ParseCIDRs(c.TrustedProxy)
|
||||
ign, _ := core.ParseCIDRs(c.Ignore + "," + c.Trusted)
|
||||
bindHost, _, _ := net.SplitHostPort(c.Bind)
|
||||
incStore, err := incidents.Open(filepath.Join(c.DataDir, "incidents.json"), log)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h := server.New(server.Options{Token: token, PeerTokens: c.PeerTokens, PeerAllow: allow, TrustedProxy: tproxy, Ignore: ign,
|
||||
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub})
|
||||
AllowHosts: []string{bindHost}, NoAuth: c.NoAuth, LocalBlocklist: strings.EqualFold(c.PeerBlocklist, "off"), Version: Version, Store: st, Hub: hub,
|
||||
Incidents: incStore})
|
||||
egressSrc, err := newEgress(c, st, log)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -132,6 +138,7 @@ func Serve(c Config) error {
|
||||
go func() { defer wg.Done(); elog.Run(ctx) }()
|
||||
}
|
||||
runner.Start(ctx, offsets, &wg)
|
||||
server.StartIncidentSync(ctx, &wg)
|
||||
if egressSrc != nil {
|
||||
egressSrc.Start(ctx, &wg)
|
||||
}
|
||||
|
||||
@@ -279,3 +279,12 @@ func TestSourceDegradedWindow(t *testing.T) {
|
||||
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.5"
|
||||
var Version = "1.6.0"
|
||||
@@ -103,7 +103,46 @@ func refusedProbe(path string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
var forgeGitea = map[string]bool{"src": true, "raw": true, "blame": true, "commits": true, "commit": true, "media": true, "history": true}
|
||||
var forgeRef = map[string]bool{"branch": true, "commit": true, "tag": true}
|
||||
var forgeGeneric = map[string]bool{"blob": true, "tree": true, "raw": true, "blame": true, "commits": true}
|
||||
|
||||
// ForgeBrowse reports whether the (decoded, lowercase, query-less) path is a
|
||||
// code forge page that shows repository content: Gitea/Forgejo
|
||||
// /{owner}/{repo}/(src|raw|blame|commits|commit|media|history)/(branch|commit|tag)/<ref>/<file>,
|
||||
// GitHub style /{owner}/{repo}/(blob|tree|raw|blame|commits)/<ref>/<file> and
|
||||
// GitLab style /{group}/{project}/-/(blob|tree|raw|blame|commits)/<ref>/<file>.
|
||||
// A file named ".env" inside a repository is content, not a probe of the host.
|
||||
// It needs an owner and a repo that are not dot names, so "/.env", "/.git/config"
|
||||
// or "/app/.env" are never forge paths. Traversal markers are checked before.
|
||||
func ForgeBrowse(path string) bool {
|
||||
if len(path) == 0 || path[0] != '/' {
|
||||
return false
|
||||
}
|
||||
seg := strings.Split(path[1:], "/")
|
||||
if len(seg) < 4 || seg[0] == "" || seg[1] == "" || seg[0][0] == '.' || seg[1][0] == '.' {
|
||||
return false
|
||||
}
|
||||
for i := 2; i+3 < len(seg); i++ { // GitLab: /group/project/-/blob/<ref>/<file>
|
||||
if seg[i] == "-" && forgeGeneric[seg[i+1]] && seg[i+2] != "" && seg[i+3] != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if seg[2] != "" && seg[3] != "" && len(seg) >= 5 && seg[4] != "" {
|
||||
if forgeGitea[seg[2]] && forgeRef[seg[3]] {
|
||||
return true // Gitea: /owner/repo/src/commit/<sha>/<file>
|
||||
}
|
||||
if forgeGeneric[seg[2]] {
|
||||
return true // GitHub: /owner/repo/blob/<ref>/<file>
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isScanner(path string, status int) bool {
|
||||
if ForgeBrowse(path) {
|
||||
return false
|
||||
}
|
||||
for _, m := range sensitive {
|
||||
if segment(path, m) {
|
||||
return true
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package core
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestForgeBrowseIsNotScanner(t *testing.T) {
|
||||
for _, p := range []string{
|
||||
"/ciberfauna/sabia/src/commit/0123abcd/.gitignore",
|
||||
"/ciberfauna/sabia/raw/commit/0123abcd/.gitignore",
|
||||
"/lucasrguerra/LambdaMail/src/commit/0123abcd/.env.example",
|
||||
"/ciberfauna/guara/blame/commit/0123abcd/.gitignore",
|
||||
"/ciberfauna/acaua/commits/commit/0123abcd/.gitignore",
|
||||
"/ciberfauna/acaua/src/branch/main/.gitignore",
|
||||
"/ciberfauna/acaua/src/tag/v1.0.0/.env.example",
|
||||
"/org/repo/blob/main/.gitignore",
|
||||
"/org/repo/tree/main/.github/workflows",
|
||||
"/group/proj/-/blob/main/.env.example",
|
||||
} {
|
||||
c := Classify("GET", p, 200)
|
||||
if c.Cat != OK {
|
||||
t.Errorf("%s: %+v", p, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestForgeBrowseKeepsRealProbes(t *testing.T) {
|
||||
for _, p := range []string{"/.env", "/.git/config", "/app/.env", "/.gitignore", "/app/.git/config", "/x/y/.env",
|
||||
"/ciberfauna/sabia/src/commit/abc/../../../.env", "/.git/src/commit/abc/x", "/a/b/src/main/.env", "/wp-config.php"} {
|
||||
if c := Classify("GET", p, 200); c.Cat == OK {
|
||||
t.Errorf("%s must stay a probe: %+v", p, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package egress
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"net/netip"
|
||||
@@ -70,7 +71,7 @@ func TestParse(t *testing.T) {
|
||||
t.Fatalf("host: %+v %v", ev, err)
|
||||
}
|
||||
// December line read in January belongs to the previous year
|
||||
dec := `Dec 31 23:59:00 h kernel: URUTAU-EGRESS: IN=a OUT=b SRC=1.2.3.4 DST=5.6.7.8 PROTO=TCP DPT=1`
|
||||
dec := `Dec 31 23:59:00 h kernel: URUTAU-EGRESS: IN=a OUT=b SRC=1.2.3.4 DST=5.6.7.8 PROTO=TCP DPT=1 SYN`
|
||||
if ev, err = ParseLine([]byte(dec), time.Date(2027, 1, 1, 0, 5, 0, 0, time.UTC)); err != nil || ev.Time.Year() != 2026 {
|
||||
t.Fatalf("year: %+v %v", ev, err)
|
||||
}
|
||||
@@ -605,3 +606,78 @@ func TestTorRelayFinding(t *testing.T) {
|
||||
t.Fatalf("tor: %+v", f)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNonSYNDropped(t *testing.T) {
|
||||
now := time.Date(2026, 11, 14, 23, 0, 0, 0, time.UTC)
|
||||
reply := `URUTAU-EGRESS: IN=br-85247344d531 OUT=enp0s6 SRC=10.0.15.3 DST=72.63.248.159 LEN=76 PROTO=TCP SPT=443 DPT=31432 WINDOW=63 RES=0x00 ACK PSH URGP=0`
|
||||
synack := `URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.15.3 DST=72.63.248.159 PROTO=TCP SPT=443 DPT=31432 RES=0x00 ACK SYN URGP=0`
|
||||
syn := `URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.15.3 DST=72.63.248.159 PROTO=TCP SPT=40000 DPT=443 RES=0x00 SYN URGP=0`
|
||||
udp := `URUTAU-EGRESS: IN=br-1 OUT=enp0s6 SRC=10.0.15.3 DST=1.1.1.1 PROTO=UDP SPT=40000 DPT=53`
|
||||
for _, l := range []string{reply, synack} {
|
||||
if _, err := ParseLine([]byte(l), now); !errors.Is(err, ErrNonSYN) {
|
||||
t.Fatalf("want ErrNonSYN: %v", err)
|
||||
}
|
||||
}
|
||||
for _, l := range []string{syn, udp} {
|
||||
if _, err := ParseLine([]byte(l), now); err != nil {
|
||||
t.Fatalf("kept line: %v", err)
|
||||
}
|
||||
}
|
||||
e := newEng(t, Config{BadDst: func(a netip.Addr) (bool, string) { return a == ip("72.63.248.159"), "attacker" }})
|
||||
e.Ingest([]byte(reply))
|
||||
e.Ingest([]byte(synack))
|
||||
e.Ingest([]byte("URUTAU-EGRESS: garbage"))
|
||||
i := e.Info()
|
||||
if i.NonSYNDropped != 2 || i.Malformed != 1 || i.Lines != 0 || len(rep(e).Findings) != 0 {
|
||||
t.Fatalf("info %+v findings %+v", i, rep(e).Findings)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBeaconMetadataAndKnownCDN(t *testing.T) {
|
||||
geo := func(s string) (string, string, string) {
|
||||
if s == "78.47.239.92" {
|
||||
return "DE", "AS24940", "Hetzner"
|
||||
}
|
||||
return "BR", "AS2", "y"
|
||||
}
|
||||
e := newEng(t, Config{Geo: geo})
|
||||
rnd := rand.New(rand.NewSource(3))
|
||||
for _, d := range []string{"23.5.1.1", "149.154.167.220", "78.47.239.92", "169.254.169.254"} {
|
||||
feedBeacon(e, "10.0.3.5", d, 80, t0, 50, 60*time.Second, 0.05, rnd)
|
||||
}
|
||||
// the host itself polling IMDS is infra; a container doing it is not
|
||||
for _, d := range []string{"fd00:c1::a9fe:a9fe", "169.254.169.254"} {
|
||||
tt := t0
|
||||
for i := 0; i < 50; i++ {
|
||||
ev := mk(tt, "10.0.0.2", d, "tcp", 80)
|
||||
ev.Host = true
|
||||
e.IngestEvent(ev)
|
||||
tt = tt.Add(60 * time.Second)
|
||||
}
|
||||
}
|
||||
containerIMDS := false
|
||||
got := map[string]Finding{}
|
||||
for _, f := range rep(e).Findings {
|
||||
if f.Dst == "169.254.169.254" && f.Kind == "beacon" && f.Severity != "info" {
|
||||
containerIMDS = true
|
||||
continue
|
||||
}
|
||||
got[f.Dst] = f
|
||||
}
|
||||
if !containerIMDS {
|
||||
t.Fatal("container polling IMDS must stay a beacon finding")
|
||||
}
|
||||
for _, d := range []string{"fd00:c1::a9fe:a9fe", "169.254.169.254"} {
|
||||
if f := got[d]; f.Kind != "infra" || f.Severity != "info" {
|
||||
t.Fatalf("%s: %+v", d, f)
|
||||
}
|
||||
}
|
||||
for _, d := range []string{"23.5.1.1", "149.154.167.220"} {
|
||||
if f := got[d]; f.Kind != "beacon" || f.Severity != "low" || !strings.Contains(f.Detail, "large CDN/cloud") {
|
||||
t.Fatalf("%s: %+v", d, f)
|
||||
}
|
||||
}
|
||||
if f := got["78.47.239.92"]; f.Kind != "beacon" || f.Severity != "medium" {
|
||||
t.Fatalf("surbl: %+v", f)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package egress
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/fnv"
|
||||
"math"
|
||||
@@ -223,9 +224,9 @@ type Engine struct {
|
||||
closed []BurstOut
|
||||
maxT int64
|
||||
|
||||
lines, malformed atomic.Uint64
|
||||
last atomic.Int64
|
||||
stateFn atomic.Pointer[func() string]
|
||||
lines, malformed, nonSYN atomic.Uint64
|
||||
last atomic.Int64
|
||||
stateFn atomic.Pointer[func() string]
|
||||
}
|
||||
|
||||
// New builds an engine.
|
||||
@@ -356,6 +357,10 @@ func (e *Engine) reloadMap() {
|
||||
func (e *Engine) Ingest(line []byte) {
|
||||
ev, err := ParseLine(line, e.now())
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrNonSYN) {
|
||||
e.nonSYN.Add(1)
|
||||
return
|
||||
}
|
||||
if len(line) > 0 {
|
||||
e.malformed.Add(1)
|
||||
}
|
||||
@@ -761,6 +766,9 @@ func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairSta
|
||||
}
|
||||
}
|
||||
}
|
||||
if ev.Host && isCloudMetadata(ev.Dst) {
|
||||
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 {
|
||||
@@ -827,16 +835,23 @@ func (e *Engine) beacon(ws *wstate, ev Event, dport uint16, dns bool, p *pairSta
|
||||
bad, sev, why = true, "high", why+"; destination: "+r
|
||||
}
|
||||
}
|
||||
if !bad && e.cfg.Geo != nil {
|
||||
if !bad && ev.Host && isCloudMetadata(ev.Dst) {
|
||||
// only the host itself: a container reaching IMDS stays a finding (SSRF/credential theft)
|
||||
sev, kind = "info", "infra"
|
||||
why += "; provider service (cloud metadata)"
|
||||
} else 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]:
|
||||
case commonCloudASNs[asn] || inCommonCDN(ev.Dst):
|
||||
sev = "low"
|
||||
why += "; large CDN/cloud network: regular connections are common for API calls"
|
||||
}
|
||||
} else if !bad && inCommonCDN(ev.Dst) {
|
||||
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(kind, sev, ws.name, ev.Dst.String(), dport, ev.Proto, p.last, med, jit, why, 0)
|
||||
@@ -851,7 +866,40 @@ 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}
|
||||
var commonCloudASNs = map[string]bool{"AS13335": true, "AS15169": true, "AS14618": true, "AS16509": true, "AS8075": true, "AS20940": true, "AS54113": true,
|
||||
"AS16625": true, // Akamai
|
||||
"AS62041": true, // Telegram
|
||||
}
|
||||
|
||||
// commonCDNPrefixes back the ASN list when the geo database has no entry:
|
||||
// Akamai and the Telegram API.
|
||||
var commonCDNPrefixes = mustPrefixes("23.0.0.0/12", "104.64.0.0/10", "184.24.0.0/13", "2.16.0.0/13",
|
||||
"149.154.160.0/20", "91.108.0.0/16")
|
||||
|
||||
// cloudMetadata are the metadata services of the clouds (IMDS), IPv4 and
|
||||
// IPv6; link-local addresses are included.
|
||||
var cloudMetadata = mustPrefixes("169.254.0.0/16", "fe80::/10", "fd00:c1::a9fe:a9fe/128", "fd00:ec2::254/128")
|
||||
|
||||
func mustPrefixes(s ...string) []netip.Prefix {
|
||||
out := make([]netip.Prefix, len(s))
|
||||
for i, v := range s {
|
||||
out[i] = netip.MustParsePrefix(v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func inPrefixes(a netip.Addr, ps []netip.Prefix) bool {
|
||||
a = a.Unmap()
|
||||
for _, p := range ps {
|
||||
if p.Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func inCommonCDN(a netip.Addr) bool { return inPrefixes(a, commonCDNPrefixes) }
|
||||
func isCloudMetadata(a netip.Addr) bool { return inPrefixes(a, cloudMetadata) }
|
||||
|
||||
func (e *Engine) providerASN(asn string) bool {
|
||||
if asn == "" {
|
||||
|
||||
@@ -25,16 +25,28 @@ type Event struct {
|
||||
SPort, DPort uint16
|
||||
In, Out string
|
||||
Host bool // IN= empty: output of the host itself
|
||||
// SYN and ACK are the TCP flags present in the log line.
|
||||
SYN, ACK bool
|
||||
}
|
||||
|
||||
// ErrNotEgress marks a line that is not an egress log line.
|
||||
var ErrNotEgress = errors.New("not an egress line")
|
||||
|
||||
// ErrNonSYN marks a TCP egress line that is not a connection attempt (no SYN,
|
||||
// or SYN+ACK): replies of a flow whose conntrack entry was recreated in the
|
||||
// middle (nf_conntrack_tcp_loose), logged by an old kit that did not filter
|
||||
// on the SYN flag.
|
||||
var ErrNonSYN = errors.New("tcp line without a pure SYN")
|
||||
|
||||
// ParseLine parses a kernel/rsyslog line. now is only used to infer the year
|
||||
// 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)
|
||||
ev, err := ParseKernel(b, marker, now)
|
||||
if err == nil && ev.Proto == "tcp" && (!ev.SYN || ev.ACK) {
|
||||
return ev, ErrNonSYN
|
||||
}
|
||||
return ev, err
|
||||
}
|
||||
|
||||
// ParseKernel parses an nftables log line carrying the given prefix marker
|
||||
@@ -51,6 +63,12 @@ func ParseKernel(b []byte, marker string, now time.Time) (Event, error) {
|
||||
for _, f := range strings.Fields(line[i+len(marker):]) {
|
||||
k, v, ok := strings.Cut(f, "=")
|
||||
if !ok {
|
||||
switch f {
|
||||
case "SYN":
|
||||
ev.SYN = true
|
||||
case "ACK":
|
||||
ev.ACK = true
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch k {
|
||||
|
||||
@@ -22,6 +22,10 @@ type Finding struct {
|
||||
Last int64 `json:"last"`
|
||||
Detail string `json:"detail"`
|
||||
Host string `json:"host,omitempty"`
|
||||
// Ticket fields are filled by the server from the incident store.
|
||||
TicketID string `json:"ticket_id"`
|
||||
TicketStatus string `json:"ticket_status"`
|
||||
Suppressed bool `json:"suppressed"`
|
||||
// Samples are the unix times of the last connections (beacons only, at most MaxSamples).
|
||||
Samples []int64 `json:"samples,omitempty"`
|
||||
}
|
||||
@@ -286,6 +290,15 @@ func clip(s string) string {
|
||||
}
|
||||
|
||||
// Sanitize bounds an untrusted peer report and stamps it with the peer name.
|
||||
// KnownKind reports whether k is a finding kind produced by the engine.
|
||||
func KnownKind(k string) bool {
|
||||
switch k {
|
||||
case "scan", "bad_dst", "tor", "port", "dns_bypass", "new_geo", "beacon", "infra":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (r *Report) Sanitize(host string) {
|
||||
if len(r.Workloads) > maxPeerWorkloads {
|
||||
r.Workloads = r.Workloads[:maxPeerWorkloads]
|
||||
@@ -303,6 +316,14 @@ func (r *Report) Sanitize(host string) {
|
||||
w := &r.Workloads[i]
|
||||
w.Name, w.Role, w.Host = clip(w.Name), clip(w.Role), host
|
||||
}
|
||||
// a peer may send only the kinds this package produces; the rest is dropped
|
||||
kept := r.Findings[:0]
|
||||
for _, f := range r.Findings {
|
||||
if KnownKind(f.Kind) {
|
||||
kept = append(kept, f)
|
||||
}
|
||||
}
|
||||
r.Findings = kept
|
||||
for i := range r.Findings {
|
||||
f := &r.Findings[i]
|
||||
f.ID, f.Kind, f.Severity = host+":"+clip(f.ID), clip(f.Kind), clip(f.Severity)
|
||||
|
||||
@@ -96,7 +96,9 @@ type SourceInfo struct {
|
||||
State string `json:"state"`
|
||||
Lines uint64 `json:"lines"`
|
||||
Malformed uint64 `json:"malformed"`
|
||||
Last int64 `json:"last"`
|
||||
// NonSYNDropped counts TCP lines without a pure SYN (old kit); not malformed.
|
||||
NonSYNDropped uint64 `json:"non_syn_dropped"`
|
||||
Last int64 `json:"last"`
|
||||
}
|
||||
|
||||
// Info reports the source state (state "disabled" when no source is attached).
|
||||
@@ -106,5 +108,5 @@ func (e *Engine) Info() SourceInfo {
|
||||
if f := e.stateFn.Load(); f != nil {
|
||||
st = (*f)()
|
||||
}
|
||||
return SourceInfo{State: st, Lines: l, Malformed: m, Last: last}
|
||||
return SourceInfo{State: st, Lines: l, Malformed: m, NonSYNDropped: e.nonSYN.Load(), Last: last}
|
||||
}
|
||||
@@ -254,7 +254,7 @@ func TestEngineSSH(t *testing.T) {
|
||||
func TestEngineRateCapAndObserve(t *testing.T) {
|
||||
r := newRig(t, ModeOn, func(c *Config) { c.MaxPerMin = 3 })
|
||||
for i := 0; i < 6; i++ {
|
||||
r.hits(fmt.Sprintf("203.0.114.%d", 50+i), 5, "/x", 404)
|
||||
r.hits(fmt.Sprintf("203.0.%d.50", 114+i), 5, "/x", 404) // one /24 each: no neighbor rule
|
||||
}
|
||||
rep := r.e.Report(0)
|
||||
if len(r.lines(t)) != 3 || rep.Counts.Written != 3 || rep.Counts.DroppedRate != 3 || rep.Counts.Decided != 6 {
|
||||
|
||||
+143
-32
@@ -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
|
||||
@@ -34,7 +35,7 @@ type Config struct {
|
||||
|
||||
// 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
|
||||
Tally func(ip string, from int64) Tally // counts of one address (24 h and 7 days)
|
||||
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
|
||||
@@ -42,20 +43,24 @@ type Config struct {
|
||||
|
||||
// Seen is one address with malicious activity, as listed by Config.Roster.
|
||||
type Seen struct {
|
||||
IP string
|
||||
Score float64
|
||||
Level core.Level
|
||||
Jails []string
|
||||
IP string
|
||||
Score float64
|
||||
Level core.Level
|
||||
Jails []string
|
||||
Est Tally // estimate from per-day counters, used when the registry holds less
|
||||
Events int // malicious events recorded for the address
|
||||
Last int64 // unix of its last event
|
||||
}
|
||||
|
||||
// Tally counts malicious events of one address in LongWindow.
|
||||
type Tally struct{ SSH, Web int }
|
||||
// Tally counts malicious events of one address: SSH, Web and Probe in the last
|
||||
// 24 h, SSH7, Web7 and Probe7 in the last 7 days (Probe: ssh-probe events).
|
||||
type Tally struct{ SSH, Web, Probe, SSH7, Web7, Probe7 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
|
||||
ssh, web, probe, ssh7, web7, probe7 int
|
||||
at int64 // when loaded from the registry
|
||||
known bool
|
||||
fresh bool // just loaded: the current event is already counted
|
||||
}
|
||||
|
||||
type cand struct {
|
||||
@@ -108,6 +113,12 @@ type Coverage struct {
|
||||
BlockedByUrutau int `json:"blocked_by_urutau"`
|
||||
WouldBlock int `json:"would_block"`
|
||||
Unblocked int `json:"unblocked"`
|
||||
// OneShot attackers made a single event: impossible to block reactively.
|
||||
OneShot int `json:"one_shot"`
|
||||
// Repeat attackers made two or more events; RepeatUnblocked is how many of
|
||||
// them nothing blocks (neither fail2ban, Urutau nor a would-ban).
|
||||
Repeat int `json:"repeat_ips"`
|
||||
RepeatUnblocked int `json:"repeat_unblocked"`
|
||||
}
|
||||
|
||||
// Report is what the API serves (mode and file status are added by the handler).
|
||||
@@ -125,6 +136,7 @@ type aevt struct {
|
||||
type ipState struct {
|
||||
ev []aevt
|
||||
ssh []int64
|
||||
sshp []int64 // ssh-probe events in Window
|
||||
probes map[uint32]int64 // proto<<16|port -> last seen (unix)
|
||||
legit int64
|
||||
uas []string
|
||||
@@ -157,15 +169,18 @@ const (
|
||||
maxPeerTTL = 6 * time.Hour
|
||||
peerConfirmAge = 7 * 24 * time.Hour
|
||||
maxTracked = 50000 // would and bans
|
||||
maxNbr = 20000 // prefixes of the neighbor rule
|
||||
saveEvery = 30 * time.Second
|
||||
)
|
||||
|
||||
// Engine is the second firewall.
|
||||
type Engine struct {
|
||||
cfg Config
|
||||
log *logFile
|
||||
ch chan item
|
||||
dropQ atomic.Int64
|
||||
cfg Config
|
||||
log *logFile
|
||||
ch chan item
|
||||
dropQ atomic.Int64
|
||||
sweeping atomic.Bool
|
||||
unlog *logFile
|
||||
|
||||
mu sync.Mutex
|
||||
ips map[netip.Addr]*ipState
|
||||
@@ -182,6 +197,9 @@ type Engine struct {
|
||||
lastSave time.Time
|
||||
hostIPs map[string][]netip.Addr // last good resolution per host
|
||||
long map[netip.Addr]*longRec
|
||||
nbr map[netip.Prefix]map[netip.Addr]int64 // banned addresses per /24 or /64 (unix of the ban)
|
||||
allows map[netip.Addr]int64 // operator allowances: address -> until (unix)
|
||||
unbans []UnbanWire
|
||||
queue []cand
|
||||
}
|
||||
|
||||
@@ -206,7 +224,8 @@ func New(c Config) *Engine {
|
||||
}
|
||||
e := &Engine{cfg: c, log: &logFile{path: c.Path}, ch: make(chan item, 4096), ips: map[netip.Addr]*ipState{},
|
||||
bans: map[netip.Addr]banRec{}, would: map[netip.Addr]int64{}, skipSeen: map[netip.Addr]int64{},
|
||||
counts: Counts{Skipped: map[string]int{}}, long: map[netip.Addr]*longRec{}}
|
||||
counts: Counts{Skipped: map[string]int{}}, long: map[netip.Addr]*longRec{}, nbr: map[netip.Prefix]map[netip.Addr]int64{}, 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()
|
||||
@@ -233,7 +252,7 @@ func (e *Engine) LogPath() string { return e.cfg.Path }
|
||||
// event and counts it.
|
||||
func (e *Engine) Observe(ev core.Event, fam string) {
|
||||
switch ev.Cat {
|
||||
case core.Ban, core.SSHFail, core.Scanner, core.Exploit, core.BruteForce:
|
||||
case core.Ban, core.SSHFail, core.SSHProbe, core.Scanner, core.Exploit, core.BruteForce:
|
||||
case core.OK:
|
||||
if ev.FetchDest != "document" || ev.Status < 200 || ev.Status > 299 {
|
||||
return
|
||||
@@ -268,13 +287,13 @@ func (e *Engine) Run(ctx context.Context) {
|
||||
e.handle(it.ev, it.fam)
|
||||
case <-sweepT.C:
|
||||
if swept {
|
||||
e.Sweep()
|
||||
go e.Sweep()
|
||||
}
|
||||
case <-flush.C:
|
||||
e.maybeSave()
|
||||
if !swept && e.cfg.Now().Sub(started) >= 20*time.Second && (e.cfg.Ready == nil || e.cfg.Ready()) {
|
||||
swept = true
|
||||
e.Sweep()
|
||||
go e.Sweep()
|
||||
}
|
||||
e.drain()
|
||||
case <-peers.C:
|
||||
@@ -422,6 +441,7 @@ func (e *Engine) process(ev core.Event, fam string) {
|
||||
st.banned = max(st.banned, ev.Time.Add(banAssume).Unix())
|
||||
st.f2bAt = max(st.f2bAt, ts)
|
||||
}
|
||||
e.noteBan(a, ts, now)
|
||||
}
|
||||
return
|
||||
case LegitVisit(ev):
|
||||
@@ -429,7 +449,7 @@ func (e *Engine) process(ev core.Event, fam string) {
|
||||
e.stateOf(a).legit = max(e.stateOf(a).legit, ts)
|
||||
}
|
||||
return
|
||||
case ev.Cat == core.SSHFail:
|
||||
case ev.Cat == core.SSHFail, ev.Cat == core.SSHProbe:
|
||||
case ev.Source == "probe" && ev.Cat == core.Scanner:
|
||||
e.processProbe(a, ev, now)
|
||||
return
|
||||
@@ -447,9 +467,12 @@ func (e *Engine) process(ev core.Event, fam string) {
|
||||
}
|
||||
cut := now.Add(-Window).Unix()
|
||||
slug, crit := attackSlug(ev, fam)
|
||||
if ev.Cat == core.SSHFail {
|
||||
switch {
|
||||
case ev.Cat == core.SSHFail:
|
||||
st.ssh = prune(append(st.ssh, ts), cut)
|
||||
} else {
|
||||
case ev.Cat == core.SSHProbe:
|
||||
st.sshp = prune(append(st.sshp, ts), cut)
|
||||
default:
|
||||
st.ev = append(st.ev, aevt{ts, slug})
|
||||
k := 0
|
||||
for _, x := range st.ev {
|
||||
@@ -482,8 +505,13 @@ func (e *Engine) process(ev core.Event, fam string) {
|
||||
lr.fresh = false
|
||||
} else if ev.Cat == core.SSHFail {
|
||||
lr.ssh++
|
||||
lr.ssh7++
|
||||
} else if ev.Cat == core.SSHProbe {
|
||||
lr.probe++
|
||||
lr.probe7++
|
||||
} else {
|
||||
lr.web++
|
||||
lr.web7++
|
||||
}
|
||||
}
|
||||
crits := 0
|
||||
@@ -492,17 +520,19 @@ func (e *Engine) process(ev core.Event, fam string) {
|
||||
crits++
|
||||
}
|
||||
}
|
||||
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)}
|
||||
in := Input{Now: now, Attacks: len(st.ev), Top: topSlug(st.ev), SSHFails: len(st.ssh), SSHProbes: len(st.sshp), Crits: crits,
|
||||
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
|
||||
in.Known, in.SSH24, in.Web24, in.Probe24 = lr.known, lr.ssh, lr.web, lr.probe
|
||||
in.SSH7, in.Web7, in.Probe7 = lr.ssh7, lr.web7, lr.probe7
|
||||
}
|
||||
in.Neighbor = e.neighborBanned(a, now) >= NeighborIPs
|
||||
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) {
|
||||
if d.Action == ActBan && e.cfg.Crawler != nil && e.cfg.Crawler(a.String(), st.uas) {
|
||||
in.Exclude = SkipCrawler
|
||||
d = Decide(in, Params{Threshold: e.cfg.Threshold})
|
||||
}
|
||||
@@ -617,11 +647,74 @@ func (e *Engine) apply(a netip.Addr, st *ipState, d Decision, src string, now ti
|
||||
b.Until, b.Last = now.Add(d.TTL).Unix(), now.Unix()
|
||||
e.bans[a] = b
|
||||
st.urutauAt = now.Unix()
|
||||
e.noteBan(a, now.Unix(), now)
|
||||
e.dirty = true
|
||||
e.addRecent(a, r)
|
||||
}
|
||||
}
|
||||
|
||||
// noteBan remembers a ban of a (by any jail or by this engine) for the neighbor
|
||||
// rule; the lock is held. Memory is bounded: expired entries go, and the table is
|
||||
// reset past maxNbr prefixes.
|
||||
func (e *Engine) noteBan(a netip.Addr, ts int64, now time.Time) {
|
||||
p, ok := neighborPrefix(a)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if len(e.nbr) >= maxNbr {
|
||||
cut := now.Add(-NeighborWindow).Unix()
|
||||
for k, m := range e.nbr {
|
||||
for ip, t := range m {
|
||||
if t < cut {
|
||||
delete(m, ip)
|
||||
}
|
||||
}
|
||||
if len(m) == 0 {
|
||||
delete(e.nbr, k)
|
||||
}
|
||||
}
|
||||
if len(e.nbr) >= maxNbr {
|
||||
e.nbr = map[netip.Prefix]map[netip.Addr]int64{}
|
||||
}
|
||||
}
|
||||
m := e.nbr[p]
|
||||
if m == nil {
|
||||
m = map[netip.Addr]int64{}
|
||||
e.nbr[p] = m
|
||||
}
|
||||
if len(m) < 256 || m[a] > 0 {
|
||||
m[a] = max(m[a], ts)
|
||||
}
|
||||
}
|
||||
|
||||
// neighborBanned counts the addresses other than a banned in the last
|
||||
// NeighborWindow in a's /24 (v4) or /64 (v6); the lock is held.
|
||||
func (e *Engine) neighborBanned(a netip.Addr, now time.Time) int {
|
||||
p, ok := neighborPrefix(a)
|
||||
if !ok {
|
||||
return 0
|
||||
}
|
||||
cut := now.Add(-NeighborWindow).Unix()
|
||||
n := 0
|
||||
for ip, t := range e.nbr[p] {
|
||||
if ip != a && t >= cut {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// neighborPrefix is the /24 (IPv4) or /64 (IPv6) of a.
|
||||
func neighborPrefix(a netip.Addr) (netip.Prefix, bool) {
|
||||
a = a.Unmap()
|
||||
bits := 64
|
||||
if a.Is4() {
|
||||
bits = 24
|
||||
}
|
||||
p, err := a.Prefix(bits)
|
||||
return p, err == nil
|
||||
}
|
||||
|
||||
func (e *Engine) addRecent(a netip.Addr, r Recent) {
|
||||
if e.cfg.Geo != nil {
|
||||
r.CC, r.ASN, r.Org = e.cfg.Geo(a.String())
|
||||
@@ -668,7 +761,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
|
||||
}
|
||||
@@ -703,6 +796,7 @@ func (e *Engine) Report(from int64) Report {
|
||||
continue
|
||||
}
|
||||
cv.AttackIPs++
|
||||
blocked := true
|
||||
switch {
|
||||
case st.f2bAt > 0 && st.f2bAt >= from:
|
||||
cv.BlockedByFirewall++
|
||||
@@ -712,10 +806,15 @@ func (e *Engine) Report(from int64) Report {
|
||||
cv.WouldBlock++
|
||||
default:
|
||||
cv.Unblocked++
|
||||
blocked = false
|
||||
}
|
||||
cv.Repeat++ // without the registry only repeated attackers are known
|
||||
if !blocked {
|
||||
cv.RepeatUnblocked++
|
||||
}
|
||||
}
|
||||
c := e.counts
|
||||
c.Skipped = map[string]int{SkipTrusted: 0, SkipPrivate: 0, SkipCrawler: 0, SkipLegit: 0, SkipPeer: 0, SkipInfra: 0, SkipUnconfirmed: 0}
|
||||
c.Skipped = map[string]int{SkipOperator: 0, SkipTrusted: 0, SkipPrivate: 0, SkipCrawler: 0, SkipLegit: 0, SkipPeer: 0, SkipInfra: 0, SkipUnconfirmed: 0}
|
||||
for k, v := range e.counts.Skipped {
|
||||
c.Skipped[k] = v
|
||||
}
|
||||
@@ -730,8 +829,9 @@ func (e *Engine) Report(from int64) Report {
|
||||
}
|
||||
|
||||
type stateFile struct {
|
||||
V int `json:"v"`
|
||||
Bans map[string]banRec `json:"bans"`
|
||||
V int `json:"v"`
|
||||
Bans map[string]banRec `json:"bans"`
|
||||
Allows map[string]int64 `json:"allows,omitempty"`
|
||||
}
|
||||
|
||||
func (e *Engine) loadState() {
|
||||
@@ -752,6 +852,12 @@ func (e *Engine) loadState() {
|
||||
e.bans[a.Unmap()] = v
|
||||
}
|
||||
}
|
||||
nowU := e.cfg.Now().Unix()
|
||||
for k, u := range sf.Allows {
|
||||
if a, err := netip.ParseAddr(k); err == nil && u > nowU && u <= nowU+MaxAllow {
|
||||
e.allows[a.Unmap()] = u
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// maybeSave writes the state at most every saveEvery.
|
||||
@@ -774,10 +880,15 @@ func (e *Engine) saveState() {
|
||||
}
|
||||
e.lastSave = e.cfg.Now()
|
||||
e.trimMaps(e.lastSave)
|
||||
sf := stateFile{V: 1, Bans: map[string]banRec{}}
|
||||
sf := stateFile{V: 1, Bans: map[string]banRec{}, Allows: map[string]int64{}}
|
||||
for a, b := range e.bans {
|
||||
sf.Bans[a.String()] = b
|
||||
}
|
||||
for a, u := range e.allows {
|
||||
if u > e.lastSave.Unix() {
|
||||
sf.Allows[a.String()] = u
|
||||
}
|
||||
}
|
||||
e.dirty = false
|
||||
e.mu.Unlock()
|
||||
b, _ := json.Marshal(sf)
|
||||
@@ -818,7 +929,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)
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func (e *Engine) prefetch(ev core.Event) {
|
||||
if e.cfg.Rep == nil && e.cfg.Tally == nil {
|
||||
return
|
||||
}
|
||||
if ev.Cat != core.SSHFail && !CountsAsAttack(ev) {
|
||||
if ev.Cat != core.SSHFail && ev.Cat != core.SSHProbe && !CountsAsAttack(ev) {
|
||||
return
|
||||
}
|
||||
a, err := netip.ParseAddr(ev.IP)
|
||||
@@ -59,9 +59,9 @@ func (e *Engine) prefetch(ev core.Event) {
|
||||
known = IsKnown(sc, lv)
|
||||
}
|
||||
}
|
||||
var ssh, web int
|
||||
var tl Tally
|
||||
if stale && e.cfg.Tally != nil {
|
||||
ssh, web = e.cfg.Tally(a.String(), now.Add(-LongWindow).Unix())
|
||||
tl = e.cfg.Tally(a.String(), now.Add(-WeekWindow).Unix())
|
||||
}
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
@@ -83,7 +83,8 @@ func (e *Engine) prefetch(ev core.Event) {
|
||||
}
|
||||
lr.known = known
|
||||
if stale {
|
||||
lr.ssh, lr.web, lr.at, lr.fresh = ssh, web, now.Unix(), true
|
||||
lr.ssh, lr.web, lr.probe, lr.ssh7, lr.web7, lr.probe7 = tl.SSH, tl.Web, tl.Probe, max(tl.SSH7, tl.SSH), max(tl.Web7, tl.Web), max(tl.Probe7, tl.Probe)
|
||||
lr.at, lr.fresh = now.Unix(), true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,8 +95,12 @@ 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()
|
||||
from := now.Add(-WeekWindow).Unix()
|
||||
roster := e.cfg.Roster(from)
|
||||
var tallies map[string]Tally
|
||||
if e.cfg.Tallies != nil {
|
||||
@@ -116,11 +121,14 @@ func (e *Engine) Sweep() {
|
||||
a = a.Unmap().WithZone("")
|
||||
st := e.stateOf(a)
|
||||
t := tallies[a.String()]
|
||||
in := Input{Now: now, Known: IsKnown(r.Score, r.Level), SSH24: t.SSH, Web24: t.Web,
|
||||
t = Tally{max(t.SSH, r.Est.SSH), max(t.Web, r.Est.Web), max(t.Probe, r.Est.Probe),
|
||||
max(t.SSH7, r.Est.SSH7, t.SSH), max(t.Web7, r.Est.Web7, t.Web), max(t.Probe7, r.Est.Probe7, t.Probe)}
|
||||
in := Input{Now: now, Known: IsKnown(r.Score, r.Level), SSH24: t.SSH, Web24: t.Web, Probe24: t.Probe,
|
||||
SSH7: t.SSH7, Web7: t.Web7, Probe7: t.Probe7, Neighbor: e.neighborBanned(a, now) >= NeighborIPs && r.Last >= now.Add(-LongWindow).Unix() && r.Last > 0,
|
||||
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) {
|
||||
if d.Action == ActBan && e.cfg.Crawler != nil && e.cfg.Crawler(a.String(), st.uas) {
|
||||
in.Exclude = SkipCrawler
|
||||
d = Decide(in, Params{Threshold: e.cfg.Threshold})
|
||||
}
|
||||
@@ -182,6 +190,12 @@ func (e *Engine) coverageOf(roster []Seen, from int64) Coverage {
|
||||
ours = true
|
||||
}
|
||||
st := e.ips[a]
|
||||
repeat := r.Events >= 2
|
||||
if repeat {
|
||||
cv.Repeat++
|
||||
} else {
|
||||
cv.OneShot++
|
||||
}
|
||||
switch {
|
||||
case f2b:
|
||||
cv.BlockedByFirewall++
|
||||
@@ -191,6 +205,9 @@ func (e *Engine) coverageOf(roster []Seen, from int64) Coverage {
|
||||
cv.WouldBlock++
|
||||
default:
|
||||
cv.Unblocked++
|
||||
if repeat {
|
||||
cv.RepeatUnblocked++
|
||||
}
|
||||
}
|
||||
}
|
||||
return cv
|
||||
|
||||
@@ -2,6 +2,9 @@ package enforce
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -58,7 +61,7 @@ func contains(s, sub string) bool {
|
||||
|
||||
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
|
||||
c.Tally = func(ip string, from int64) Tally { return Tally{SSH: 9} } // 9 already in the registry
|
||||
})
|
||||
r.e.handle(sshEv("203.0.114.60", r.now), "")
|
||||
if len(r.lines(t)) != 0 {
|
||||
@@ -74,7 +77,7 @@ func TestSlowSSH24h(t *testing.T) {
|
||||
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.Tally = func(string, int64) Tally { return Tally{SSH: 500, Web: 500} }
|
||||
c.Roster = func(int64) []Seen {
|
||||
return []Seen{{IP: "168.196.85.9", Score: 200, Level: core.LevelHostile}}
|
||||
}
|
||||
@@ -177,3 +180,54 @@ func itoa(n int) string {
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestOperatorAllowBlocksBansAndExpires(t *testing.T) {
|
||||
r := histRig(t, func(c *Config) { c.UnbanPath = filepath.Join(t.TempDir(), "u", "unban.log") })
|
||||
ip := netip.MustParseAddr("203.0.114.80")
|
||||
r.hits(ip.String(), 5, "/x", 404)
|
||||
if len(r.lines(t)) != 1 {
|
||||
t.Fatalf("expected a ban: %v", r.lines(t))
|
||||
}
|
||||
if err := r.e.Unban(ip, 3600, "local"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(r.e.UnbanLogPath()); !strings.HasSuffix(string(b), " urutau unban ip=203.0.114.80 allow=3600\n") {
|
||||
t.Fatalf("file %q", b)
|
||||
}
|
||||
r.now = r.now.Add(time.Minute)
|
||||
r.hits(ip.String(), 8, "/y", 404)
|
||||
if len(r.lines(t)) != 1 {
|
||||
t.Fatalf("allowed address was banned: %v", r.lines(t))
|
||||
}
|
||||
if r.e.counts.Skipped[SkipOperator] == 0 {
|
||||
t.Fatal("skip not counted")
|
||||
}
|
||||
// survives a restart
|
||||
e2 := New(Config{Mode: ModeOn, Path: r.log, StatePath: r.e.cfg.StatePath, Now: func() time.Time { return r.now }})
|
||||
if len(e2.Allows()) != 1 {
|
||||
t.Fatal("allow not persisted")
|
||||
}
|
||||
// expires by itself
|
||||
r.now = r.now.Add(2 * time.Hour)
|
||||
if len(r.e.Allows()) != 0 {
|
||||
t.Fatal("allow did not expire")
|
||||
}
|
||||
r.hits(ip.String(), 8, "/z", 404)
|
||||
if len(r.lines(t)) != 2 {
|
||||
t.Fatalf("not banned after expiry: %v", r.lines(t))
|
||||
}
|
||||
// ending early lets the engine decide again
|
||||
r.e.Unban(ip, 3600, "local")
|
||||
if !r.e.EndAllow(ip) || r.e.EndAllow(ip) {
|
||||
t.Fatal("EndAllow")
|
||||
}
|
||||
if got := r.e.UnbansSince(0); len(got) != 2 || got[0].IP != ip.String() {
|
||||
t.Fatalf("unbans for peers: %v", got)
|
||||
}
|
||||
if rep := r.e.Report(0); rep.Recent[0].Action != "unban" {
|
||||
t.Fatalf("recent: %+v", rep.Recent[0])
|
||||
}
|
||||
if err := New(Config{Mode: ModeOn, Path: r.log}).Unban(ip, 0, "local"); err != ErrNoUnbanLog {
|
||||
t.Fatalf("no file: %v", err)
|
||||
}
|
||||
}
|
||||
+57
-26
@@ -35,13 +35,16 @@ const (
|
||||
ReasonLog4Shell = "log4shell"
|
||||
ReasonPortScan = "port-scan"
|
||||
ReasonKnownAttacker = "known-attacker"
|
||||
// ReasonNeighbor: another address of a /24 (v4) or /64 (v6) where several
|
||||
// addresses were banned in the last 24 h attacked again.
|
||||
ReasonNeighbor = "neighbor-campaign"
|
||||
)
|
||||
|
||||
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, ReasonKnownAttacker: true,
|
||||
ReasonPortScan: true, ReasonKnownAttacker: true, ReasonNeighbor: true,
|
||||
}
|
||||
|
||||
// ValidReason reports whether s is one of the fixed slugs.
|
||||
@@ -72,6 +75,17 @@ const (
|
||||
SSH24Threshold = 10
|
||||
Web24Threshold = 20
|
||||
LongWindow = 24 * time.Hour
|
||||
// WeekWindow is the slow-attacker window: SSH7Threshold SSH failures (an
|
||||
// ssh-probe counts half), or Web7Threshold web scan/exploit events without a
|
||||
// legitimate visit, in 7 days justify a ban.
|
||||
WeekWindow = 7 * 24 * time.Hour
|
||||
SSH7Threshold = 10
|
||||
Web7Threshold = 10
|
||||
// ProbeWeight is the weight of one ssh-probe against the SSH rules (in halves).
|
||||
// NeighborIPs distinct banned addresses of one prefix in NeighborWindow make
|
||||
// the prefix a campaign: one attack event of another address of it is enough.
|
||||
NeighborIPs = 3
|
||||
NeighborWindow = 24 * time.Hour
|
||||
// KnownSuspiciousScore: a "suspicious" address at or above this score counts as a known attacker.
|
||||
KnownSuspiciousScore = 100
|
||||
)
|
||||
@@ -92,11 +106,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"
|
||||
)
|
||||
@@ -112,23 +127,32 @@ const (
|
||||
|
||||
// Input is everything Decide needs about one address.
|
||||
type Input struct {
|
||||
Now time.Time
|
||||
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
|
||||
Exclude string // Excluded() result or "crawler"
|
||||
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
|
||||
Now time.Time
|
||||
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
|
||||
SSHProbes int // ssh-probe events in the window (each counts half a failure)
|
||||
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
|
||||
Exclude string // Excluded() result or "crawler"
|
||||
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
|
||||
Probe24 int // ssh-probe events in LongWindow
|
||||
SSH7 int // failed SSH logins in WeekWindow
|
||||
Probe7 int // ssh-probe events in WeekWindow
|
||||
Web7 int // web scan/exploit events in WeekWindow
|
||||
Neighbor bool // an attack event just seen, in a prefix with NeighborIPs banned addresses
|
||||
}
|
||||
|
||||
// sshEff is failures plus half the probes.
|
||||
func sshEff(fails, probes int) int { return fails + probes/2 }
|
||||
|
||||
// Params are the thresholds.
|
||||
type Params struct{ Threshold int }
|
||||
|
||||
@@ -155,8 +179,9 @@ func Decide(in Input, p Params) Decision {
|
||||
switch {
|
||||
case in.Crit != "" && in.Crits >= CritHits:
|
||||
reason, score = in.Crit, 90
|
||||
case in.SSHFails >= sshTh:
|
||||
reason, score = ReasonSSHBrute, min(100, 60+(in.SSHFails-sshTh)*5)
|
||||
case sshEff(in.SSHFails, in.SSHProbes) >= sshTh:
|
||||
n := sshEff(in.SSHFails, in.SSHProbes)
|
||||
reason, score = ReasonSSHBrute, min(100, 60+(n-sshTh)*5)
|
||||
case in.Probes >= PortScanPorts:
|
||||
reason, score = ReasonPortScan, min(100, 60+(in.Probes-PortScanPorts)*3)
|
||||
case in.Attacks >= th:
|
||||
@@ -164,12 +189,18 @@ func Decide(in Input, p Params) Decision {
|
||||
if !ValidReason(reason) {
|
||||
reason = ReasonScannerFlood
|
||||
}
|
||||
case in.Neighbor && !in.Legit:
|
||||
reason, score = ReasonNeighbor, 70
|
||||
case in.Known:
|
||||
reason, score = ReasonKnownAttacker, 80
|
||||
case in.SSH24 >= SSH24Threshold:
|
||||
reason, score = ReasonSSHBrute, min(100, 60+(in.SSH24-SSH24Threshold))
|
||||
case sshEff(in.SSH24, in.Probe24) >= SSH24Threshold:
|
||||
reason, score = ReasonSSHBrute, min(100, 60+(sshEff(in.SSH24, in.Probe24)-SSH24Threshold))
|
||||
case in.Web24 >= Web24Threshold:
|
||||
reason, score = ReasonScannerFlood, min(100, 55+(in.Web24-Web24Threshold)/2)
|
||||
case sshEff(in.SSH7, in.Probe7) >= SSH7Threshold:
|
||||
reason, score = ReasonSSHBrute, min(100, 60+(sshEff(in.SSH7, in.Probe7)-SSH7Threshold)/2)
|
||||
case in.Web7 >= Web7Threshold && !in.Legit:
|
||||
reason, score = ReasonScannerFlood, min(100, 55+(in.Web7-Web7Threshold)/2)
|
||||
default:
|
||||
return Decision{}
|
||||
}
|
||||
@@ -263,7 +294,7 @@ func (x Exclusions) Excluded(a netip.Addr) string {
|
||||
|
||||
// attackSlug is the reason slug of one attack event, and whether it is critical.
|
||||
func attackSlug(ev core.Event, fam string) (slug string, crit bool) {
|
||||
if ev.Cat == core.SSHFail {
|
||||
if ev.Cat == core.SSHFail || ev.Cat == core.SSHProbe {
|
||||
return ReasonSSHBrute, false
|
||||
}
|
||||
if r, ok := criticalFam[fam]; ok {
|
||||
|
||||
@@ -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,215 @@
|
||||
package enforce
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
func TestDecideSlowRules(t *testing.T) {
|
||||
p := Params{Threshold: 5}
|
||||
cases := []struct {
|
||||
name string
|
||||
in Input
|
||||
act string
|
||||
why string
|
||||
}{
|
||||
{"10 probes in window = 5 fails", Input{SSHProbes: 10}, ActBan, ReasonSSHBrute},
|
||||
{"9 probes", Input{SSHProbes: 9}, ActNone, ""},
|
||||
{"fails and probes mix", Input{SSHFails: 3, SSHProbes: 4}, ActBan, ReasonSSHBrute},
|
||||
{"ssh 7 days", Input{SSH7: 14}, ActBan, ReasonSSHBrute},
|
||||
{"ssh 7 days below", Input{SSH7: 9}, ActNone, ""},
|
||||
{"23.132.164.185 profile", Input{SSH7: 18, Probe7: 10}, ActBan, ReasonSSHBrute},
|
||||
{"77.239.124.130 profile", Input{Probe7: 28}, ActBan, ReasonSSHBrute},
|
||||
{"probes 24h", Input{Probe24: 20}, ActBan, ReasonSSHBrute},
|
||||
{"web 7 days", Input{Web7: 10}, ActBan, ReasonScannerFlood},
|
||||
{"web 7 days below", Input{Web7: 9}, ActNone, ""},
|
||||
{"web 7 days with a legit visit", Input{Web7: 30, Legit: true}, ActNone, ""},
|
||||
{"neighbor", Input{Neighbor: true}, ActBan, ReasonNeighbor},
|
||||
{"neighbor legit", Input{Neighbor: true, Legit: true}, ActNone, ""},
|
||||
{"neighbor trusted", Input{Neighbor: true, Exclude: SkipTrusted}, ActSkip, ""},
|
||||
{"neighbor crawler", Input{Neighbor: true, Exclude: SkipCrawler}, ActSkip, ""},
|
||||
{"neighbor operator", Input{Neighbor: true, Exclude: SkipOperator}, ActSkip, ""},
|
||||
{"neighbor already banned", Input{Neighbor: true, Banned: true}, ActAlready, ""},
|
||||
}
|
||||
for _, c := range cases {
|
||||
d := Decide(c.in, p)
|
||||
if d.Action != c.act || (c.why != "" && d.Reason != c.why) {
|
||||
t.Errorf("%s: %+v", c.name, d)
|
||||
}
|
||||
}
|
||||
if !ValidReason(ReasonNeighbor) || ReasonNeighbor != "neighbor-campaign" {
|
||||
t.Fatal("slug")
|
||||
}
|
||||
}
|
||||
|
||||
func probeEv(ip string, at time.Time) core.Event {
|
||||
return core.Event{Time: at, IP: ip, Cat: core.SSHProbe, Source: "ssh"}
|
||||
}
|
||||
|
||||
func TestSSHProbesBanLive(t *testing.T) {
|
||||
r := histRig(t, nil)
|
||||
for i := 0; i < 9; i++ {
|
||||
r.e.handle(probeEv("203.0.114.70", r.now.Add(-time.Duration(i)*time.Second)), "")
|
||||
}
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("9 probes must not ban")
|
||||
}
|
||||
r.e.handle(probeEv("203.0.114.70", r.now), "")
|
||||
if l := r.lines(t); len(l) != 1 || !contains(l[0], "ssh-bruteforce") {
|
||||
t.Fatalf("%v", l)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlowWeekLive(t *testing.T) {
|
||||
r := histRig(t, func(c *Config) {
|
||||
c.Tally = func(string, int64) Tally { return Tally{SSH: 2, SSH7: 13} } // 144.22.238.238: 14 in 7 days
|
||||
})
|
||||
r.e.handle(sshEv("203.0.114.71", r.now), "")
|
||||
if l := r.lines(t); len(l) != 1 || !contains(l[0], "ssh-bruteforce") {
|
||||
t.Fatalf("%v", l)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSweepWeekAndNeighbors(t *testing.T) {
|
||||
r := histRig(t, func(c *Config) {
|
||||
c.Roster = func(from int64) []Seen {
|
||||
if from > r0(t0).Add(-6*24*time.Hour).Unix() {
|
||||
t.Errorf("sweep must look back 7 days, from=%d", from)
|
||||
}
|
||||
return []Seen{
|
||||
{IP: "203.0.114.80", Score: 20, Level: core.LevelSuspicious, Events: 14, Last: t0.Add(-2 * 24 * time.Hour).Unix()},
|
||||
{IP: "203.0.114.81", Score: 20, Level: core.LevelSuspicious, Events: 3, Last: t0.Add(-2 * 24 * time.Hour).Unix()},
|
||||
}
|
||||
}
|
||||
c.Tallies = func(int64) map[string]Tally {
|
||||
return map[string]Tally{"203.0.114.80": {SSH7: 14}, "203.0.114.81": {SSH7: 3}}
|
||||
}
|
||||
})
|
||||
r.e.Sweep()
|
||||
r.e.drain()
|
||||
if l := r.lines(t); len(l) != 1 || !contains(l[0], "203.0.114.80") {
|
||||
t.Fatalf("%v", l)
|
||||
}
|
||||
}
|
||||
|
||||
func r0(t time.Time) time.Time { return t }
|
||||
|
||||
func ban(ip string, at time.Time, jail string) core.Event {
|
||||
return core.Event{Time: at, IP: ip, Cat: core.Ban, Source: "fail2ban", Jail: jail}
|
||||
}
|
||||
|
||||
func TestNeighborCampaign(t *testing.T) {
|
||||
r := histRig(t, nil)
|
||||
for _, ip := range []string{"203.0.114.1", "203.0.114.2"} {
|
||||
r.e.process(ban(ip, r.now.Add(-time.Hour), "sshd"), "")
|
||||
}
|
||||
r.e.process(atk("203.0.114.9", r.now, "/x", 404), "")
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatal("two banned neighbors are not a campaign")
|
||||
}
|
||||
r.e.process(ban("203.0.114.3", r.now.Add(-time.Hour), "sshd"), "")
|
||||
r.e.process(atk("203.0.114.9", r.now, "/x", 404), "")
|
||||
l := r.lines(t)
|
||||
if len(l) != 1 || !contains(l[0], "ip=203.0.114.9") || !contains(l[0], "neighbor-campaign") {
|
||||
t.Fatalf("%v", l)
|
||||
}
|
||||
// another /24 is untouched
|
||||
r.e.process(atk("203.0.115.9", r.now, "/x", 404), "")
|
||||
if len(r.lines(t)) != 1 {
|
||||
t.Fatal("other prefix banned")
|
||||
}
|
||||
// bans older than 24 h expire
|
||||
r.now = r.now.Add(25 * time.Hour)
|
||||
r.e.process(atk("203.0.114.77", r.now, "/x", 404), "")
|
||||
if len(r.lines(t)) != 1 {
|
||||
t.Fatal("expired campaign banned")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeighborRespectsExclusions(t *testing.T) {
|
||||
r := histRig(t, func(c *Config) { c.Crawler = func(ip string, _ []string) bool { return ip == "203.0.114.9" } })
|
||||
for _, ip := range []string{"203.0.114.1", "203.0.114.2", "203.0.114.3"} {
|
||||
r.e.process(ban(ip, r.now.Add(-time.Hour), "sshd"), "")
|
||||
}
|
||||
r.e.process(atk("203.0.114.9", r.now, "/x", 404), "") // verified crawler, no UA at all
|
||||
if len(r.lines(t)) != 0 {
|
||||
t.Fatalf("crawler banned: %v", r.lines(t))
|
||||
}
|
||||
r.e.process(atk("203.0.114.10", r.now, "/x", 404), "")
|
||||
if len(r.lines(t)) != 1 {
|
||||
t.Fatal("expected one ban")
|
||||
}
|
||||
// operator allowance
|
||||
if err := r.e.Unban(mustAddr("203.0.114.11"), 3600, "t"); err != nil && err != ErrNoUnbanLog {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// trusted prefix inside the campaign
|
||||
r.e.process(ban("168.196.85.1", r.now, "sshd"), "")
|
||||
r.e.process(ban("168.196.85.2", r.now, "sshd"), "")
|
||||
r.e.process(ban("168.196.85.3", r.now, "sshd"), "")
|
||||
r.e.process(atk("168.196.85.9", r.now, "/x", 404), "")
|
||||
for _, l := range r.lines(t) {
|
||||
if contains(l, "168.196.85.9") {
|
||||
t.Fatal("trusted banned")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeighborV6AndPeers(t *testing.T) {
|
||||
r := histRig(t, nil)
|
||||
for _, ip := range []string{"2606:4701:1:2::1", "2606:4701:1:2::2", "2606:4701:1:2::3"} {
|
||||
r.e.process(ban(ip, r.now.Add(-time.Hour), "sshd"), "")
|
||||
}
|
||||
r.e.process(atk("2606:4701:1:2::99", r.now, "/x", 404), "")
|
||||
if l := r.lines(t); len(l) != 1 || !contains(l[0], "neighbor-campaign") {
|
||||
t.Fatalf("%v", l)
|
||||
}
|
||||
// a peer may send the slug; this node must have seen the address attack
|
||||
r.e.process(atk("203.0.114.200", r.now, "/x", 404), "")
|
||||
acc, inv := r.e.AcceptPeer("hub", []Wire{{T: r.now.Unix(), IP: "203.0.114.200", Reason: ReasonNeighbor, Score: 70, TTL: 3600}})
|
||||
if acc != 1 || inv != 0 {
|
||||
t.Fatalf("accepted %d invalid %d", acc, inv)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnJailBanDoesNotChangeAttackLogic(t *testing.T) {
|
||||
r := histRig(t, nil)
|
||||
r.e.process(ban("203.0.114.5", r.now, "urutau"), "")
|
||||
if st := r.e.ips[mustAddr("203.0.114.5")]; st == nil || st.f2bAt != 0 || st.urutauAt == 0 {
|
||||
t.Fatalf("%+v", st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrawlerExcludedWithoutUA(t *testing.T) {
|
||||
r := histRig(t, func(c *Config) { c.Crawler = func(string, []string) bool { return true } })
|
||||
e := atk("203.0.114.40", r.now, "/.env", 404)
|
||||
e.UA = ""
|
||||
for i := 0; i < 10; i++ {
|
||||
e.Time = r.now.Add(-time.Duration(i) * time.Second)
|
||||
r.e.process(e, "env-credentials")
|
||||
}
|
||||
if len(r.lines(t)) != 0 || r.e.counts.Skipped[SkipCrawler] == 0 {
|
||||
t.Fatalf("%v %v", r.lines(t), r.e.counts.Skipped)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageOneShot(t *testing.T) {
|
||||
r := histRig(t, func(c *Config) {
|
||||
c.Roster = func(int64) []Seen {
|
||||
return []Seen{
|
||||
{IP: "203.0.114.90", Events: 1},
|
||||
{IP: "203.0.114.91", Events: 5},
|
||||
{IP: "203.0.114.92", Events: 5, Jails: []string{"sshd"}},
|
||||
}
|
||||
}
|
||||
})
|
||||
cv := r.e.Report(0).Coverage
|
||||
if cv.AttackIPs != 3 || cv.OneShot != 1 || cv.Repeat != 2 || cv.RepeatUnblocked != 1 || cv.Unblocked != 2 {
|
||||
t.Fatalf("%+v", cv)
|
||||
}
|
||||
}
|
||||
|
||||
func mustAddr(s string) netip.Addr { return netip.MustParseAddr(s) }
|
||||
@@ -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
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,311 @@
|
||||
package incidents
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func fnd(sev string, last int64, count int) Finding {
|
||||
return Finding{Host: "oracle", Kind: "port", Severity: sev, Workload: "container 10.0.3.5", Dst: "203.0.113.3", DPort: 6667, Proto: "tcp",
|
||||
Detail: "irc", First: 100, Last: last, Count: count}
|
||||
}
|
||||
|
||||
func newStore(t *testing.T) (*Store, string, *int64) {
|
||||
p := filepath.Join(t.TempDir(), "incidents.json")
|
||||
s, err := Open(p, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clock := int64(1000)
|
||||
s.now = func() time.Time { return time.Unix(clock, 0) }
|
||||
return s, p, &clock
|
||||
}
|
||||
|
||||
func str(v string) *string { return &v }
|
||||
|
||||
func TestPersistenceAndCorrupt(t *testing.T) {
|
||||
s, p, _ := newStore(t)
|
||||
s.Sync([]Finding{fnd("medium", 500, 3)})
|
||||
if _, err := s.AddComment("INC-1", "visto", "ana", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := os.Stat(p)
|
||||
if err != nil || st.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("file: %v %v", st, err)
|
||||
}
|
||||
if _, err := os.Stat(p + ".tmp"); err == nil {
|
||||
t.Fatal("tmp left behind")
|
||||
}
|
||||
s2, _ := Open(p, nil)
|
||||
tk, err := s2.Get("INC-1")
|
||||
if err != nil || tk.Count != 3 || len(tk.Comments) != 1 || tk.History[0].Field != "created" || tk.History[0].Author != "urutau" {
|
||||
t.Fatalf("reload: %+v %v", tk, err)
|
||||
}
|
||||
if m, _ := s2.Create(NewManual{Title: "x"}); m.ID != "INC-2" {
|
||||
t.Fatalf("sequence after reload: %s", m.ID)
|
||||
}
|
||||
os.WriteFile(p, []byte("{not json"), 0o600)
|
||||
s3, err := Open(p, nil)
|
||||
if err != nil || s3.List(Query{}).Total != 0 {
|
||||
t.Fatalf("corrupt store not empty: %v", err)
|
||||
}
|
||||
if m, _ := filepath.Glob(p + ".corrupt-*"); len(m) != 1 {
|
||||
t.Fatal("no timestamped .corrupt file")
|
||||
}
|
||||
// a read error that is not "does not exist" aborts
|
||||
dir := t.TempDir()
|
||||
if _, err := Open(dir, nil); err == nil {
|
||||
t.Fatal("unreadable store accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSync(t *testing.T) {
|
||||
s, _, clock := newStore(t)
|
||||
if c, _ := s.Sync([]Finding{fnd("info", 500, 1)}); c != 0 {
|
||||
t.Fatal("info created a ticket")
|
||||
}
|
||||
if c, _ := s.Sync([]Finding{fnd("medium", 500, 3)}); c != 1 {
|
||||
t.Fatal("not created")
|
||||
}
|
||||
s.Sync([]Finding{fnd("high", 600, 5)})
|
||||
tk, _ := s.Get("INC-1")
|
||||
if tk.Status != "open" || tk.Count != 5 || tk.LastSeen != 600 || tk.Severity != "high" || tk.MaxSeverity != "high" || len(s.byID) != 1 {
|
||||
t.Fatalf("update: %+v", tk)
|
||||
}
|
||||
// resolved, finding older than the resolution: stays resolved; newer: reopens
|
||||
*clock = 2000
|
||||
s.Update("INC-1", Patch{Status: str("resolved"), Author: "ana"})
|
||||
s.Sync([]Finding{fnd("medium", 1500, 5)})
|
||||
if tk, _ = s.Get("INC-1"); tk.Status != "resolved" {
|
||||
t.Fatal("reopened by an old finding")
|
||||
}
|
||||
*clock = 3000
|
||||
if _, r := s.Sync([]Finding{fnd("medium", 2500, 6)}); r != 1 {
|
||||
t.Fatal("not reopened")
|
||||
}
|
||||
tk, _ = s.Get("INC-1")
|
||||
last := tk.History[len(tk.History)-1]
|
||||
if tk.Status != "open" || last.Field != "reappeared" {
|
||||
t.Fatalf("reopen: %+v", tk.History)
|
||||
}
|
||||
// false positive is never reopened and only counts
|
||||
*clock = 4000
|
||||
s.Update("INC-1", Patch{Status: str("false_positive")})
|
||||
s.Sync([]Finding{fnd("high", 3500, 9)})
|
||||
tk, _ = s.Get("INC-1")
|
||||
if tk.Status != "false_positive" || tk.Count != 9 {
|
||||
t.Fatalf("fp: %+v", tk)
|
||||
}
|
||||
// leaving the status drops the suppression
|
||||
s.Update("INC-1", Patch{Status: str("open")})
|
||||
if tk, _ = s.Get("INC-1"); tk.Suppress {
|
||||
t.Fatal("suppress kept")
|
||||
}
|
||||
if _, err := s.Update("INC-1", Patch{Suppress: &[]bool{true}[0]}); !errors.Is(err, ErrConflict) {
|
||||
t.Fatal("suppress allowed in open")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLimits(t *testing.T) {
|
||||
s, _, clock := newStore(t)
|
||||
s.Create(NewManual{Title: "a"})
|
||||
for i := 0; i < MaxComments; i++ {
|
||||
if _, err := s.AddComment("INC-1", "c", "", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if _, err := s.AddComment("INC-1", "c", "", ""); err == nil {
|
||||
t.Fatal("201st comment accepted")
|
||||
}
|
||||
for i := 0; i < MaxHistory+20; i++ {
|
||||
*clock++
|
||||
st := "investigating"
|
||||
if i%2 == 1 {
|
||||
st = "open"
|
||||
}
|
||||
s.Update("INC-1", Patch{Status: &st})
|
||||
}
|
||||
if tk, _ := s.Get("INC-1"); len(tk.History) != MaxHistory {
|
||||
t.Fatalf("history %d", len(tk.History))
|
||||
}
|
||||
// ticket cap: oldest closed goes first, open tickets are kept
|
||||
s2, _, c2 := newStore(t)
|
||||
for i := 0; i < MaxTickets; i++ {
|
||||
*c2++
|
||||
s2.Create(NewManual{Title: "t"})
|
||||
s2.save() // keep the test honest about cost? no: cheap enough
|
||||
if i > 50 {
|
||||
break
|
||||
}
|
||||
}
|
||||
s2.mu.Lock()
|
||||
for i := len(s2.byID); i < MaxTickets; i++ {
|
||||
s2.add(&Ticket{base: base{Key: "k" + string(rune(i)) + "x", Status: "open", UpdatedAt: 5000}})
|
||||
}
|
||||
s2.mu.Unlock()
|
||||
s2.Update("INC-3", Patch{Status: str("resolved")})
|
||||
s2.Update("INC-2", Patch{Status: str("benign"), Verdict: str("kept")}) // a verdict protects it from eviction
|
||||
if tk, err := s2.Create(NewManual{Title: "new"}); err != nil || len(s2.byID) != MaxTickets {
|
||||
t.Fatalf("create at cap: %v %d", err, len(s2.byID))
|
||||
} else if _, err := s2.Get("INC-3"); err == nil && tk.ID != "" {
|
||||
t.Fatal("INC-3 not evicted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidation(t *testing.T) {
|
||||
s, _, _ := newStore(t)
|
||||
s.Create(NewManual{Title: "a"})
|
||||
bad := []Patch{
|
||||
{Status: str("nope")}, {Severity: str("urgent")}, {Title: str("")}, {Title: str(strings.Repeat("a", 201))},
|
||||
{Verdict: str(strings.Repeat("a", 4001))}, {Verdict: str("a\x00b")}, {Assignee: str(strings.Repeat("a", 65))},
|
||||
{Tags: &[]string{"UP"}}, {Tags: &[]string{"a b"}}, {Tags: &[]string{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"}},
|
||||
{Author: strings.Repeat("a", 65)}, {Author: "a\nb"},
|
||||
}
|
||||
for i, p := range bad {
|
||||
if _, err := s.Update("INC-1", p); err == nil {
|
||||
t.Errorf("patch %d accepted", i)
|
||||
}
|
||||
}
|
||||
if _, err := s.Update("INC-9", Patch{}); err != ErrNotFound {
|
||||
t.Fatal("404 expected")
|
||||
}
|
||||
if tk, err := s.Update("INC-1", Patch{Verdict: str("a\nb\tc"), Tags: &[]string{"ok-1", "x.y_z"}}); err != nil || tk.Verdict != "a\nb\tc" {
|
||||
t.Fatalf("good patch: %v", err)
|
||||
}
|
||||
if _, err := s.AddComment("INC-1", strings.Repeat("a", 5001), "", ""); err == nil {
|
||||
t.Fatal("long comment accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestListFilters(t *testing.T) {
|
||||
s, _, _ := newStore(t)
|
||||
s.Sync([]Finding{fnd("medium", 500, 3), {Host: "h2", Kind: "bad_dst", Severity: "high", Workload: "host", Dst: "198.51.100.9", DPort: 22, Proto: "tcp", Last: 700, Count: 1}})
|
||||
s.Update("INC-2", Patch{Status: str("investigating")})
|
||||
pg := s.List(Query{Status: []string{"investigating"}, Sort: "severity"})
|
||||
if pg.Total != 1 || pg.Counts["open"] != 1 || pg.Counts["investigating"] != 1 || pg.Items[0].ID != "INC-2" {
|
||||
t.Fatalf("%+v", pg)
|
||||
}
|
||||
if s.List(Query{Host: "oracle"}).Total != 1 || s.List(Query{Q: "BAD_DST"}).Total != 1 || s.List(Query{Severity: []string{"high"}}).Total != 1 {
|
||||
t.Fatal("filters")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuppressionPolicy(t *testing.T) {
|
||||
s, _, clock := newStore(t)
|
||||
yes := true
|
||||
s.Sync([]Finding{fnd("medium", 500, 3)})
|
||||
*clock = 2000
|
||||
if _, err := s.Update("INC-1", Patch{Status: str("false_positive"), Suppress: &yes, SuppressUntil: &[]int64{2000 + 91*86400}[0]}); !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("91 days accepted: %v", err)
|
||||
}
|
||||
tk, err := s.Update("INC-1", Patch{Status: str("false_positive"), Suppress: &yes, Author: "ana"})
|
||||
if err != nil || !tk.Suppress || tk.SuppressedSev != "medium" || tk.SuppressUntil != 2000+30*86400 {
|
||||
t.Fatalf("suppress: %+v %v", tk, err)
|
||||
}
|
||||
if tk.History[len(tk.History)-1].Author != "ana" {
|
||||
t.Fatal("author")
|
||||
}
|
||||
// same severity: stays suppressed; worse severity: reopens
|
||||
s.Sync([]Finding{fnd("medium", 2100, 4)})
|
||||
if tk, _ = s.Get("INC-1"); !tk.Suppress || tk.Status != "false_positive" {
|
||||
t.Fatal("reopened without cause")
|
||||
}
|
||||
s.Sync([]Finding{fnd("high", 2200, 4)})
|
||||
tk, _ = s.Get("INC-1")
|
||||
if tk.Suppress || tk.Status != "open" || tk.Severity != "high" || tk.History[len(tk.History)-2].Field != "reappeared" {
|
||||
t.Fatalf("worse severity: %+v", tk)
|
||||
}
|
||||
// high/critical can never be suppressed
|
||||
if _, err := s.Update("INC-1", Patch{Status: str("benign"), Suppress: &yes}); !errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("high suppressed: %v", err)
|
||||
}
|
||||
// TTL
|
||||
s2, _, c2 := newStore(t)
|
||||
s2.Sync([]Finding{fnd("low", 500, 1)})
|
||||
*c2 = 5000
|
||||
until := int64(5000 + 86400)
|
||||
s2.Update("INC-1", Patch{Status: str("benign"), Suppress: &yes, SuppressUntil: &until})
|
||||
*c2 = 5000 + 2*86400
|
||||
s2.Sync([]Finding{fnd("low", *c2, 2)})
|
||||
if tk, _ = s2.Get("INC-1"); tk.Suppress || tk.Status != "open" || tk.History[len(tk.History)-1].Field != "suppression expired" {
|
||||
t.Fatalf("ttl: %+v", tk)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeverityFollowsFinding(t *testing.T) {
|
||||
s, _, _ := newStore(t)
|
||||
s.Sync([]Finding{fnd("low", 500, 1)})
|
||||
s.Sync([]Finding{fnd("high", 600, 1)})
|
||||
if tk, _ := s.Get("INC-1"); tk.Severity != "high" || tk.History[len(tk.History)-1].Field != "severity" {
|
||||
t.Fatalf("%+v", tk)
|
||||
}
|
||||
s.Create(NewManual{Title: "m"})
|
||||
s.Sync([]Finding{{Host: "h", Kind: "port", Severity: "low", Workload: "w", Dst: "1.1.1.1", DPort: 1, Proto: "tcp", Last: 1}})
|
||||
s.Update("INC-3", Patch{Severity: str("critical")})
|
||||
s.Sync([]Finding{{Host: "h", Kind: "port", Severity: "high", Workload: "w", Dst: "1.1.1.1", DPort: 1, Proto: "tcp", Last: 2}})
|
||||
if tk, _ := s.Get("INC-3"); tk.Severity != "critical" || !tk.SeverityManual {
|
||||
t.Fatalf("manual severity overwritten: %+v", tk)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFloodQuota(t *testing.T) {
|
||||
s, _, _ := newStore(t)
|
||||
var fs []Finding
|
||||
for i := 0; i < HostQuota+20; i++ {
|
||||
fs = append(fs, Finding{Host: "h", Kind: "port", Severity: "low", Workload: "w", Dst: "10.0." + strconv.Itoa(i/250) + "." + strconv.Itoa(i%250), DPort: 80, Proto: "tcp", Last: int64(i)})
|
||||
}
|
||||
s.Sync(fs)
|
||||
s.Sync(fs) // idempotent
|
||||
fs = append(fs, Finding{Host: "h", Kind: "bad_dst", Severity: "high", Workload: "w", Dst: "9.9.9.9", DPort: 22, Proto: "tcp", Last: 5})
|
||||
s.Sync(fs)
|
||||
pg := s.List(Query{Host: "h"})
|
||||
if pg.Total != HostQuota+2 { // quota + flood + the high one, never grouped
|
||||
t.Fatalf("total %d", pg.Total)
|
||||
}
|
||||
var flood *Summary
|
||||
for i := range pg.Items {
|
||||
if pg.Items[i].Kind == "flood" {
|
||||
flood = &pg.Items[i]
|
||||
}
|
||||
}
|
||||
if flood == nil || flood.Count != 20 || !strings.Contains(flood.Detail, "port 10.0.") {
|
||||
t.Fatalf("flood: %+v", flood)
|
||||
}
|
||||
// other hosts are unaffected
|
||||
s.Sync([]Finding{{Host: "other", Kind: "port", Severity: "low", Workload: "w", Dst: "1.1.1.1", DPort: 1, Proto: "tcp", Last: 1}})
|
||||
if s.List(Query{Host: "other"}).Total != 1 {
|
||||
t.Fatal("other host grouped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConflictAndKeyMigration(t *testing.T) {
|
||||
s, p, _ := newStore(t)
|
||||
s.Sync([]Finding{fnd("medium", 500, 1)})
|
||||
tk, _ := s.Get("INC-1")
|
||||
stale := tk.UpdatedAt - 1
|
||||
if _, err := s.Update("INC-1", Patch{Verdict: str("x"), ExpectedUpdatedAt: &stale}); !errors.Is(err, ErrConflict) {
|
||||
t.Fatalf("stale write: %v", err)
|
||||
}
|
||||
if _, err := s.Update("INC-1", Patch{Verdict: str("x"), ExpectedUpdatedAt: &tk.UpdatedAt, Via: "token"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tk, _ = s.Get("INC-1"); tk.History[len(tk.History)-1].Author != "operator (via token)" {
|
||||
t.Fatalf("author: %+v", tk.History)
|
||||
}
|
||||
if _, err := s.Update("INC-1", Patch{Title: str("a\nb")}); err == nil {
|
||||
t.Fatal("newline in title")
|
||||
}
|
||||
// an old-format key is recomputed on load
|
||||
b, _ := os.ReadFile(p)
|
||||
old := strings.Replace(string(b), tk.Key, "oracle|port|old", 1)
|
||||
os.WriteFile(p, []byte(old), 0o600)
|
||||
s2, _ := Open(p, nil)
|
||||
if r := s2.Lookup([]string{fnd("medium", 1, 1).Key()}); len(r) != 1 {
|
||||
t.Fatal("key not migrated")
|
||||
}
|
||||
}
|
||||
@@ -148,6 +148,13 @@ func vcsMarker(dec string) string {
|
||||
return firstSub(dec, vcsRules)
|
||||
}
|
||||
|
||||
func pathOnly(p string) string {
|
||||
if i := strings.IndexAny(p, "?#"); i >= 0 {
|
||||
return p[:i]
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func backupMarker(dec string) string {
|
||||
p := dec
|
||||
if i := strings.IndexAny(p, "?#"); i >= 0 {
|
||||
@@ -185,6 +192,9 @@ func matchFamily(raw, dec string) (fam, marker string) {
|
||||
if m := firstSub(sp, rceRules); m != "" {
|
||||
return FamRCE, m
|
||||
}
|
||||
if core.ForgeBrowse(pathOnly(dec)) { // repository content on a code forge, not a probe
|
||||
return "", ""
|
||||
}
|
||||
if m := webshellMarker(dec); m != "" {
|
||||
return FamWebshell, m
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package intel
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
func TestForgeBrowseHasNoFamily(t *testing.T) {
|
||||
for _, p := range []string{"/ciberfauna/sabia/src/commit/0123abcd/.gitignore", "/lucasrguerra/LambdaMail/src/commit/0123abcd/.env.example",
|
||||
"/ciberfauna/guara/blame/commit/0123abcd/.gitignore"} {
|
||||
if f := Family(p, core.OK, 200, false); f != "" {
|
||||
t.Errorf("%s: %q", p, f)
|
||||
}
|
||||
if f := PathFamily(p); f != "" {
|
||||
t.Errorf("PathFamily %s: %q", p, f)
|
||||
}
|
||||
}
|
||||
for p, want := range map[string]string{"/.env": FamEnvCreds, "/.git/config": FamVCS, "/app/.env": FamEnvCreds} {
|
||||
if f := PathFamily(p); f != want {
|
||||
t.Errorf("%s: %q want %q", p, f, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"sort"
|
||||
@@ -23,6 +24,7 @@ type egressOut struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Source egress.SourceInfo `json:"source"`
|
||||
egress.Report
|
||||
SuppressedCount int `json:"suppressed_count"`
|
||||
}
|
||||
|
||||
// egressAPI: GET /api/v1/egress?range=24h&host=all|<name>. On a hub the
|
||||
@@ -48,7 +50,21 @@ func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) {
|
||||
out.Source = eng.Info()
|
||||
out.Enabled = true
|
||||
}
|
||||
rep := egress.EmptyReport()
|
||||
rep, peerOn := s.egressReport(r.Context(), from, to, local, peers, only)
|
||||
if peerOn {
|
||||
out.Enabled = true
|
||||
}
|
||||
// incidents are fed only by the 60 s loop, never by a request
|
||||
out.Report = rep
|
||||
out.SuppressedCount = s.annotateFindings(&out.Report, r.URL.Query().Get("suppressed") == "1")
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// egressReport builds the report of the window: the local engine and, on a hub,
|
||||
// the peers' reports merged (items carrying "host"). peerOn is true when a peer answered.
|
||||
func (s *Server) egressReport(ctx context.Context, from, to int64, local, peers bool, only string) (rep egress.Report, peerOn bool) {
|
||||
eng := egressEngine.Load()
|
||||
rep = egress.EmptyReport()
|
||||
if local && eng != nil {
|
||||
rep = eng.Report(from, to)
|
||||
}
|
||||
@@ -59,7 +75,7 @@ func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) {
|
||||
rep.Stamp(s.opt.Store.Name())
|
||||
merged.Merge(rep, s.opt.Store.Name())
|
||||
}
|
||||
raws := s.opt.Hub.EgressFor(r.Context(), from, to, only)
|
||||
raws := s.opt.Hub.EgressFor(ctx, from, to, only)
|
||||
names := make([]string, 0, len(raws))
|
||||
for n := range raws {
|
||||
names = append(names, n)
|
||||
@@ -72,12 +88,11 @@ func (s *Server) egressAPI(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
pr.Sanitize(n)
|
||||
merged.Merge(pr, n)
|
||||
out.Enabled = true
|
||||
peerOn = true
|
||||
}
|
||||
rep = merged
|
||||
}
|
||||
out.Report = rep
|
||||
writeJSON(w, 200, out)
|
||||
return rep, peerOn
|
||||
}
|
||||
|
||||
// peerEgress: GET /api/v1/peer/egress, the local report a hub merges; opened
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/csv"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
)
|
||||
|
||||
const maxIncidentBody = 64 << 10
|
||||
|
||||
func init() {
|
||||
registerUserRoute("GET /api/v1/incidents", func(s *Server) http.HandlerFunc { return s.incidentList })
|
||||
registerUserRoute("GET /api/v1/incidents/export.csv", func(s *Server) http.HandlerFunc { return s.incidentCSV })
|
||||
registerUserRoute("GET /api/v1/incidents/{id}", func(s *Server) http.HandlerFunc { return s.incidentGet })
|
||||
registerUserRoute("POST /api/v1/incidents", func(s *Server) http.HandlerFunc { return s.incidentCreate })
|
||||
registerUserRoute("PATCH /api/v1/incidents/{id}", func(s *Server) http.HandlerFunc { return s.incidentPatch })
|
||||
registerUserRoute("POST /api/v1/incidents/{id}/comments", func(s *Server) http.HandlerFunc { return s.incidentComment })
|
||||
}
|
||||
|
||||
var incidentServer atomic.Pointer[Server]
|
||||
|
||||
// StartIncidentSync runs the 60 s loop that feeds the incident store from the
|
||||
// merged egress report (same as GET /api/v1/egress, 24 h window). It does
|
||||
// nothing when incidents or egress are off.
|
||||
func StartIncidentSync(ctx context.Context, wg *sync.WaitGroup) {
|
||||
s := incidentServer.Load()
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
t := time.NewTicker(60 * time.Second)
|
||||
defer t.Stop()
|
||||
for {
|
||||
s.syncNow(ctx)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
s.opt.Incidents.Flush()
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Server) syncNow(ctx context.Context) {
|
||||
if s.opt.Incidents == nil || egressEngine.Load() == nil {
|
||||
return
|
||||
}
|
||||
now := s.opt.Store.Now().Unix()
|
||||
cctx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
rep, _ := s.egressReport(cctx, now-24*3600, now, true, s.opt.Hub != nil, "")
|
||||
s.syncIncidents(rep)
|
||||
}
|
||||
|
||||
func (s *Server) findingHost(f egress.Finding) string {
|
||||
if f.Host != "" {
|
||||
return f.Host
|
||||
}
|
||||
return s.opt.Store.Name()
|
||||
}
|
||||
|
||||
func (s *Server) findingKey(f egress.Finding) string {
|
||||
return incidents.Key(s.findingHost(f), f.Kind, f.Workload, f.Dst, f.DPort, f.Proto)
|
||||
}
|
||||
|
||||
func (s *Server) syncIncidents(rep egress.Report) {
|
||||
if s.opt.Incidents == nil {
|
||||
return
|
||||
}
|
||||
fs := make([]incidents.Finding, 0, len(rep.Findings))
|
||||
for _, f := range rep.Findings {
|
||||
fs = append(fs, incidents.Finding{Host: s.findingHost(f), Kind: f.Kind, Severity: f.Severity, Workload: f.Workload, Dst: f.Dst,
|
||||
Proto: f.Proto, Detail: f.Detail, DPort: f.DPort, First: f.First, Last: f.Last, Count: f.Count})
|
||||
}
|
||||
s.opt.Incidents.Sync(fs)
|
||||
}
|
||||
|
||||
// annotateFindings fills ticket_id/ticket_status/suppressed and, unless show
|
||||
// is set, drops the findings whose ticket suppresses their exact key. It
|
||||
// returns how many were suppressed.
|
||||
func (s *Server) annotateFindings(rep *egress.Report, show bool) int {
|
||||
if s.opt.Incidents == nil || len(rep.Findings) == 0 {
|
||||
return 0
|
||||
}
|
||||
keys := make([]string, len(rep.Findings))
|
||||
for i, f := range rep.Findings {
|
||||
keys[i] = s.findingKey(f)
|
||||
}
|
||||
refs := s.opt.Incidents.Lookup(keys)
|
||||
out := rep.Findings[:0:0]
|
||||
n := 0
|
||||
for i, f := range rep.Findings {
|
||||
if ref, ok := refs[keys[i]]; ok {
|
||||
f.TicketID, f.TicketStatus, f.Suppressed = ref.ID, ref.Status, ref.Suppress
|
||||
}
|
||||
if f.Suppressed {
|
||||
n++
|
||||
if !show {
|
||||
continue
|
||||
}
|
||||
}
|
||||
out = append(out, f)
|
||||
}
|
||||
rep.Findings = out
|
||||
return n
|
||||
}
|
||||
|
||||
func (s *Server) incidentsOn(w http.ResponseWriter) bool {
|
||||
if s.opt.Incidents == nil {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "incident management is not enabled"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func incidentErr(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, incidents.ErrNotFound):
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "incident not found"})
|
||||
case errors.Is(err, incidents.ErrConflict):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": strings.TrimPrefix(err.Error(), "conflict: ")})
|
||||
case errors.Is(err, incidents.ErrInvalid):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": strings.TrimPrefix(err.Error(), "invalid: ")})
|
||||
default:
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
|
||||
}
|
||||
}
|
||||
|
||||
// incidentBody checks the origin and decodes a strict JSON body (64 KiB max).
|
||||
func incidentBody(w http.ResponseWriter, r *http.Request, v any) bool {
|
||||
if !sameOrigin(r) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "cross-site request refused"})
|
||||
return false
|
||||
}
|
||||
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxIncidentBody))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(v); err != nil || dec.More() {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON body"})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func csvList(v string) []string {
|
||||
var out []string
|
||||
for _, p := range strings.Split(v, ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) incidentQuery(w http.ResponseWriter, r *http.Request) (incidents.Query, bool) {
|
||||
v := r.URL.Query()
|
||||
q := incidents.Query{Status: csvList(v.Get("status")), Severity: csvList(v.Get("severity")), Host: v.Get("host"), Q: v.Get("q"), Sort: v.Get("sort")}
|
||||
if len(q.Host) > 253 || len(q.Q) > 200 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad host or q"})
|
||||
return q, false
|
||||
}
|
||||
for _, p := range []struct {
|
||||
name string
|
||||
dst *int
|
||||
}{{"page", &q.Page}, {"per_page", &q.PerPage}} {
|
||||
if x := v.Get(p.name); x != "" {
|
||||
n, err := strconv.Atoi(x)
|
||||
if err != nil || n < 1 || n > 100000 {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "bad " + p.name})
|
||||
return q, false
|
||||
}
|
||||
*p.dst = n
|
||||
}
|
||||
}
|
||||
if err := q.Validate(); err != nil {
|
||||
incidentErr(w, err)
|
||||
return q, false
|
||||
}
|
||||
return q, true
|
||||
}
|
||||
|
||||
func (s *Server) incidentList(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
}
|
||||
q, ok := s.incidentQuery(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, s.opt.Incidents.List(q))
|
||||
}
|
||||
|
||||
func (s *Server) incidentGet(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
}
|
||||
t, err := s.opt.Incidents.Get(r.PathValue("id"))
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, t)
|
||||
}
|
||||
|
||||
func (s *Server) incidentCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
}
|
||||
var in incidents.NewManual
|
||||
if !incidentBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
in.Via = s.via(r)
|
||||
t, err := s.opt.Incidents.Create(in)
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, t)
|
||||
}
|
||||
|
||||
func (s *Server) incidentPatch(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
}
|
||||
var p incidents.Patch
|
||||
if !incidentBody(w, r, &p) {
|
||||
return
|
||||
}
|
||||
p.Via = s.via(r)
|
||||
t, err := s.opt.Incidents.Update(r.PathValue("id"), p)
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, t)
|
||||
}
|
||||
|
||||
func (s *Server) incidentComment(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
}
|
||||
var in struct {
|
||||
Text string `json:"text"`
|
||||
Author string `json:"author"`
|
||||
}
|
||||
if !incidentBody(w, r, &in) {
|
||||
return
|
||||
}
|
||||
t, err := s.opt.Incidents.AddComment(r.PathValue("id"), in.Text, in.Author, s.via(r))
|
||||
if err != nil {
|
||||
incidentErr(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, t)
|
||||
}
|
||||
|
||||
// csvCell neutralises spreadsheet formulas.
|
||||
func csvCell(v string) string {
|
||||
if v == "" {
|
||||
return v
|
||||
}
|
||||
if v[0] == '\t' || v[0] == '\r' {
|
||||
return "'" + v
|
||||
}
|
||||
if t := strings.TrimLeft(v, " \t\r\n"); t != "" && strings.ContainsRune("=+-@", rune(t[0])) {
|
||||
return "'" + v
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// via names the credential that made a write, for the history.
|
||||
func (s *Server) via(r *http.Request) string {
|
||||
if s.authKind(r) == "bearer" {
|
||||
return "token"
|
||||
}
|
||||
return "session"
|
||||
}
|
||||
|
||||
func (s *Server) incidentCSV(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.incidentsOn(w) {
|
||||
return
|
||||
}
|
||||
q, ok := s.incidentQuery(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="incidents.csv"`)
|
||||
cw := csv.NewWriter(w)
|
||||
cw.Write([]string{"id", "status", "severity", "host", "kind", "workload", "dst", "dport", "proto", "title", "first_seen", "last_seen", "count", "assignee", "tags", "verdict", "suppress", "created_at", "updated_at"})
|
||||
for _, t := range s.opt.Incidents.All(q) {
|
||||
row := []string{t.ID, t.Status, t.Severity, t.Host, t.Kind, t.Workload, t.Dst, strconv.Itoa(int(t.DPort)), t.Proto, t.Title,
|
||||
strconv.FormatInt(t.FirstSeen, 10), strconv.FormatInt(t.LastSeen, 10), strconv.Itoa(t.Count), t.Assignee, strings.Join(t.Tags, ","), t.Verdict,
|
||||
strconv.FormatBool(t.Suppress), strconv.FormatInt(t.CreatedAt, 10), strconv.FormatInt(t.UpdatedAt, 10)}
|
||||
for i := range row {
|
||||
row[i] = csvCell(row[i])
|
||||
}
|
||||
cw.Write(row)
|
||||
}
|
||||
cw.Flush()
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/egress"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
func incRig(t *testing.T) http.Handler {
|
||||
t.Helper()
|
||||
st := store.New(store.Config{Name: "oracle", Version: "t", Retention: 720 * time.Hour})
|
||||
inc, err := incidents.Open(filepath.Join(t.TempDir(), "incidents.json"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return New(Options{Token: userTok, PeerTokens: []string{peerTok}, Version: "t", Store: st, Incidents: inc})
|
||||
}
|
||||
|
||||
func TestIncidentsEgressSuppression(t *testing.T) {
|
||||
h := incRig(t)
|
||||
auth := map[string]string{"Authorization": "Bearer " + userTok}
|
||||
e, err := egress.New(egress.Config{Workloads: "ciberlab=10.0.5.0/24:scanner"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
SetEgress(e)
|
||||
defer SetEgress(nil)
|
||||
now := time.Now()
|
||||
e.IngestEvent(egress.Event{Time: now.Add(-time.Hour), Src: netip.MustParseAddr("10.0.3.5"), Dst: netip.MustParseAddr("203.0.113.3"), Proto: "tcp", DPort: 6667, In: "br-1"})
|
||||
|
||||
d := getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
if w := req(h, "GET", "/api/v1/incidents", ``, auth); !strings.Contains(w.Body.String(), `"total":0`) {
|
||||
t.Fatalf("a request fed the incidents: %s", w.Body)
|
||||
}
|
||||
incidentServer.Load().syncNow(context.Background())
|
||||
d = getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
var f map[string]any
|
||||
for _, x := range d["findings"].([]any) {
|
||||
if m := x.(map[string]any); m["kind"] == "port" {
|
||||
f = m
|
||||
}
|
||||
}
|
||||
if f == nil || f["ticket_id"] != "INC-1" || f["ticket_status"] != "open" || f["suppressed"] != false || d["suppressed_count"].(float64) != 0 {
|
||||
t.Fatalf("annotated: %v", d)
|
||||
}
|
||||
// suppression needs false_positive/benign
|
||||
if w := do(h, "GET", "/api/v1/incidents", cloneHdr(auth), nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"INC-1"`) || strings.Contains(w.Body.String(), `"history"`) || !strings.Contains(w.Body.String(), `"comment_count"`) {
|
||||
t.Fatalf("list: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := req(h, "PATCH", "/api/v1/incidents/INC-1", `{"suppress":true}`, auth); w.Code != 409 {
|
||||
t.Fatalf("suppress in open: %d", w.Code)
|
||||
}
|
||||
if w := req(h, "PATCH", "/api/v1/incidents/INC-1", `{"status":"false_positive","suppress":true,"author":"ana"}`, auth); w.Code != 200 {
|
||||
t.Fatalf("patch: %d %s", w.Code, w.Body)
|
||||
}
|
||||
incidentServer.Load().syncNow(context.Background())
|
||||
d = getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
for _, x := range d["findings"].([]any) {
|
||||
if x.(map[string]any)["kind"] == "port" {
|
||||
t.Fatalf("suppressed finding still listed: %v", x)
|
||||
}
|
||||
}
|
||||
if d["suppressed_count"].(float64) != 1 {
|
||||
t.Fatalf("suppressed_count: %v", d["suppressed_count"])
|
||||
}
|
||||
d = getJSON(t, h, "/api/v1/egress?range=24h&suppressed=1", auth)
|
||||
shown := false
|
||||
for _, x := range d["findings"].([]any) {
|
||||
if m := x.(map[string]any); m["kind"] == "port" && m["suppressed"] == true && m["ticket_status"] == "false_positive" {
|
||||
shown = true
|
||||
}
|
||||
}
|
||||
if !shown {
|
||||
t.Fatalf("?suppressed=1: %v", d["findings"])
|
||||
}
|
||||
// another destination is not covered by the exact key
|
||||
e.IngestEvent(egress.Event{Time: now.Add(-time.Hour), Src: netip.MustParseAddr("10.0.3.5"), Dst: netip.MustParseAddr("203.0.113.4"), Proto: "tcp", DPort: 6667, In: "br-1"})
|
||||
d = getJSON(t, h, "/api/v1/egress?range=24h", auth)
|
||||
if len(d["findings"].([]any)) == 0 {
|
||||
t.Fatal("a different key was suppressed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIncidentsAPI(t *testing.T) {
|
||||
h := incRig(t)
|
||||
auth := map[string]string{"Authorization": "Bearer " + userTok}
|
||||
paths := [][2]string{{"GET", "/api/v1/incidents"}, {"GET", "/api/v1/incidents/INC-1"}, {"POST", "/api/v1/incidents"}, {"PATCH", "/api/v1/incidents/INC-1"}, {"POST", "/api/v1/incidents/INC-1/comments"}, {"GET", "/api/v1/incidents/export.csv"}}
|
||||
for _, p := range paths {
|
||||
if w := req(h, p[0], p[1], `{}`, nil); w.Code != 401 {
|
||||
t.Errorf("%v no auth: %d", p, w.Code)
|
||||
}
|
||||
if w := req(h, p[0], p[1], `{}`, map[string]string{"Authorization": "Bearer " + peerTok}); w.Code != 403 {
|
||||
t.Errorf("%v peer token: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
cross := map[string]string{"Authorization": "Bearer " + userTok, "Sec-Fetch-Site": "cross-site"}
|
||||
for _, p := range paths[2:5] {
|
||||
if w := req(h, p[0], p[1], `{"title":"x"}`, cross); w.Code != 403 {
|
||||
t.Errorf("%v cross-site: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
w := req(h, "POST", "/api/v1/incidents", `{"title":"Servidor estranho","detail":"d","severity":"high","host":"oracle","tags":["a-b"],"author":"ana"}`, auth)
|
||||
if w.Code != 201 {
|
||||
t.Fatalf("create: %d %s", w.Code, w.Body)
|
||||
}
|
||||
var tk map[string]any
|
||||
json.Unmarshal(w.Body.Bytes(), &tk)
|
||||
if tk["id"] != "INC-1" || tk["source"] != "manual" || tk["status"] != "open" {
|
||||
t.Fatalf("ticket: %v", tk)
|
||||
}
|
||||
bad := []struct{ m, p, b string }{
|
||||
{"POST", "/api/v1/incidents", `nope`},
|
||||
{"POST", "/api/v1/incidents", `{"title":"x","extra":1}`},
|
||||
{"POST", "/api/v1/incidents", `{"title":""}`},
|
||||
{"POST", "/api/v1/incidents", `{"title":"x","severity":"urgent"}`},
|
||||
{"POST", "/api/v1/incidents", `{"title":"x"}{"title":"y"}`},
|
||||
{"POST", "/api/v1/incidents", `{"title":"` + strings.Repeat("a", 70<<10) + `"}`},
|
||||
{"PATCH", "/api/v1/incidents/INC-1", `{"status":"bogus"}`},
|
||||
{"PATCH", "/api/v1/incidents/INC-1", `{"tags":["BAD"]}`},
|
||||
{"PATCH", "/api/v1/incidents/INC-1", `{"title":"a\u0000b"}`},
|
||||
{"PATCH", "/api/v1/incidents/INC-1", `{"id":"INC-2"}`},
|
||||
{"POST", "/api/v1/incidents/INC-1/comments", `{"text":""}`},
|
||||
{"POST", "/api/v1/incidents/INC-1/comments", `{"text":"` + strings.Repeat("a", 5001) + `"}`},
|
||||
{"GET", "/api/v1/incidents?status=nope", ``},
|
||||
{"GET", "/api/v1/incidents?sort=x", ``},
|
||||
{"GET", "/api/v1/incidents?page=0", ``},
|
||||
}
|
||||
for _, c := range bad {
|
||||
if w := req(h, c.m, c.p, c.b, auth); w.Code != 400 {
|
||||
t.Errorf("%s %s %.40q: %d", c.m, c.p, c.b, w.Code)
|
||||
}
|
||||
}
|
||||
for _, p := range [][2]string{{"GET", "/api/v1/incidents/INC-99"}, {"PATCH", "/api/v1/incidents/INC-99"}, {"POST", "/api/v1/incidents/INC-99/comments"}} {
|
||||
body := `{"title":"x"}`
|
||||
if strings.HasSuffix(p[1], "/comments") {
|
||||
body = `{"text":"x"}`
|
||||
}
|
||||
if w := req(h, p[0], p[1], body, auth); w.Code != 404 {
|
||||
t.Errorf("%v: %d", p, w.Code)
|
||||
}
|
||||
}
|
||||
if w := req(h, "POST", "/api/v1/incidents/INC-1/comments", `{"text":"visto"}`, auth); w.Code != 201 || !strings.Contains(w.Body.String(), `operator (via token)`) {
|
||||
t.Fatalf("comment: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if w := req(h, "PATCH", "/api/v1/incidents/INC-1", `{"status":"resolved","verdict":"ok","assignee":"bia"}`, auth); w.Code != 200 {
|
||||
t.Fatalf("patch: %d %s", w.Code, w.Body)
|
||||
}
|
||||
d := getJSON(t, h, "/api/v1/incidents/INC-1", auth)
|
||||
if d["status"] != "resolved" || len(d["history"].([]any)) != 4 || len(d["comments"].([]any)) != 1 {
|
||||
t.Fatalf("full: %v", d)
|
||||
}
|
||||
l := getJSON(t, h, "/api/v1/incidents?status=resolved,open&per_page=1&page="+strconv.Itoa(1), auth)
|
||||
if l["total"].(float64) != 1 || l["counts"].(map[string]any)["resolved"].(float64) != 1 {
|
||||
t.Fatalf("list: %v", l)
|
||||
}
|
||||
if w := req(h, "GET", "/api/v1/incidents/export.csv", ``, auth); w.Code != 200 || !strings.HasPrefix(w.Body.String(), "id,status") || !strings.Contains(w.Body.String(), "INC-1") {
|
||||
t.Fatalf("csv: %d %s", w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -32,8 +32,9 @@ type enforceView struct {
|
||||
|
||||
// egressView is the outbound-traffic data of the report (nil: analysis not running).
|
||||
type egressView struct {
|
||||
Source egress.SourceInfo
|
||||
Report egress.Report
|
||||
Source egress.SourceInfo
|
||||
Report egress.Report
|
||||
Suppressed int // findings hidden by tickets
|
||||
}
|
||||
|
||||
// reportInput is everything the renderer needs. To wire another source, fill a
|
||||
@@ -543,6 +544,9 @@ func (r *renderer) build(in reportInput, genTS int64) viewV {
|
||||
} else {
|
||||
v.XNotes = append(v.XNotes, r.t("x.sev", r.num(float64(len(rep.Findings))), r.num(float64(xHigh))))
|
||||
}
|
||||
if x.Suppressed > 0 {
|
||||
v.XNotes = append(v.XNotes, r.t("x.supp", r.num(float64(x.Suppressed))))
|
||||
}
|
||||
v.XNotes = append(v.XNotes, r.t("x.src", x.Source.State))
|
||||
v.XWl = tableV{Head: []string{r.t("col.wl"), r.t("col.role"), r.t("col.conns"), r.t("col.dst")}, Num: map[int]bool{2: true, 3: true}}
|
||||
var items []chartItem
|
||||
@@ -693,7 +697,9 @@ func (s *Server) reportExtras(r *http.Request, rc *reportCtx) reportInput {
|
||||
in.Enforce = &enforceView{Mode: e.Mode(), Share: e.Share(), Coverage: rep.Coverage, Counts: rep.Counts, Recent: rep.Recent}
|
||||
}
|
||||
if e := egressEngine.Load(); e != nil {
|
||||
in.Egress = &egressView{Source: e.Info(), Report: e.Report(rc.from, rc.to)}
|
||||
rep := e.Report(rc.from, rc.to)
|
||||
sup := s.annotateFindings(&rep, false) // tickets marked false positive/benign leave the report
|
||||
in.Egress = &egressView{Source: e.Info(), Report: rep, Suppressed: sup}
|
||||
}
|
||||
}
|
||||
return in
|
||||
|
||||
@@ -140,7 +140,7 @@ var reportText = map[string][2]string{
|
||||
"d.refused": {"Exploits recusados", "Exploits refused"},
|
||||
"d.cover.m": {"Parte dos IPs hostis que já estava banida.", "Share of hostile IPs that were already banned."},
|
||||
"d.mttb.m": {"Quanto menor, melhor: é a janela entre o primeiro ataque e o bloqueio.", "Lower is better: the window between the first attack and the block."},
|
||||
"d.block.m": {"Parte dos atacantes que já constava em listas públicas de bloqueio.", "Share of attackers already in public blocklists."},
|
||||
"d.block.m": {"Parte dos atacantes hostis protegidos: na lista de bloqueio publicada ou já banidos por algum jail.", "Share of hostile attackers protected: on the published blocklist or already banned by a jail."},
|
||||
"d.expo.m": {"Parte dos ataques que recebeu resposta de sucesso. Deve ficar perto de zero.", "Share of attacks that got a success answer. Should stay near zero."},
|
||||
"d.refused.m": {"Parte das tentativas de exploração recusada pelo servidor.", "Share of exploit attempts refused by the server."},
|
||||
"e.mode": {"Modo", "Mode"},
|
||||
@@ -158,6 +158,7 @@ var reportText = map[string][2]string{
|
||||
"e.werr": {"Erros de gravação", "Write errors"},
|
||||
"x.lead": {"Tráfego de saída é o que os seus servidores iniciam em direção à internet. Um servidor sadio fala com poucos destinos conhecidos; conversas periódicas com destinos estranhos podem indicar invasão.", "Outbound traffic is what your servers start towards the internet. A healthy server talks to a few known destinations; periodic talks to strange destinations may indicate a breach."},
|
||||
"x.nof": {"Nenhum alerta de saída no período.", "No outbound alerts in this period."},
|
||||
"x.supp": {"%s achado(s) suprimido(s) por chamados de incidente.", "%s finding(s) suppressed by incident tickets."},
|
||||
"x.sev": {"%s alerta(s) de saída, %s de severidade alta.", "%s outbound alert(s), %s of high severity."},
|
||||
"x.src": {"Fonte dos dados: %s.", "Data source: %s."},
|
||||
"stage.recon": {"reconhecimento", "reconnaissance"},
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/incidents"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
@@ -67,7 +68,9 @@ type Options struct {
|
||||
Version string
|
||||
Store *store.Store
|
||||
Hub *fed.Hub
|
||||
Now func() time.Time
|
||||
// Incidents is the ticket store (nil: incident management off).
|
||||
Incidents *incidents.Store
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Server is the HTTP handler.
|
||||
@@ -126,6 +129,9 @@ func New(opt Options) http.Handler {
|
||||
m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream))
|
||||
m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false)))
|
||||
m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true)))
|
||||
if opt.Incidents != nil {
|
||||
incidentServer.Store(s)
|
||||
}
|
||||
return s.headers(m)
|
||||
}
|
||||
|
||||
|
||||
+110
-5
@@ -28,6 +28,7 @@
|
||||
* pt-BR "nas últimas 6 horas" / "na última hora" / "nos últimos 7 dias" / "entre 12 nov 10:00 e 14 nov 18:00"
|
||||
* Urutau.href(pageId, segments?, query?) -> hash that keeps the current slice
|
||||
* Urutau.toast(msg) short confirmation toast
|
||||
* Urutau.setNavBadge(pageId, n, title?) counter on the page's rail/tab item (0 removes it)
|
||||
* Urutau.help(node, key) appends an accessible "?" button to node (keyboard focus, aria-describedby,
|
||||
* popover with a short text and "what to do"). Urutau.glossary = { has(key), get(key) -> {text, action} }.
|
||||
* Keys (central dictionary, en + pt-BR, each with a ".do" companion): help.cat.<category>,
|
||||
@@ -989,6 +990,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]) + ')'; }
|
||||
@@ -1196,7 +1252,7 @@
|
||||
// rail groups; ids not listed go to the end of their group (page.group, else Analyze)
|
||||
var GROUPS = [
|
||||
['monitor', ['overview', 'live', 'slo']],
|
||||
['investigate', ['ips', 'sessions', 'campaigns', 'replay', 'search']],
|
||||
['investigate', ['ips', 'sessions', 'campaigns', 'replay', 'search', 'incidents']],
|
||||
['analyze', ['threats', 'mitre', 'geo', 'evolution', 'concentration', 'survival', 'traffic', 'errors', 'protocol']],
|
||||
['operate', ['defense', 'sources', 'integrity']],
|
||||
['reports', ['reports']]
|
||||
@@ -1857,6 +1913,22 @@
|
||||
}
|
||||
|
||||
function navId() { return current ? (current.id === 'ip' ? 'ips' : current.id) : null; }
|
||||
// small counter on a rail/tab item (e.g. open incidents); n <= 0 removes it. Set by page scripts.
|
||||
var navBadges = {};
|
||||
function setNavBadge(id, n, label) {
|
||||
n = Math.max(0, Math.floor(Number(n) || 0));
|
||||
var old = navBadges[id];
|
||||
if (old ? old.n === n && old.label === label : n === 0) return;
|
||||
if (n) navBadges[id] = { n: n, label: label || '' }; else delete navBadges[id];
|
||||
if (booted) renderNav();
|
||||
}
|
||||
function navBadgeNode(id) {
|
||||
var b = navBadges[id];
|
||||
if (!b) return null;
|
||||
var n = h('span', 'nav-badge', b.n > 99 ? '99+' : String(b.n));
|
||||
if (b.label) n.title = b.label;
|
||||
return n;
|
||||
}
|
||||
function renderNav() {
|
||||
var list = orderedPages(), nav = $('#nav'), bar = $('#tabbar'), more = $('#more'), cur = navId();
|
||||
clear(nav); clear(bar); clear(more);
|
||||
@@ -1864,13 +1936,13 @@
|
||||
list.forEach(function (p) {
|
||||
var label = t(p.titleKey), gr = groupOf(p);
|
||||
if (gr !== lastGroup) { nav.appendChild(h('div', 'nav-group', t('nav.group.' + gr))); lastGroup = gr; }
|
||||
var a = el('a', { class: 'nav-item', href: hrefFor(p.id), title: label }, h('span', 'nav-ico', iconNode(p.icon)), h('span', 'nav-label', label));
|
||||
var a = el('a', { class: 'nav-item', href: hrefFor(p.id), title: label }, h('span', 'nav-ico', iconNode(p.icon)), h('span', 'nav-label', label), navBadgeNode(p.id));
|
||||
if (cur === p.id) a.setAttribute('aria-current', 'page');
|
||||
nav.appendChild(a);
|
||||
});
|
||||
var direct = list.length <= 5 ? list : list.slice(0, 4), rest = list.length <= 5 ? [] : list.slice(4);
|
||||
direct.forEach(function (p) {
|
||||
var a = el('a', { class: 'tab', href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)));
|
||||
var a = el('a', { class: 'tab', href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)), navBadgeNode(p.id));
|
||||
if (cur === p.id) a.setAttribute('aria-current', 'page');
|
||||
bar.appendChild(a);
|
||||
});
|
||||
@@ -1884,7 +1956,7 @@
|
||||
rest.forEach(function (p) {
|
||||
var g2 = groupOf(p);
|
||||
if (g2 !== rg) { more.appendChild(h('div', 'nav-group', t('nav.group.' + g2))); rg = g2; }
|
||||
var a = el('a', { href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)));
|
||||
var a = el('a', { href: hrefFor(p.id) }, h('span', 'nav-ico', iconNode(p.icon)), h('span', null, t(p.titleKey)), navBadgeNode(p.id));
|
||||
if (cur === p.id) a.setAttribute('aria-current', 'page');
|
||||
more.appendChild(a);
|
||||
});
|
||||
@@ -1939,6 +2011,39 @@
|
||||
}
|
||||
if (current) { try { current.page.unmount(); } catch (e) { console.error(e); } }
|
||||
var view = $('#view');
|
||||
// Mobile tables: every plain data table of a page gets data-label on its cells (from the header)
|
||||
// and the class "mc"; style.css turns those rows into stacked cards under 768 px. Tables that
|
||||
// already handle phones (stack, tbl-cards, eg-table, ipx-tbl, no-mc) and the sr-only chart tables are skipped.
|
||||
function cardTables() {
|
||||
var tabs = view.querySelectorAll('table:not(.sr-only):not(.stack):not(.tbl-cards):not(.eg-table):not(.ipx-tbl):not(.no-mc):not(.mc)');
|
||||
for (var i = 0; i < tabs.length; i++) {
|
||||
var tb = tabs[i], hr = tb.querySelector('thead tr');
|
||||
if (!hr) continue;
|
||||
var labels = [].map.call(hr.children, function (c) { return (c.textContent || '').trim(); });
|
||||
[].forEach.call(tb.tBodies, function (body) {
|
||||
[].forEach.call(body.rows, function (r) {
|
||||
var k = 0;
|
||||
[].forEach.call(r.cells, function (c) {
|
||||
if (!c.hasAttribute('data-label')) c.setAttribute('data-label', labels[k] || '');
|
||||
if (c.childNodes.length > 1) { // one flex item per cell, so mixed content flows as text
|
||||
var w = document.createElement('span');
|
||||
w.className = 'mc-v';
|
||||
while (c.firstChild) w.appendChild(c.firstChild);
|
||||
c.appendChild(w);
|
||||
}
|
||||
k += c.colSpan || 1;
|
||||
});
|
||||
});
|
||||
});
|
||||
tb.classList.add('mc');
|
||||
}
|
||||
}
|
||||
var cardQueued = false;
|
||||
new MutationObserver(function () {
|
||||
if (cardQueued) return;
|
||||
cardQueued = true;
|
||||
requestAnimationFrame(function () { cardQueued = false; cardTables(); });
|
||||
}).observe(view, { childList: true, subtree: true });
|
||||
clear(view);
|
||||
state.note = '';
|
||||
var page = pages[id];
|
||||
@@ -2056,7 +2161,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, setNavBadge: setNavBadge,
|
||||
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)',
|
||||
@@ -115,6 +125,7 @@
|
||||
'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.reason.neighbor-campaign': 'Part of a campaign: several neighbours in the same network range were already banned',
|
||||
'df.en.error': 'Could not load the second firewall data.'
|
||||
},
|
||||
'pt-BR': {
|
||||
@@ -200,6 +211,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)',
|
||||
@@ -221,6 +242,7 @@
|
||||
'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.reason.neighbor-campaign': 'Parte de uma campanha: vários vizinhos da mesma faixa de rede já foram banidos',
|
||||
'df.en.error': 'Não foi possível carregar os dados do segundo firewall.'
|
||||
}
|
||||
});
|
||||
@@ -387,7 +409,7 @@
|
||||
k(U.ui.metric(t('df.en.c.already'), nf(cn.already_blocked || 0)));
|
||||
np.body.appendChild(kp);
|
||||
var skl = el('ul', { class: 'df-skips' });
|
||||
['trusted', 'private', 'crawler', 'legit_visitor', 'peer'].forEach(function (key) {
|
||||
['trusted', 'private', 'crawler', 'legit_visitor', 'peer', 'operator_allow'].forEach(function (key) {
|
||||
if (!sk[key]) return;
|
||||
skl.appendChild(el('li', null, el('span', { class: 'num' }, nf(sk[key])), ' ' + t('df.en.skip.' + key)));
|
||||
});
|
||||
@@ -401,8 +423,9 @@
|
||||
var cols = [{ label: t('df.en.col.time') }, { label: t('df.en.col.ip'), cls: 'mono' }, { label: t('df.en.col.cc') }, { label: t('df.en.col.reason') },
|
||||
{ label: t('df.en.col.score'), cls: 'num' }, { label: t('df.en.col.ttl'), cls: 'num' }, { label: t('df.en.col.action') }, { label: t('df.en.col.src') }];
|
||||
rp.body.appendChild(tbl(cols, rec.map(function (r) {
|
||||
var act = /^(ban|would_ban|skip)$/.test(r.action) ? r.action : 'skip';
|
||||
var act = /^(ban|would_ban|skip|unban)$/.test(r.action) ? r.action : 'skip';
|
||||
var actNode = el('span', { class: 'df-act' }, U.ui.badge(t('df.en.act.' + act), act === 'ban' ? 'ok' : act === 'would_ban' ? 'warn' : 'neutral'));
|
||||
if (act === 'ban') actNode.appendChild(el('button', { type: 'button', class: 'btn btn-sm df-unban', onclick: function () { U.unbanDialog(r.ip, loadEnforce); } }, t('unban.btn')));
|
||||
if (act === 'skip' && r.skip_reason) {
|
||||
var sk2 = 'df.en.skip.' + r.skip_reason;
|
||||
actNode.appendChild(el('small', { class: 'df-skipwhy' }, t(sk2) !== sk2 ? t(sk2) : r.skip_reason));
|
||||
@@ -414,6 +437,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() {
|
||||
|
||||
@@ -153,3 +153,9 @@
|
||||
.eg-bursts li { grid-template-columns: 84px minmax(0, 1fr); }
|
||||
.eg-b-chips { grid-column: 1 / -1; }
|
||||
}
|
||||
|
||||
/* ticket badge and suppressed findings (v1.5.0) */
|
||||
.eg-ticket { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; color: var(--ink); max-width: 100%; }
|
||||
.eg-ticket:hover .badge, .eg-ticket:focus-visible .badge { border-color: var(--line-strong); }
|
||||
.eg-ev-sup { opacity: .7; }
|
||||
.eg-sup-toggle { display: inline-flex; align-items: center; gap: 6px; font-size: .875rem; color: var(--ink-muted); cursor: pointer; min-height: 36px; }
|
||||
@@ -14,6 +14,8 @@
|
||||
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;
|
||||
var TICKET_STATUS = ['open', 'investigating', 'true_positive', 'false_positive', 'benign', 'resolved'];
|
||||
var TICKET_TONE = { open: 'warn', investigating: 'info', true_positive: 'danger', false_positive: 'neutral', benign: 'neutral', resolved: 'ok' };
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
@@ -250,7 +252,7 @@
|
||||
});
|
||||
|
||||
var el = U.el, t = U.t, nf = U.fmt.num;
|
||||
var root = null, seq = 0, alive = false, ctx = null, data = null, hosts = null;
|
||||
var root = null, seq = 0, alive = false, ctx = null, data = null, hosts = null, showSup = false;
|
||||
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
function help(node, key) { if (U.help) U.help(node, key); return node; }
|
||||
@@ -344,6 +346,12 @@
|
||||
if (kind) help(title, KIND_HELP[kind]);
|
||||
var head = el('div', { class: 'eg-ev-head' }, U.ui.badge(t('eg.sev.' + sev), SEV_TONE[sev]), title);
|
||||
if (st.multi && f.host) head.appendChild(el('span', { class: 'chip' }, t('eg.f.host', { h: f.host })));
|
||||
if (f.ticket_id) {
|
||||
var ts = TICKET_STATUS.indexOf(f.ticket_status) >= 0 ? f.ticket_status : 'open';
|
||||
head.appendChild(el('a', { class: 'eg-ticket', href: U.href('incidents', [String(f.ticket_id)]), title: t('eg.f.ticket', { id: String(f.ticket_id) }) },
|
||||
el('span', { class: 'mono' }, String(f.ticket_id)), U.ui.badge(t('inc.status.' + ts), TICKET_TONE[ts])));
|
||||
}
|
||||
if (f.suppressed) head.appendChild(el('span', { class: 'chip' }, t('eg.suppressed.chip')));
|
||||
|
||||
var route = el('div', { class: 'eg-route' },
|
||||
el('span', { class: 'eg-node' }, el('span', { class: 'eg-node-k' }, t('eg.f.from')), el('strong', { class: 'mono' }, f.workload || '-')),
|
||||
@@ -368,7 +376,7 @@
|
||||
el('div', { class: 'eg-ev-todo' }, el('p', { class: 'eg-ev-lab' }, t('eg.f.todo')), el('p', null, t('eg.do.' + kind)))));
|
||||
}
|
||||
if (f.dst) body.appendChild(el('a', { class: 'btn eg-ev-btn', href: U.href('ip', [f.dst]) }, t('eg.f.open') + ' →'));
|
||||
return el('article', { class: 'eg-ev eg-sev-' + sev }, head, body);
|
||||
return el('article', { class: 'eg-ev eg-sev-' + sev + (f.suppressed ? ' eg-ev-sup' : '') }, head, body);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ map
|
||||
@@ -543,7 +551,14 @@
|
||||
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' });
|
||||
var supN = data.suppressed_count || 0, fpActs = null;
|
||||
if (supN || showSup) {
|
||||
var cb = el('input', { type: 'checkbox', id: 'eg-sup' });
|
||||
cb.checked = showSup;
|
||||
cb.addEventListener('change', function () { showSup = cb.checked; load(); });
|
||||
fpActs = el('label', { class: 'eg-sup-toggle', for: 'eg-sup' }, cb, el('span', null, t('eg.suppressed.toggle', { n: nf(supN) })));
|
||||
}
|
||||
var fp = U.ui.panel({ title: t('eg.findings'), hint: t('eg.findings.hint'), cls: 'span-12', actions: fpActs });
|
||||
if (!st.fnd.length) {
|
||||
fp.body.appendChild(el('div', { class: 'eg-calm' }, el('span', { class: 'eg-calm-ico', 'aria-hidden': 'true' }, '✓'),
|
||||
el('div', null, el('strong', null, t('eg.calm')), el('p', null, t('eg.calm.sub')))));
|
||||
@@ -590,6 +605,7 @@
|
||||
var my = ++seq;
|
||||
var p = Object.assign({}, U.rangeParams());
|
||||
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
|
||||
if (showSup) p.suppressed = 1;
|
||||
if (!hosts) {
|
||||
hosts = [];
|
||||
U.api('/api/v1/summary', { range: '1h', host: 'all' }).then(function (s) {
|
||||
|
||||
@@ -44,6 +44,19 @@ window.URUTAU_I18N = {
|
||||
'range.widen': 'Choose another period',
|
||||
'timeline.bucket': '{n}-minute buckets',
|
||||
'toast.copied': 'Copied',
|
||||
'unban.btn': 'Unban',
|
||||
'unban.title': 'Unban {ip}',
|
||||
'unban.explain': 'This lifts the block on this address in the server firewall (fail2ban) right away. Use it when the block was a mistake or when you are testing your own system.',
|
||||
'unban.keep': 'Do not block it again for:',
|
||||
'unban.keep.none': 'Do not keep (it can be blocked again)',
|
||||
'unban.keep.1h': '1 hour',
|
||||
'unban.keep.24h': '24 hours',
|
||||
'unban.keep.7d': '7 days',
|
||||
'unban.confirm': 'Unban',
|
||||
'unban.cancel': 'Cancel',
|
||||
'unban.done': '{ip} unbanned',
|
||||
'unban.err': 'Could not unban. Try again.',
|
||||
'unban.err.off': 'The second firewall is off, so there is nothing to unban from here.',
|
||||
'state.retry': 'Try again',
|
||||
'top.empty.title': 'No data',
|
||||
'ips.empty.title': 'No IPs found',
|
||||
@@ -546,6 +559,19 @@ window.URUTAU_I18N = {
|
||||
'range.widen': 'Escolher outro período',
|
||||
'timeline.bucket': 'caixas de {n} min',
|
||||
'toast.copied': 'Copiado',
|
||||
'unban.btn': 'Desbanir',
|
||||
'unban.title': 'Desbanir {ip}',
|
||||
'unban.explain': 'Isto libera agora o bloqueio deste endereço no firewall do servidor (fail2ban). Use quando o bloqueio foi um engano ou quando você está testando o seu próprio sistema.',
|
||||
'unban.keep': 'Não bloquear de novo por:',
|
||||
'unban.keep.none': 'Não manter (pode ser bloqueado de novo)',
|
||||
'unban.keep.1h': '1 hora',
|
||||
'unban.keep.24h': '24 horas',
|
||||
'unban.keep.7d': '7 dias',
|
||||
'unban.confirm': 'Desbanir',
|
||||
'unban.cancel': 'Cancelar',
|
||||
'unban.done': '{ip} desbanido',
|
||||
'unban.err': 'Não foi possível desbanir. Tente de novo.',
|
||||
'unban.err.off': 'O segundo firewall está desligado, então não há o que desbanir por aqui.',
|
||||
'state.retry': 'Tentar novamente',
|
||||
'top.empty.title': 'Sem dados',
|
||||
'ips.empty.title': 'Nenhum IP encontrado',
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
/* Urutau - INCIDENTS page. Ticket text is untrusted: long words wrap or truncate, nothing forces horizontal scroll.
|
||||
Spacing scale 4/8/12/16/24; controls 32px; secondary text .8125rem muted. */
|
||||
.inc-page { min-width: 0; }
|
||||
.inc-hint { font-size: .8125rem; color: var(--ink-muted); overflow-wrap: anywhere; }
|
||||
.inc-link { background: none; border: 0; padding: 0; color: var(--accent); cursor: pointer; font: inherit; font-size: .8125rem; }
|
||||
.inc-link:hover { text-decoration: underline; }
|
||||
.inc-link:focus-visible, .inc-title-btn:focus-visible, .inc-tab:focus-visible, .inc-info:focus-visible { outline: 0; box-shadow: var(--focus-ring); border-radius: 4px; }
|
||||
.inc-page .btn, .inc-page select, .inc-page input[type="text"], .inc-page input[type="search"] { min-height: 32px; padding-top: 3px; padding-bottom: 3px; }
|
||||
.inc-page .btn.sm { min-height: 32px; padding: 3px 12px; font-size: .875rem; }
|
||||
.inc-page textarea, .inc-dlg textarea {
|
||||
background: var(--surface-raised); color: var(--ink); border: 1px solid var(--line); border-radius: var(--radius-sm);
|
||||
padding: 8px 12px; font: inherit; resize: vertical; min-height: 64px; width: 100%; box-sizing: border-box;
|
||||
}
|
||||
.inc-page textarea:focus-visible, .inc-dlg textarea:focus-visible { outline: 0; box-shadow: var(--focus-ring); }
|
||||
.inc-field { display: grid; gap: 4px; min-width: 0; }
|
||||
.inc-field label { font-size: .875rem; font-weight: 600; }
|
||||
.inc-form { display: grid; gap: var(--s-3); }
|
||||
.inc-field input[type="text"], .inc-field select { width: 100%; box-sizing: border-box; min-width: 0; }
|
||||
.inc-dlg { width: min(34rem, calc(100vw - 32px)); }
|
||||
.inc-btns { display: flex; flex-wrap: wrap; gap: var(--s-2); justify-content: flex-end; margin-top: var(--s-2); }
|
||||
.inc-err { color: var(--danger); margin: var(--s-2) 0 0; font-size: .875rem; }
|
||||
.inc-dot { width: 10px; height: 10px; border-radius: 50%; background: var(--ink-faint); flex: none; display: inline-block; }
|
||||
.inc-d-critical, .inc-d-high { background: var(--danger); }
|
||||
.inc-d-medium { background: var(--warn); }
|
||||
.inc-d-low { background: var(--info); }
|
||||
.inc-id { font-weight: 600; white-space: nowrap; }
|
||||
|
||||
/* ---------------- list */
|
||||
.inc-bar { display: flex; flex-wrap: nowrap; align-items: center; justify-content: space-between; gap: var(--s-4); margin-bottom: var(--s-4); border-bottom: 1px solid var(--line); }
|
||||
.inc-tabwrap { display: flex; align-items: center; gap: var(--s-2); min-width: 0; flex: 1 1 auto; }
|
||||
.inc-info { color: var(--ink-muted); cursor: help; font-size: 1rem; flex: none; }
|
||||
.inc-tabs { display: flex; flex-wrap: nowrap; overflow-x: auto; gap: var(--s-1); min-width: 0; scrollbar-width: thin; }
|
||||
.inc-tab { display: inline-flex; align-items: center; gap: 6px; height: 36px; padding: 0 var(--s-3); border: 0; border-bottom: 2px solid transparent; background: none; color: var(--ink-muted); cursor: pointer; font: inherit; font-size: .875rem; white-space: nowrap; flex: none; margin-bottom: -1px; }
|
||||
.inc-tab:hover { color: var(--ink); }
|
||||
.inc-tab.on { color: var(--ink); font-weight: 600; border-bottom-color: var(--accent); }
|
||||
.inc-tab.zero { opacity: .6; }
|
||||
.inc-n { font-size: .75rem; color: var(--ink-muted); background: var(--surface-raised); border-radius: 999px; padding: 0 6px; }
|
||||
.inc-tab-sep { width: 1px; background: var(--line); margin: 8px var(--s-2); flex: none; }
|
||||
.inc-toolbar { display: flex; flex-wrap: wrap; gap: var(--s-2); align-items: center; padding-bottom: var(--s-2); flex: none; }
|
||||
.inc-search { width: 240px; max-width: 100%; }
|
||||
@media (max-width: 1500px) {
|
||||
.inc-bar { flex-direction: column; align-items: stretch; gap: var(--s-2); border-bottom: 0; }
|
||||
.inc-tabwrap { border-bottom: 1px solid var(--line); }
|
||||
.inc-toolbar { padding-bottom: 0; }
|
||||
.inc-search { flex: 1 1 200px; }
|
||||
}
|
||||
|
||||
.inc-table { border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-panel); }
|
||||
.inc-thead, .inc-row {
|
||||
display: grid; grid-template-columns: 10px 64px minmax(0, 1fr) 124px 90px 200px 76px; gap: var(--s-3); align-items: center; padding: 8px var(--s-3);
|
||||
}
|
||||
.inc-thead { border-radius: var(--radius-sm) var(--radius-sm) 0 0; position: sticky; top: var(--topbar-h, 56px); z-index: 2; background: var(--surface-raised); border-bottom: 1px solid var(--line); font-size: .75rem; color: var(--ink-muted); text-transform: uppercase; letter-spacing: .04em; }
|
||||
.inc-thead .r { text-align: right; }
|
||||
.inc-row { min-height: 44px; box-sizing: border-box; color: var(--ink); text-decoration: none; border-bottom: 1px solid var(--line); }
|
||||
.inc-row:last-child { border-bottom: 0; }
|
||||
.inc-row:hover { background: var(--surface-raised); }
|
||||
.inc-row:focus-visible { outline: 0; box-shadow: inset 0 0 0 2px var(--accent); }
|
||||
.inc-main { display: flex; align-items: center; gap: var(--s-2); min-width: 0; }
|
||||
.inc-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; font-weight: 500; }
|
||||
.inc-rtags { display: inline-flex; gap: 4px; flex: none; }
|
||||
.inc-rtags .chip { margin: 0; font-size: .75rem; }
|
||||
.inc-who, .inc-where { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: .8125rem; color: var(--ink-muted); min-width: 0; }
|
||||
.inc-where { font-size: .75rem; }
|
||||
.inc-when { text-align: right; font-size: .8125rem; color: var(--ink-muted); white-space: nowrap; }
|
||||
.inc-empty { display: grid; justify-items: center; gap: var(--s-2); padding: 48px var(--s-4); text-align: center; }
|
||||
.inc-results .pgr { margin-top: var(--s-4); }
|
||||
@media (max-width: 720px) {
|
||||
.inc-thead { display: none; }
|
||||
.inc-row { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-1) var(--s-3); padding: var(--s-3); }
|
||||
.inc-row > :nth-child(3) { order: 4; flex: 1 1 100%; }
|
||||
.inc-row > :nth-child(4) { order: 5; flex: none; }
|
||||
.inc-row > :nth-child(5) { order: 6; flex: none; }
|
||||
.inc-row > :nth-child(6) { order: 7; flex: 1 1 100%; }
|
||||
.inc-row > :nth-child(7) { order: 3; margin-left: auto; }
|
||||
.inc-search { width: 100%; flex-basis: 100%; }
|
||||
}
|
||||
|
||||
/* ---------------- detail */
|
||||
.inc-back { display: inline-block; margin-bottom: var(--s-3); color: var(--accent); text-decoration: none; font-size: .875rem; }
|
||||
.inc-back:hover { text-decoration: underline; }
|
||||
.inc-detail.busy { pointer-events: none; }
|
||||
.inc-head { position: sticky; top: var(--topbar-h, 56px); z-index: 5; display: grid; gap: var(--s-2); padding: var(--s-3) 0; margin-bottom: var(--s-4); background: var(--surface-base); border-bottom: 1px solid var(--line); }
|
||||
.inc-h1 { display: flex; align-items: center; gap: var(--s-3); min-width: 0; }
|
||||
.inc-h-title { flex: 1 1 auto; margin: 0; font-size: 1.25rem; font-weight: 700; min-width: 0; line-height: 1.3; }
|
||||
.inc-title-btn { all: unset; cursor: text; display: block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.inc-title-btn:hover { text-decoration: underline dotted; }
|
||||
.inc-title-in { width: 100%; box-sizing: border-box; font-size: 1.125rem; }
|
||||
.inc-quick { display: flex; gap: var(--s-2); flex: none; }
|
||||
.inc-q-tp:not(:disabled) { border-color: var(--danger); color: var(--danger); }
|
||||
.inc-q-ok:not(:disabled) { border-color: var(--ok); color: var(--ok); }
|
||||
.inc-h2 { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-2); min-width: 0; }
|
||||
.inc-h2 .chip { margin: 0; }
|
||||
.inc-metaline { margin-left: var(--s-2); }
|
||||
|
||||
.inc-layout { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: var(--s-4); align-items: start; max-width: 1280px; }
|
||||
.inc-maincol { display: grid; gap: var(--s-4); min-width: 0; }
|
||||
.inc-aside { display: grid; gap: var(--s-4); position: sticky; top: calc(var(--topbar-h, 56px) + 96px); min-width: 0; align-self: start; }
|
||||
.inc-card { background: var(--surface-panel); border: 1px solid var(--line); border-radius: var(--radius-sm); padding: var(--s-3) var(--s-4); min-width: 0; box-sizing: border-box; }
|
||||
.inc-card h2, .inc-tech summary { margin: 0 0 var(--s-3); font-size: .9375rem; font-weight: 600; }
|
||||
.inc-card-h { display: flex; align-items: center; justify-content: space-between; gap: var(--s-2); margin-bottom: var(--s-2); }
|
||||
.inc-card-h h2 { margin: 0; }
|
||||
.inc-summary.empty { background: none; border: 0; padding: 0; }
|
||||
.inc-text { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.inc-pre { margin: var(--s-2) 0 0; padding: var(--s-2) var(--s-3); background: var(--surface-sunken); border: 1px solid var(--line); border-radius: var(--radius-sm); font: .75rem/1.5 var(--font-mono); white-space: pre-wrap; overflow-wrap: anywhere; max-height: 12rem; overflow: auto; }
|
||||
|
||||
.inc-prop { display: grid; grid-template-columns: 88px minmax(0, 1fr); gap: var(--s-2) var(--s-3); align-items: start; padding: 6px 0; }
|
||||
.inc-prop > label { font-size: .8125rem; color: var(--ink-muted); line-height: 32px; }
|
||||
.inc-prop-c { min-width: 0; }
|
||||
.inc-prop select, .inc-prop input[type="text"] { width: 100%; box-sizing: border-box; min-width: 0; }
|
||||
.inc-stack { display: grid; gap: 4px; }
|
||||
.inc-stack .inc-link { justify-self: start; }
|
||||
.inc-switch { appearance: none; -webkit-appearance: none; width: 36px; height: 20px; border-radius: 999px; background: var(--line-strong); border: 0; position: relative; cursor: pointer; margin: 6px 0 0; transition: background .15s; }
|
||||
.inc-switch::after { content: ""; position: absolute; top: 2px; left: 2px; width: 16px; height: 16px; border-radius: 50%; background: var(--surface-base); transition: transform .15s; }
|
||||
.inc-switch:checked { background: var(--accent); }
|
||||
.inc-switch:checked::after { transform: translateX(16px); }
|
||||
.inc-switch:disabled { opacity: .45; cursor: default; }
|
||||
.inc-switch:focus-visible { outline: 0; box-shadow: var(--focus-ring); }
|
||||
|
||||
.inc-tech summary { cursor: pointer; list-style: none; }
|
||||
.inc-tech summary::-webkit-details-marker { display: none; }
|
||||
.inc-tech summary::after { content: "\25BE"; float: right; color: var(--ink-muted); }
|
||||
.inc-tech:not([open]) summary { margin-bottom: 0; }
|
||||
.inc-tech:not([open]) summary::after { content: "\25B8"; }
|
||||
.inc-dl { display: grid; grid-template-columns: minmax(0, auto) minmax(0, 1fr); gap: 4px var(--s-3); margin: 0; }
|
||||
.inc-dl dt { color: var(--ink-muted); font-size: .75rem; line-height: 20px; }
|
||||
.inc-dl dd { margin: 0; overflow-wrap: anywhere; min-width: 0; font-size: .8125rem; line-height: 20px; }
|
||||
.inc-keyrow { display: flex; gap: var(--s-2); align-items: center; }
|
||||
.inc-key { font-size: .75rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1 1 auto; }
|
||||
|
||||
.inc-newc { display: grid; gap: var(--s-2); margin-bottom: var(--s-3); }
|
||||
.inc-newc-f { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-2) var(--s-3); }
|
||||
.inc-newc-f .btn { margin-left: auto; }
|
||||
.inc-as { font-size: .8125rem; color: var(--ink-muted); }
|
||||
.inc-as strong { color: var(--ink); }
|
||||
.inc-as-in { width: 9rem; }
|
||||
.inc-feed { list-style: none; margin: 0; padding: 0; display: grid; gap: var(--s-2); }
|
||||
.inc-cmt { display: flex; gap: var(--s-3); padding: var(--s-3); background: var(--surface-raised); border: 1px solid var(--line); border-radius: var(--radius-sm); }
|
||||
.inc-av { width: 28px; height: 28px; border-radius: 50%; background: var(--accent-soft); color: var(--accent); display: inline-flex; align-items: center; justify-content: center; font-weight: 700; font-size: .8125rem; flex: none; }
|
||||
.inc-cmt-b { min-width: 0; flex: 1; }
|
||||
.inc-c-h { display: flex; flex-wrap: wrap; gap: var(--s-2) var(--s-3); align-items: baseline; margin-bottom: 2px; }
|
||||
.inc-ev { display: flex; align-items: baseline; gap: var(--s-2); font-size: .8125rem; color: var(--ink-muted); min-width: 0; padding: 0 var(--s-1); }
|
||||
.inc-ev-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--line-strong); flex: none; align-self: center; display: inline-block; margin-right: var(--s-2); }
|
||||
.inc-ev-t { min-width: 0; overflow-wrap: anywhere; flex: 1; }
|
||||
.inc-ev-chg { display: inline; }
|
||||
.inc-ev-chg .inc-from, .inc-ev-chg strong { display: -webkit-inline-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; vertical-align: bottom; max-width: 100%; }
|
||||
.inc-from { text-decoration: line-through; }
|
||||
.inc-ev-chg strong { color: var(--ink); font-weight: 600; }
|
||||
.inc-ev-when { flex: none; white-space: nowrap; }
|
||||
.inc-grp { display: block; }
|
||||
.inc-grp summary { cursor: pointer; list-style: none; display: flex; align-items: baseline; gap: var(--s-2); }
|
||||
.inc-grp summary::-webkit-details-marker { display: none; }
|
||||
.inc-sub { margin: var(--s-2) 0 0 var(--s-4); }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.inc-head { position: static; }
|
||||
.inc-layout { display: flex; flex-direction: column; gap: var(--s-4); }
|
||||
.inc-aside { display: contents; position: static; }
|
||||
.inc-props { order: 1; }
|
||||
.inc-maincol { order: 2; width: 100%; }
|
||||
.inc-tech { order: 3; }
|
||||
}
|
||||
@media (max-width: 600px) {
|
||||
.inc-h1 { flex-wrap: wrap; }
|
||||
.inc-quick { flex: 1 1 100%; order: 5; overflow-x: auto; padding-bottom: 2px; }
|
||||
.inc-quick .btn { flex: none; }
|
||||
.inc-metaline { margin-left: 0; flex-basis: 100%; }
|
||||
}
|
||||
|
||||
.inc-st { min-width: 0; }
|
||||
.inc-st .badge { max-width: 100%; overflow: hidden; text-overflow: ellipsis; }
|
||||
.inc-row:last-child { border-radius: 0 0 var(--radius-sm) var(--radius-sm); }
|
||||
.inc-keyrow > :not(.inc-key) { flex: none; white-space: nowrap; }
|
||||
.inc-dl dd { min-width: 0; }
|
||||
.inc-main { flex-direction: column; align-items: stretch; justify-content: center; gap: 2px; }
|
||||
.inc-mrow { display: flex; align-items: center; gap: var(--s-2); min-width: 0; }
|
||||
.inc-sub { font-size: .75rem; color: var(--ink-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
|
||||
.inc-tabs { gap: 0; }
|
||||
.inc-tab { padding: 0 10px; font-size: .8125rem; }
|
||||
.inc-tab-sep { margin: 8px 4px; }
|
||||
.inc-main > .inc-sub { padding: 0; margin: 0; background: none; border: 0; align-self: flex-start; max-width: 100%; }
|
||||
@media (max-width: 600px) {
|
||||
.inc-quick { flex-wrap: wrap; overflow-x: visible; }
|
||||
.inc-quick .btn { flex: 1 1 auto; }
|
||||
.inc-toolbar > select { flex: 1 1 calc(50% - var(--s-2)); min-width: 0; }
|
||||
.inc-toolbar > .btn { flex: 1 1 100%; }
|
||||
}
|
||||
@@ -0,0 +1,734 @@
|
||||
/* Urutau - INCIDENTS page: every finding of the outbound traffic (egress) becomes a ticket that
|
||||
people triage (open, investigating, true/false positive, benign, resolved), comment on and,
|
||||
for false positives, suppress. #/incidents is the list, #/incidents/<id> the ticket.
|
||||
Data: /api/v1/incidents (GET list, GET one, PATCH, POST comments, POST create).
|
||||
Ticket text (workload names, details, comments, tags) comes from hostile logs and from users:
|
||||
dynamic text goes through textContent only. */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var STATUSES = ['open', 'investigating', 'true_positive', 'false_positive', 'benign', 'resolved'];
|
||||
var STATUS_TONE = { open: 'warn', investigating: 'info', true_positive: 'danger', false_positive: 'neutral', benign: 'neutral', resolved: 'ok' };
|
||||
var SEVS = ['critical', 'high', 'medium', 'low', 'info'];
|
||||
var SEV_TONE = { critical: 'danger', high: 'danger', medium: 'warn', low: 'info', info: 'neutral' };
|
||||
var SORTS = ['updated', 'severity', 'last_seen'];
|
||||
var SUPPRESSIBLE = ['false_positive', 'benign'];
|
||||
var PER_PAGE = 25;
|
||||
var AUTHOR_KEY = 'urutau.author';
|
||||
|
||||
function boot() {
|
||||
var U = window.Urutau;
|
||||
if (!U || !U.registerPage) return false;
|
||||
var el = U.el, t = U.t;
|
||||
|
||||
U.registerI18n({
|
||||
en: {
|
||||
'inc.title': 'Incidents',
|
||||
'inc.nav.open': '{n} open or under investigation',
|
||||
'inc.lead': 'Every outbound finding is a ticket. Open it, investigate, write down what you found, and close it as a real incident, a false positive or benign.',
|
||||
'inc.author': 'Your name',
|
||||
'inc.author.hint': 'Saved in this browser and shown next to your comments and changes.',
|
||||
'inc.new': 'New ticket',
|
||||
'inc.search': 'Search tickets',
|
||||
'inc.sev.all': 'All severities',
|
||||
'inc.sev.critical': 'Critical', 'inc.sev.high': 'High', 'inc.sev.medium': 'Medium', 'inc.sev.low': 'Low', 'inc.sev.info': 'Info',
|
||||
'inc.sort': 'Sort by',
|
||||
'inc.sort.updated': 'Recently updated', 'inc.sort.severity': 'Severity', 'inc.sort.last_seen': 'Last seen',
|
||||
'inc.h.created': '{who} opened the ticket (severity: {sev})', 'inc.h.flood': 'flood grouping',
|
||||
'inc.status.open': 'Open', 'inc.status.investigating': 'Investigating', 'inc.status.true_positive': 'True positive',
|
||||
'inc.status.false_positive': 'False positive', 'inc.status.benign': 'Benign', 'inc.status.resolved': 'Resolved',
|
||||
'inc.tab.active': 'Active', 'inc.tab.all': 'All',
|
||||
'inc.tabs': 'Filter by status',
|
||||
'inc.list.empty': 'No tickets here',
|
||||
'inc.list.empty.sub': 'Nothing matches these filters. Findings from the outbound traffic page appear here by themselves.',
|
||||
'inc.list.err': 'Could not load the tickets.',
|
||||
'inc.retry': 'Try again',
|
||||
'inc.comments.n.one': '{n} comment', 'inc.comments.n.other': '{n} comments',
|
||||
'inc.seen': 'seen {when}',
|
||||
'inc.source.egress': 'Outbound traffic', 'inc.source.manual': 'Manual',
|
||||
'inc.back': 'All incidents',
|
||||
'inc.notfound': 'Ticket not found',
|
||||
'inc.notfound.sub': 'It may have been removed, or the link is wrong.',
|
||||
'inc.f.title': 'Title', 'inc.f.severity': 'Severity', 'inc.f.status': 'Status', 'inc.f.assignee': 'Assigned to',
|
||||
'inc.f.tags': 'Tags', 'inc.f.tags.hint': 'Separate with commas.',
|
||||
'inc.f.verdict': 'Conclusion', 'inc.f.verdict.hint': 'What you found and why you closed it this way.',
|
||||
'inc.f.detail': 'Details', 'inc.f.host': 'Server',
|
||||
'inc.f.suppress': 'Suppress identical alerts',
|
||||
'inc.f.suppress.help': 'Only for false positive or benign. Future findings with the same fingerprint stop showing on the outbound traffic page (they stay behind "show suppressed").',
|
||||
'inc.f.suppress.off': 'Pick False positive or Benign to enable this.',
|
||||
'inc.edit': 'Ticket',
|
||||
'inc.save': 'Save changes',
|
||||
'inc.saved': 'Ticket updated',
|
||||
'inc.quick': 'Quick actions',
|
||||
'inc.quick.fp': 'Mark false positive', 'inc.quick.tp': 'Confirm incident', 'inc.quick.resolve': 'Resolve',
|
||||
'inc.tech': 'Technical data',
|
||||
'inc.t.kind': 'Pattern', 'inc.t.source': 'Source', 'inc.t.workload': 'Workload', 'inc.t.dst': 'Destination', 'inc.t.port': 'Port',
|
||||
'inc.t.proto': 'Protocol', 'inc.t.host': 'Server', 'inc.t.first': 'First seen', 'inc.t.last': 'Last seen', 'inc.t.count': 'Occurrences',
|
||||
'inc.t.key': 'Fingerprint', 'inc.t.created': 'Opened', 'inc.t.updated': 'Updated',
|
||||
'inc.comments': 'Comments',
|
||||
'inc.comments.none': 'No comments yet.',
|
||||
'inc.comment.ph': 'Write what you checked or decided',
|
||||
'inc.comment.add': 'Add comment',
|
||||
'inc.comment.added': 'Comment added',
|
||||
'inc.history': 'History',
|
||||
'inc.history.none': 'No changes yet.',
|
||||
'inc.h.line': '{who} changed {field}',
|
||||
'inc.h.field.status': 'status', 'inc.h.field.severity': 'severity', 'inc.h.field.assignee': 'assignee', 'inc.h.field.tags': 'tags',
|
||||
'inc.h.field.title': 'title', 'inc.h.field.verdict': 'conclusion', 'inc.h.field.suppress': 'alert suppression',
|
||||
'inc.h.empty': 'empty', 'inc.h.on': 'on', 'inc.h.off': 'off',
|
||||
'inc.err.save': 'Could not save. Check the fields and try again.',
|
||||
'inc.err.suppress': 'Suppression is only allowed for False positive or Benign.',
|
||||
'inc.err.comment': 'Could not add the comment.',
|
||||
'inc.err.create': 'Could not create the ticket.',
|
||||
'inc.new.title': 'New ticket',
|
||||
'inc.new.explain': 'Open a ticket by hand for something you saw that the system did not flag.',
|
||||
'inc.new.create': 'Create ticket',
|
||||
'inc.cancel': 'Cancel',
|
||||
'inc.required': 'Title is required.',
|
||||
'eg.f.ticket': 'Ticket {id}',
|
||||
'eg.suppressed.toggle': 'Show suppressed ({n})',
|
||||
'eg.suppressed.chip': 'suppressed'
|
||||
},
|
||||
'pt-BR': {
|
||||
'inc.title': 'Incidentes',
|
||||
'inc.nav.open': '{n} em aberto ou em investigação',
|
||||
'inc.lead': 'Cada achado de tráfego de saída é um chamado. Abra, investigue, anote o que descobriu e encerre como incidente real, falso positivo ou benigno.',
|
||||
'inc.author': 'Seu nome',
|
||||
'inc.author.hint': 'Fica salvo neste navegador e aparece junto dos seus comentários e alterações.',
|
||||
'inc.new': 'Novo chamado',
|
||||
'inc.search': 'Buscar chamados',
|
||||
'inc.sev.all': 'Todas as severidades',
|
||||
'inc.sev.critical': 'Crítica', 'inc.sev.high': 'Alta', 'inc.sev.medium': 'Média', 'inc.sev.low': 'Baixa', 'inc.sev.info': 'Informativa',
|
||||
'inc.sort': 'Ordenar por',
|
||||
'inc.sort.updated': 'Atualizados recentemente', 'inc.sort.severity': 'Severidade', 'inc.sort.last_seen': 'Última ocorrência',
|
||||
'inc.h.created': '{who} abriu o chamado (severidade: {sev})', 'inc.h.flood': 'agrupamento de flood',
|
||||
'inc.status.open': 'Aberto', 'inc.status.investigating': 'Em investigação', 'inc.status.true_positive': 'Verdadeiro positivo',
|
||||
'inc.status.false_positive': 'Falso positivo', 'inc.status.benign': 'Benigno', 'inc.status.resolved': 'Resolvido',
|
||||
'inc.tab.active': 'Ativos', 'inc.tab.all': 'Todos',
|
||||
'inc.tabs': 'Filtrar por status',
|
||||
'inc.list.empty': 'Nenhum chamado aqui',
|
||||
'inc.list.empty.sub': 'Nada corresponde a estes filtros. Os achados da página de tráfego de saída aparecem aqui sozinhos.',
|
||||
'inc.list.err': 'Não foi possível carregar os chamados.',
|
||||
'inc.retry': 'Tentar de novo',
|
||||
'inc.comments.n.one': '{n} comentário', 'inc.comments.n.other': '{n} comentários',
|
||||
'inc.seen': 'visto {when}',
|
||||
'inc.source.egress': 'Tráfego de saída', 'inc.source.manual': 'Manual',
|
||||
'inc.back': 'Todos os incidentes',
|
||||
'inc.notfound': 'Chamado não encontrado',
|
||||
'inc.notfound.sub': 'Ele pode ter sido removido ou o link está errado.',
|
||||
'inc.f.title': 'Título', 'inc.f.severity': 'Severidade', 'inc.f.status': 'Status', 'inc.f.assignee': 'Responsável',
|
||||
'inc.f.tags': 'Etiquetas', 'inc.f.tags.hint': 'Separe com vírgulas.',
|
||||
'inc.f.verdict': 'Conclusão', 'inc.f.verdict.hint': 'O que você descobriu e por que encerrou assim.',
|
||||
'inc.f.detail': 'Detalhes', 'inc.f.host': 'Servidor',
|
||||
'inc.f.suppress': 'Suprimir alertas iguais',
|
||||
'inc.f.suppress.help': 'Só para falso positivo ou benigno. Os próximos achados com a mesma impressão digital deixam de aparecer na página de tráfego de saída (ficam atrás de "mostrar suprimidos").',
|
||||
'inc.f.suppress.off': 'Escolha Falso positivo ou Benigno para habilitar.',
|
||||
'inc.edit': 'Chamado',
|
||||
'inc.save': 'Salvar alterações',
|
||||
'inc.saved': 'Chamado atualizado',
|
||||
'inc.quick': 'Ações rápidas',
|
||||
'inc.quick.fp': 'Marcar falso positivo', 'inc.quick.tp': 'Confirmar incidente', 'inc.quick.resolve': 'Resolver',
|
||||
'inc.tech': 'Dados técnicos',
|
||||
'inc.t.kind': 'Padrão', 'inc.t.source': 'Origem', 'inc.t.workload': 'Carga de trabalho', 'inc.t.dst': 'Destino', 'inc.t.port': 'Porta',
|
||||
'inc.t.proto': 'Protocolo', 'inc.t.host': 'Servidor', 'inc.t.first': 'Primeira vez', 'inc.t.last': 'Última vez', 'inc.t.count': 'Ocorrências',
|
||||
'inc.t.key': 'Impressão digital', 'inc.t.created': 'Aberto em', 'inc.t.updated': 'Atualizado em',
|
||||
'inc.comments': 'Comentários',
|
||||
'inc.comments.none': 'Nenhum comentário ainda.',
|
||||
'inc.comment.ph': 'Escreva o que você verificou ou decidiu',
|
||||
'inc.comment.add': 'Comentar',
|
||||
'inc.comment.added': 'Comentário adicionado',
|
||||
'inc.history': 'Histórico',
|
||||
'inc.history.none': 'Nenhuma alteração ainda.',
|
||||
'inc.h.line': '{who} alterou {field}',
|
||||
'inc.h.field.status': 'o status', 'inc.h.field.severity': 'a severidade', 'inc.h.field.assignee': 'o responsável', 'inc.h.field.tags': 'as etiquetas',
|
||||
'inc.h.field.title': 'o título', 'inc.h.field.verdict': 'a conclusão', 'inc.h.field.suppress': 'a supressão de alertas',
|
||||
'inc.h.empty': 'vazio', 'inc.h.on': 'ligada', 'inc.h.off': 'desligada',
|
||||
'inc.err.save': 'Não foi possível salvar. Confira os campos e tente de novo.',
|
||||
'inc.err.suppress': 'A supressão só é permitida em Falso positivo ou Benigno.',
|
||||
'inc.err.comment': 'Não foi possível adicionar o comentário.',
|
||||
'inc.err.create': 'Não foi possível criar o chamado.',
|
||||
'inc.new.title': 'Novo chamado',
|
||||
'inc.new.explain': 'Abra um chamado à mão para algo que você viu e o sistema não sinalizou.',
|
||||
'inc.new.create': 'Criar chamado',
|
||||
'inc.cancel': 'Cancelar',
|
||||
'inc.required': 'O título é obrigatório.',
|
||||
'eg.f.ticket': 'Chamado {id}',
|
||||
'eg.suppressed.toggle': 'Mostrar suprimidos ({n})',
|
||||
'eg.suppressed.chip': 'suprimido'
|
||||
}
|
||||
});
|
||||
|
||||
// layout v2 strings
|
||||
U.registerI18n({
|
||||
en: {
|
||||
'inc.col.id': 'ID', 'inc.col.title': 'Title', 'inc.col.status': 'Status', 'inc.col.assignee': 'Assignee', 'inc.col.where': 'Server / destination', 'inc.col.seen': 'Last seen',
|
||||
'inc.empty.all': 'View all ({n})',
|
||||
'inc.summary': 'Summary', 'inc.edit.btn': 'Edit', 'inc.save.one': 'Save', 'inc.concl.add': 'Add conclusion', 'inc.detail.label': 'Detail',
|
||||
'inc.activity': 'Activity',
|
||||
'inc.commenting': 'Commenting as', 'inc.author.change': 'Change name', 'inc.comment.hint': 'Ctrl+Enter to send',
|
||||
'inc.props': 'Properties',
|
||||
'inc.assign.me': 'Assign to me',
|
||||
'inc.sup.short': 'Hide identical alerts', 'inc.sup.hint': 'Only for false positive or benign.',
|
||||
'inc.meta': 'opened {a} · updated {b} · {n} occurrences',
|
||||
'inc.h.group': '{who} made {n} changes',
|
||||
'inc.copy': 'Copy', 'inc.copied': 'Copied',
|
||||
'inc.title.edit': 'Edit title'
|
||||
},
|
||||
'pt-BR': {
|
||||
'inc.col.id': 'ID', 'inc.col.title': 'Título', 'inc.col.status': 'Status', 'inc.col.assignee': 'Responsável', 'inc.col.where': 'Servidor / destino', 'inc.col.seen': 'Última vez',
|
||||
'inc.empty.all': 'Ver todos ({n})',
|
||||
'inc.summary': 'Resumo', 'inc.edit.btn': 'Editar', 'inc.save.one': 'Salvar', 'inc.concl.add': 'Adicionar conclusão', 'inc.detail.label': 'Detalhe',
|
||||
'inc.activity': 'Atividade',
|
||||
'inc.commenting': 'Comentando como', 'inc.author.change': 'Alterar nome', 'inc.comment.hint': 'Ctrl+Enter para enviar',
|
||||
'inc.props': 'Propriedades',
|
||||
'inc.assign.me': 'Atribuir a mim',
|
||||
'inc.sup.short': 'Ocultar alertas iguais', 'inc.sup.hint': 'Só para falso positivo ou benigno.',
|
||||
'inc.meta': 'aberto {a} · atualizado {b} · {n} ocorrências',
|
||||
'inc.h.group': '{who} fez {n} alterações',
|
||||
'inc.copy': 'Copiar', 'inc.copied': 'Copiado',
|
||||
'inc.title.edit': 'Editar título'
|
||||
}
|
||||
});
|
||||
|
||||
var root = null, ctx = null, view = null;
|
||||
|
||||
// ------------------------------------------------------------ helpers
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
function pick(list, v, d) { return list.indexOf(v) >= 0 ? v : d; }
|
||||
function nf(n) { return U.fmt.num(n || 0); }
|
||||
function sevOf(s) { return pick(SEVS, s, 'info'); }
|
||||
function statusOf(s) { return pick(STATUSES, s, 'open'); }
|
||||
function sevBadge(s) { s = sevOf(s); return U.ui.badge(t('inc.sev.' + s), SEV_TONE[s]); }
|
||||
function statusBadge(s) { s = statusOf(s); return U.ui.badge(t('inc.status.' + s), STATUS_TONE[s]); }
|
||||
function dot(sev) { return el('span', { class: 'inc-dot inc-d-' + sevOf(sev), title: t('inc.sev.' + sevOf(sev)) }); }
|
||||
function isIP(s) { s = String(s || ''); return /^\d{1,3}(\.\d{1,3}){3}$/.test(s) || (s.indexOf(':') > 0 && /^[0-9a-f:.]+$/i.test(s)); }
|
||||
function tr(key, fallback) { var v = t(key); return v === key ? fallback : v; }
|
||||
function tagChips(list, cls) { return (Array.isArray(list) ? list : []).map(function (x) { return el('span', { class: 'chip ' + (cls || '') }, String(x)); }); }
|
||||
function when(ts) { return el('time', { title: ts ? U.fmt.date(ts) : '' }, ts ? U.fmt.ago(ts) : '-'); }
|
||||
function getAuthor() {
|
||||
var v = '';
|
||||
try { v = (localStorage.getItem(AUTHOR_KEY) || '').trim(); } catch (e) { /* storage blocked */ }
|
||||
return v.slice(0, 64);
|
||||
}
|
||||
function setAuthor(v) { try { localStorage.setItem(AUTHOR_KEY, String(v || '').trim().slice(0, 64)); } catch (e) { /* storage blocked */ } }
|
||||
function authorName() { return getAuthor() || 'operator'; }
|
||||
function field(label, control, hint, id) {
|
||||
return el('div', { class: 'inc-field' }, el('label', { for: id }, label), control, hint ? el('span', { class: 'inc-hint' }, hint) : null);
|
||||
}
|
||||
function selectOf(id, values, labelFn, cur) {
|
||||
var s = el('select', { id: id });
|
||||
values.forEach(function (v) { var o = el('option', { value: v }, labelFn(v)); if (v === cur) o.selected = true; s.appendChild(o); });
|
||||
return s;
|
||||
}
|
||||
function parseTags(s) {
|
||||
var out = [];
|
||||
String(s || '').split(',').forEach(function (x) { x = x.trim().slice(0, 40); if (x && out.indexOf(x) < 0) out.push(x); });
|
||||
return out.slice(0, 20);
|
||||
}
|
||||
function sameList(a, b) { return JSON.stringify(a || []) === JSON.stringify(b || []); }
|
||||
|
||||
// open + investigating counter in the rail
|
||||
function pollBadge() {
|
||||
if (document.hidden) return;
|
||||
U.api('/api/v1/incidents', { status: 'open,investigating', per_page: 1 }).then(function (r) {
|
||||
var c = (r && r.counts) || {};
|
||||
var n = (c.open || 0) + (c.investigating || 0);
|
||||
U.setNavBadge('incidents', n, n ? t('inc.nav.open', { n: nf(n) }) : '');
|
||||
}, function () { /* the page itself shows its errors */ });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ list
|
||||
function listView(host) {
|
||||
var seq = 0, on = true, timer = 0;
|
||||
var results = el('div', { class: 'inc-results' });
|
||||
var tabsBox = el('div', { class: 'inc-tabs', role: 'group', 'aria-label': t('inc.tabs') });
|
||||
var counts = null;
|
||||
|
||||
function cur() {
|
||||
var s = U.param('s') || U.param('status') || 'active';
|
||||
return { s: s === 'active' || s === 'all' || STATUSES.indexOf(s) >= 0 ? s : 'active', sev: pick(SEVS, U.param('sev'), ''), q: (U.param('q') || '').slice(0, 200), sort: pick(SORTS, U.param('sort'), 'updated'), p: U.pageParam() };
|
||||
}
|
||||
function query(f) {
|
||||
var p = { per_page: PER_PAGE, page: f.p, sort: f.sort };
|
||||
if (f.s === 'active') p.status = 'open,investigating';
|
||||
else if (f.s !== 'all') p.status = f.s;
|
||||
if (f.sev) p.severity = f.sev;
|
||||
if (f.q) p.q = f.q;
|
||||
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
|
||||
return p;
|
||||
}
|
||||
var search = el('input', { type: 'search', class: 'inc-search', autocomplete: 'off', placeholder: t('inc.search'), 'aria-label': t('inc.search') });
|
||||
search.value = cur().q;
|
||||
var sevSel = el('select', { 'aria-label': t('inc.f.severity') });
|
||||
sevSel.appendChild(el('option', { value: '' }, t('inc.sev.all')));
|
||||
SEVS.forEach(function (s) { sevSel.appendChild(el('option', { value: s }, t('inc.sev.' + s))); });
|
||||
sevSel.value = cur().sev;
|
||||
var sortSel = el('select', { 'aria-label': t('inc.sort') });
|
||||
SORTS.forEach(function (s) { sortSel.appendChild(el('option', { value: s }, t('inc.sort.' + s))); });
|
||||
sortSel.value = cur().sort;
|
||||
var newBtn = el('button', { type: 'button', class: 'btn primary' }, t('inc.new'));
|
||||
newBtn.addEventListener('click', function () { newDialog(); });
|
||||
|
||||
function reload() { U.setParam('p', ''); load(); }
|
||||
search.addEventListener('input', function () {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(function () { U.setParam('q', search.value.trim()); reload(); }, 300);
|
||||
});
|
||||
sevSel.addEventListener('change', function () { U.setParam('sev', sevSel.value); reload(); });
|
||||
sortSel.addEventListener('change', function () { U.setParam('sort', sortSel.value === 'updated' ? '' : sortSel.value); reload(); });
|
||||
|
||||
var info = el('span', { class: 'inc-info', tabindex: '0', role: 'img', title: t('inc.lead'), 'aria-label': t('inc.lead') }, 'ⓘ');
|
||||
host.appendChild(el('div', { class: 'inc-bar' }, el('div', { class: 'inc-tabwrap' }, info, tabsBox), el('div', { class: 'inc-toolbar' }, search, sevSel, sortSel, newBtn)));
|
||||
host.appendChild(results);
|
||||
|
||||
function paintTabs(f) {
|
||||
clear(tabsBox);
|
||||
var c = counts || {}, total = 0;
|
||||
STATUSES.forEach(function (s) { total += c[s] || 0; });
|
||||
var items = [['active', t('inc.tab.active'), (c.open || 0) + (c.investigating || 0)], ['all', t('inc.tab.all'), total], null]
|
||||
.concat(STATUSES.map(function (s) { return [s, t('inc.status.' + s), c[s] || 0]; }));
|
||||
items.forEach(function (it) {
|
||||
if (!it) { tabsBox.appendChild(el('span', { class: 'inc-tab-sep', 'aria-hidden': 'true' })); return; }
|
||||
var b = el('button', { type: 'button', class: 'inc-tab' + (f.s === it[0] ? ' on' : '') + (counts && !it[2] ? ' zero' : ''), 'aria-pressed': f.s === it[0] ? 'true' : 'false' },
|
||||
el('span', null, it[1]), counts ? el('span', { class: 'inc-n num' }, nf(it[2])) : null);
|
||||
b.addEventListener('click', function () { U.setParam('s', it[0] === 'active' ? '' : it[0]); reload(); });
|
||||
tabsBox.appendChild(b);
|
||||
});
|
||||
}
|
||||
function row(it) {
|
||||
var where = [it.host ? String(it.host) : '', it.dst ? it.dst + (it.dport ? ':' + it.dport : '') : ''].filter(Boolean).join(' · ');
|
||||
var full = [(it.workload || ''), it.dst ? '→ ' + it.dst + (it.dport ? ':' + it.dport : '') : ''].filter(Boolean).join(' ');
|
||||
// egress tickets: pattern on top, workload below (the auto title repeats both and gets cut)
|
||||
var auto = it.source === 'egress' && it.kind && it.workload;
|
||||
var head = auto ? tr('eg.kind.' + it.kind, String(it.kind)) : String(it.title || it.id);
|
||||
var titleLine = el('span', { class: 'inc-main' + (auto ? ' two' : '') },
|
||||
el('span', { class: 'inc-mrow' }, el('strong', { class: 'inc-title', title: String(it.title || it.id) }, head),
|
||||
(it.tags && it.tags.length) ? el('span', { class: 'inc-rtags' }, tagChips(it.tags.slice(0, 1))) : null),
|
||||
auto ? el('span', { class: 'inc-sub mono', title: String(it.workload) }, String(it.workload)) : null);
|
||||
return el('a', { class: 'inc-row', href: U.href('incidents', [String(it.id)]), title: full },
|
||||
dot(it.severity),
|
||||
el('span', { class: 'inc-id mono' }, String(it.id)),
|
||||
titleLine,
|
||||
el('span', { class: 'inc-st' }, statusBadge(it.status)),
|
||||
el('span', { class: 'inc-who' }, it.assignee ? String(it.assignee) : '—'),
|
||||
el('span', { class: 'inc-where mono' }, where),
|
||||
el('span', { class: 'inc-when' }, when(it.last_seen)));
|
||||
}
|
||||
function paint(r, f) {
|
||||
clear(results);
|
||||
var items = Array.isArray(r.items) ? r.items : [];
|
||||
var box = el('div', { class: 'inc-table' });
|
||||
results.appendChild(box);
|
||||
if (!items.length) {
|
||||
var c = counts || {}, total = 0;
|
||||
STATUSES.forEach(function (s) { total += c[s] || 0; });
|
||||
var e = el('div', { class: 'inc-empty' }, el('strong', null, t('inc.list.empty')), el('span', { class: 'inc-hint' }, t('inc.list.empty.sub')));
|
||||
if (f.s === 'active' && total > 0) {
|
||||
var all = el('button', { type: 'button', class: 'btn' }, t('inc.empty.all', { n: nf(total) }));
|
||||
all.addEventListener('click', function () { U.setParam('s', 'all'); reload(); });
|
||||
e.appendChild(all);
|
||||
}
|
||||
box.appendChild(e);
|
||||
return;
|
||||
}
|
||||
box.appendChild(el('div', { class: 'inc-thead', 'aria-hidden': 'true' }, el('span'), el('span', null, t('inc.col.id')), el('span', null, t('inc.col.title')), el('span', null, t('inc.col.status')),
|
||||
el('span', null, t('inc.col.assignee')), el('span', null, t('inc.col.where')), el('span', { class: 'r' }, t('inc.col.seen'))));
|
||||
items.forEach(function (it) { box.appendChild(row(it)); });
|
||||
var total2 = r.total || items.length, pages = Math.max(1, Math.ceil(total2 / PER_PAGE));
|
||||
var pg = U.ui.pager({ page: f.p, pages: pages, total: total2, onPage: function (n) { U.setParam('p', n); load(); window.scrollTo(0, 0); } });
|
||||
if (pg) results.appendChild(pg);
|
||||
}
|
||||
function load() {
|
||||
var my = ++seq, f = cur();
|
||||
paintTabs(f);
|
||||
if (!results.firstChild) results.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } }));
|
||||
U.api('/api/v1/incidents', query(f)).then(function (r) {
|
||||
if (!on || my !== seq) return;
|
||||
counts = r.counts || {};
|
||||
paintTabs(f);
|
||||
paint(r, f);
|
||||
var n = (counts.open || 0) + (counts.investigating || 0);
|
||||
U.setNavBadge('incidents', n, n ? t('inc.nav.open', { n: nf(n) }) : '');
|
||||
}, function () {
|
||||
if (!on || my !== seq) return;
|
||||
clear(results);
|
||||
var b = el('button', { type: 'button', class: 'btn' }, t('inc.retry'));
|
||||
b.addEventListener('click', load);
|
||||
results.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('inc.list.err')), b));
|
||||
});
|
||||
}
|
||||
load();
|
||||
return { refresh: load, update: load, destroy: function () { on = false; seq++; clearTimeout(timer); } };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ new ticket dialog
|
||||
function newDialog() {
|
||||
var prev = document.activeElement;
|
||||
var dlg = el('dialog', { class: 'unban-dlg inc-dlg', 'aria-labelledby': 'inc-new-h', 'aria-describedby': 'inc-new-p' });
|
||||
var err = el('p', { class: 'unban-err', role: 'alert', hidden: true });
|
||||
var title = el('input', { type: 'text', id: 'inc-n-title', maxlength: '200', required: true });
|
||||
var detail = el('textarea', { id: 'inc-n-detail', rows: '4', maxlength: '4000' });
|
||||
var sev = selectOf('inc-n-sev', SEVS, function (s) { return t('inc.sev.' + s); }, 'medium');
|
||||
var hostIn = el('input', { type: 'text', id: 'inc-n-host', maxlength: '100' });
|
||||
if (ctx && ctx.host && ctx.host !== 'all') hostIn.value = ctx.host;
|
||||
var tg = el('input', { type: 'text', id: 'inc-n-tags', maxlength: '300' });
|
||||
var who = el('input', { type: 'text', id: 'inc-n-who', maxlength: '64', placeholder: 'operator' });
|
||||
who.value = getAuthor();
|
||||
var ok = el('button', { type: 'button', class: 'btn primary' }, t('inc.new.create'));
|
||||
var cancel = el('button', { type: 'button', class: 'btn' }, t('inc.cancel'));
|
||||
dlg.appendChild(el('h2', { id: 'inc-new-h' }, t('inc.new.title')));
|
||||
dlg.appendChild(el('p', { id: 'inc-new-p' }, t('inc.new.explain')));
|
||||
dlg.appendChild(el('div', { class: 'inc-form' },
|
||||
field(t('inc.f.title'), title, null, 'inc-n-title'),
|
||||
field(t('inc.f.detail'), detail, null, 'inc-n-detail'),
|
||||
field(t('inc.f.severity'), sev, null, 'inc-n-sev'),
|
||||
field(t('inc.f.host'), hostIn, null, 'inc-n-host'),
|
||||
field(t('inc.f.tags'), tg, t('inc.f.tags.hint'), 'inc-n-tags'),
|
||||
field(t('inc.author'), who, t('inc.author.hint'), 'inc-n-who')));
|
||||
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 ttl = title.value.trim();
|
||||
if (!ttl) { err.textContent = t('inc.required'); err.hidden = false; title.focus(); return; }
|
||||
ok.disabled = true;
|
||||
setAuthor(who.value);
|
||||
U.apiSend('POST', '/api/v1/incidents', { title: ttl, detail: detail.value.trim(), severity: sev.value, host: hostIn.value.trim(), tags: parseTags(tg.value), author: authorName() }).then(function (r) {
|
||||
close();
|
||||
pollBadge();
|
||||
if (r && r.id) location.hash = U.href('incidents', [String(r.id)]); else if (view && view.update) view.update();
|
||||
}, function () {
|
||||
ok.disabled = false;
|
||||
err.textContent = t('inc.err.create');
|
||||
err.hidden = false;
|
||||
});
|
||||
});
|
||||
document.body.appendChild(dlg);
|
||||
if (dlg.showModal) dlg.showModal(); else dlg.setAttribute('open', '');
|
||||
title.focus();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ one ticket
|
||||
function detailView(host, id) {
|
||||
var seq = 0, on = true, tk = null, busy = false;
|
||||
var box = el('div', { class: 'inc-detail' });
|
||||
host.appendChild(el('a', { class: 'inc-back', href: U.href('incidents') }, '← ' + t('inc.back')));
|
||||
host.appendChild(box);
|
||||
var errBox = el('p', { class: 'inc-err', role: 'alert', hidden: true });
|
||||
|
||||
function url(suffix) { return '/api/v1/incidents/' + encodeURIComponent(id) + (suffix || ''); }
|
||||
function send(method, suffix, body, errKey, okKey) {
|
||||
if (busy) return;
|
||||
busy = true; box.classList.add('busy');
|
||||
body.author = authorName();
|
||||
errBox.hidden = true;
|
||||
U.apiSend(method, url(suffix), body).then(function () {
|
||||
busy = false; box.classList.remove('busy');
|
||||
if (okKey) U.toast(t(okKey));
|
||||
pollBadge();
|
||||
load(true);
|
||||
}, function (e) {
|
||||
busy = false; box.classList.remove('busy');
|
||||
errBox.textContent = t(e && e.status === 409 ? 'inc.err.suppress' : errKey);
|
||||
errBox.hidden = false;
|
||||
load(true); // put the controls back to the saved values
|
||||
});
|
||||
}
|
||||
function patch(body) { send('PATCH', '', body, 'inc.err.save', 'inc.saved'); }
|
||||
|
||||
// ---- header
|
||||
function header(x) {
|
||||
var title = el('h1', { class: 'inc-h-title' });
|
||||
function showTitle() {
|
||||
clear(title);
|
||||
var b = el('button', { type: 'button', class: 'inc-title-btn', title: t('inc.title.edit') }, String(x.title || x.id));
|
||||
b.addEventListener('click', editTitle);
|
||||
title.appendChild(b);
|
||||
}
|
||||
function editTitle() {
|
||||
clear(title);
|
||||
var inp = el('input', { type: 'text', class: 'inc-title-in', maxlength: '200', 'aria-label': t('inc.f.title') });
|
||||
inp.value = String(x.title || '');
|
||||
var done = false;
|
||||
function finish(save) {
|
||||
if (done) return; done = true;
|
||||
var v = inp.value.trim();
|
||||
if (save && v && v !== x.title) patch({ title: v }); else showTitle();
|
||||
}
|
||||
inp.addEventListener('keydown', function (e) { if (e.key === 'Enter') finish(true); else if (e.key === 'Escape') finish(false); });
|
||||
inp.addEventListener('blur', function () { finish(true); });
|
||||
title.appendChild(inp);
|
||||
inp.focus(); inp.select();
|
||||
}
|
||||
showTitle();
|
||||
function quick(label, status, tone) {
|
||||
var b = el('button', { type: 'button', class: 'btn sm inc-q-' + tone }, label);
|
||||
b.disabled = statusOf(x.status) === status;
|
||||
b.addEventListener('click', function () {
|
||||
var d = { status: status };
|
||||
if (x.suppress && SUPPRESSIBLE.indexOf(status) < 0) d.suppress = false;
|
||||
patch(d);
|
||||
});
|
||||
return b;
|
||||
}
|
||||
var q = el('div', { class: 'inc-quick', role: 'group', 'aria-label': t('inc.quick') },
|
||||
quick(t('inc.quick.fp'), 'false_positive', 'fp'), quick(t('inc.quick.tp'), 'true_positive', 'tp'), quick(t('inc.quick.resolve'), 'resolved', 'ok'));
|
||||
var meta = el('span', { class: 'inc-hint inc-metaline' }, t('inc.meta', { a: x.created_at ? U.fmt.ago(x.created_at) : '-', b: x.updated_at ? U.fmt.ago(x.updated_at) : '-', n: nf(x.count) }));
|
||||
return el('header', { class: 'inc-head' },
|
||||
el('div', { class: 'inc-h1' }, dot(x.severity), el('span', { class: 'inc-id mono' }, String(x.id)), title, q),
|
||||
el('div', { class: 'inc-h2' }, sevBadge(x.severity), statusBadge(x.status), x.suppress ? el('span', { class: 'chip' }, t('eg.suppressed.chip')) : null, tagChips(x.tags), meta));
|
||||
}
|
||||
|
||||
// ---- properties (each control saves by itself)
|
||||
function propsCard(x) {
|
||||
function row(label, control, id) { return el('div', { class: 'inc-prop' }, el('label', { for: id }, label), el('div', { class: 'inc-prop-c' }, control)); }
|
||||
var st = selectOf('inc-e-status', STATUSES, function (s) { return t('inc.status.' + s); }, statusOf(x.status));
|
||||
var sev = selectOf('inc-e-sev', SEVS, function (s) { return t('inc.sev.' + s); }, sevOf(x.severity));
|
||||
var asg = el('input', { type: 'text', id: 'inc-e-asg', maxlength: '64' });
|
||||
asg.value = String(x.assignee || '');
|
||||
var me = el('button', { type: 'button', class: 'inc-link' }, t('inc.assign.me'));
|
||||
var tg = el('input', { type: 'text', id: 'inc-e-tags', maxlength: '300', 'aria-describedby': 'inc-e-tags-h' });
|
||||
tg.value = (x.tags || []).join(', ');
|
||||
var sup = el('input', { type: 'checkbox', id: 'inc-e-sup', role: 'switch', class: 'inc-switch', 'aria-describedby': 'inc-e-sup-h' });
|
||||
sup.checked = !!x.suppress;
|
||||
sup.disabled = SUPPRESSIBLE.indexOf(statusOf(x.status)) < 0;
|
||||
st.addEventListener('change', function () {
|
||||
var d = { status: st.value };
|
||||
if (x.suppress && SUPPRESSIBLE.indexOf(st.value) < 0) d.suppress = false;
|
||||
patch(d);
|
||||
});
|
||||
sev.addEventListener('change', function () { patch({ severity: sev.value }); });
|
||||
function saveAsg() { var v = asg.value.trim(); if (v !== (x.assignee || '')) patch({ assignee: v }); }
|
||||
asg.addEventListener('change', saveAsg);
|
||||
asg.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); asg.blur(); } });
|
||||
me.addEventListener('click', function () { if (authorName() !== (x.assignee || '')) patch({ assignee: authorName() }); });
|
||||
tg.addEventListener('change', function () { var l = parseTags(tg.value); if (!sameList(l, x.tags)) patch({ tags: l }); });
|
||||
tg.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); tg.blur(); } });
|
||||
sup.addEventListener('change', function () { patch({ suppress: sup.checked }); });
|
||||
var supHint = el('span', { class: 'inc-hint', id: 'inc-e-sup-h', title: t('inc.f.suppress.help') }, t('inc.sup.hint'));
|
||||
return el('section', { class: 'inc-card inc-props' }, el('h2', null, t('inc.props')),
|
||||
row(t('inc.f.status'), st, 'inc-e-status'),
|
||||
row(t('inc.f.severity'), sev, 'inc-e-sev'),
|
||||
row(t('inc.f.assignee'), el('div', { class: 'inc-stack' }, asg, me), 'inc-e-asg'),
|
||||
row(t('inc.f.tags'), el('div', { class: 'inc-stack' }, tg, el('span', { class: 'inc-hint', id: 'inc-e-tags-h' }, t('inc.f.tags.hint'))), 'inc-e-tags'),
|
||||
row(t('inc.sup.short'), el('div', { class: 'inc-stack' }, sup, supHint), 'inc-e-sup'),
|
||||
errBox);
|
||||
}
|
||||
|
||||
// ---- summary: conclusion + original detail
|
||||
function summaryBlock(x) {
|
||||
var node = el('section', { class: 'inc-card inc-summary' });
|
||||
function render(edit) {
|
||||
clear(node);
|
||||
var has = !!(x.verdict || x.detail);
|
||||
node.classList.toggle('empty', !has && !edit);
|
||||
if (!has && !edit) {
|
||||
var add = el('button', { type: 'button', class: 'btn sm' }, '+ ' + t('inc.concl.add'));
|
||||
add.addEventListener('click', function () { render(true); });
|
||||
node.appendChild(add);
|
||||
return;
|
||||
}
|
||||
var head = el('div', { class: 'inc-card-h' }, el('h2', null, t('inc.summary')));
|
||||
if (!edit) {
|
||||
var eb = el('button', { type: 'button', class: 'btn sm' }, t('inc.edit.btn'));
|
||||
eb.addEventListener('click', function () { render(true); });
|
||||
head.appendChild(eb);
|
||||
}
|
||||
node.appendChild(head);
|
||||
if (edit) {
|
||||
var ta = el('textarea', { rows: '4', maxlength: '4000', 'aria-label': t('inc.f.verdict') });
|
||||
ta.value = String(x.verdict || '');
|
||||
var sv = el('button', { type: 'button', class: 'btn sm primary' }, t('inc.save.one'));
|
||||
var cn = el('button', { type: 'button', class: 'btn sm' }, t('inc.cancel'));
|
||||
sv.addEventListener('click', function () { var v = ta.value.trim(); if (v !== (x.verdict || '').trim()) patch({ verdict: v }); else render(false); });
|
||||
cn.addEventListener('click', function () { render(false); });
|
||||
node.appendChild(ta);
|
||||
node.appendChild(el('div', { class: 'inc-btns' }, cn, sv));
|
||||
setTimeout(function () { ta.focus(); }, 0);
|
||||
} else if (x.verdict) node.appendChild(el('p', { class: 'inc-text' }, String(x.verdict)));
|
||||
if (x.detail) node.appendChild(el('pre', { class: 'inc-pre', 'aria-label': t('inc.detail.label') }, String(x.detail)));
|
||||
}
|
||||
render(false);
|
||||
return node;
|
||||
}
|
||||
|
||||
// ---- activity
|
||||
function histValue(f, v) {
|
||||
if (v === undefined || v === null || v === '' || (Array.isArray(v) && !v.length)) return t('inc.h.empty');
|
||||
if (f === 'status') return tr('inc.status.' + v, String(v));
|
||||
if (f === 'severity') return tr('inc.sev.' + v, String(v));
|
||||
if (f === 'suppress') return t(v === true || v === 'true' ? 'inc.h.on' : 'inc.h.off');
|
||||
if (Array.isArray(v)) return v.join(', ');
|
||||
return String(v);
|
||||
}
|
||||
function histLine(h) {
|
||||
var f = String(h.field || '');
|
||||
var li = el('li', { class: 'inc-ev' }, el('span', { class: 'inc-ev-dot', 'aria-hidden': 'true' }));
|
||||
var body = el('span', { class: 'inc-ev-t' });
|
||||
if (f === 'created') {
|
||||
body.appendChild(document.createTextNode(t('inc.h.created', { who: String(h.author || '-'), sev: h.to === 'flood' ? t('inc.h.flood') : histValue('severity', h.to) })));
|
||||
} else {
|
||||
body.appendChild(document.createTextNode(t('inc.h.line', { who: String(h.author || '-'), field: tr('inc.h.field.' + f, f) }) + ' '));
|
||||
body.appendChild(el('span', { class: 'inc-ev-chg' }, el('span', { class: 'inc-from' }, histValue(f, h.from)), ' → ', el('strong', null, histValue(f, h.to))));
|
||||
}
|
||||
li.appendChild(body);
|
||||
li.appendChild(el('span', { class: 'inc-ev-when' }, when(h.at)));
|
||||
return li;
|
||||
}
|
||||
function commentCard(c) {
|
||||
var a = String(c.author || '-');
|
||||
return el('li', { class: 'inc-cmt' },
|
||||
el('span', { class: 'inc-av', 'aria-hidden': 'true' }, (a.trim().charAt(0) || '?').toUpperCase()),
|
||||
el('div', { class: 'inc-cmt-b' },
|
||||
el('div', { class: 'inc-c-h' }, el('strong', null, a), el('span', { class: 'inc-hint' }, when(c.at))),
|
||||
el('p', { class: 'inc-text' }, String(c.text || ''))));
|
||||
}
|
||||
function composer() {
|
||||
var ta = el('textarea', { id: 'inc-comment', rows: '2', maxlength: '4000', placeholder: t('inc.comment.ph'), 'aria-label': t('inc.comment.ph') });
|
||||
var err = el('p', { class: 'inc-err', role: 'alert', hidden: true });
|
||||
var add = el('button', { type: 'button', class: 'btn sm primary' }, t('inc.comment.add'));
|
||||
var who = el('span', { class: 'inc-as' });
|
||||
function paintWho() {
|
||||
clear(who);
|
||||
var b = el('button', { type: 'button', class: 'inc-link', title: t('inc.author.change'), 'aria-label': t('inc.author.change') }, '✎');
|
||||
b.addEventListener('click', function () {
|
||||
clear(who);
|
||||
var inp = el('input', { type: 'text', class: 'inc-as-in', maxlength: '64', placeholder: 'operator', 'aria-label': t('inc.author') });
|
||||
inp.value = getAuthor();
|
||||
function fin() { setAuthor(inp.value); paintWho(); }
|
||||
inp.addEventListener('keydown', function (e) { if (e.key === 'Enter' || e.key === 'Escape') { e.preventDefault(); fin(); } });
|
||||
inp.addEventListener('blur', fin);
|
||||
who.appendChild(inp); inp.focus();
|
||||
});
|
||||
who.appendChild(document.createTextNode(t('inc.commenting') + ' '));
|
||||
who.appendChild(el('strong', null, authorName()));
|
||||
who.appendChild(document.createTextNode(' '));
|
||||
who.appendChild(b);
|
||||
}
|
||||
paintWho();
|
||||
function submit() {
|
||||
var txt = ta.value.trim();
|
||||
if (!txt) { ta.focus(); return; }
|
||||
send('POST', '/comments', { text: txt }, 'inc.err.comment', 'inc.comment.added');
|
||||
}
|
||||
add.addEventListener('click', submit);
|
||||
ta.addEventListener('focus', function () { ta.rows = 4; });
|
||||
ta.addEventListener('keydown', function (e) { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); submit(); } });
|
||||
return el('div', { class: 'inc-newc' }, ta, el('div', { class: 'inc-newc-f' }, who, el('span', { class: 'inc-hint inc-kbd' }, t('inc.comment.hint')), add));
|
||||
}
|
||||
function activity(x) {
|
||||
var evs = [];
|
||||
(x.comments || []).forEach(function (c) { evs.push({ at: c.at || 0, c: c }); });
|
||||
(x.history || []).forEach(function (h) { evs.push({ at: h.at || 0, h: h }); });
|
||||
evs.sort(function (a, b) { return b.at - a.at; });
|
||||
var ul = el('ul', { class: 'inc-feed' });
|
||||
for (var i = 0; i < evs.length; i++) {
|
||||
var e = evs[i];
|
||||
if (e.c) { ul.appendChild(commentCard(e.c)); continue; }
|
||||
// consecutive changes by the same author in the same minute collapse into one expandable line
|
||||
var grp = [e.h];
|
||||
while (i + 1 < evs.length && evs[i + 1].h && evs[i + 1].h.author === e.h.author && String(evs[i + 1].h.field) !== 'created' && String(e.h.field) !== 'created' &&
|
||||
Math.floor(evs[i + 1].at / 60) === Math.floor(e.at / 60)) { grp.push(evs[i + 1].h); i++; }
|
||||
if (grp.length < 2) { ul.appendChild(histLine(e.h)); continue; }
|
||||
var inner = el('ul', { class: 'inc-feed inc-sub' }, grp.map(histLine));
|
||||
ul.appendChild(el('li', { class: 'inc-ev inc-grp' }, el('details', null,
|
||||
el('summary', null, el('span', { class: 'inc-ev-dot', 'aria-hidden': 'true' }), t('inc.h.group', { who: String(e.h.author || '-'), n: grp.length }), ' ', el('span', { class: 'inc-ev-when' }, when(e.at))), inner)));
|
||||
}
|
||||
return el('section', { class: 'inc-card inc-activity' }, el('div', { class: 'inc-card-h' }, el('h2', null, t('inc.activity'))), composer(), evs.length ? ul : null);
|
||||
}
|
||||
|
||||
// ---- technical data
|
||||
function techRow(dl, k, v, cls) {
|
||||
if (v === undefined || v === null || v === '') return;
|
||||
dl.appendChild(el('dt', null, t(k)));
|
||||
dl.appendChild(el('dd', { class: cls || '' }, v));
|
||||
}
|
||||
function techCard(x) {
|
||||
var dl = el('dl', { class: 'inc-dl' });
|
||||
var kind = String(x.kind || '');
|
||||
techRow(dl, 'inc.t.source', tr('inc.source.' + x.source, String(x.source || '')));
|
||||
techRow(dl, 'inc.t.kind', kind ? tr('eg.kind.' + kind, kind) : '');
|
||||
techRow(dl, 'inc.t.workload', x.workload ? String(x.workload) : '', 'mono');
|
||||
techRow(dl, 'inc.t.dst', x.dst ? (isIP(x.dst) ? el('a', { href: U.href('ip', [String(x.dst)]) }, String(x.dst)) : String(x.dst)) : '', 'mono');
|
||||
techRow(dl, 'inc.t.port', x.dport ? String(x.dport) : '', 'mono');
|
||||
techRow(dl, 'inc.t.proto', x.proto ? String(x.proto) : '', 'mono');
|
||||
techRow(dl, 'inc.t.host', x.host ? String(x.host) : '');
|
||||
techRow(dl, 'inc.t.first', x.first_seen ? when(x.first_seen) : '');
|
||||
techRow(dl, 'inc.t.last', x.last_seen ? when(x.last_seen) : '');
|
||||
techRow(dl, 'inc.t.count', x.count ? nf(x.count) : '');
|
||||
if (x.key) {
|
||||
var cp = el('button', { type: 'button', class: 'inc-link', 'aria-label': t('inc.copy') }, t('inc.copy'));
|
||||
cp.addEventListener('click', function () {
|
||||
try { navigator.clipboard.writeText(String(x.key)).then(function () { U.toast(t('inc.copied')); }, function () { }); } catch (e) { /* clipboard blocked */ }
|
||||
});
|
||||
dl.appendChild(el('dt', null, t('inc.t.key')));
|
||||
dl.appendChild(el('dd', { class: 'inc-keyrow' }, el('span', { class: 'mono inc-key', title: String(x.key) }, String(x.key)), cp));
|
||||
}
|
||||
var d = el('details', { class: 'inc-card inc-tech' }, el('summary', null, t('inc.tech')), dl);
|
||||
if (window.innerWidth > 900) d.open = true;
|
||||
return d;
|
||||
}
|
||||
|
||||
function paint() {
|
||||
clear(box);
|
||||
var x = tk;
|
||||
box.appendChild(header(x));
|
||||
var main = el('div', { class: 'inc-maincol' });
|
||||
main.appendChild(summaryBlock(x));
|
||||
main.appendChild(activity(x));
|
||||
box.appendChild(el('div', { class: 'inc-layout' }, main, el('aside', { class: 'inc-aside' }, propsCard(x), techCard(x))));
|
||||
}
|
||||
function load(keepScroll) {
|
||||
var my = ++seq;
|
||||
var y = window.scrollY;
|
||||
U.api(url()).then(function (r) {
|
||||
if (!on || my !== seq) return;
|
||||
tk = r; paint();
|
||||
if (keepScroll) window.scrollTo(0, y);
|
||||
}, function (e) {
|
||||
if (!on || my !== seq) return;
|
||||
clear(box);
|
||||
if (e && e.status === 404) { box.appendChild(U.ui.empty(t('inc.notfound'), t('inc.notfound.sub'))); return; }
|
||||
var b = el('button', { type: 'button', class: 'btn' }, t('inc.retry'));
|
||||
b.addEventListener('click', function () { load(); });
|
||||
box.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('inc.list.err')), b));
|
||||
});
|
||||
}
|
||||
box.appendChild(el('div', { class: 'skeleton', style: { height: '10rem' } }));
|
||||
load();
|
||||
return { refresh: null, update: function () { load(true); }, destroy: function () { on = false; seq++; } };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ page
|
||||
function render() {
|
||||
if (view) { view.destroy(); view = null; }
|
||||
clear(root);
|
||||
var seg = ctx && ctx.params && ctx.params.segments ? ctx.params.segments : [];
|
||||
var id = seg[0] ? String(seg[0]).slice(0, 64) : '';
|
||||
view = id ? detailView(root, id) : listView(root);
|
||||
}
|
||||
|
||||
U.registerPage({
|
||||
id: 'incidents', group: 'investigate', titleKey: 'inc.title',
|
||||
icon: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor"><path d="M4 5h16v11H9l-5 4z"/><path d="M12 8.5v3.5"/><path d="M12 14.2h.01"/></svg>',
|
||||
mount: function (node, cx) { root = el('div', { class: 'inc-page' }); node.appendChild(root); ctx = cx; render(); },
|
||||
update: function (cx) { ctx = cx; if (root) render(); },
|
||||
refresh: function () { if (view && view.refresh) view.refresh(); },
|
||||
unmount: function () { if (view) { view.destroy(); view = null; } if (root && root.parentNode) root.parentNode.removeChild(root); root = null; }
|
||||
});
|
||||
|
||||
// the rail counter works from any page
|
||||
pollBadge();
|
||||
setInterval(function () { if (!document.hidden) pollBadge(); }, 30000);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!boot()) {
|
||||
var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100);
|
||||
}
|
||||
})();
|
||||
@@ -1288,6 +1288,9 @@
|
||||
});
|
||||
b.appendChild(ol);
|
||||
}
|
||||
if (banned && window.Urutau && Urutau.unbanDialog) {
|
||||
b.appendChild(Urutau.el('button', { type: 'button', class: 'btn btn-sm ipx-unban', onclick: function () { Urutau.unbanDialog(d.ip, function () { location.reload(); }); } }, t('unban.btn')));
|
||||
}
|
||||
c.body.appendChild(b);
|
||||
var f = h('dl', 'ipx-facts');
|
||||
if (has(ttb) || list.length) {
|
||||
|
||||
@@ -71,6 +71,10 @@
|
||||
{
|
||||
"name": "egress",
|
||||
"css": true
|
||||
},
|
||||
{
|
||||
"name": "incidents",
|
||||
"css": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -5,6 +5,15 @@
|
||||
.hl-table th { color: var(--ink-muted); font-weight: 500; position: sticky; top: 0; background: var(--surface-panel); }
|
||||
.hl-table .num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.hl-page .panel { min-width: 0; }
|
||||
@media (max-width: 900px) { .hl-page .span-6, { grid-column: 1 / -1; } }
|
||||
@media (max-width: 900px) { .hl-page .span-4, .hl-page .span-6, .hl-page .span-8 { grid-column: 1 / -1; } }
|
||||
.hl-helps { display: flex; flex-wrap: wrap; gap: 6px 12px; margin-top: var(--s-3, 10px); font-size: .8125rem; color: var(--ink-muted); }
|
||||
.hl-help { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.hl-legend { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: var(--s-3); font-size: .8125rem; color: var(--ink-muted); }
|
||||
.hl-legend span { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.hl-legend i { display: inline-block; width: 10px; height: 10px; border-radius: 2px; flex: none; }
|
||||
.hl-table td.hl-brk { overflow-wrap: normal; min-width: 14rem; color: var(--ink-muted); }
|
||||
.hl-brk-m { display: none; font-family: var(--font-sans); font-size: .75rem; color: var(--ink-muted); margin-top: 2px; overflow-wrap: normal; }
|
||||
@media (max-width: 600px) {
|
||||
.hl-table .hl-brk { display: none; }
|
||||
.hl-brk-m { display: block; }
|
||||
}
|
||||
@@ -78,7 +78,7 @@
|
||||
var pt = U.ui.panel({ title: t('hl.pr.tls'), hint: t('hl.pr.tls.hint'), variant: 'chart', loading: true, cls: 'span-6' });
|
||||
var ps = U.ui.panel({ title: t('hl.pr.scheme'), hint: t('hl.pr.scheme.hint'), loading: true, cls: 'span-4' });
|
||||
var pc = U.ui.panel({ title: t('hl.pr.ciphers'), hint: t('hl.pr.ciphers.hint'), variant: 'chart', loading: true, cls: 'span-8' });
|
||||
var pm = U.ui.panel({ title: t('hl.pr.methods'), hint: t('hl.pr.methods.hint'), variant: 'list', loading: true, cls: 'span-12' });
|
||||
var pm = U.ui.panel({ title: t('hl.pr.methods'), hint: t('hl.pr.methods.hint'), loading: true, cls: 'span-12' });
|
||||
[lead, pp, pt, ps, pc, pm].forEach(function (n) { grid.appendChild(n); });
|
||||
root.appendChild(grid);
|
||||
|
||||
@@ -103,17 +103,19 @@
|
||||
// http vs https
|
||||
if (U.charts && U.charts.donut) ps.body.appendChild(U.charts.donut([{ key: 'https', label: t('hl.pr.s.https'), value: https }, { key: 'http', label: t('hl.pr.s.http'), value: plain }],
|
||||
{ title: t('hl.pr.scheme'), colors: ['--ok', '--warn'], centerLabel: t('hl.pr.col.n') }));
|
||||
var ci = (d.ciphers || []).slice(0, 12).map(function (x) { return { key: x.name, label: x.name, value: x.n }; });
|
||||
var ci = (d.ciphers || []).slice(0, 12).map(function (x) { return { key: x.name, label: String(x.name).replace(/_/g, '_\u200b'), value: x.n }; });
|
||||
if (ci.length && U.charts && U.charts.bars) pc.body.appendChild(U.charts.bars(ci, { horizontal: true, title: t('hl.pr.ciphers') }));
|
||||
else pc.body.appendChild(U.ui.empty(t('hl.pr.empty')));
|
||||
var tb = el('tbody');
|
||||
(d.methods || []).forEach(function (m) {
|
||||
var errs = sum(m.classes) - (m.classes.ok || 0);
|
||||
tb.appendChild(el('tr', null, el('td', { class: 'mono' }, m.method, m.odd ? U.ui.badge(t('hl.pr.odd'), 'warn') : null), el('td', { class: 'num' }, U.fmt.num(m.n)), el('td', { class: 'num' }, U.fmt.num(errs)),
|
||||
el('td', null, CLS.filter(function (k) { return m.classes[k] || (k === 'client' && false); }).map(function (k) { return t('hl.pr.c.' + k) + ' ' + U.fmt.num(m.classes[k]); }).join(' · '))));
|
||||
var brk = CLS.filter(function (k) { return m.classes[k]; }).map(function (k) { return t('hl.pr.c.' + k) + ' ' + U.fmt.num(m.classes[k]); }).join(' · ');
|
||||
// on phones the breakdown moves under the method (the 4th column is hidden)
|
||||
tb.appendChild(el('tr', null, el('td', { class: 'mono' }, m.method, m.odd ? U.ui.badge(t('hl.pr.odd'), 'warn') : null, el('div', { class: 'hl-brk-m' }, brk)), el('td', { class: 'num' }, U.fmt.num(m.n)), el('td', { class: 'num' }, U.fmt.num(errs)),
|
||||
el('td', { class: 'hl-brk' }, brk)));
|
||||
});
|
||||
pm.body.appendChild(el('div', { class: 'hl-scroll' }, el('table', { class: 'hl-table' },
|
||||
el('thead', null, el('tr', null, el('th', null, t('hl.pr.col.method')), el('th', { class: 'num' }, t('hl.pr.col.n')), el('th', { class: 'num' }, t('hl.pr.col.errs')), el('th', null, ''))), tb)));
|
||||
pm.body.appendChild(el('div', { class: 'hl-scroll' }, el('table', { class: 'hl-table no-mc' },
|
||||
el('thead', null, el('tr', null, el('th', null, t('hl.pr.col.method')), el('th', { class: 'num' }, t('hl.pr.col.n')), el('th', { class: 'num' }, t('hl.pr.col.errs')), el('th', { class: 'hl-brk' }, ''))), tb)));
|
||||
}
|
||||
function load() {
|
||||
var my = ++seq;
|
||||
|
||||
@@ -191,6 +191,10 @@ h1, h2, h3, p, dl, dd, ul { margin: 0; }
|
||||
.nav-item[aria-current="page"] { background: var(--rail-active); color: #fff; border-left-color: var(--accent); }
|
||||
.nav-ico { width: 20px; height: 20px; flex: none; display: inline-flex; }
|
||||
.nav-ico svg { width: 20px; height: 20px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.nav-item, .tab { position: relative; }
|
||||
.nav-badge { margin-left: auto; min-width: 20px; padding: 0 6px; border-radius: 999px; background: var(--danger); color: var(--surface-base); font-size: .75rem; font-weight: 700; line-height: 20px; text-align: center; font-variant-numeric: tabular-nums; }
|
||||
.more-sheet .nav-badge { margin-left: auto; }
|
||||
.tab .nav-badge { position: absolute; top: 4px; left: calc(50% + 4px); min-width: 18px; line-height: 18px; padding: 0 5px; font-size: .6875rem; }
|
||||
.rail-foot { margin-top: auto; padding: var(--s-2); color: var(--rail-ink-muted); font-size: .8125rem; }
|
||||
.main { min-width: 0; display: flex; flex-direction: column; }
|
||||
.topbar {
|
||||
@@ -385,6 +389,7 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
|
||||
.rail { padding: var(--s-3) var(--s-2); align-items: center; }
|
||||
.brand-name, .nav-label, .rail-foot { display: none; }
|
||||
.nav-item { justify-content: center; padding: 8px; border-left: 0; width: 44px; }
|
||||
.nav-item .nav-badge { position: absolute; top: 2px; right: 0; min-width: 16px; padding: 0 4px; font-size: .625rem; line-height: 16px; }
|
||||
.nav-item[aria-current="page"] { box-shadow: inset 3px 0 0 var(--accent); }
|
||||
.grid.g3 { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
@@ -417,7 +422,7 @@ aside#detail li { overflow-wrap: anywhere; margin-bottom: 2px; }
|
||||
}
|
||||
.tab { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px; min-height: 56px; border: 0; background: none; color: var(--rail-ink); text-decoration: none; font-size: .75rem; border-radius: var(--radius-sm); cursor: pointer; padding: 4px 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 span:not(.nav-ico):not(.nav-badge) { 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); 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; }
|
||||
@@ -599,6 +604,9 @@ input[type="datetime-local"] { background: var(--surface-raised); border: 1px so
|
||||
|
||||
/* ================================================================ charts and help */
|
||||
.sr-only { position: absolute !important; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; padding: 0; margin: -1px; }
|
||||
table.sr-only { table-layout: fixed; max-width: 1px; }
|
||||
/* clip, not hidden: nothing may widen the mobile layout viewport (it drags the fixed tabbar along); sticky still works */
|
||||
html, body { overflow-x: clip; }
|
||||
.vz { min-width: 0; }
|
||||
.vz-donut-wrap { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-3) var(--s-4); }
|
||||
.vz-donut-svg { flex: 0 1 190px; min-width: 140px; }
|
||||
@@ -656,3 +664,29 @@ 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; }
|
||||
|
||||
/* Plain data tables on phones: rows become stacked cards (labels from data-label, set by cardTables() in app.js). */
|
||||
@media (max-width: 767px) {
|
||||
.an-scroll, .df-scroll, .hl-scroll { overflow-x: hidden; max-width: 100%; }
|
||||
.ig-scroll, .mt-tablewrap { overflow: visible; max-width: 100%; }
|
||||
table.mc { min-width: 0 !important; }
|
||||
table.mc thead { display: none; }
|
||||
table.mc, table.mc tbody, table.mc tr, table.mc td { display: block; width: 100%; box-sizing: border-box; }
|
||||
table.mc tr { margin: 6px 0; padding: 8px 10px; border: 1px solid var(--line); border-radius: var(--radius-sm); background: var(--surface-raised); }
|
||||
table.mc td { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; border: 0; padding: 2px 0; text-align: right; min-width: 0; overflow-wrap: anywhere; word-break: normal; white-space: normal; }
|
||||
table.mc td::before { content: attr(data-label); flex: none; max-width: 45%; color: var(--ink-muted); font-size: .75rem; text-transform: uppercase; letter-spacing: .06em; text-align: left; }
|
||||
table.mc td[data-label=""]::before { display: none; }
|
||||
table.mc td.num, table.mc td.num * { font-variant-numeric: tabular-nums; }
|
||||
table.mc td.an-key, table.mc td .mono { overflow-wrap: anywhere; word-break: break-all; }
|
||||
table.mc td[colspan] { display: block; text-align: left; }
|
||||
}
|
||||
@media (max-width: 767px) { table.mc .mc-v { min-width: 0; overflow-wrap: anywhere; word-break: normal; } }
|
||||
@@ -47,11 +47,20 @@ type SSHDefense struct {
|
||||
|
||||
// BlocklistStat describes the blocklist the instance would publish.
|
||||
type BlocklistStat struct {
|
||||
Size int `json:"size"`
|
||||
V4 int `json:"v4"`
|
||||
V6 int `json:"v6"`
|
||||
Updated int64 `json:"updated"`
|
||||
CoveragePct float64 `json:"coverage_pct"` // attackers of the window that are listed
|
||||
Size int `json:"size"`
|
||||
V4 int `json:"v4"`
|
||||
V6 int `json:"v6"`
|
||||
Updated int64 `json:"updated"`
|
||||
// CoveragePct is the share of the window's attackers that are protected: listed
|
||||
// on the blocklist OR banned by any jail (fail2ban or Urutau's enforce).
|
||||
CoveragePct float64 `json:"coverage_pct"`
|
||||
Attackers int `json:"attackers"` // distinct attackers of the window
|
||||
Covered int `json:"covered"` // of them, listed or banned
|
||||
OneShot int `json:"one_shot"` // attackers with a single event: impossible to block reactively
|
||||
Repeat int `json:"repeat_ips"` // attackers with 2 or more events
|
||||
RepeatCover int `json:"repeat_covered"`
|
||||
// RepeatCoveragePct is the coverage among the repeated attackers (>= 2 events).
|
||||
RepeatCoveragePct float64 `json:"repeat_coverage_pct"`
|
||||
}
|
||||
|
||||
// LeakStat counts attackers that kept arriving after a ban or listing.
|
||||
@@ -89,6 +98,7 @@ func defenseStep(span int64) int64 {
|
||||
|
||||
type ipDef struct {
|
||||
firstMal, firstBan, firstFail int64
|
||||
malN int
|
||||
okAfter bool
|
||||
mal, bans []int64
|
||||
}
|
||||
@@ -162,6 +172,7 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
|
||||
fallthrough
|
||||
case c.IsMalicious():
|
||||
d := get(key)
|
||||
d.malN++
|
||||
if d.firstMal == 0 || r.T < d.firstMal {
|
||||
d.firstMal = r.T
|
||||
}
|
||||
@@ -182,10 +193,12 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
|
||||
// live state of the registry: active bans, jails, blocklist
|
||||
active := map[string]int{}
|
||||
listed := map[string]int64{}
|
||||
jailed := map[string]bool{}
|
||||
s.mu.RLock()
|
||||
for ip, r := range s.ips {
|
||||
if len(r.Jails) > 0 {
|
||||
out.BansActive++
|
||||
jailed[ip] = true
|
||||
for _, j := range r.Jails {
|
||||
active[j]++
|
||||
}
|
||||
@@ -246,9 +259,19 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
|
||||
continue
|
||||
}
|
||||
attackers++
|
||||
if _, ok := listed[ip]; ok {
|
||||
_, isListed := listed[ip]
|
||||
protected := isListed || d.firstBan > 0 || jailed[ip]
|
||||
if protected {
|
||||
covered++
|
||||
}
|
||||
if d.malN >= 2 {
|
||||
out.Blocklist.Repeat++
|
||||
if protected {
|
||||
out.Blocklist.RepeatCover++
|
||||
}
|
||||
} else {
|
||||
out.Blocklist.OneShot++
|
||||
}
|
||||
ttb = append(ttb, episodeTTB(d.mal, d.bans)...)
|
||||
cut := d.firstBan
|
||||
if l := listed[ip]; l > 0 && (cut == 0 || l < cut) {
|
||||
@@ -277,6 +300,10 @@ func (s *Store) defense(q PeriodQuery) DefenseOut {
|
||||
if attackers > 0 {
|
||||
out.Blocklist.CoveragePct = float64(covered) / float64(attackers) * 100
|
||||
}
|
||||
out.Blocklist.Attackers, out.Blocklist.Covered = attackers, covered
|
||||
if out.Blocklist.Repeat > 0 {
|
||||
out.Blocklist.RepeatCoveragePct = float64(out.Blocklist.RepeatCover) / float64(out.Blocklist.Repeat) * 100
|
||||
}
|
||||
for u, c := range users {
|
||||
out.SSH.Users = append(out.SSH.Users, SSHUser{User: u, N: c, Admin: adminOf[u]})
|
||||
}
|
||||
|
||||
@@ -547,14 +547,16 @@ func (s *Store) metrics(rg Range) MetricsOut {
|
||||
if core.LevelOf(r.Score, strong, r.adminAt(now)) == core.LevelHostile {
|
||||
hostile++
|
||||
banned := len(r.Jails) > 0
|
||||
listed := false
|
||||
// protected: on the blocklist this instance publishes (public address)
|
||||
// or already banned by a jail; a private address can be neither.
|
||||
listed := r.ListedSince > 0
|
||||
if a, err := netip.ParseAddr(strings.SplitN(ip, "/", 2)[0]); err == nil {
|
||||
listed = core.IsGlobal(a)
|
||||
listed = listed && core.IsGlobal(a)
|
||||
}
|
||||
if banned {
|
||||
hostileBanned++
|
||||
}
|
||||
if listed {
|
||||
if listed || banned {
|
||||
hostileListed++
|
||||
}
|
||||
if !banned && !listed {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
)
|
||||
|
||||
type fakeRDNS struct{ ok map[string]bool }
|
||||
|
||||
func (f fakeRDNS) Lookup(string) string { return "" }
|
||||
func (f fakeRDNS) FCrDNS(ip string, suffixes []string) bool {
|
||||
for _, s := range suffixes {
|
||||
if s == "googlebot.com" {
|
||||
return f.ok[ip]
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func TestVerifiedCrawlerIgnoresUA(t *testing.T) {
|
||||
s := store30("x")
|
||||
s.SetRDNS(fakeRDNS{ok: map[string]bool{"66.249.66.1": true}})
|
||||
if !s.VerifiedCrawler("66.249.66.1") || s.VerifiedCrawler("47.82.1.1") {
|
||||
t.Fatal("verified crawler")
|
||||
}
|
||||
if v := s.FCrDNS("66.249.66.1", []string{"Mozilla/5.0 (compatible; GoogleOther)"}); v == nil || !*v {
|
||||
t.Fatalf("GoogleOther UA: %v", v)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOwnJailBanIsNotEvidence(t *testing.T) {
|
||||
s := store30("x")
|
||||
for _, j := range []string{"urutau", "recidive"} {
|
||||
ip := "203.0.114.9"
|
||||
if j == "recidive" {
|
||||
ip = "203.0.114.10"
|
||||
}
|
||||
s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: ip, Cat: core.Ban, Source: "fail2ban", Jail: j})
|
||||
r := s.ips[ip]
|
||||
if r == nil || r.Strong || r.StrongWhy&whyBan != 0 || r.Score != 0 || len(r.Jails) != 1 {
|
||||
t.Fatalf("%s: %+v", j, r)
|
||||
}
|
||||
if listedRule(r, t0.Unix()) {
|
||||
t.Fatalf("%s listed", j)
|
||||
}
|
||||
}
|
||||
s.Ingest(core.Event{Time: t0.Add(-time.Hour), IP: "203.0.114.11", Cat: core.Ban, Source: "fail2ban", Jail: "sshd"})
|
||||
if r := s.ips["203.0.114.11"]; r == nil || !r.Strong || r.Score < 10 {
|
||||
t.Fatalf("sshd ban must stay evidence: %+v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefenseCoverageMetrics(t *testing.T) {
|
||||
s := store30("x")
|
||||
l := openLog(t)
|
||||
s.SetEventLog(l)
|
||||
scan := func(ip string, n int) {
|
||||
for i := 0; i < n; i++ {
|
||||
s.Ingest(core.Event{Time: t0.Add(-time.Duration(60+i) * time.Minute), IP: ip, Cat: core.Scanner, Source: "traefik",
|
||||
Domain: "a.example", Method: "GET", Path: "/x", Status: 404, UA: "curl/8"})
|
||||
}
|
||||
}
|
||||
scan("203.0.114.20", 1) // one shot
|
||||
scan("203.0.114.21", 3) // repeated, banned by our own jail
|
||||
s.Ingest(core.Event{Time: t0.Add(-30 * time.Minute), IP: "203.0.114.21", Cat: core.Ban, Source: "fail2ban", Jail: "urutau"})
|
||||
scan("203.0.114.22", 3) // repeated, unprotected
|
||||
l.Flush()
|
||||
d := s.Defense(PeriodQuery{From: t0.Add(-24 * time.Hour).Unix(), To: t0.Unix()})
|
||||
b := d.Blocklist
|
||||
if b.Attackers != 3 || b.Covered != 1 || b.OneShot != 1 || b.Repeat != 2 || b.RepeatCover != 1 {
|
||||
t.Fatalf("%+v", b)
|
||||
}
|
||||
if b.RepeatCoveragePct != 50 || b.CoveragePct < 33 || b.CoveragePct > 34 {
|
||||
t.Fatalf("%+v", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTalliesCountSSHProbeAndWeek(t *testing.T) {
|
||||
s := store30("x")
|
||||
l := openLog(t)
|
||||
s.SetEventLog(l)
|
||||
for i := 0; i < 4; i++ {
|
||||
s.Ingest(core.Event{Time: t0.Add(-time.Duration(i+1) * time.Hour), IP: "203.0.114.30", Cat: core.SSHProbe, Source: "ssh"})
|
||||
s.Ingest(core.Event{Time: t0.Add(-time.Duration(i+3) * 24 * time.Hour), IP: "203.0.114.30", Cat: core.SSHFail, Source: "ssh", User: "root"})
|
||||
}
|
||||
l.Flush()
|
||||
m := s.AttackTallies(t0.Add(-7 * 24 * time.Hour).Unix())
|
||||
x := m["203.0.114.30"]
|
||||
if x.Probe != 4 || x.Probe7 != 4 || x.SSH != 0 || x.SSH7 != 4 {
|
||||
t.Fatalf("%+v", x)
|
||||
}
|
||||
}
|
||||
+100
-20
@@ -2,6 +2,7 @@ package store
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/evlog"
|
||||
@@ -9,15 +10,62 @@ import (
|
||||
|
||||
// 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
|
||||
IP string
|
||||
Score float64
|
||||
Level core.Level
|
||||
Jails []string
|
||||
Last int64
|
||||
Events int // malicious events recorded for the address
|
||||
Est Tally24 // 24 h estimate from the per-day counters (the registry may not cover the whole window)
|
||||
}
|
||||
|
||||
// dayEstimate estimates the SSH, ssh-probe and web malicious events of the last
|
||||
// 24 h (SSH, Web, Probe) and of the last 7 days (SSH7, Web7, Probe7) from the
|
||||
// per-day counters: today plus the share of the oldest day 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 <= 7; k++ {
|
||||
i := int(r.DayBase - (today - k))
|
||||
if i < 0 || i >= len(r.DayCats) {
|
||||
continue
|
||||
}
|
||||
c := r.DayCats[i]
|
||||
ssh, probe := float64(c[core.SSHFail.Index()]), float64(c[core.SSHProbe.Index()])
|
||||
web := float64(c[core.Scanner.Index()] + c[core.Exploit.Index()] + c[core.BruteForce.Index()])
|
||||
if k <= 1 {
|
||||
w := 1.0
|
||||
if k == 1 {
|
||||
w = frac
|
||||
}
|
||||
t.SSH += int(ssh*w + 0.999)
|
||||
t.Web += int(web*w + 0.999)
|
||||
t.Probe += int(probe*w + 0.999)
|
||||
}
|
||||
if k <= 6 {
|
||||
w := 1.0
|
||||
if k == 6 {
|
||||
w = frac
|
||||
}
|
||||
t.SSH7 += int(ssh*w + 0.999)
|
||||
t.Web7 += int(web*w + 0.999)
|
||||
t.Probe7 += int(probe*w + 0.999)
|
||||
}
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
// Tally24 counts the malicious events of one address in a window.
|
||||
type Tally24 struct{ SSH, Web int }
|
||||
// SSH, Web and Probe cover the last 24 h; SSH7, Web7 and Probe7 the whole scanned
|
||||
// window (7 days for the enforce sweep).
|
||||
type Tally24 struct{ SSH, Web, Probe, SSH7, Web7, Probe7 int }
|
||||
|
||||
// maxTallyIPs bounds the memory of one tally pass.
|
||||
const maxTallyIPs = 100000
|
||||
|
||||
// AttackRoster lists the addresses with malicious activity since from (unix).
|
||||
func (s *Store) AttackRoster(from int64) []RosterRow {
|
||||
@@ -31,7 +79,7 @@ func (s *Store) AttackRoster(from int64) []RosterRow {
|
||||
}
|
||||
strong := r.Strong || attackKinds(r.Counts) >= 2
|
||||
out = append(out, RosterRow{IP: ip, Score: round1(r.Score), Level: core.LevelOf(r.Score, strong, r.adminAt(nowU)),
|
||||
Jails: append([]string(nil), r.Jails...), Last: r.Last})
|
||||
Jails: append([]string(nil), r.Jails...), Last: r.Last, Events: int(malOf(r.Counts)), Est: dayEstimate(r, nowU)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -49,31 +97,47 @@ func (s *Store) Reputation(ip string) (float64, core.Level, bool) {
|
||||
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}
|
||||
var tallyCats = map[string]bool{string(core.SSHFail): true, string(core.SSHProbe): true, string(core.Scanner): true, string(core.Exploit): true, string(core.BruteForce): true}
|
||||
|
||||
func tallyAdd(m map[string]*Tally24, r evlog.Rec) {
|
||||
func tallyAdd(m map[string]*Tally24, r evlog.Rec, cut24 int64) {
|
||||
t := m[r.IP]
|
||||
if t == nil {
|
||||
if len(m) >= maxTallyIPs {
|
||||
return
|
||||
}
|
||||
t = &Tally24{}
|
||||
m[r.IP] = t
|
||||
}
|
||||
recent := r.T >= cut24
|
||||
switch {
|
||||
case r.Cat == string(core.SSHFail):
|
||||
t.SSH++
|
||||
t.SSH7++
|
||||
if recent {
|
||||
t.SSH++
|
||||
}
|
||||
case r.Cat == string(core.SSHProbe):
|
||||
t.Probe7++
|
||||
if recent {
|
||||
t.Probe++
|
||||
}
|
||||
case r.Source == "traefik" && !strings.Contains(r.Flags, "F"):
|
||||
t.Web++
|
||||
t.Web7++
|
||||
if recent {
|
||||
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.
|
||||
// AttackTallies counts, in one pass over the event log, the SSH failures, ssh
|
||||
// probes 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
|
||||
}
|
||||
cut24 := s.now().Add(-24 * time.Hour).Unix()
|
||||
m := map[string]*Tally24{}
|
||||
s.elog.Scan(evlog.Filter{From: from, Cats: tallyCats}, 256<<20, false, func(r evlog.Rec, _ []byte) bool {
|
||||
tallyAdd(m, r)
|
||||
s.elog.Scan(evlog.Filter{From: from, Cats: tallyCats}, 4<<30, false, func(r evlog.Rec, _ []byte) bool {
|
||||
tallyAdd(m, r, cut24)
|
||||
return true
|
||||
})
|
||||
out := make(map[string]Tally24, len(m))
|
||||
@@ -85,18 +149,34 @@ func (s *Store) AttackTallies(from int64) map[string]Tally24 {
|
||||
|
||||
// AttackTally is AttackTallies for one address.
|
||||
func (s *Store) AttackTally(ip string, from int64) Tally24 {
|
||||
if s.elog == nil {
|
||||
return 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
|
||||
}
|
||||
cut24 := s.now().Add(-24 * time.Hour).Unix()
|
||||
m := map[string]*Tally24{}
|
||||
s.elog.Scan(evlog.Filter{From: from, IP: ip, Cats: tallyCats}, 64<<20, false, func(r evlog.Rec, _ []byte) bool {
|
||||
tallyAdd(m, r)
|
||||
s.elog.Scan(evlog.Filter{From: from, IP: ip, Cats: tallyCats}, 1<<30, false, func(r evlog.Rec, _ []byte) bool {
|
||||
tallyAdd(m, r, cut24)
|
||||
return true
|
||||
})
|
||||
var t Tally24
|
||||
for _, v := range m {
|
||||
t.SSH += v.SSH
|
||||
t.Web += v.Web
|
||||
t.Probe += v.Probe
|
||||
t.SSH7 += v.SSH7
|
||||
t.Web7 += v.Web7
|
||||
t.Probe7 += v.Probe7
|
||||
}
|
||||
return t
|
||||
return MaxTally(t, est)
|
||||
}
|
||||
|
||||
// MaxTally is the field-wise maximum.
|
||||
func MaxTally(a, b Tally24) Tally24 {
|
||||
return Tally24{max(a.SSH, b.SSH), max(a.Web, b.Web), max(a.Probe, b.Probe), max(a.SSH7, b.SSH7), max(a.Web7, b.Web7), max(a.Probe7, b.Probe7)}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+42
-1
@@ -186,7 +186,32 @@ var crawlerSuffixes = []struct {
|
||||
suffixes []string
|
||||
}{
|
||||
{"googlebot", []string{"googlebot.com", "google.com"}},
|
||||
{"googleother", []string{"googlebot.com", "google.com"}},
|
||||
{"google-inspectiontool", []string{"googlebot.com", "google.com"}},
|
||||
{"adsbot-google", []string{"googlebot.com", "google.com"}},
|
||||
{"mediapartners-google", []string{"googlebot.com", "google.com"}},
|
||||
{"apis-google", []string{"googlebot.com", "google.com"}},
|
||||
{"storebot-google", []string{"googlebot.com", "google.com"}},
|
||||
{"bingbot", []string{"search.msn.com"}},
|
||||
{"msnbot", []string{"search.msn.com"}},
|
||||
{"applebot", []string{"applebot.apple.com"}},
|
||||
}
|
||||
|
||||
// verifiedSuffixes are the reverse DNS domains of the crawlers Urutau trusts once
|
||||
// forward-confirmed, whatever the User-Agent says.
|
||||
var verifiedSuffixes = []string{"googlebot.com", "google.com", "search.msn.com", "applebot.apple.com"}
|
||||
|
||||
// VerifiedCrawler reports whether ip is a crawler of a known search engine,
|
||||
// proven by forward-confirmed reverse DNS alone (no User-Agent is trusted).
|
||||
func (s *Store) VerifiedCrawler(ip string) bool {
|
||||
v, ok := s.rdns.(FCrDNSVerifier)
|
||||
if !ok || s.rdns == nil {
|
||||
return false
|
||||
}
|
||||
if a, err := netip.ParseAddr(ip); err != nil || a.Zone() != "" {
|
||||
return false
|
||||
}
|
||||
return v.FCrDNS(ip, verifiedSuffixes)
|
||||
}
|
||||
|
||||
// FCrDNS verifies an address that claims, through one of its User-Agents, to
|
||||
@@ -474,6 +499,10 @@ func (s *Store) Ingest(ev core.Event) {
|
||||
if scored {
|
||||
r.Counts[ci]++
|
||||
w := ev.Cat.Weight()
|
||||
derived := ev.Cat == core.Ban && DerivedJail(ev.Jail)
|
||||
if derived {
|
||||
w = 0 // our own decision (or its repetition) is not independent evidence
|
||||
}
|
||||
if ev.Soft && (ev.Cat == core.Scanner || ev.Cat == core.Exploit) {
|
||||
w = softWeight // answered 2xx/3xx: probably nothing was found
|
||||
}
|
||||
@@ -495,7 +524,7 @@ func (s *Store) Ingest(ev core.Event) {
|
||||
r.StrongWhy |= whyTool
|
||||
r.StrongAt = max(r.StrongAt, ts)
|
||||
}
|
||||
if (ev.Strong && !framed) || ev.Cat == core.Ban {
|
||||
if (ev.Strong && !framed) || ev.Cat == core.Ban && !derived {
|
||||
r.Strong = true
|
||||
if ev.Cat == core.Ban {
|
||||
r.StrongWhy |= whyBan
|
||||
@@ -580,6 +609,18 @@ func (s *Store) feedOf(ev core.Event, ts int64, fam string, tech []string, marke
|
||||
Bytes: ev.Bytes, DurMS: ev.DurationNS / 1e6, Flags: flags, Port: int(ev.Port), Proto: probeProto(ev)}
|
||||
}
|
||||
|
||||
// DerivedJail reports whether bans of the jail come from Urutau's own decisions
|
||||
// (the "urutau" jail reads the enforce file; "recidive" only repeats bans of
|
||||
// other jails, ours included). Such bans must never feed back as evidence in the
|
||||
// score, the strong signal or the blocklist. Independent jails (sshd, traefik...) still count.
|
||||
func DerivedJail(j string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(j)) {
|
||||
case "urutau", "recidive":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// listedRule is the blocklist rule: score of 50, a strong signal and not an admin.
|
||||
func listedRule(r *IPRec, now int64) bool {
|
||||
return r.Score >= core.HostileScore && (r.Strong || attackKinds(r.Counts) >= 2) && !r.adminAt(now)
|
||||
|
||||
@@ -80,7 +80,7 @@ func TestBansAndFeed(t *testing.T) {
|
||||
b.Unban, b.Jail = true, "sshd"
|
||||
s.Ingest(b)
|
||||
r, _ := s.IP("5.5.5.5")
|
||||
if len(r.Jails) != 1 || r.Jails[0] != "recidive" || r.Score != 20 {
|
||||
if len(r.Jails) != 1 || r.Jails[0] != "recidive" || r.Score != 10 { // the recidive ban adds no evidence
|
||||
t.Fatalf("%+v", r)
|
||||
}
|
||||
if rec := s.Recent(10); len(rec) != 3 || !rec[0].Unban {
|
||||
|
||||
@@ -98,6 +98,10 @@ done
|
||||
pids+=($!)
|
||||
sleep 6
|
||||
|
||||
if [ -n "${TABLES_ONLY:-}" ]; then
|
||||
# mobile table check (375x812) instead of the documentation pictures: TABLES_ONLY=1 OUT=/tmp/x scripts/screenshots.sh
|
||||
node "$root/scripts/screenshots/tables.mjs" "http://127.0.0.1:$hub_port" "$out"; exit $?
|
||||
fi
|
||||
node "$root/scripts/screenshots/shots.mjs" "http://127.0.0.1:$hub_port" "http://127.0.0.1:$login_port" "$out"
|
||||
|
||||
if command -v oxipng >/dev/null; then oxipng -q -o 3 --strip safe "$out"/*.png
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// Mobile table check: node tables.mjs <hub-url> <out-dir>
|
||||
// Captures every page that has a visible table at 375x812 (plus one desktop control),
|
||||
// and reports document scrollWidth and tables that overflow their container.
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { homedir } from "node:os";
|
||||
|
||||
const [hub, out] = process.argv.slice(2);
|
||||
const core = process.env.PUPPETEER_CORE || `${homedir()}/.claude/tools/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js`;
|
||||
const { default: puppeteer } = await import(core);
|
||||
const chrome = process.env.CHROME || execFileSync("bash", ["-c", `ls -1d "$HOME"/.cache/puppeteer/chrome/*/chrome-linux64/chrome | sort -V | tail -1`], { encoding: "utf8" }).trim();
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const PHONE = { width: 375, height: 812, deviceScaleFactor: 2, isMobile: true, hasTouch: true };
|
||||
const DESKTOP = { width: 1440, height: 900, deviceScaleFactor: 1 };
|
||||
const IP = "203.0.113.45";
|
||||
async function firstCampaign() {
|
||||
const j = await (await fetch(`${hub}/api/v1/campaigns?range=30d`)).json();
|
||||
return encodeURIComponent(((j.campaigns || [])[0] || {}).id || "");
|
||||
}
|
||||
const pages = [
|
||||
["overview", "overview?r=7d"], ["ips", "ips?r=7d"], ["sources", "sources?r=24h"], ["ip-analysis", `ip/${IP}?r=7d`],
|
||||
["sessions", "sessions?r=7d"], ["campaigns", "campaigns?r=30d"], ["campaign-detail", async () => `campaigns/${await firstCampaign()}?r=30d`],
|
||||
["search", `search?r=7d&ip=${IP}`], ["mitre", "mitre?r=30d"], ["defense", "defense?r=7d"], ["evolution", "evolution?r=30d"],
|
||||
["concentration", "concentration?r=30d"], ["survival", "survival?r=30d"], ["errors", "errors?r=7d"], ["slo", "slo?r=7d"],
|
||||
["protocol", "protocol?r=7d"], ["integrity", "integrity?r=7d"], ["reports", "reports?r=7d"], ["egress", "egress?r=7d"],
|
||||
["incidents", "incidents"], ["geo", "geo?r=30d"], ["live", "live?r=24h"], ["replay", "replay?r=2d"], ["threats", "threats?r=24h"], ["traffic", "traffic?r=30d"],
|
||||
];
|
||||
const browser = await puppeteer.launch({ executablePath: chrome, args: ["--no-sandbox", "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader"], defaultViewport: DESKTOP });
|
||||
let bad = 0;
|
||||
async function run(id, route, vp, suffix) {
|
||||
const page = await browser.newPage();
|
||||
await page.setViewport(vp);
|
||||
await page.evaluateOnNewDocument(() => { try { localStorage.setItem("urutau.theme", "dark"); localStorage.setItem("urutau.lang", "en"); localStorage.setItem("urutau.host", "all"); } catch {} });
|
||||
const hash = "#/" + (typeof route === "function" ? await route() : route);
|
||||
await page.goto(hub + "/", { waitUntil: "domcontentloaded" });
|
||||
await page.goto(hub + "/" + hash, { waitUntil: "domcontentloaded" });
|
||||
await page.evaluate((h) => { location.hash = h; }, hash);
|
||||
try { await page.waitForFunction(() => { const v = document.querySelector("#view"); return v && (v.innerText || "").trim().length > 80 && !v.querySelector(".skeleton"); }, { timeout: 20000, polling: 300 }); } catch {}
|
||||
await sleep(2500);
|
||||
const r = await page.evaluate(() => {
|
||||
const tabs = [...document.querySelectorAll("#view table")].filter((t) => !t.classList.contains("sr-only") && t.offsetParent !== null);
|
||||
const over = tabs.filter((t) => { let p = t.parentElement; return t.scrollWidth > (p ? p.clientWidth : 0) + 1 || t.getBoundingClientRect().right > innerWidth + 1; }).map((t) => t.className || "(no class)");
|
||||
return { sw: document.documentElement.scrollWidth, tables: tabs.length, over };
|
||||
});
|
||||
const ok = r.sw <= vp.width && (vp.width > 500 || r.over.length === 0);
|
||||
if (!ok && vp.width < 500) bad++;
|
||||
console.log(`${suffix} ${id.padEnd(16)} tables=${r.tables} scrollWidth=${r.sw} overflow=[${r.over}] ${ok ? "OK" : "BAD"}`);
|
||||
if (r.tables > 0) await page.screenshot({ path: `${out}/tbl-${id}-${suffix}.png`, fullPage: true });
|
||||
await page.close();
|
||||
}
|
||||
try {
|
||||
for (const [id, route] of pages) await run(id, route, PHONE, "m375");
|
||||
await run("concentration", "concentration?r=30d", DESKTOP, "desktop");
|
||||
await run("ips", "ips?r=7d", DESKTOP, "desktop");
|
||||
} finally { await browser.close(); }
|
||||
process.exit(bad ? 1 : 0);
|
||||
Reference in new issue
Block a user