Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22ccde539b | ||
|
|
bc3ce09088 | ||
|
|
54b9ae65cd | ||
|
|
393a31cebe | ||
|
|
2a14924ed9 | ||
|
|
7e1f70bf40 | ||
|
|
a689dd8824 | ||
|
|
804d2c6e8d | ||
|
|
612516db76 |
No files matched your search
@@ -4,6 +4,62 @@
|
||||
|
||||
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer.
|
||||
|
||||
## [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
|
||||
|
||||
@@ -4,6 +4,62 @@
|
||||
|
||||
Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versionamento segue SemVer.
|
||||
|
||||
## [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
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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 |
|
||||
|
||||
+14
-5
@@ -38,14 +38,19 @@ func newEnforce(c Config, st *store.Store, peers []fed.Peer, en enricher, ready
|
||||
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, Est: enforce.Tally{SSH: r.Est.SSH, Web: r.Est.Web}}
|
||||
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
|
||||
},
|
||||
@@ -203,3 +208,7 @@ func unbanLogPath(c Config) string {
|
||||
}
|
||||
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}
|
||||
}
|
||||
@@ -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.5.1"
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
+113
-21
@@ -35,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
|
||||
@@ -43,21 +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
|
||||
Est Tally // estimate from per-day counters, used when the registry holds less
|
||||
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 {
|
||||
@@ -110,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).
|
||||
@@ -127,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
|
||||
@@ -159,6 +169,7 @@ 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
|
||||
)
|
||||
|
||||
@@ -186,7 +197,8 @@ type Engine struct {
|
||||
lastSave time.Time
|
||||
hostIPs map[string][]netip.Addr // last good resolution per host
|
||||
long map[netip.Addr]*longRec
|
||||
allows map[netip.Addr]int64 // operator allowances: address -> until (unix)
|
||||
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
|
||||
}
|
||||
@@ -212,7 +224,7 @@ func New(c Config) *Engine {
|
||||
}
|
||||
e := &Engine{cfg: c, log: &logFile{path: c.Path}, ch: make(chan item, 4096), ips: map[netip.Addr]*ipState{},
|
||||
bans: map[netip.Addr]banRec{}, would: map[netip.Addr]int64{}, skipSeen: map[netip.Addr]int64{},
|
||||
counts: Counts{Skipped: map[string]int{}}, long: map[netip.Addr]*longRec{}, allows: map[netip.Addr]int64{}}
|
||||
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{}}
|
||||
@@ -240,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
|
||||
@@ -429,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):
|
||||
@@ -436,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
|
||||
@@ -454,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 {
|
||||
@@ -489,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
|
||||
@@ -499,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,
|
||||
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})
|
||||
}
|
||||
@@ -624,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())
|
||||
@@ -710,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++
|
||||
@@ -719,6 +806,11 @@ 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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,7 +100,7 @@ func (e *Engine) Sweep() {
|
||||
}
|
||||
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 {
|
||||
@@ -120,12 +121,14 @@ func (e *Engine) Sweep() {
|
||||
a = a.Unmap().WithZone("")
|
||||
st := e.stateOf(a)
|
||||
t := tallies[a.String()]
|
||||
t.SSH, t.Web = max(t.SSH, r.Est.SSH), max(t.Web, r.Est.Web)
|
||||
in := Input{Now: now, Known: IsKnown(r.Score, r.Level), SSH24: t.SSH, Web24: t.Web,
|
||||
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})
|
||||
}
|
||||
@@ -187,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++
|
||||
@@ -196,6 +205,9 @@ func (e *Engine) coverageOf(roster []Seen, from int64) Coverage {
|
||||
cv.WouldBlock++
|
||||
default:
|
||||
cv.Unblocked++
|
||||
if repeat {
|
||||
cv.RepeatUnblocked++
|
||||
}
|
||||
}
|
||||
}
|
||||
return cv
|
||||
|
||||
@@ -61,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 {
|
||||
@@ -77,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}}
|
||||
}
|
||||
|
||||
+51
-21
@@ -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
|
||||
)
|
||||
@@ -113,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 }
|
||||
|
||||
@@ -156,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:
|
||||
@@ -165,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{}
|
||||
}
|
||||
@@ -264,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,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) }
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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"},
|
||||
|
||||
@@ -2011,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];
|
||||
|
||||
@@ -125,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': {
|
||||
@@ -241,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.'
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,87 +1,186 @@
|
||||
/* Urutau - INCIDENTS page. Ticket text is untrusted: long words wrap, nothing forces horizontal scroll. */
|
||||
/* 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-lead { color: var(--ink-muted); max-width: 70ch; margin: 0 0 var(--s-3); }
|
||||
.inc-hint { font-size: .8125rem; color: var(--ink-muted); overflow-wrap: anywhere; }
|
||||
.inc-author { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-2) var(--s-3); margin-bottom: var(--s-3); }
|
||||
.inc-author label { font-size: .875rem; color: var(--ink-muted); }
|
||||
.inc-author input { width: 12rem; max-width: 100%; min-height: 32px; padding: 3px 10px; }
|
||||
|
||||
.inc-tabs { display: flex; flex-wrap: wrap; gap: var(--s-2); margin-bottom: var(--s-3); }
|
||||
.inc-tab { display: inline-flex; align-items: center; gap: 8px; min-height: 36px; padding: 4px 12px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface-raised); color: var(--ink); cursor: pointer; font: inherit; }
|
||||
.inc-tab:hover { border-color: var(--line-strong); }
|
||||
.inc-tab:focus-visible { outline: 0; box-shadow: var(--focus-ring); }
|
||||
.inc-tab.on { background: var(--accent-soft); border-color: var(--accent); font-weight: 600; }
|
||||
.inc-n { font-size: .8125rem; color: var(--ink-muted); }
|
||||
.inc-toolbar select { max-width: 100%; }
|
||||
|
||||
.inc-list { display: grid; gap: var(--s-2); }
|
||||
.inc-row {
|
||||
display: grid; grid-template-columns: auto auto minmax(0, 1fr) auto; gap: var(--s-2) var(--s-3); align-items: center;
|
||||
padding: var(--s-3) var(--s-4); background: var(--surface-panel); border: 1px solid var(--line); border-left: 4px solid var(--line-strong);
|
||||
border-radius: var(--radius-sm); color: var(--ink); text-decoration: none;
|
||||
}
|
||||
.inc-row:hover { border-color: var(--line-strong); background: var(--surface-raised); }
|
||||
.inc-row:focus-visible { outline: 0; box-shadow: var(--focus-ring); }
|
||||
.inc-sev-critical, .inc-sev-high { border-left-color: var(--danger); }
|
||||
.inc-sev-medium { border-left-color: var(--warn); }
|
||||
.inc-sev-low { border-left-color: var(--info); }
|
||||
.inc-id { font-weight: 600; white-space: nowrap; }
|
||||
.inc-badges { display: inline-flex; gap: 6px; flex-wrap: wrap; }
|
||||
.inc-main { min-width: 0; display: grid; gap: 2px; }
|
||||
.inc-title { overflow-wrap: anywhere; }
|
||||
.inc-meta { display: flex; flex-wrap: wrap; gap: 4px 8px; align-items: center; color: var(--ink-muted); min-width: 0; }
|
||||
.inc-route { overflow-wrap: anywhere; }
|
||||
.inc-side { display: grid; gap: 2px; justify-items: end; font-size: .8125rem; color: var(--ink-muted); white-space: nowrap; }
|
||||
|
||||
.inc-back { display: inline-block; margin-bottom: var(--s-3); color: var(--accent); text-decoration: none; }
|
||||
.inc-back:hover { text-decoration: underline; }
|
||||
.inc-head { display: flex; flex-wrap: wrap; align-items: center; gap: var(--s-2) var(--s-3); margin-bottom: var(--s-4); padding: var(--s-3) var(--s-4); background: var(--surface-panel); border: 1px solid var(--line); border-left: 4px solid var(--line-strong); border-radius: var(--radius-sm); }
|
||||
.inc-h-title { flex: 1 1 100%; margin: 0; font-size: 1.25rem; overflow-wrap: anywhere; }
|
||||
.inc-tags { display: inline-flex; flex-wrap: wrap; gap: 4px; }
|
||||
.inc-detail.busy { opacity: .6; pointer-events: none; }
|
||||
.inc-grid { align-items: start; }
|
||||
|
||||
.inc-quick { display: flex; flex-wrap: wrap; gap: var(--s-2); margin-bottom: var(--s-4); }
|
||||
.inc-q-fp:not(:disabled) { border-color: var(--line-strong); }
|
||||
.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-form { display: grid; gap: var(--s-3); }
|
||||
.inc-two { align-items: start; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: var(--s-3); }
|
||||
.inc-field { display: grid; gap: 4px; min-width: 0; }
|
||||
.inc-field label { font-size: .875rem; font-weight: 600; }
|
||||
.inc-field input[type="text"], .inc-field select, .inc-field textarea, .inc-newc textarea { width: 100%; min-width: 0; box-sizing: border-box; }
|
||||
.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: 72px;
|
||||
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-check { display: flex; align-items: center; gap: var(--s-2); }
|
||||
.inc-check input { width: 18px; height: 18px; flex: none; }
|
||||
.inc-btns { display: flex; flex-wrap: wrap; gap: var(--s-2); justify-content: flex-end; margin-top: var(--s-3); }
|
||||
.inc-err { color: var(--danger); margin: var(--s-2) 0 0; }
|
||||
.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; }
|
||||
|
||||
.inc-dl { display: grid; grid-template-columns: minmax(0, auto) minmax(0, 1fr); gap: 6px var(--s-3); margin: 0; }
|
||||
.inc-dl dt { color: var(--ink-muted); font-size: .8125rem; }
|
||||
.inc-dl dd { margin: 0; overflow-wrap: anywhere; min-width: 0; }
|
||||
.inc-key { font-size: .75rem; }
|
||||
|
||||
.inc-comments { list-style: none; margin: 0 0 var(--s-3); padding: 0; display: grid; gap: var(--s-3); }
|
||||
.inc-comments li { padding: var(--s-3); background: var(--surface-raised); border: 1px solid var(--line); border-radius: var(--radius-sm); }
|
||||
.inc-c-h { display: flex; flex-wrap: wrap; gap: var(--s-2) var(--s-3); align-items: baseline; margin-bottom: 4px; }
|
||||
/* ---------------- 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-tl { list-style: none; margin: 0; padding: 0 0 0 var(--s-3); border-left: 2px solid var(--line); display: grid; gap: var(--s-3); }
|
||||
.inc-tl li { display: grid; gap: 2px; min-width: 0; }
|
||||
.inc-tl-when { font-size: .75rem; color: var(--ink-muted); }
|
||||
.inc-tl-what { overflow-wrap: anywhere; }
|
||||
.inc-tl-chg { overflow-wrap: anywhere; font-size: .875rem; }
|
||||
.inc-from { color: var(--ink-muted); text-decoration: line-through; }
|
||||
.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); }
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.inc-row { grid-template-columns: minmax(0, 1fr); }
|
||||
.inc-side { justify-items: start; grid-auto-flow: column; gap: var(--s-3); }
|
||||
.inc-two { grid-template-columns: minmax(0, 1fr); }
|
||||
.inc-quick .btn { flex: 1 1 100%; white-space: normal; }
|
||||
.inc-tab { flex: 1 1 auto; }
|
||||
.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%; }
|
||||
}
|
||||
+313
-203
@@ -158,6 +158,38 @@
|
||||
}
|
||||
});
|
||||
|
||||
// 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
|
||||
@@ -168,23 +200,18 @@
|
||||
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 tags(list) { return el('span', { class: 'inc-tags' }, (Array.isArray(list) ? list : []).map(function (x) { return el('span', { class: 'chip' }, String(x)); })); }
|
||||
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 authorBox() {
|
||||
var inp = el('input', { type: 'text', id: 'inc-author', maxlength: '64', autocomplete: 'name', placeholder: 'operator', 'aria-describedby': 'inc-author-h' });
|
||||
inp.value = getAuthor();
|
||||
inp.addEventListener('input', function () {
|
||||
try { localStorage.setItem(AUTHOR_KEY, inp.value.trim().slice(0, 64)); } catch (e) { /* storage blocked */ }
|
||||
});
|
||||
return el('div', { class: 'inc-author' }, el('label', { for: 'inc-author' }, t('inc.author')), inp, el('span', { id: 'inc-author-h', class: 'inc-hint' }, t('inc.author.hint')));
|
||||
}
|
||||
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);
|
||||
}
|
||||
@@ -230,7 +257,7 @@
|
||||
if (ctx && ctx.host && ctx.host !== 'all') p.host = ctx.host;
|
||||
return p;
|
||||
}
|
||||
var search = el('input', { type: 'search', autocomplete: 'off', placeholder: t('inc.search'), 'aria-label': t('inc.search') });
|
||||
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')));
|
||||
@@ -250,51 +277,65 @@
|
||||
sevSel.addEventListener('change', function () { U.setParam('sev', sevSel.value); reload(); });
|
||||
sortSel.addEventListener('change', function () { U.setParam('sort', sortSel.value === 'updated' ? '' : sortSel.value); reload(); });
|
||||
|
||||
host.appendChild(el('p', { class: 'inc-lead' }, t('inc.lead')));
|
||||
host.appendChild(authorBox());
|
||||
host.appendChild(tabsBox);
|
||||
host.appendChild(el('div', { class: 'toolbar inc-toolbar' }, search, sevSel, sortSel, newBtn));
|
||||
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)]]
|
||||
.concat(STATUSES.map(function (s) { return [s, t('inc.status.' + s), c[s] || 0]; }))
|
||||
.concat([['all', t('inc.tab.all'), total]]);
|
||||
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) {
|
||||
var b = el('button', { type: 'button', class: 'inc-tab' + (f.s === it[0] ? ' on' : ''), 'aria-pressed': f.s === it[0] ? 'true' : 'false' },
|
||||
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 sev = sevOf(it.severity);
|
||||
var n = it.comment_count || 0;
|
||||
var route = it.workload || it.dst ? [(it.workload || '-'), ' → ', (it.dst || '-') + (it.dport ? ':' + it.dport : '')].join('') : '';
|
||||
var meta = el('div', { class: 'inc-meta' });
|
||||
if (route) meta.appendChild(el('span', { class: 'mono inc-route' }, route));
|
||||
if (it.host) meta.appendChild(el('span', { class: 'chip' }, String(it.host)));
|
||||
var a = el('a', { class: 'inc-row inc-sev-' + sev, href: U.href('incidents', [String(it.id)]) },
|
||||
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)),
|
||||
el('span', { class: 'inc-badges' }, sevBadge(it.severity), statusBadge(it.status)),
|
||||
el('span', { class: 'inc-main' }, el('strong', { class: 'inc-title' }, String(it.title || it.id)), meta),
|
||||
el('span', { class: 'inc-side' },
|
||||
el('span', { class: 'inc-when', title: it.last_seen ? U.fmt.date(it.last_seen) : '' }, t('inc.seen', { when: U.fmt.ago(it.last_seen) })),
|
||||
n ? el('span', { class: 'inc-cm' }, U.pl('inc.comments.n', n)) : null));
|
||||
return a;
|
||||
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 : [];
|
||||
if (!items.length) { results.appendChild(U.ui.empty(t('inc.list.empty'), t('inc.list.empty.sub'))); return; }
|
||||
var list = el('div', { class: 'inc-list' });
|
||||
items.forEach(function (it) { list.appendChild(row(it)); });
|
||||
results.appendChild(list);
|
||||
var total = r.total || items.length, pages = Math.max(1, Math.ceil(total / PER_PAGE));
|
||||
var pg = U.ui.pager({ page: f.p, pages: pages, total: total, onPage: function (n) { U.setParam('p', n); load(); window.scrollTo(0, 0); } });
|
||||
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() {
|
||||
@@ -331,6 +372,8 @@
|
||||
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')));
|
||||
@@ -340,7 +383,8 @@
|
||||
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.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(); }
|
||||
@@ -353,6 +397,7 @@
|
||||
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();
|
||||
@@ -373,15 +418,15 @@
|
||||
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(authorBox());
|
||||
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 fail(node, key) { node.textContent = t(key); node.hidden = false; }
|
||||
function send(method, suffix, body, errNode, errKey, okKey) {
|
||||
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));
|
||||
@@ -389,189 +434,254 @@
|
||||
load(true);
|
||||
}, function (e) {
|
||||
busy = false; box.classList.remove('busy');
|
||||
fail(errNode, e && e.status === 409 ? 'inc.err.suppress' : errKey);
|
||||
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'); }
|
||||
|
||||
function techRow(dl, k, v) {
|
||||
if (v === undefined || v === null || v === '') return;
|
||||
dl.appendChild(el('dt', null, t(k)));
|
||||
dl.appendChild(el('dd', null, v));
|
||||
}
|
||||
function techPanel(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 ? el('span', { class: 'mono' }, String(x.workload)) : '');
|
||||
techRow(dl, 'inc.t.dst', x.dst ? (isIP(x.dst) ? el('a', { class: 'mono', href: U.href('ip', [String(x.dst)]) }, String(x.dst)) : el('span', { class: 'mono' }, String(x.dst))) : '');
|
||||
techRow(dl, 'inc.t.port', x.dport ? el('span', { class: 'mono' }, String(x.dport)) : '');
|
||||
techRow(dl, 'inc.t.proto', x.proto ? el('span', { class: 'mono' }, String(x.proto)) : '');
|
||||
techRow(dl, 'inc.t.host', x.host ? String(x.host) : '');
|
||||
techRow(dl, 'inc.t.first', x.first_seen ? U.fmt.date(x.first_seen) : '');
|
||||
techRow(dl, 'inc.t.last', x.last_seen ? U.fmt.date(x.last_seen) : '');
|
||||
techRow(dl, 'inc.t.count', x.count ? nf(x.count) : '');
|
||||
techRow(dl, 'inc.t.created', x.created_at ? U.fmt.date(x.created_at) : '');
|
||||
techRow(dl, 'inc.t.updated', x.updated_at ? U.fmt.date(x.updated_at) : '');
|
||||
techRow(dl, 'inc.t.key', x.key ? el('span', { class: 'mono inc-key' }, String(x.key)) : '');
|
||||
var p = U.ui.panel({ title: t('inc.tech'), cls: 'span-4' }, dl);
|
||||
return p;
|
||||
}
|
||||
|
||||
function histValue(field, v) {
|
||||
if (v === undefined || v === null || v === '' || (Array.isArray(v) && !v.length)) return t('inc.h.empty');
|
||||
if (field === 'status') return tr('inc.status.' + v, String(v));
|
||||
if (field === 'severity') return tr('inc.sev.' + v, String(v));
|
||||
if (field === 'suppress') return t(v === true || v === 'true' ? 'inc.h.on' : 'inc.h.off');
|
||||
if (Array.isArray(v)) return v.join(', ');
|
||||
return String(v);
|
||||
}
|
||||
function histPanel(x) {
|
||||
var hist = Array.isArray(x.history) ? x.history.slice().reverse() : [];
|
||||
var p = U.ui.panel({ title: t('inc.history'), cls: 'span-4' });
|
||||
if (!hist.length) { p.body.appendChild(el('p', { class: 'inc-hint' }, t('inc.history.none'))); return p; }
|
||||
var ol = el('ol', { class: 'inc-tl' });
|
||||
hist.forEach(function (h) {
|
||||
var f = String(h.field || '');
|
||||
var fl = tr('inc.h.field.' + f, f);
|
||||
if (f === 'created') {
|
||||
ol.appendChild(el('li', null,
|
||||
el('span', { class: 'inc-tl-when' }, U.fmt.date(h.at)),
|
||||
el('span', { class: 'inc-tl-what' }, t('inc.h.created', { who: String(h.author || '-'), sev: f === 'created' && h.to === 'flood' ? t('inc.h.flood') : histValue('severity', h.to) }))));
|
||||
return;
|
||||
// ---- 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();
|
||||
}
|
||||
ol.appendChild(el('li', null,
|
||||
el('span', { class: 'inc-tl-when' }, U.fmt.date(h.at)),
|
||||
el('span', { class: 'inc-tl-what' }, t('inc.h.line', { who: String(h.author || '-'), field: fl })),
|
||||
el('span', { class: 'inc-tl-chg' }, el('span', { class: 'inc-from' }, histValue(f, h.from)), ' → ', el('strong', null, histValue(f, h.to)))));
|
||||
});
|
||||
p.body.appendChild(ol);
|
||||
return p;
|
||||
}
|
||||
|
||||
function commentsPanel(x) {
|
||||
var p = U.ui.panel({ title: t('inc.comments'), cls: 'span-8' });
|
||||
var list = Array.isArray(x.comments) ? x.comments : [];
|
||||
if (!list.length) p.body.appendChild(el('p', { class: 'inc-hint' }, t('inc.comments.none')));
|
||||
else {
|
||||
var ul = el('ul', { class: 'inc-comments' });
|
||||
list.forEach(function (c) {
|
||||
ul.appendChild(el('li', null,
|
||||
el('div', { class: 'inc-c-h' }, el('strong', null, String(c.author || '-')), el('span', { class: 'inc-hint' }, c.at ? U.fmt.date(c.at) : '')),
|
||||
el('p', { class: 'inc-text' }, String(c.text || ''))));
|
||||
});
|
||||
p.body.appendChild(ul);
|
||||
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();
|
||||
}
|
||||
var ta = el('textarea', { id: 'inc-comment', rows: '3', 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 primary' }, t('inc.comment.add'));
|
||||
function submit() {
|
||||
var txt = ta.value.trim();
|
||||
if (!txt) { ta.focus(); return; }
|
||||
err.hidden = true;
|
||||
send('POST', '/comments', { text: txt }, err, 'inc.err.comment', 'inc.comment.added');
|
||||
}
|
||||
add.addEventListener('click', submit);
|
||||
ta.addEventListener('keydown', function (e) { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); submit(); } });
|
||||
p.body.appendChild(el('div', { class: 'inc-newc' }, ta, err, el('div', { class: 'inc-btns' }, add)));
|
||||
return p;
|
||||
}
|
||||
|
||||
function formPanel(x) {
|
||||
var title = el('input', { type: 'text', id: 'inc-e-title', maxlength: '200', value: String(x.title || '') });
|
||||
var sev = selectOf('inc-e-sev', SEVS, function (s) { return t('inc.sev.' + s); }, sevOf(x.severity));
|
||||
var st = selectOf('inc-e-status', STATUSES, function (s) { return t('inc.status.' + s); }, statusOf(x.status));
|
||||
var asg = el('input', { type: 'text', id: 'inc-e-asg', maxlength: '64', value: String(x.assignee || '') });
|
||||
var tg = el('input', { type: 'text', id: 'inc-e-tags', maxlength: '300', value: (x.tags || []).join(', ') });
|
||||
var vd = el('textarea', { id: 'inc-e-verdict', rows: '4', maxlength: '4000' });
|
||||
vd.value = String(x.verdict || '');
|
||||
var sup = el('input', { type: 'checkbox', id: 'inc-e-sup' });
|
||||
sup.checked = !!x.suppress;
|
||||
var supHelp = el('span', { class: 'inc-hint', id: 'inc-e-sup-h' });
|
||||
sup.setAttribute('aria-describedby', 'inc-e-sup-h');
|
||||
var err = el('p', { class: 'inc-err', role: 'alert', hidden: true });
|
||||
var save = el('button', { type: 'button', class: 'btn primary' }, t('inc.save'));
|
||||
|
||||
function syncSup() {
|
||||
var okSt = SUPPRESSIBLE.indexOf(st.value) >= 0;
|
||||
sup.disabled = !okSt;
|
||||
if (!okSt) sup.checked = false;
|
||||
supHelp.textContent = t('inc.f.suppress.help') + (okSt ? '' : ' ' + t('inc.f.suppress.off'));
|
||||
}
|
||||
function diff() {
|
||||
var d = {}, ttl = title.value.trim();
|
||||
if (ttl && ttl !== x.title) d.title = ttl;
|
||||
if (sev.value !== sevOf(x.severity)) d.severity = sev.value;
|
||||
if (st.value !== statusOf(x.status)) d.status = st.value;
|
||||
if (asg.value.trim() !== (x.assignee || '')) d.assignee = asg.value.trim();
|
||||
var tl = parseTags(tg.value);
|
||||
if (!sameList(tl, x.tags)) d.tags = tl;
|
||||
if (vd.value.trim() !== (x.verdict || '').trim()) d.verdict = vd.value.trim();
|
||||
if (sup.checked !== !!x.suppress) d.suppress = sup.checked;
|
||||
return d;
|
||||
}
|
||||
function sync() { syncSup(); save.disabled = busy || !Object.keys(diff()).length; }
|
||||
[title, sev, st, asg, tg, vd, sup].forEach(function (c) { c.addEventListener('input', sync); c.addEventListener('change', sync); });
|
||||
sync();
|
||||
save.addEventListener('click', function () {
|
||||
var d = diff();
|
||||
if (!Object.keys(d).length) return;
|
||||
err.hidden = true;
|
||||
send('PATCH', '', d, err, 'inc.err.save', 'inc.saved');
|
||||
});
|
||||
|
||||
showTitle();
|
||||
function quick(label, status, tone) {
|
||||
var b = el('button', { type: 'button', class: 'btn inc-q-' + tone }, label);
|
||||
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;
|
||||
err.hidden = true;
|
||||
send('PATCH', '', d, err, 'inc.err.save', 'inc.saved');
|
||||
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));
|
||||
}
|
||||
|
||||
var supRow = el('div', { class: 'inc-field inc-sup' },
|
||||
el('div', { class: 'inc-check' }, sup, el('label', { for: 'inc-e-sup' }, t('inc.f.suppress'))), supHelp);
|
||||
var p = U.ui.panel({ title: t('inc.edit'), cls: 'span-8' },
|
||||
q,
|
||||
el('div', { class: 'inc-form' },
|
||||
field(t('inc.f.title'), title, null, 'inc-e-title'),
|
||||
el('div', { class: 'inc-two' }, field(t('inc.f.status'), st, null, 'inc-e-status'), field(t('inc.f.severity'), sev, null, 'inc-e-sev')),
|
||||
el('div', { class: 'inc-two' }, field(t('inc.f.assignee'), asg, null, 'inc-e-asg'), field(t('inc.f.tags'), tg, t('inc.f.tags.hint'), 'inc-e-tags')),
|
||||
field(t('inc.f.verdict'), vd, t('inc.f.verdict.hint'), 'inc-e-verdict'),
|
||||
supRow),
|
||||
err, el('div', { class: 'inc-btns' }, save));
|
||||
return p;
|
||||
// ---- 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;
|
||||
var sev = sevOf(x.severity);
|
||||
var head = el('header', { class: 'inc-head inc-sev-' + sev },
|
||||
el('span', { class: 'inc-id mono' }, String(x.id)),
|
||||
sevBadge(x.severity), statusBadge(x.status),
|
||||
x.suppress ? el('span', { class: 'chip' }, t('eg.suppressed.chip')) : null,
|
||||
el('h2', { class: 'inc-h-title' }, String(x.title || x.id)),
|
||||
tags(x.tags));
|
||||
var grid = el('div', { class: 'grid-12 inc-grid' });
|
||||
grid.appendChild(formPanel(x));
|
||||
grid.appendChild(techPanel(x));
|
||||
if (x.detail) {
|
||||
var dp = U.ui.panel({ title: t('inc.f.detail'), cls: 'span-8' }, el('p', { class: 'inc-text mono' }, String(x.detail)));
|
||||
grid.appendChild(dp);
|
||||
grid.appendChild(histPanel(x));
|
||||
grid.appendChild(commentsPanel(x));
|
||||
} else {
|
||||
grid.appendChild(commentsPanel(x));
|
||||
grid.appendChild(histPanel(x));
|
||||
}
|
||||
box.appendChild(head);
|
||||
box.appendChild(grid);
|
||||
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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -604,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; }
|
||||
@@ -670,3 +673,20 @@ input[type="datetime-local"] { background: var(--surface-raised); border: 1px so
|
||||
.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)
|
||||
}
|
||||
}
|
||||
+74
-27
@@ -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,16 +10,18 @@ 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
|
||||
Est Tally24 // 24 h estimate from the per-day counters (the registry may not cover the whole window)
|
||||
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 and web malicious events of the last 24 h from
|
||||
// the per-day counters: today plus the share of yesterday still inside the 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{}
|
||||
@@ -26,24 +29,43 @@ func dayEstimate(r *IPRec, nowU int64) Tally24 {
|
||||
today := nowU / 86400
|
||||
frac := 1 - float64(nowU%86400)/86400
|
||||
var t Tally24
|
||||
for k := int64(0); k <= 1; k++ {
|
||||
for k := int64(0); k <= 7; k++ {
|
||||
i := int(r.DayBase - (today - k))
|
||||
if i < 0 || i >= len(r.DayCats) {
|
||||
continue
|
||||
}
|
||||
w := 1.0
|
||||
if k == 1 {
|
||||
w = frac
|
||||
}
|
||||
c := r.DayCats[i]
|
||||
t.SSH += int(float64(c[core.SSHFail.Index()])*w + 0.999)
|
||||
t.Web += int(float64(c[core.Scanner.Index()]+c[core.Exploit.Index()]+c[core.BruteForce.Index()])*w + 0.999)
|
||||
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 {
|
||||
@@ -57,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, Est: dayEstimate(r, nowU)})
|
||||
Jails: append([]string(nil), r.Jails...), Last: r.Last, Events: int(malOf(r.Counts)), Est: dayEstimate(r, nowU)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -75,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}, 4<<30, false, func(r evlog.Rec, _ []byte) bool {
|
||||
tallyAdd(m, r)
|
||||
tallyAdd(m, r, cut24)
|
||||
return true
|
||||
})
|
||||
out := make(map[string]Tally24, len(m))
|
||||
@@ -120,16 +158,25 @@ func (s *Store) AttackTally(ip string, from int64) Tally24 {
|
||||
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}, 1<<30, false, func(r evlog.Rec, _ []byte) bool {
|
||||
tallyAdd(m, r)
|
||||
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
|
||||
}
|
||||
t.SSH, t.Web = max(t.SSH, est.SSH), max(t.Web, est.Web)
|
||||
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)}
|
||||
}
|
||||
+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