feat: record own and trusted web traffic in its own classes instead of dropping it
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4143bf599e
commit
3511a7141c
18 files changed
+434
-17
No files matched your search
@@ -6,6 +6,10 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- Own and trusted traffic is recorded instead of dropped. Web requests from `URUTAU_TRUSTED` (class `trusted`) and from the `URUTAU_IGNORE` ranges, private networks by default (class `internal`), used to vanish at ingestion, which hid about half of the real requests on a busy host (the other server, a CI runner, the Docker gateway). They are now counted in aggregates only (no event record each, kept in the snapshot) and never score an IP or enter threats, campaigns, sessions, maps, the blocklist, ban evidence, egress logic or visitor analytics. API: `totals.trusted`, `totals.internal`, `totals.requests_all` (`requests` plus both classes), `totals.counts.trusted` and `.internal`, and `own` in `/api/v1/summary` (status classes, timeline `series`, `origins`, `domains`, `paths`). The Traffic page has a new section "Own infrastructure and trusted origins". Probes need no change: the hub classifies. Tests `TestOwnTrafficIsCountedNeverAnalysed` and `TestOwnTrafficThroughFeed`.
|
||||||
|
|
||||||
## [2.2.2] - 2026-11-19
|
## [2.2.2] - 2026-11-19
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|||||||
@@ -6,6 +6,10 @@ Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
|
|||||||
|
|
||||||
## [Não lançado]
|
## [Não lançado]
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
|
||||||
|
- O tráfego próprio e confiável é registrado em vez de descartado. As requisições web de `URUTAU_TRUSTED` (classe `trusted`) e das faixas de `URUTAU_IGNORE`, redes privadas por padrão (classe `internal`), sumiam na ingestão, o que escondia cerca de metade das requisições reais de um host movimentado (o outro servidor, um runner de CI, o gateway do Docker). Agora são contadas só em agregados (sem registro de evento cada, mantidas no snapshot) e nunca pontuam um IP nem entram em ameaças, campanhas, sessões, mapas, lista de bloqueio, evidência de banimento, lógica de egress ou análise de visitantes. API: `totals.trusted`, `totals.internal`, `totals.requests_all` (`requests` mais as duas classes), `totals.counts.trusted` e `.internal`, e `own` em `/api/v1/summary` (classes de status, `series` da linha do tempo, `origins`, `domains`, `paths`). A página Tráfego ganhou a seção "Infraestrutura própria e origens confiáveis". As sondas não precisam mudar: o hub classifica. Testes `TestOwnTrafficIsCountedNeverAnalysed` e `TestOwnTrafficThroughFeed`.
|
||||||
|
|
||||||
## [2.2.2] - 2026-11-19
|
## [2.2.2] - 2026-11-19
|
||||||
|
|
||||||
### Corrigido
|
### Corrigido
|
||||||
|
|||||||
@@ -315,7 +315,7 @@ The user routes under `/api/v1/*` need `URUTAU_TOKEN` (bearer) or a session cook
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `GET /api/health` | `{"status":"ok"}`, no authentication |
|
| `GET /api/health` | `{"status":"ok"}`, no authentication |
|
||||||
| `GET /login`, `POST /login`, `POST /logout` | session cookie |
|
| `GET /login`, `POST /login`, `POST /logout` | session cookie |
|
||||||
| `GET /api/v1/summary`, `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totals, web analytics, IP table, one address, STIX 2.1 bundle |
|
| `GET /api/v1/summary` (also `own`: web requests of `--trusted` and `--ignore` origins, counted apart; `totals.trusted`, `totals.internal` and `totals.requests_all` = `requests` + both; `totals.counts.trusted` and `.internal`), `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totals, web analytics, IP table, one address, STIX 2.1 bundle |
|
||||||
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | study of a period, event registry search (cursor), sessions |
|
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | study of a period, event registry search (cursor), sessions |
|
||||||
| `GET /api/v1/events/stream` | live stream over SSE (`?visits=1` adds anonymous visits) |
|
| `GET /api/v1/events/stream` | live stream over SSE (`?visits=1` adds anonymous visits) |
|
||||||
| `GET /api/v1/live/recent`, `/geo` | latest live events, geography |
|
| `GET /api/v1/live/recent`, `/geo` | latest live events, geography |
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ Settings are split by role. The **hub** (`urutau serve`) takes the variables in
|
|||||||
|
|
||||||
| Variable | Default | Meaning |
|
| Variable | Default | Meaning |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `URUTAU_TRUSTED` | empty | trusted CIDRs or IPs, comma separated; their events are dropped entirely. Also feeds the exclusions of the second firewall and the egress allow list |
|
| `URUTAU_TRUSTED` | empty | trusted CIDRs or IPs, comma separated; their web requests are counted as own traffic (class `trusted`) and never analysed: no score, threat, visitor or ban. Also feeds the exclusions of the second firewall and the egress allow list |
|
||||||
| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | same effect, kept as the alias that carries the private ranges as default |
|
| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | same effect (class `internal`), kept as the alias that carries the private ranges as default |
|
||||||
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents; empty disables; an invalid expression refuses to start |
|
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | regular expression of monitoring User-Agents; empty disables; an invalid expression refuses to start |
|
||||||
| `URUTAU_MONITOR_FROM` | empty | CIDRs the monitors really come from; when set, the monitoring User-Agent only counts from them |
|
| `URUTAU_MONITOR_FROM` | empty | CIDRs the monitors really come from; when set, the monitoring User-Agent only counts from them |
|
||||||
| `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h after the last login (a later strong signal cancels it); the immunity is off unless this is set |
|
| `URUTAU_ADMIN_USERS` | empty | SSH users whose successful login keeps their IP out of the blocklist for 24 h after the last login (a later strong signal cancels it); the immunity is off unless this is set |
|
||||||
@@ -109,7 +109,7 @@ The probe image defaults to the paths above because the compose file in `deploy/
|
|||||||
## Noise and monitoring
|
## Noise and monitoring
|
||||||
|
|
||||||
- **Traefik headers.** Log `Sec-Fetch-Site`, `Sec-Fetch-Dest` and `Referer` so Urutau can tell a page framing your site from a real visit: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` and `--accesslog.fields.headers.names.Referer=keep`. A request framed by another page (`Sec-Fetch-Site` of `cross-site` or `same-site`, or a sub-resource `Sec-Fetch-Dest` such as `image` or `script`) appears in the timeline and creates an IP record like any other, but weighs 0.25 per event, with at most 30 points per IP coming from such requests (below the hostile threshold), and never counts as a strong signal. With an attack-tool User-Agent the headers are ignored.
|
- **Traefik headers.** Log `Sec-Fetch-Site`, `Sec-Fetch-Dest` and `Referer` so Urutau can tell a page framing your site from a real visit: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` and `--accesslog.fields.headers.names.Referer=keep`. A request framed by another page (`Sec-Fetch-Site` of `cross-site` or `same-site`, or a sub-resource `Sec-Fetch-Dest` such as `image` or `script`) appears in the timeline and creates an IP record like any other, but weighs 0.25 per event, with at most 30 points per IP coming from such requests (below the hostile threshold), and never counts as a strong signal. With an attack-tool User-Agent the headers are ignored.
|
||||||
- **Trusted origins** (`URUTAU_TRUSTED`): your own network, offices, monitors and other servers. `URUTAU_IGNORE` already drops loopback and the private ranges by default, so internal traffic never scores. Add your public monitor IPs. If your proxy reports the Docker gateway as the client, that address is private and already dropped; fix the proxy to pass the real client address instead.
|
- **Trusted origins** (`URUTAU_TRUSTED`): your own network, offices, monitors and other servers. `URUTAU_IGNORE` already covers loopback and the private ranges by default, so internal traffic never scores. Nothing is silently dropped: web requests from these origins are counted in aggregates only (not as one event record each) and shown in the Traffic page under "Own infrastructure and trusted origins"; they stay out of `totals.requests`, scores, threats, maps, visitors and the blocklist. SSH, fail2ban and network-probe lines from these origins are still ignored. Add your public monitor IPs. If your proxy reports the Docker gateway as the client, that address is private and counted as `internal` own traffic; fix the proxy to pass the real client address instead.
|
||||||
- **Monitoring User-Agent** (`URUTAU_MONITOR_UA`): a Go regular expression. A request that matches and is benign is counted as "monitoring" instead of traffic. If the request is a `scanner`, `exploit` or `bruteforce` it counts as an attack: a User-Agent is trivial to forge, so it never grants immunity.
|
- **Monitoring User-Agent** (`URUTAU_MONITOR_UA`): a Go regular expression. A request that matches and is benign is counted as "monitoring" instead of traffic. If the request is a `scanner`, `exploit` or `bruteforce` it counts as an attack: a User-Agent is trivial to forge, so it never grants immunity.
|
||||||
- **Where monitors come from** (`URUTAU_MONITOR_FROM`): CIDRs of your monitors. When set, the monitoring User-Agent is honored only from those networks and benign requests (`ok` or `notfound`) are filtered. When empty, only `ok` answers are filtered: a `notfound` carrying a monitor User-Agent still counts, because anyone can send that header.
|
- **Where monitors come from** (`URUTAU_MONITOR_FROM`): CIDRs of your monitors. When set, the monitoring User-Agent is honored only from those networks and benign requests (`ok` or `notfound`) are filtered. When empty, only `ok` answers are filtered: a `notfound` carrying a monitor User-Agent still counts, because anyone can send that header.
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -113,7 +113,7 @@ A side rail (a tab bar on phones, with a "More" menu that scrolls when it is tal
|
|||||||
|
|
||||||
<p align="center"><img src="img/survival-dark.png" width="900" alt="Page: Survival"><br><sub>Survival: how long attackers keep coming back.</sub></p>
|
<p align="center"><img src="img/survival-dark.png" width="900" alt="Page: Survival"><br><sub>Survival: how long attackers keep coming back.</sub></p>
|
||||||
|
|
||||||
**Traffic** (`#/traffic`): privacy-friendly web analytics for legitimate traffic, built from the same Traefik log: unique visitors, pages, referrers, countries, browsers, operating systems, devices, response latency (p50 and p95), bytes sent and a world map of visitor countries, per domain. A unique visitor is a person with a real browser (a successful GET of a document by a browser User-Agent, one per IP per day, deduplicated globally); bots, tools and unknown clients are counted apart as "non-human clients". Visitors are counted by a hash with a daily salt; the IP of a legitimate visitor is never stored. See [SECURITY.md](../SECURITY.md).
|
**Traffic** (`#/traffic`): privacy-friendly web analytics for legitimate traffic, built from the same Traefik log: unique visitors, pages, referrers, countries, browsers, operating systems, devices, response latency (p50 and p95), bytes sent and a world map of visitor countries, per domain. A unique visitor is a person with a real browser (a successful GET of a document by a browser User-Agent, one per IP per day, deduplicated globally); bots, tools and unknown clients are counted apart as "non-human clients". Visitors are counted by a hash with a daily salt; the IP of a legitimate visitor is never stored. See [SECURITY.md](../SECURITY.md). A section at the bottom, "Own infrastructure and trusted origins", shows the web requests of `--trusted` and private (`--ignore`) origins (your servers, probes, CI runners, the Docker gateway) that are kept out of every other number: totals per class, a timeline, status classes, a table by origin (address, class, requests), and top domains and paths. They never score an IP or enter threats, maps, visitors or the blocklist.
|
||||||
|
|
||||||
<p align="center"><img src="img/traffic-dark.png" width="900" alt="Traffic page: web analytics of legitimate visitors"><br><sub>Traffic: privacy-friendly web analytics.</sub></p>
|
<p align="center"><img src="img/traffic-dark.png" width="900" alt="Traffic page: web analytics of legitimate visitors"><br><sub>Traffic: privacy-friendly web analytics.</sub></p>
|
||||||
|
|
||||||
|
|||||||
@@ -315,7 +315,7 @@ As rotas de usuário em `/api/v1/*` exigem `URUTAU_TOKEN` (bearer) ou um cookie
|
|||||||
|---|---|
|
|---|---|
|
||||||
| `GET /api/health` | `{"status":"ok"}`, sem autenticação |
|
| `GET /api/health` | `{"status":"ok"}`, sem autenticação |
|
||||||
| `GET /login`, `POST /login`, `POST /logout` | cookie de sessão |
|
| `GET /login`, `POST /login`, `POST /logout` | cookie de sessão |
|
||||||
| `GET /api/v1/summary`, `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totais, web analytics, tabela de IPs, um endereço, bundle STIX 2.1 |
|
| `GET /api/v1/summary` (também `own`: requisições web de origens `--trusted` e `--ignore`, contadas à parte; `totals.trusted`, `totals.internal` e `totals.requests_all` = `requests` + ambas; `totals.counts.trusted` e `.internal`), `/traffic`, `/ips`, `/ip/{ip}`, `/ip/{ip}/stix` | totais, web analytics, tabela de IPs, um endereço, bundle STIX 2.1 |
|
||||||
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | estudo de um período, busca no registro de eventos (cursor), sessões |
|
| `GET /api/v1/period`, `/period/events`, `/events`, `/events/sessions` | estudo de um período, busca no registro de eventos (cursor), sessões |
|
||||||
| `GET /api/v1/events/stream` | stream ao vivo por SSE (`?visits=1` inclui visitas anônimas) |
|
| `GET /api/v1/events/stream` | stream ao vivo por SSE (`?visits=1` inclui visitas anônimas) |
|
||||||
| `GET /api/v1/live/recent`, `/geo` | últimos eventos ao vivo, geografia |
|
| `GET /api/v1/live/recent`, `/geo` | últimos eventos ao vivo, geografia |
|
||||||
|
|||||||
@@ -38,8 +38,8 @@ Os ajustes se dividem por papel. O **hub** (`urutau serve`) usa as variáveis da
|
|||||||
|
|
||||||
| Variável | Padrão | Significado |
|
| Variável | Padrão | Significado |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `URUTAU_TRUSTED` | vazio | CIDRs ou IPs confiáveis, separados por vírgula; os eventos deles são descartados por completo. Também alimenta as exclusões do segundo firewall e a lista de permitidos do egress |
|
| `URUTAU_TRUSTED` | vazio | CIDRs ou IPs confiáveis, separados por vírgula; as requisições web deles são contadas como tráfego próprio (classe `trusted`) e nunca analisadas: sem pontuação, ameaça, visitante ou banimento. Também alimenta as exclusões do segundo firewall e a lista de permitidos do egress |
|
||||||
| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | mesmo efeito, mantido como o alias que carrega as faixas privadas como padrão |
|
| `URUTAU_IGNORE` | `127.0.0.0/8,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,fc00::/7,fe80::/10,100.64.0.0/10,169.254.0.0/16` | mesmo efeito (classe `internal`), mantido como o alias que carrega as faixas privadas como padrão |
|
||||||
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento; vazio desativa; expressão inválida impede a inicialização |
|
| `URUTAU_MONITOR_UA` | `(?i)^(Uptime-Kuma/\|Beszel\|Coolify\|kube-probe/\|Go-http-client/.*healthcheck)` | expressão regular de User-Agents de monitoramento; vazio desativa; expressão inválida impede a inicialização |
|
||||||
| `URUTAU_MONITOR_FROM` | vazio | CIDRs de onde os monitores realmente vêm; quando definido, o User-Agent de monitoramento só vale vindo deles |
|
| `URUTAU_MONITOR_FROM` | vazio | CIDRs de onde os monitores realmente vêm; quando definido, o User-Agent de monitoramento só vale vindo deles |
|
||||||
| `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da lista de bloqueio por 24 h após o último login (um sinal forte posterior cancela); a imunidade fica desligada se isto não for definido |
|
| `URUTAU_ADMIN_USERS` | vazio | usuários SSH cujo login bem-sucedido mantém o IP fora da lista de bloqueio por 24 h após o último login (um sinal forte posterior cancela); a imunidade fica desligada se isto não for definido |
|
||||||
@@ -109,7 +109,7 @@ A imagem da sonda usa os caminhos acima como padrão porque o compose em `deploy
|
|||||||
## Ruído e monitoramento
|
## Ruído e monitoramento
|
||||||
|
|
||||||
- **Cabeçalhos do Traefik.** Registre `Sec-Fetch-Site`, `Sec-Fetch-Dest` e `Referer` para o Urutau distinguir uma página que embute seu site de uma visita real: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` e `--accesslog.fields.headers.names.Referer=keep`. Uma requisição enquadrada por outra página (`Sec-Fetch-Site` `cross-site` ou `same-site`, ou `Sec-Fetch-Dest` de subrecurso como `image` ou `script`) aparece na linha do tempo e cria registro de IP como qualquer outra, mas pesa 0,25 por evento, com no máximo 30 pontos por IP vindos delas (abaixo do limiar hostil), e nunca conta como sinal forte. Com User-Agent de ferramenta de ataque os cabeçalhos são ignorados.
|
- **Cabeçalhos do Traefik.** Registre `Sec-Fetch-Site`, `Sec-Fetch-Dest` e `Referer` para o Urutau distinguir uma página que embute seu site de uma visita real: `--accesslog.fields.headers.names.Sec-Fetch-Site=keep`, `--accesslog.fields.headers.names.Sec-Fetch-Dest=keep` e `--accesslog.fields.headers.names.Referer=keep`. Uma requisição enquadrada por outra página (`Sec-Fetch-Site` `cross-site` ou `same-site`, ou `Sec-Fetch-Dest` de subrecurso como `image` ou `script`) aparece na linha do tempo e cria registro de IP como qualquer outra, mas pesa 0,25 por evento, com no máximo 30 pontos por IP vindos delas (abaixo do limiar hostil), e nunca conta como sinal forte. Com User-Agent de ferramenta de ataque os cabeçalhos são ignorados.
|
||||||
- **Origens confiáveis** (`URUTAU_TRUSTED`): sua própria rede, escritórios, monitores e outros servidores. `URUTAU_IGNORE` já descarta loopback e as faixas privadas por padrão, então o tráfego interno nunca pontua. Acrescente os IPs públicos dos seus monitores. Se o proxy informa o gateway do Docker como cliente, esse endereço é privado e já é descartado; corrija o proxy para repassar o endereço real do cliente.
|
- **Origens confiáveis** (`URUTAU_TRUSTED`): sua própria rede, escritórios, monitores e outros servidores. `URUTAU_IGNORE` já cobre loopback e as faixas privadas por padrão, então o tráfego interno nunca pontua. Nada é descartado em silêncio: as requisições web dessas origens são contadas só em agregados (não como um registro de evento cada) e aparecem na página Tráfego em "Infraestrutura própria e origens confiáveis"; ficam fora de `totals.requests`, pontuação, ameaças, mapas, visitantes e lista de bloqueio. Linhas de SSH, fail2ban e sondas de rede dessas origens continuam ignoradas. Acrescente os IPs públicos dos seus monitores. Se o proxy informa o gateway do Docker como cliente, esse endereço é privado e contado como tráfego próprio `internal`; corrija o proxy para repassar o endereço real do cliente.
|
||||||
- **User-Agent de monitoramento** (`URUTAU_MONITOR_UA`): uma expressão regular do Go. Uma requisição que casa e é benigna é contada como "monitoring" em vez de tráfego. Se a requisição for `scanner`, `exploit` ou `bruteforce`, conta como ataque: um User-Agent é trivial de forjar, então nunca concede imunidade.
|
- **User-Agent de monitoramento** (`URUTAU_MONITOR_UA`): uma expressão regular do Go. Uma requisição que casa e é benigna é contada como "monitoring" em vez de tráfego. Se a requisição for `scanner`, `exploit` ou `bruteforce`, conta como ataque: um User-Agent é trivial de forjar, então nunca concede imunidade.
|
||||||
- **De onde vêm os monitores** (`URUTAU_MONITOR_FROM`): CIDRs dos seus monitores. Quando definido, o User-Agent de monitoramento só vale vindo dessas redes e requisições benignas (`ok` ou `notfound`) são filtradas. Quando vazio, só respostas `ok` são filtradas: um `notfound` com User-Agent de monitor ainda conta, porque qualquer um pode enviar esse cabeçalho.
|
- **De onde vêm os monitores** (`URUTAU_MONITOR_FROM`): CIDRs dos seus monitores. Quando definido, o User-Agent de monitoramento só vale vindo dessas redes e requisições benignas (`ok` ou `notfound`) são filtradas. Quando vazio, só respostas `ok` são filtradas: um `notfound` com User-Agent de monitor ainda conta, porque qualquer um pode enviar esse cabeçalho.
|
||||||
|
|
||||||
|
|||||||
@@ -113,7 +113,7 @@ Uma barra lateral (barra de abas no celular, com um menu "Mais" que rola quando
|
|||||||
|
|
||||||
<p align="center"><img src="../img/survival-dark-pt.png" width="900" alt="Página: Sobrevivência"><br><sub>Sobrevivência: por quanto tempo os atacantes continuam voltando.</sub></p>
|
<p align="center"><img src="../img/survival-dark-pt.png" width="900" alt="Página: Sobrevivência"><br><sub>Sobrevivência: por quanto tempo os atacantes continuam voltando.</sub></p>
|
||||||
|
|
||||||
**Tráfego** (`#/traffic`): web analytics amigável à privacidade do tráfego legítimo, feito a partir do mesmo log do Traefik: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência de resposta (p50 e p95), bytes enviados e um mapa-múndi dos países dos visitantes, por domínio. Um visitante único é uma pessoa com navegador real (um GET bem-sucedido de um documento por um User-Agent de navegador, um por IP por dia, deduplicado globalmente); bots, ferramentas e clientes desconhecidos são contados à parte como "clientes não humanos". Visitantes são contados por um hash com sal diário; o IP de um visitante legítimo nunca é guardado. Veja [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md).
|
**Tráfego** (`#/traffic`): web analytics amigável à privacidade do tráfego legítimo, feito a partir do mesmo log do Traefik: visitantes únicos, páginas, referrers, países, navegadores, sistemas operacionais, dispositivos, latência de resposta (p50 e p95), bytes enviados e um mapa-múndi dos países dos visitantes, por domínio. Um visitante único é uma pessoa com navegador real (um GET bem-sucedido de um documento por um User-Agent de navegador, um por IP por dia, deduplicado globalmente); bots, ferramentas e clientes desconhecidos são contados à parte como "clientes não humanos". Visitantes são contados por um hash com sal diário; o IP de um visitante legítimo nunca é guardado. Veja [SECURITY.pt-BR.md](../../SECURITY.pt-BR.md). Uma seção no fim, "Infraestrutura própria e origens confiáveis", mostra as requisições web de origens `--trusted` e privadas (`--ignore`) (seus servidores, sondas, runners de CI, o gateway do Docker) que ficam fora de todos os outros números: totais por classe, linha do tempo, classes de status, tabela por origem (endereço, classe, requisições) e os domínios e caminhos mais pedidos. Elas nunca pontuam um IP nem entram em ameaças, mapas, visitantes ou na lista de bloqueio.
|
||||||
|
|
||||||
<p align="center"><img src="../img/traffic-dark-pt.png" width="900" alt="Página Tráfego: web analytics dos visitantes legítimos"><br><sub>Tráfego: web analytics amigável à privacidade.</sub></p>
|
<p align="center"><img src="../img/traffic-dark-pt.png" width="900" alt="Página Tráfego: web analytics dos visitantes legítimos"><br><sub>Tráfego: web analytics amigável à privacidade.</sub></p>
|
||||||
|
|
||||||
|
|||||||
@@ -62,13 +62,13 @@ func TestMonitoringTrustedAndForged(t *testing.T) {
|
|||||||
t.Fatalf("feed %+v", rec)
|
t.Fatalf("feed %+v", rec)
|
||||||
}
|
}
|
||||||
|
|
||||||
// trusted origins are dropped entirely, even for exploits and with other UAs
|
// trusted origins are only counted (see TestOwnTrafficIsCountedNeverAnalysed), even for exploits
|
||||||
h(line("136.248.78.83", "GET", "/?x=../../etc/passwd", "curl/8", 200))
|
h(line("136.248.78.83", "GET", "/?x=../../etc/passwd", "curl/8", 200))
|
||||||
h(line("2001:db8:1::5", "GET", "/.env", "curl/8", 404))
|
h(line("2001:db8:1::5", "GET", "/.env", "curl/8", 404))
|
||||||
h(line("127.0.0.1", "GET", "/.env", "curl/8", 404))
|
h(line("127.0.0.1", "GET", "/.env", "curl/8", 404))
|
||||||
for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "127.0.0.1"} {
|
for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "127.0.0.1"} {
|
||||||
if _, ok := st.IP(a); ok {
|
if _, ok := st.IP(a); ok {
|
||||||
t.Fatalf("%s must be dropped", a)
|
t.Fatalf("%s must not become an IP record", a)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// a non-matching UA from an external IP is a normal request
|
// a non-matching UA from an external IP is a normal request
|
||||||
@@ -374,3 +374,100 @@ func TestLocationFlagIsValidated(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestOwnTrafficIsCountedNeverAnalysed(t *testing.T) {
|
||||||
|
r, st := runner(t, nil)
|
||||||
|
h := r.handle(&source{name: "traefik", parse: traefikParse})
|
||||||
|
h(line("198.51.100.4", "GET", "/", "Mozilla/5.0 (X11; Linux x86_64) Firefox/120.0", 200)) // external: counted as usual
|
||||||
|
before := st.Summary("1h")
|
||||||
|
// trusted (--trusted), including an attack-looking request, and a private address (--ignore default)
|
||||||
|
h(line("136.248.78.83", "GET", "/.env", "curl/8", 404))
|
||||||
|
h(line("136.248.78.83", "GET", "/api/x?token=secret", "curl/8", 200))
|
||||||
|
h(line("2001:db8:1::5", "POST", "/login", "curl/8", 401))
|
||||||
|
h(line("172.18.0.1", "GET", "/", "Mozilla/5.0 (X11; Linux x86_64) Firefox/120.0", 200))
|
||||||
|
h(line("127.0.0.1", "GET", "/", "x", 502))
|
||||||
|
after := st.Summary("2h") // another range: the summary of "1h" is cached for 2 s
|
||||||
|
if after.Totals.Trusted != 3 || after.Totals.Internal != 2 {
|
||||||
|
t.Fatalf("own counts: %+v", after.Totals)
|
||||||
|
}
|
||||||
|
if after.Totals.Requests != before.Totals.Requests || after.Totals.Malicious != before.Totals.Malicious ||
|
||||||
|
after.Totals.RequestsAll != before.Totals.Requests+5 {
|
||||||
|
t.Fatalf("totals: before %+v after %+v", before.Totals, after.Totals)
|
||||||
|
}
|
||||||
|
if after.Totals.Counts["trusted"] != 3 || after.Totals.Counts["internal"] != 2 {
|
||||||
|
t.Fatalf("counts: %v", after.Totals.Counts)
|
||||||
|
}
|
||||||
|
if after.Totals.UniqueIPs != before.Totals.UniqueIPs || after.Totals.HostileIPs != 0 || after.Totals.SuspiciousIPs != 0 {
|
||||||
|
t.Fatalf("own traffic must not create IPs: %+v", after.Totals)
|
||||||
|
}
|
||||||
|
for _, a := range []string{"136.248.78.83", "2001:db8:1::5", "172.18.0.1", "127.0.0.1"} {
|
||||||
|
if _, ok := st.IP(a); ok {
|
||||||
|
t.Fatalf("%s must not have an IP record", a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(st.Recent(10)) != len(before.Recent) || len(after.IPs) != len(before.IPs) || len(after.TopPaths) != len(before.TopPaths) {
|
||||||
|
t.Fatal("own traffic must not reach the feed, the IP table or the attack tops")
|
||||||
|
}
|
||||||
|
if tr := after; tr.Totals.Monitoring != 0 {
|
||||||
|
t.Fatalf("monitoring: %+v", tr.Totals)
|
||||||
|
}
|
||||||
|
if v := st.TrafficFor(store.ParseRange("1h"), "all"); v.Requests != 1 || v.Visitors != 0 {
|
||||||
|
t.Fatalf("web analytics must not count own traffic (one external request, no visitor without an enricher): %+v", v)
|
||||||
|
}
|
||||||
|
o := after.Own
|
||||||
|
if o.Status[0] != 2 || o.Status[2] != 2 || o.Status[3] != 1 {
|
||||||
|
t.Fatalf("status classes: %v", o.Status)
|
||||||
|
}
|
||||||
|
var sum uint32
|
||||||
|
for _, c := range []string{"trusted", "internal"} {
|
||||||
|
for _, v := range o.Series[c] {
|
||||||
|
sum += v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sum != 5 {
|
||||||
|
t.Fatalf("series sum %d", sum)
|
||||||
|
}
|
||||||
|
got := map[string]string{}
|
||||||
|
for _, c := range o.Origins {
|
||||||
|
got[c.Key] = c.Label
|
||||||
|
}
|
||||||
|
if got["136.248.78.83"] != "trusted" || got["172.18.0.1"] != "internal" || got["2001:db8:1::/64"] != "trusted" {
|
||||||
|
t.Fatalf("origins: %+v", o.Origins)
|
||||||
|
}
|
||||||
|
for _, p := range o.Paths {
|
||||||
|
if strings.Contains(p.Key, "secret") {
|
||||||
|
t.Fatalf("query strings must not be kept: %+v", o.Paths)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// a snapshot keeps the own traffic
|
||||||
|
dir := t.TempDir()
|
||||||
|
if err := st.Save(SnapshotPath(dir), nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
st2 := store.New(store.Config{Name: "t", Version: "t"})
|
||||||
|
if _, err := st2.Load(SnapshotPath(dir)); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if s2 := st2.Summary("3h"); s2.Totals.Trusted != 3 || s2.Totals.Internal != 2 {
|
||||||
|
t.Fatalf("after reload: %+v", s2.Totals)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOwnTrafficThroughFeed(t *testing.T) {
|
||||||
|
// the probe sends every line; the hub runner (remote mode) classifies it
|
||||||
|
c := Config{Ignore: DefaultIgnore, Trusted: "10.9.9.9", Retention: 168 * time.Hour, Name: "n"}
|
||||||
|
st := store.New(store.Config{Name: "n", Version: "t"})
|
||||||
|
r, err := NewRemoteRunner(c, st, slog.New(slog.NewTextHandler(io.Discard, nil)), t.TempDir())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !r.Feed("traefik", line("10.9.9.9", "GET", "/", "x", 200), store.Offset{Inode: 1, Offset: 10}) ||
|
||||||
|
!r.Feed("traefik", line("203.0.113.9", "GET", "/", "x", 200), store.Offset{Inode: 1, Offset: 20}) ||
|
||||||
|
!r.Feed("traefik", line("192.168.1.2", "GET", "/", "x", 200), store.Offset{Inode: 1, Offset: 30}) {
|
||||||
|
t.Fatal("feed refused")
|
||||||
|
}
|
||||||
|
s := st.Summary("1h")
|
||||||
|
if s.Totals.Trusted != 1 || s.Totals.Internal != 1 || s.Totals.Requests != 1 || s.Totals.RequestsAll != 3 {
|
||||||
|
t.Fatalf("totals: %+v", s.Totals)
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
-1
@@ -105,7 +105,8 @@ func (s *source) status() store.SourceStatus {
|
|||||||
// Runner owns the log sources of one instance.
|
// Runner owns the log sources of one instance.
|
||||||
type Runner struct {
|
type Runner struct {
|
||||||
St *store.Store
|
St *store.Store
|
||||||
Ignore []netip.Prefix
|
Ignore []netip.Prefix // --ignore and --trusted: their web requests are counted as own traffic only
|
||||||
|
Trusted []netip.Prefix // --trusted: the class "trusted"; the rest of Ignore is "internal"
|
||||||
Monitor *regexp.Regexp
|
Monitor *regexp.Regexp
|
||||||
MonitorFrom []netip.Prefix // when set, monitors are only believed from these networks
|
MonitorFrom []netip.Prefix // when set, monitors are only believed from these networks
|
||||||
Enr core.Enricher // optional geo and User-Agent resolver
|
Enr core.Enricher // optional geo and User-Agent resolver
|
||||||
@@ -132,6 +133,9 @@ func NewRunner(c Config, st *store.Store, log *slog.Logger) (*Runner, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
r := &Runner{St: st, Ignore: ign, DataDir: c.DataDir, Log: log}
|
r := &Runner{St: st, Ignore: ign, DataDir: c.DataDir, Log: log}
|
||||||
|
if r.Trusted, err = core.ParseCIDRs(c.Trusted); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
if r.MonitorFrom, err = core.ParseCIDRs(c.MonitorFrom); err != nil {
|
if r.MonitorFrom, err = core.ParseCIDRs(c.MonitorFrom); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -377,6 +381,17 @@ func (r *Runner) handle(s *source) func([]byte) {
|
|||||||
}
|
}
|
||||||
s.win.add(false)
|
s.win.add(false)
|
||||||
if core.Ignored(r.Ignore, ev.IP) {
|
if core.Ignored(r.Ignore, ev.IP) {
|
||||||
|
// own and trusted origins are counted, never analysed
|
||||||
|
if ev.Source == "traefik" {
|
||||||
|
if _, err := netip.ParseAddr(ev.IP); err == nil {
|
||||||
|
class := store.OwnInternal
|
||||||
|
if core.Ignored(r.Trusted, ev.IP) {
|
||||||
|
class = store.OwnTrusted
|
||||||
|
}
|
||||||
|
s.lastEvent.Store(time.Now().Unix())
|
||||||
|
r.St.Own(ev, class)
|
||||||
|
}
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if r.monitorTraffic(&ev) {
|
if r.monitorTraffic(&ev) {
|
||||||
|
|||||||
@@ -1579,6 +1579,31 @@
|
|||||||
var CLIENT_COLORS = { desktop: '--viz-1', mobile: '--viz-6', tablet: '--viz-5', bot: '--viz-3', tool: '--viz-7', unknown: '--viz-8', misc: '--viz-2' };
|
var CLIENT_COLORS = { desktop: '--viz-1', mobile: '--viz-6', tablet: '--viz-5', bot: '--viz-3', tool: '--viz-7', unknown: '--viz-8', misc: '--viz-2' };
|
||||||
var CLIENT_ORDER = ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown', 'misc'];
|
var CLIENT_ORDER = ['desktop', 'mobile', 'tablet', 'bot', 'tool', 'unknown', 'misc'];
|
||||||
var STATUS_TOKENS = ['--ok', '--info', '--warn', '--danger'];
|
var STATUS_TOKENS = ['--ok', '--info', '--warn', '--danger'];
|
||||||
|
// Own infrastructure and trusted origins: counted apart, never analysed (s.own, s.totals.trusted/internal)
|
||||||
|
function renderOwnTraffic(box, s) {
|
||||||
|
var o = s.own || {}, T = s.totals || {}, tr = o.trusted || 0, inn = o.internal || 0, tot = tr + inn;
|
||||||
|
ready(box); clear(box.body);
|
||||||
|
if (!tot) { box.body.appendChild(empty(t('own.none'), t('own.noneBody'))); return; }
|
||||||
|
var kp = h('div', 'kpi-row');
|
||||||
|
kp.appendChild(stat(t('own.trusted'), nf(tr), t('own.sub.trusted'), 'neutral'));
|
||||||
|
kp.appendChild(stat(t('own.internal'), nf(inn), t('own.sub.internal'), 'neutral'));
|
||||||
|
kp.appendChild(stat(t('own.all'), nf(T.requests_all || (T.requests || 0) + tot), t('own.sub.all', { n: nf(T.requests || 0), o: nf(tot) }), 'neutral'));
|
||||||
|
box.body.appendChild(kp);
|
||||||
|
var ser = o.series || {};
|
||||||
|
box.body.appendChild(charts.stackedArea([{ key: 'trusted', label: t('own.trusted'), values: ser.trusted || [] }, { key: 'internal', label: t('own.internal'), values: ser.internal || [] }], o.step, { start: o.start, colors: ['--viz-5', '--viz-8'], title: t('own.title') }));
|
||||||
|
var cls = ['2xx', '3xx', '4xx', '5xx'];
|
||||||
|
box.body.appendChild(charts.bars(cls.map(function (k, i) { return { key: k, label: t('traffic.status.' + k), value: (o.status || [])[i] || 0, color: STATUS_TOKENS[i] }; }), { title: t('traffic.status') }));
|
||||||
|
var rows = o.origins || [], tb = el('table', { class: 'tbl' });
|
||||||
|
tb.appendChild(h('thead', null, h('tr', null, h('th', null, t('own.col.origin')), h('th', null, t('own.col.class')), h('th', 'num', t('own.col.requests')))));
|
||||||
|
var body = el('tbody');
|
||||||
|
rows.forEach(function (r) { body.appendChild(h('tr', null, h('td', 'mono', r.key), h('td', null, t('own.' + pick(['trusted', 'internal'], r.label, 'internal'))), h('td', 'num', nf(r.n)))); });
|
||||||
|
tb.appendChild(body);
|
||||||
|
box.body.appendChild(h('h3', null, t('own.origins'))); box.body.appendChild(tb);
|
||||||
|
var two = h('div', 'grid-12');
|
||||||
|
var dm = h('div', 'span-6', h('h3', null, t('own.domains')), bars(o.domains || [], { mono: true }));
|
||||||
|
var ph = h('div', 'span-6', h('h3', null, t('own.paths')), bars(o.paths || [], { mono: true }));
|
||||||
|
two.appendChild(dm); two.appendChild(ph); box.body.appendChild(two);
|
||||||
|
}
|
||||||
var pTraffic = corePage({
|
var pTraffic = corePage({
|
||||||
id: 'traffic', icon: ICONS.traffic, titleKey: 'nav.traffic', domain: true,
|
id: 'traffic', icon: ICONS.traffic, titleKey: 'nav.traffic', domain: true,
|
||||||
build: function (root) {
|
build: function (root) {
|
||||||
@@ -1594,19 +1619,22 @@
|
|||||||
v.browsers = panel({ title: t('traffic.browsers'), hint: t('traffic.browsers.hint'), loading: true });
|
v.browsers = panel({ title: t('traffic.browsers'), hint: t('traffic.browsers.hint'), loading: true });
|
||||||
v.oses = panel({ title: t('traffic.oses'), hint: t('traffic.oses.hint'), loading: true });
|
v.oses = panel({ title: t('traffic.oses'), hint: t('traffic.oses.hint'), loading: true });
|
||||||
v.status = panel({ title: t('traffic.status'), hint: t('traffic.status.hint'), loading: true, help: 'term.status_class' });
|
v.status = panel({ title: t('traffic.status'), hint: t('traffic.status.hint'), loading: true, help: 'term.status_class' });
|
||||||
|
v.own = panel({ title: t('own.title'), hint: t('own.hint'), loading: true });
|
||||||
v.privacy = sp(12, h('p', 'note', t('traffic.privacy')));
|
v.privacy = sp(12, h('p', 'note', t('traffic.privacy')));
|
||||||
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline)); g.appendChild(sp(12, v.map));
|
g.appendChild(v.lead); g.appendChild(v.kpis); g.appendChild(sp(12, v.timeline)); g.appendChild(sp(12, v.map));
|
||||||
g.appendChild(sp(4, v.client)); g.appendChild(sp(4, v.browsers)); g.appendChild(sp(4, v.oses));
|
g.appendChild(sp(4, v.client)); g.appendChild(sp(4, v.browsers)); g.appendChild(sp(4, v.oses));
|
||||||
g.appendChild(sp(6, v.status)); g.appendChild(sp(6, v.bots));
|
g.appendChild(sp(6, v.status)); g.appendChild(sp(6, v.bots));
|
||||||
['pages', 'refs', 'cities'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
|
['pages', 'refs', 'cities'].forEach(function (k) { g.appendChild(sp(4, v[k])); });
|
||||||
|
g.appendChild(sp(12, v.own));
|
||||||
g.appendChild(v.privacy);
|
g.appendChild(v.privacy);
|
||||||
root.appendChild(g);
|
root.appendChild(g);
|
||||||
return v;
|
return v;
|
||||||
},
|
},
|
||||||
load: function (c) { return api('/api/v1/traffic', Object.assign({ host: c.host, domain: c.domain }, c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range })); },
|
load: function (c) { return api('/api/v1/traffic', Object.assign({ host: c.host, domain: c.domain }, c.from !== null && c.from !== undefined ? { from: c.from, to: c.to } : { range: c.range })); },
|
||||||
render: function (v, d) {
|
render: function (v, d, c) {
|
||||||
v.data = d;
|
v.data = d;
|
||||||
setDomains(d.domains || []);
|
setDomains(d.domains || []);
|
||||||
|
getSummary(c).then(function (s) { renderOwnTraffic(v.own, s); }, function () { ready(v.own); clear(v.own.body); v.own.body.appendChild(empty(t('own.none'), '')); });
|
||||||
var hasData = d.requests > 0;
|
var hasData = d.requests > 0;
|
||||||
clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel');
|
clear(v.lead); v.lead.classList.remove('skeleton', 'lead-skel');
|
||||||
v.lead.appendChild(hasData
|
v.lead.appendChild(hasData
|
||||||
|
|||||||
@@ -321,6 +321,22 @@ window.URUTAU_I18N = {
|
|||||||
'traffic.browsers': 'Browsers',
|
'traffic.browsers': 'Browsers',
|
||||||
'traffic.oses': 'Operating systems',
|
'traffic.oses': 'Operating systems',
|
||||||
'traffic.status': 'Status codes',
|
'traffic.status': 'Status codes',
|
||||||
|
'own.title': 'Own infrastructure and trusted origins',
|
||||||
|
'own.hint': 'Requests from --trusted origins and private networks. They are counted here and nowhere else: they never score an IP, enter threats, maps, visitors or the blocklist.',
|
||||||
|
'own.none': 'No requests from own or trusted origins',
|
||||||
|
'own.noneBody': 'Nothing came from --trusted or --ignore addresses in this range.',
|
||||||
|
'own.trusted': 'Trusted origins',
|
||||||
|
'own.internal': 'Internal networks',
|
||||||
|
'own.all': 'All requests',
|
||||||
|
'own.sub.trusted': 'addresses of --trusted',
|
||||||
|
'own.sub.internal': 'private and --ignore ranges',
|
||||||
|
'own.sub.all': '{n} external + {o} own',
|
||||||
|
'own.origins': 'By origin',
|
||||||
|
'own.domains': 'By domain',
|
||||||
|
'own.paths': 'Top paths',
|
||||||
|
'own.col.origin': 'Origin',
|
||||||
|
'own.col.class': 'Class',
|
||||||
|
'own.col.requests': 'Requests',
|
||||||
'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.',
|
'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.',
|
||||||
'traffic.sub.visitors': 'distinct, hash per day',
|
'traffic.sub.visitors': 'distinct, hash per day',
|
||||||
'traffic.sub.requests': 'incl. assets and bots',
|
'traffic.sub.requests': 'incl. assets and bots',
|
||||||
@@ -857,6 +873,22 @@ window.URUTAU_I18N = {
|
|||||||
'traffic.browsers': 'Navegadores',
|
'traffic.browsers': 'Navegadores',
|
||||||
'traffic.oses': 'Sistemas operacionais',
|
'traffic.oses': 'Sistemas operacionais',
|
||||||
'traffic.status': 'Códigos de status',
|
'traffic.status': 'Códigos de status',
|
||||||
|
'own.title': 'Infraestrutura própria e origens confiáveis',
|
||||||
|
'own.hint': 'Requisições de origens --trusted e de redes privadas. Elas são contadas aqui e em mais nenhum lugar: nunca pontuam um IP, nem entram em ameaças, mapas, visitantes ou na lista de bloqueio.',
|
||||||
|
'own.none': 'Nenhuma requisição de origens próprias ou confiáveis',
|
||||||
|
'own.noneBody': 'Nada veio de endereços --trusted ou --ignore neste período.',
|
||||||
|
'own.trusted': 'Origens confiáveis',
|
||||||
|
'own.internal': 'Redes internas',
|
||||||
|
'own.all': 'Todas as requisições',
|
||||||
|
'own.sub.trusted': 'endereços de --trusted',
|
||||||
|
'own.sub.internal': 'faixas privadas e --ignore',
|
||||||
|
'own.sub.all': '{n} externas + {o} próprias',
|
||||||
|
'own.origins': 'Por origem',
|
||||||
|
'own.domains': 'Por domínio',
|
||||||
|
'own.paths': 'Caminhos mais pedidos',
|
||||||
|
'own.col.origin': 'Origem',
|
||||||
|
'own.col.class': 'Classe',
|
||||||
|
'own.col.requests': 'Requisições',
|
||||||
'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.',
|
'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.',
|
||||||
'traffic.sub.visitors': 'distintos, hash diário',
|
'traffic.sub.visitors': 'distintos, hash diário',
|
||||||
'traffic.sub.requests': 'inclui recursos e bots',
|
'traffic.sub.requests': 'inclui recursos e bots',
|
||||||
|
|||||||
@@ -128,7 +128,7 @@ func (e *PeerExport) SanitizeRange(rg Range) error {
|
|||||||
cats[string(c)] = true
|
cats[string(c)] = true
|
||||||
}
|
}
|
||||||
for k := range s.Totals.Counts {
|
for k := range s.Totals.Counts {
|
||||||
if !cats[k] {
|
if !cats[k] && k != OwnTrusted && k != OwnInternal {
|
||||||
delete(s.Totals.Counts, k)
|
delete(s.Totals.Counts, k)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -124,6 +124,9 @@ func Merge(host string, parts []Summary) Summary {
|
|||||||
out.Totals.Malicious += p.Totals.Malicious
|
out.Totals.Malicious += p.Totals.Malicious
|
||||||
out.Totals.ActiveBans += p.Totals.ActiveBans
|
out.Totals.ActiveBans += p.Totals.ActiveBans
|
||||||
out.Totals.Monitoring += p.Totals.Monitoring
|
out.Totals.Monitoring += p.Totals.Monitoring
|
||||||
|
out.Totals.Trusted += p.Totals.Trusted
|
||||||
|
out.Totals.Internal += p.Totals.Internal
|
||||||
|
out.Totals.RequestsAll += p.Totals.RequestsAll
|
||||||
for k, v := range p.Totals.Counts {
|
for k, v := range p.Totals.Counts {
|
||||||
out.Totals.Counts[k] += v
|
out.Totals.Counts[k] += v
|
||||||
}
|
}
|
||||||
@@ -148,6 +151,7 @@ func Merge(host string, parts []Summary) Summary {
|
|||||||
ctry = append(ctry, p.Countries)
|
ctry = append(ctry, p.Countries)
|
||||||
recent = append(recent, p.Recent...)
|
recent = append(recent, p.Recent...)
|
||||||
}
|
}
|
||||||
|
out.Own = mergeOwn(parts, out.Timeline)
|
||||||
out.IPs = MergeIPs(ipLists...)
|
out.IPs = MergeIPs(ipLists...)
|
||||||
// Peers only ship their top IPs, so the merged list can undercount; never
|
// Peers only ship their top IPs, so the merged list can undercount; never
|
||||||
// report less than the largest single instance, and exact for one part.
|
// report less than the largest single instance, and exact for one part.
|
||||||
|
|||||||
@@ -0,0 +1,221 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Own traffic: web requests whose client is an own or trusted origin (--trusted
|
||||||
|
// and the --ignore ranges, private networks by default). They are counted in
|
||||||
|
// aggregates only, apart from every attack and visitor aggregate: they never
|
||||||
|
// create an IP record, score, session, campaign, technique, family, ban
|
||||||
|
// evidence or page view, and they leave no event record. The classes are the
|
||||||
|
// two names below.
|
||||||
|
const (
|
||||||
|
OwnTrusted = "trusted" // an address of --trusted (URUTAU_TRUSTED)
|
||||||
|
OwnInternal = "internal" // an address of an --ignore range (private networks by default)
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ownCap = 64 // distinct origins, domains and paths kept per hour and class-agnostic
|
||||||
|
ownPath = 120
|
||||||
|
)
|
||||||
|
|
||||||
|
// ownHour is the own traffic of one hour. Class index: 0 trusted, 1 internal.
|
||||||
|
type ownHour struct {
|
||||||
|
N [2]uint32
|
||||||
|
S [2][4]uint32 // 2xx 3xx 4xx 5xx
|
||||||
|
Origins, Domains, Paths map[string]uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
func ownIdx(class string) int {
|
||||||
|
if class == OwnInternal {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Own counts one web request of an own or trusted origin (class OwnTrusted or
|
||||||
|
// OwnInternal). Only the Traefik source is recorded.
|
||||||
|
func (s *Store) Own(ev core.Event, class string) {
|
||||||
|
now := s.now()
|
||||||
|
if ev.Time.Before(now.Add(-s.cfg.Retention)) || ev.IP == "" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
ts := ev.Time.Unix()
|
||||||
|
if max := now.Unix() + 300; ts > max {
|
||||||
|
ts = max
|
||||||
|
}
|
||||||
|
ci := ownIdx(class)
|
||||||
|
m, h := ts/60, ts/3600
|
||||||
|
i := int(m % slots)
|
||||||
|
path := ev.Path
|
||||||
|
if j := strings.IndexAny(path, "?#"); j >= 0 {
|
||||||
|
path = path[:j]
|
||||||
|
}
|
||||||
|
if len(path) > ownPath {
|
||||||
|
path = path[:ownPath]
|
||||||
|
}
|
||||||
|
origin := class[:1] + "|" + KeyOf(ev.IP)
|
||||||
|
s.mu.Lock()
|
||||||
|
if s.ownSt[i] != m {
|
||||||
|
s.ownSt[i], s.ownN[i] = m, [2]uint32{}
|
||||||
|
}
|
||||||
|
s.ownN[i][ci]++
|
||||||
|
hs := &s.hours[int(h%hourSlots)]
|
||||||
|
if hs.Hour != h {
|
||||||
|
*hs = hourSlot{Hour: h}
|
||||||
|
}
|
||||||
|
if hs.Own == nil {
|
||||||
|
hs.Own = &ownHour{}
|
||||||
|
}
|
||||||
|
o := hs.Own
|
||||||
|
o.N[ci]++
|
||||||
|
if k := ev.Status/100 - 2; k >= 0 && k < 4 {
|
||||||
|
o.S[ci][k]++
|
||||||
|
}
|
||||||
|
bumpCap(&o.Origins, origin, ownCap)
|
||||||
|
bumpCap(&o.Domains, normDomain(ev.Domain), ownCap)
|
||||||
|
bumpCap(&o.Paths, path, ownCap)
|
||||||
|
s.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// OwnTraffic is the own and trusted traffic of a window. It is not part of
|
||||||
|
// totals.requests: RequestsAll in the totals adds it.
|
||||||
|
type OwnTraffic struct {
|
||||||
|
Trusted uint64 `json:"trusted"`
|
||||||
|
Internal uint64 `json:"internal"`
|
||||||
|
Status [4]uint64 `json:"status"` // 2xx 3xx 4xx 5xx
|
||||||
|
Start int64 `json:"start"`
|
||||||
|
Step int64 `json:"step"`
|
||||||
|
Series map[string][]uint32 `json:"series"` // "trusted" and "internal"
|
||||||
|
Origins []Count `json:"origins"` // Key: address (an IPv6 /64 as a prefix), Label: class
|
||||||
|
Domains []Count `json:"domains"`
|
||||||
|
Paths []Count `json:"paths"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ownLocked adds the own traffic of the grid to the totals and, when o is not
|
||||||
|
// nil, to the breakdown. The caller holds s.mu.
|
||||||
|
func (s *Store) ownLocked(g grid, to int64, tot *Totals) OwnTraffic {
|
||||||
|
o := OwnTraffic{Start: g.Start, Step: g.Step, Series: map[string][]uint32{
|
||||||
|
OwnTrusted: make([]uint32, g.N), OwnInternal: make([]uint32, g.N)}}
|
||||||
|
if g.minute() {
|
||||||
|
for m := g.Start / 60; m <= to/60; m++ {
|
||||||
|
i := int(m % slots)
|
||||||
|
if s.ownSt[i] != m {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if b := int((m*60 - g.Start) / g.Step); b >= 0 && b < g.N {
|
||||||
|
o.Series[OwnTrusted][b] += s.ownN[i][0]
|
||||||
|
o.Series[OwnInternal][b] += s.ownN[i][1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
origins, doms, paths := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
|
||||||
|
for h := g.Start / 3600; h <= to/3600; h++ {
|
||||||
|
hs := &s.hours[int(h%hourSlots)]
|
||||||
|
if hs.Hour != h || hs.Own == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
oh := hs.Own
|
||||||
|
o.Trusted += uint64(oh.N[0])
|
||||||
|
o.Internal += uint64(oh.N[1])
|
||||||
|
for c := range oh.S {
|
||||||
|
for k, v := range oh.S[c] {
|
||||||
|
o.Status[k] += uint64(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !g.minute() {
|
||||||
|
if b := int(h - g.Start/3600); b >= 0 && b < g.N {
|
||||||
|
o.Series[OwnTrusted][b] += oh.N[0]
|
||||||
|
o.Series[OwnInternal][b] += oh.N[1]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, p := range [...]struct{ from, to map[string]uint32 }{{oh.Origins, origins}, {oh.Domains, doms}, {oh.Paths, paths}} {
|
||||||
|
for k, v := range p.from {
|
||||||
|
p.to[k] += v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tot.Trusted, tot.Internal = o.Trusted, o.Internal
|
||||||
|
tot.RequestsAll = tot.Requests + o.Trusted + o.Internal
|
||||||
|
if o.Trusted > 0 {
|
||||||
|
tot.Counts[OwnTrusted] = o.Trusted
|
||||||
|
}
|
||||||
|
if o.Internal > 0 {
|
||||||
|
tot.Counts[OwnInternal] = o.Internal
|
||||||
|
}
|
||||||
|
o.Origins = ownOrigins(topN(origins, 40))
|
||||||
|
o.Domains, o.Paths = topN(doms, 20), topN(paths, 20)
|
||||||
|
return o
|
||||||
|
}
|
||||||
|
|
||||||
|
// ownOrigins splits the stored "<class>|<address>" keys into key and label.
|
||||||
|
func ownOrigins(in []Count) []Count {
|
||||||
|
for i, c := range in {
|
||||||
|
if len(c.Key) > 2 && c.Key[1] == '|' {
|
||||||
|
if c.Key[0] == 't' {
|
||||||
|
in[i].Label = OwnTrusted
|
||||||
|
} else {
|
||||||
|
in[i].Label = OwnInternal
|
||||||
|
}
|
||||||
|
in[i].Key = c.Key[2:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return in
|
||||||
|
}
|
||||||
|
|
||||||
|
// mergeOwn adds the own traffic of several hosts. Series are aligned by
|
||||||
|
// timestamp like the attack timeline.
|
||||||
|
func mergeOwn(parts []Summary, grid Timeline) OwnTraffic {
|
||||||
|
n := 0
|
||||||
|
for _, c := range grid.Cats {
|
||||||
|
n = len(grid.Series[c])
|
||||||
|
break
|
||||||
|
}
|
||||||
|
out := OwnTraffic{Start: grid.Start, Step: grid.Step, Series: map[string][]uint32{
|
||||||
|
OwnTrusted: make([]uint32, n), OwnInternal: make([]uint32, n)}}
|
||||||
|
var origins, doms, paths [][]Count
|
||||||
|
for _, p := range parts {
|
||||||
|
o := p.Own
|
||||||
|
out.Trusted += o.Trusted
|
||||||
|
out.Internal += o.Internal
|
||||||
|
for k, v := range o.Status {
|
||||||
|
out.Status[k] += v
|
||||||
|
}
|
||||||
|
if o.Step == out.Step && o.Step > 0 {
|
||||||
|
shift := (o.Start - out.Start) / out.Step
|
||||||
|
for _, c := range []string{OwnTrusted, OwnInternal} {
|
||||||
|
for i, v := range o.Series[c] {
|
||||||
|
if j := int64(i) + shift; j >= 0 && j < int64(n) {
|
||||||
|
out.Series[c][j] += v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
origins = append(origins, o.Origins)
|
||||||
|
doms = append(doms, o.Domains)
|
||||||
|
paths = append(paths, o.Paths)
|
||||||
|
}
|
||||||
|
out.Origins = mergeOwnOrigins(40, origins)
|
||||||
|
out.Domains, out.Paths = mergeCounts(20, doms...), mergeCounts(20, paths...)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
func mergeOwnOrigins(n int, lists [][]Count) []Count {
|
||||||
|
m, lab := map[string]uint32{}, map[string]string{}
|
||||||
|
for _, l := range lists {
|
||||||
|
for _, c := range l {
|
||||||
|
k := c.Label + "|" + c.Key
|
||||||
|
m[k] += c.N
|
||||||
|
lab[k] = c.Label
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out := topN(m, n)
|
||||||
|
for i := range out {
|
||||||
|
out[i].Label = lab[out[i].Key]
|
||||||
|
out[i].Key = out[i].Key[len(out[i].Label)+1:]
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -28,6 +28,8 @@ type snapshot struct {
|
|||||||
Hours [hourSlots]hourSlot
|
Hours [hourSlots]hourSlot
|
||||||
MonSt [slots]int64
|
MonSt [slots]int64
|
||||||
MonN [slots]uint32
|
MonN [slots]uint32
|
||||||
|
OwnSt [slots]int64 // own traffic minute buckets (optional: older snapshots lack it)
|
||||||
|
OwnN [slots][2]uint32
|
||||||
Dom map[string]*domData
|
Dom map[string]*domData
|
||||||
GDays [anDays]gDay
|
GDays [anDays]gDay
|
||||||
Svc map[string]*svcData // service health (optional: older snapshots lack it)
|
Svc map[string]*svcData // service health (optional: older snapshots lack it)
|
||||||
@@ -73,7 +75,7 @@ func (s *Store) Save(path string, offsets map[string]Offset) error {
|
|||||||
}
|
}
|
||||||
bw := bufio.NewWriterSize(f, 256*1024)
|
bw := bufio.NewWriterSize(f, 256*1024)
|
||||||
s.mu.RLock()
|
s.mu.RLock()
|
||||||
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, Dom: s.tr.dom, GDays: s.tr.gdays, Svc: s.sv.m,
|
snap := snapshot{V: snapshotVersion, Saved: s.now().Unix(), Stamps: s.stamps, Counts: s.counts, Hours: s.hours, MonSt: s.monSt, MonN: s.monN, OwnSt: s.ownSt, OwnN: s.ownN, Dom: s.tr.dom, GDays: s.tr.gdays, Svc: s.sv.m,
|
||||||
IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets, IDSeq: s.ids.Load()}
|
IPs: s.ips, Recent: s.recent, Rhead: s.rhead, Offsets: offsets, IDSeq: s.ids.Load()}
|
||||||
err = gob.NewEncoder(bw).Encode(&snap)
|
err = gob.NewEncoder(bw).Encode(&snap)
|
||||||
s.mu.RUnlock()
|
s.mu.RUnlock()
|
||||||
@@ -124,6 +126,7 @@ func (s *Store) Load(path string) (map[string]Offset, error) {
|
|||||||
s.mu.Lock()
|
s.mu.Lock()
|
||||||
s.stamps, s.counts, s.hours = snap.Stamps, snap.Counts, snap.Hours
|
s.stamps, s.counts, s.hours = snap.Stamps, snap.Counts, snap.Hours
|
||||||
s.monSt, s.monN = snap.MonSt, snap.MonN
|
s.monSt, s.monN = snap.MonSt, snap.MonN
|
||||||
|
s.ownSt, s.ownN = snap.OwnSt, snap.OwnN
|
||||||
s.tr.dom, s.tr.gdays = snap.Dom, snap.GDays
|
s.tr.dom, s.tr.gdays = snap.Dom, snap.GDays
|
||||||
s.sv.m = snap.Svc
|
s.sv.m = snap.Svc
|
||||||
for _, d := range s.tr.dom {
|
for _, d := range s.tr.dom {
|
||||||
|
|||||||
@@ -135,6 +135,7 @@ type hourSlot struct {
|
|||||||
Paths, Domains, UAs, Users, Countries map[string]uint32
|
Paths, Domains, UAs, Users, Countries map[string]uint32
|
||||||
C [core.NumCats]uint32 // events per category in the hour
|
C [core.NumCats]uint32 // events per category in the hour
|
||||||
Mon uint32 // monitoring requests in the hour
|
Mon uint32 // monitoring requests in the hour
|
||||||
|
Own *ownHour // own and trusted traffic (see own.go), nil when none
|
||||||
}
|
}
|
||||||
|
|
||||||
// FeedEvent is one entry of the live feed.
|
// FeedEvent is one entry of the live feed.
|
||||||
@@ -261,6 +262,8 @@ type Store struct {
|
|||||||
hours [hourSlots]hourSlot
|
hours [hourSlots]hourSlot
|
||||||
monSt [slots]int64
|
monSt [slots]int64
|
||||||
monN [slots]uint32
|
monN [slots]uint32
|
||||||
|
ownSt [slots]int64
|
||||||
|
ownN [slots][2]uint32
|
||||||
tr trafficState
|
tr trafficState
|
||||||
sv svcState
|
sv svcState
|
||||||
allow []string
|
allow []string
|
||||||
|
|||||||
@@ -32,6 +32,10 @@ type Totals struct {
|
|||||||
ActiveBans int `json:"active_bans"`
|
ActiveBans int `json:"active_bans"`
|
||||||
Monitoring uint64 `json:"monitoring"`
|
Monitoring uint64 `json:"monitoring"`
|
||||||
Counts map[string]uint64 `json:"counts"`
|
Counts map[string]uint64 `json:"counts"`
|
||||||
|
// Own and trusted traffic (see own.go) is NOT in Requests; RequestsAll adds it.
|
||||||
|
Trusted uint64 `json:"trusted"`
|
||||||
|
Internal uint64 `json:"internal"`
|
||||||
|
RequestsAll uint64 `json:"requests_all"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// IPSummary describes one IP. Samples, UAs and Domains are only filled in the
|
// IPSummary describes one IP. Samples, UAs and Domains are only filled in the
|
||||||
@@ -98,6 +102,7 @@ type Summary struct {
|
|||||||
Generated int64 `json:"generated"`
|
Generated int64 `json:"generated"`
|
||||||
Hosts []HostInfo `json:"hosts"`
|
Hosts []HostInfo `json:"hosts"`
|
||||||
Totals Totals `json:"totals"`
|
Totals Totals `json:"totals"`
|
||||||
|
Own OwnTraffic `json:"own"` // own and trusted origins, apart from every attack number
|
||||||
Timeline Timeline `json:"timeline"`
|
Timeline Timeline `json:"timeline"`
|
||||||
Rates Rates `json:"rates"`
|
Rates Rates `json:"rates"`
|
||||||
IPs []IPSummary `json:"ips"`
|
IPs []IPSummary `json:"ips"`
|
||||||
@@ -428,6 +433,7 @@ func (s *Store) buildSummary(rg Range) Summary {
|
|||||||
tot.Monitoring += uint64(hs.Mon)
|
tot.Monitoring += uint64(hs.Mon)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
own := s.ownLocked(g, to, &tot)
|
||||||
paths, doms, uas, users, ctry := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
|
paths, doms, uas, users, ctry := map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}, map[string]uint32{}
|
||||||
firstHour, lastHour := start/3600, to/3600
|
firstHour, lastHour := start/3600, to/3600
|
||||||
for i := range s.hours {
|
for i := range s.hours {
|
||||||
@@ -522,7 +528,7 @@ func (s *Store) buildSummary(rg Range) Summary {
|
|||||||
Hosts: []HostInfo{{Name: s.cfg.Name, Self: true, Online: true, Version: s.cfg.Version, LastSeen: nowU,
|
Hosts: []HostInfo{{Name: s.cfg.Name, Self: true, Online: true, Version: s.cfg.Version, LastSeen: nowU,
|
||||||
Requests: tot.Requests, Malicious: tot.Malicious, HostileIPs: tot.HostileIPs, ActiveBans: tot.ActiveBans,
|
Requests: tot.Requests, Malicious: tot.Malicious, HostileIPs: tot.HostileIPs, ActiveBans: tot.ActiveBans,
|
||||||
Live: true, Location: s.Location()}},
|
Live: true, Location: s.Location()}},
|
||||||
Totals: tot, Timeline: tl, Rates: rates, IPs: ips,
|
Totals: tot, Own: own, Timeline: tl, Rates: rates, IPs: ips,
|
||||||
TopPaths: topN(paths, topKeep), TopDomains: topN(doms, topKeep), TopUAs: topUAs, TopUsers: topN(users, topKeep), Countries: topN(ctry, 120),
|
TopPaths: topN(paths, topKeep), TopDomains: topN(doms, topKeep), TopUAs: topUAs, TopUsers: topN(users, topKeep), Countries: topN(ctry, 120),
|
||||||
Recent: recent, Sources: srcs, Attribution: s.attrib,
|
Recent: recent, Sources: srcs, Attribution: s.attrib,
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user