Compare commits
33
Commits
v0.1.0
...
feat/auth-mfa
No files matched your search
+16
-2
@@ -2,8 +2,22 @@
|
|||||||
ZEEK_INTERFACE=eth0
|
ZEEK_INTERFACE=eth0
|
||||||
# Acauã image tag: latest (last release), X.Y.Z / X.Y (pinned), or edge (main).
|
# Acauã image tag: latest (last release), X.Y.Z / X.Y (pinned), or edge (main).
|
||||||
ACAUA_VERSION=latest
|
ACAUA_VERSION=latest
|
||||||
# Host address and port of the dashboard. Keep it on loopback unless an
|
# How the dashboard is reached. The daemon refuses to start without a valid mode.
|
||||||
# authenticating reverse proxy sits in front of it.
|
# local - plain HTTP on loopback only; ACAUA_PUBLISH must be 127.0.0.1 or [::1]
|
||||||
|
# tls - the daemon terminates HTTPS; set ACAUA_TLS_CERT and ACAUA_TLS_KEY
|
||||||
|
# (PEM paths inside the container, mounted by you)
|
||||||
|
# proxy - an HTTPS reverse proxy in front; set ACAUA_TRUSTED_PROXIES to its
|
||||||
|
# address as comma-separated CIDRs, e.g. 172.18.0.0/16
|
||||||
|
ACAUA_TRANSPORT=local
|
||||||
|
# Host address and port of the dashboard. Login and MFA protect it in every
|
||||||
|
# mode, but only tls and proxy encrypt the traffic: publish beyond loopback
|
||||||
|
# only with one of them.
|
||||||
ACAUA_PUBLISH=127.0.0.1:8787
|
ACAUA_PUBLISH=127.0.0.1:8787
|
||||||
|
# Secret key outside the data volume (recommended): a Docker secret mounted by
|
||||||
|
# a compose override; the default keeps the key in the volume.
|
||||||
|
# ACAUA_SECRET_KEY_FILE=/run/secrets/acaua_key
|
||||||
|
# ACAUA_TLS_CERT=/tls/cert.pem
|
||||||
|
# ACAUA_TLS_KEY=/tls/key.pem
|
||||||
|
# ACAUA_TRUSTED_PROXIES=172.18.0.0/16
|
||||||
# Zeek image, pinned to an exact version.
|
# Zeek image, pinned to an exact version.
|
||||||
ZEEK_IMAGE=zeek/zeek:9.0.1
|
ZEEK_IMAGE=zeek/zeek:9.0.1
|
||||||
@@ -33,3 +33,6 @@ research/.ipynb_checkpoints/
|
|||||||
CLAUDE.md
|
CLAUDE.md
|
||||||
AGENTS.md
|
AGENTS.md
|
||||||
GEMINI.md
|
GEMINI.md
|
||||||
|
|
||||||
|
# Local specs and plans: never versioned
|
||||||
|
docs/superpowers/
|
||||||
@@ -6,6 +6,31 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Authentication: first-run setup code, login always required, TOTP MFA with recovery codes (mandatory for administrators, optional for analysts), sessions, `read`/`admin` API tokens, user management and an audit log. Only `GET /api/health`, `GET /api/auth/state`, `POST /api/auth/{bootstrap,login,mfa,password-change-required}` and the login assets (`/login.html`, `/login.js`, `/app.css`, `/logo.png`, `/i18n.js`, `/i18n-en.js`) work without a session or token; `/api/analyze` is admin-only.
|
||||||
|
- Login limits per username and client address with decay (IPv6 counted per /48), plus a budget of at most 100 failures in any 24 hours (true rolling window) per username from unknown addresses: once spent, those addresses are refused before Argon2, usernames with no account included. An address with a completed login in the last 30 days skips the budget, stored as a hash, at most 10 per account, replaced by the acting address on a password or MFA change from a session, cleared by promotion to administrator or `acaua auth reset`. An attacker can therefore delay login from a new address for a real user for up to the budget window, or longer while they keep spending it; known addresses and open sessions are unaffected. MFA remains recommended for analysts.
|
||||||
|
- `login.budget_exhausted` audit event, once per real account per 24 hours. The audit log has no rotation yet.
|
||||||
|
- Security headers on every response: CSP, `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy`.
|
||||||
|
- Explicit transport modes (`ACAUA_TRANSPORT=local|tls|proxy`); `local` refuses a port published beyond loopback and, outside a container, a non-loopback `--bind`.
|
||||||
|
- `acaua auth reset --username <name>`: local recovery for any account that prints a temporary password once and forces a password change (administrators also enroll MFA again). It never starts the daemon.
|
||||||
|
- `ACAUA_SECRET_KEY_FILE` to keep the secret key in a Docker secret.
|
||||||
|
- The image smoke test checks the unauthenticated 401/redirect, the setup code in the log and the `local` refusal.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- `/api/health` no longer reports the version.
|
||||||
|
- Documentation no longer presents a reverse proxy as the only protection.
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-11-04
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Executive report: a **Relatório** button in the analysis view opens `GET /relatorio`, an A4 report of the latest analysis paginated by the vendored Paged.js, with a full-bleed cover (logo, TLP badge, beacon-lane motif drawn from the top hosts), table of contents, KPIs, host ranking, one section per pillar, every alert with its evidence, methodology and glossary. Defaults to `TLP:AMBER` (`?tlp=` changes it) and HTML-escapes every string read from the logs.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Documentation reviewed; the Xexéu references in this changelog now read Harpia.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- The image smoke test piped `curl` and `acaua doctor` into `grep -q` under `pipefail`; `grep` exits at the first match, the writer can get SIGPIPE, and the step failed at random (it already broke Harpia's arm64 build). Outputs are now captured before checking.
|
||||||
|
|
||||||
## [0.1.0] - 2026-11-01
|
## [0.1.0] - 2026-11-01
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
+26
-1
@@ -4,7 +4,32 @@
|
|||||||
|
|
||||||
Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versões seguem SemVer.
|
Formato baseado no [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versões seguem SemVer.
|
||||||
|
|
||||||
## [Unreleased]
|
## [Não lançado]
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- Autenticação: código de configuração na primeira execução, login sempre exigido, MFA TOTP com códigos de recuperação (obrigatório para administradores, opcional para analistas), sessões, tokens de API `read`/`admin`, gestão de usuários e log de auditoria. Só `GET /api/health`, `GET /api/auth/state`, `POST /api/auth/{bootstrap,login,mfa,password-change-required}` e os arquivos da tela de login (`/login.html`, `/login.js`, `/app.css`, `/logo.png`, `/i18n.js`, `/i18n-en.js`) funcionam sem sessão ou token; `/api/analyze` é exclusivo de administrador.
|
||||||
|
- Limites de login por usuário e endereço do cliente com decaimento (IPv6 contado por /48), mais uma cota de no máximo 100 falhas em quaisquer 24 horas (janela móvel real) por usuário vindas de endereços desconhecidos: esgotada, esses endereços são recusados antes do Argon2, inclusive para usuários inexistentes. Um endereço com login completo nos últimos 30 dias não usa a cota; fica guardado como hash, no máximo 10 por conta, é substituído pelo endereço que age em uma troca de senha ou de MFA feita de uma sessão, e é apagado por promoção a administrador ou `acaua auth reset`. Assim, um atacante consegue atrasar o login de um usuário real a partir de um endereço novo por até a janela da cota, ou mais enquanto continuar gastando-a; endereços conhecidos e sessões abertas não são afetados. O MFA continua recomendado para analistas.
|
||||||
|
- Evento de auditoria `login.budget_exhausted`, uma vez por conta real a cada 24 horas. O log de auditoria ainda não tem rotação.
|
||||||
|
- Cabeçalhos de segurança em toda resposta: CSP, `X-Frame-Options`, `X-Content-Type-Options`, `Referrer-Policy`.
|
||||||
|
- Modos de transporte explícitos (`ACAUA_TRANSPORT=local|tls|proxy`); `local` recusa uma porta publicada além do loopback e, fora de container, um `--bind` que não seja loopback.
|
||||||
|
- `acaua auth reset --username <nome>`: recuperação local de qualquer conta que exibe uma senha temporária uma vez e força a troca de senha (administradores também cadastram o MFA de novo). Nunca inicia o daemon.
|
||||||
|
- `ACAUA_SECRET_KEY_FILE` para manter a chave secreta em um Docker secret.
|
||||||
|
- O smoke test da imagem verifica o 401/redirecionamento sem login, o código de configuração no log e a recusa do modo `local`.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- `/api/health` não informa mais a versão.
|
||||||
|
- A documentação não apresenta mais o proxy reverso como única proteção.
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-11-04
|
||||||
|
|
||||||
|
### Adicionado
|
||||||
|
- Relatório executivo: o botão **Relatório** na tela de análise abre `GET /relatorio`, um relatório A4 da última análise paginado pelo Paged.js empacotado, com capa sangrada (logo, selo TLP, motivo de faixas de beacon desenhado a partir dos hosts do topo), sumário, indicadores, ranking de hosts, uma seção por pilar, todos os alertas com a evidência, metodologia e glossário. Padrão `TLP:AMBER` (`?tlp=` troca) e escapa em HTML todo texto lido dos logs.
|
||||||
|
|
||||||
|
### Alterado
|
||||||
|
- Documentação revisada; as referências ao Xexéu neste changelog agora citam o Harpia.
|
||||||
|
|
||||||
|
### Corrigido
|
||||||
|
- O smoke test da imagem passava a saída de `curl` e `acaua doctor` por pipe para `grep -q` sob `pipefail`; o `grep` sai no primeiro acerto, quem escreve pode levar SIGPIPE e o passo falhava ao acaso (isso já quebrou o build arm64 do Harpia). As saídas agora são capturadas antes da checagem.
|
||||||
|
|
||||||
## [0.1.0] - 2026-11-01
|
## [0.1.0] - 2026-11-01
|
||||||
|
|
||||||
|
|||||||
Generated
+825
-3
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -4,7 +4,7 @@ members = ["crates/acaua-core", "crates/acaua-cli"]
|
|||||||
exclude = ["research"]
|
exclude = ["research"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
repository = "https://git.lucasrguerra.dev.br/ciberfauna/acaua"
|
repository = "https://git.lucasrguerra.dev.br/ciberfauna/acaua"
|
||||||
|
|||||||
+2
-1
@@ -42,10 +42,11 @@ LABEL org.opencontainers.image.title="Acauã" \
|
|||||||
org.opencontainers.image.source="https://git.lucasrguerra.dev.br/ciberfauna/acaua" \
|
org.opencontainers.image.source="https://git.lucasrguerra.dev.br/ciberfauna/acaua" \
|
||||||
org.opencontainers.image.licenses="MIT OR Apache-2.0"
|
org.opencontainers.image.licenses="MIT OR Apache-2.0"
|
||||||
ENV ACAUA_RUNTIME=container
|
ENV ACAUA_RUNTIME=container
|
||||||
|
ENV ACAUA_TRANSPORT=local
|
||||||
USER acaua
|
USER acaua
|
||||||
WORKDIR /data
|
WORKDIR /data
|
||||||
EXPOSE 8787
|
EXPOSE 8787
|
||||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||||
CMD curl -fsS http://127.0.0.1:8787/api/health >/dev/null || exit 1
|
CMD ["sh", "-c", "if [ \"$ACAUA_TRANSPORT\" = tls ]; then curl -kfsS https://127.0.0.1:8787/api/health; else curl -fsS http://127.0.0.1:8787/api/health; fi >/dev/null || exit 1"]
|
||||||
ENTRYPOINT ["acaua"]
|
ENTRYPOINT ["acaua"]
|
||||||
CMD ["serve", "--bind", "0.0.0.0:8787", "--data-dir", "/data/acaua"]
|
CMD ["serve", "--bind", "0.0.0.0:8787", "--data-dir", "/data/acaua"]
|
||||||
@@ -26,8 +26,9 @@ not an opaque model. The goal is to answer not only "this looks suspicious" but
|
|||||||
for identity and lateral-movement analysis. NetFlow/IPFIX is a documented
|
for identity and lateral-movement analysis. NetFlow/IPFIX is a documented
|
||||||
degraded mode, never presented as equivalent. Suricata EVE JSON is an optional
|
degraded mode, never presented as equivalent. Suricata EVE JSON is an optional
|
||||||
secondary input.
|
secondary input.
|
||||||
- **Server daemon and web dashboard:** `acaua serve` runs continuous ingestion,
|
- **Server daemon and web dashboard:** `acaua serve` runs the API and the
|
||||||
scheduling, the API and the embedded web UI, distributed 100% via Docker.
|
embedded web UI, and analyzes a directory when asked (continuous ingestion is on
|
||||||
|
the roadmap); distributed 100% via Docker.
|
||||||
- **Research stays outside the product:** `research/` is an isolated Python
|
- **Research stays outside the product:** `research/` is an isolated Python
|
||||||
workspace for scientific validation and fixtures. It is never compiled,
|
workspace for scientific validation and fixtures. It is never compiled,
|
||||||
packaged or released.
|
packaged or released.
|
||||||
@@ -99,13 +100,19 @@ Supported platform matrix for published container images: `linux/amd64` and `lin
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
acaua doctor
|
acaua doctor
|
||||||
acaua serve --bind 127.0.0.1:8787 --data-dir .acaua
|
ACAUA_TRANSPORT=local acaua serve --bind 127.0.0.1:8787 --data-dir .acaua
|
||||||
acaua analyze /var/log/zeek/current --json
|
acaua analyze /var/log/zeek/current --json
|
||||||
acaua update
|
acaua update
|
||||||
```
|
```
|
||||||
|
|
||||||
`analyze` currently validates the directory and returns a skeleton report; it
|
`analyze` ingests `conn.log` and `dns.log` and runs the detection pillars.
|
||||||
does not parse Zeek logs yet. `serve` exposes the stub API and the embedded web UI.
|
`serve` exposes the API and the embedded web UI. It refuses to start without
|
||||||
|
`ACAUA_TRANSPORT` (`local`, `tls` or `proxy`). Login is always required; MFA is mandatory for
|
||||||
|
administrators and optional for analysts. In `local` mode outside a container, a
|
||||||
|
non-loopback `--bind` is refused. On the first start the daemon prints a one-time setup code (valid for 1 hour) to its
|
||||||
|
log, which you enter in the dashboard to create the first administrator; once it
|
||||||
|
expires, restart the daemon for a new one. See
|
||||||
|
[Authentication and transport](docs/docker.md#authentication-and-transport).
|
||||||
`update` checks for new versions and guides container image updates.
|
`update` checks for new versions and guides container image updates.
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
@@ -123,9 +130,11 @@ See **[CONTRIBUTING.md](CONTRIBUTING.md)** and **[docs/architecture.md](docs/arc
|
|||||||
|
|
||||||
## Known limits
|
## Known limits
|
||||||
|
|
||||||
- The detection engine, Zeek parser and storage layer are stubs.
|
- Ingestion runs on request: there is no continuous ingestion or scheduling yet.
|
||||||
|
- Alerts are kept in memory and lost when the daemon restarts.
|
||||||
|
- Only `conn.log` and `dns.log` are parsed today.
|
||||||
- There is no published release image yet.
|
- There is no published release image yet.
|
||||||
- NetFlow/IPFIX is a degraded input mode by design; it cannot replace the Zeek
|
- NetFlow/IPFIX is planned as a degraded input mode; it cannot replace the Zeek
|
||||||
protocol logs for every pillar.
|
protocol logs for every pillar.
|
||||||
- The project targets Linux container environments (`linux/amd64`, `linux/arm64`).
|
- The project targets Linux container environments (`linux/amd64`, `linux/arm64`).
|
||||||
|
|
||||||
@@ -135,10 +144,10 @@ Summary of the [ROADMAP](ROADMAP.md):
|
|||||||
|
|
||||||
| | |
|
| | |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **Done** | Workspace, CLI/API stubs, web dashboard, Docker containerization, CI/release workflows |
|
| **Done** | CLI, API and web dashboard; Docker deployment; Zeek `conn.log`/`dns.log` parser; Parquet storage; pillars 1 to 4 (v1); authentication; CI/release workflows |
|
||||||
| **Next** | Pillar 1 and 2 implementations with deterministic fixtures; real Zeek parser |
|
| **Next** | Continuous ingestion, persistent alerts, live long-connection tracking, Public Suffix List, allowlisting and baselining |
|
||||||
| **Later** | Full Parquet partitioning, TTL pruning, pillar 3 and 4, evidence fusion |
|
| **Later** | UDP sessions and more protocol parsers, identity and lateral movement, NetFlow/IPFIX and Suricata EVE inputs, signed release metadata and SBOM |
|
||||||
| **Not planned** | Opaque AI scoring, a required cloud service, Python in the shipped runtime |
|
| **Not planned** | Opaque AI scoring, a required cloud service, Python in the shipped runtime, treating flows as equal to Zeek logs, native desktop shell |
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
+19
-11
@@ -27,8 +27,9 @@ produziram esta pontuação".
|
|||||||
protocolo necessários para identidade e movimento lateral. NetFlow/IPFIX é um
|
protocolo necessários para identidade e movimento lateral. NetFlow/IPFIX é um
|
||||||
modo degradado documentado, nunca apresentado como equivalente. Suricata EVE
|
modo degradado documentado, nunca apresentado como equivalente. Suricata EVE
|
||||||
JSON é uma entrada secundária opcional.
|
JSON é uma entrada secundária opcional.
|
||||||
- **Daemon servidor e dashboard web:** `acaua serve` roda ingestão contínua,
|
- **Daemon servidor e dashboard web:** `acaua serve` roda a API e o dashboard
|
||||||
agendador, API e o dashboard web embutido, distribuído 100% via Docker.
|
web embutido, e analisa um diretório quando solicitado (a ingestão contínua está
|
||||||
|
no roadmap); distribuído 100% via Docker.
|
||||||
- **Pesquisa fora do produto:** `research/` é um espaço Python isolado para
|
- **Pesquisa fora do produto:** `research/` é um espaço Python isolado para
|
||||||
validação científica e fixtures. Ele nunca é compilado, empacotado ou
|
validação científica e fixtures. Ele nunca é compilado, empacotado ou
|
||||||
distribuído.
|
distribuído.
|
||||||
@@ -101,13 +102,18 @@ Matriz de plataformas suportadas para as imagens publicadas: `linux/amd64` e `li
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
acaua doctor
|
acaua doctor
|
||||||
acaua serve --bind 127.0.0.1:8787 --data-dir .acaua
|
ACAUA_TRANSPORT=local acaua serve --bind 127.0.0.1:8787 --data-dir .acaua
|
||||||
acaua analyze /var/log/zeek/current --json
|
acaua analyze /var/log/zeek/current --json
|
||||||
acaua update
|
acaua update
|
||||||
```
|
```
|
||||||
|
|
||||||
O `analyze` hoje valida o diretório e devolve um relatório de esqueleto; ele
|
O `analyze` ingere `conn.log` e `dns.log` e executa os pilares de detecção.
|
||||||
ainda não lê logs Zeek. O `serve` expõe a API stub e o dashboard web embutido.
|
O `serve` expõe a API e o dashboard web embutido. Ele recusa iniciar sem
|
||||||
|
`ACAUA_TRANSPORT` (`local`, `tls` ou `proxy`). O login é sempre exigido; o MFA é obrigatório
|
||||||
|
para administradores e opcional para analistas. No modo `local` fora de container,
|
||||||
|
um `--bind` que não seja loopback é recusado. Na primeira inicialização o daemon imprime no log um código de configuração de uso
|
||||||
|
único (válido por 1 hora), que você informa no dashboard para criar o primeiro
|
||||||
|
administrador; depois que ele expira, reinicie o daemon para obter outro. Veja [Autenticação e transporte](docs/pt-BR/docker.md#autenticação-e-transporte).
|
||||||
O `update` checa por versões novas e orienta a atualização da imagem do container.
|
O `update` checa por versões novas e orienta a atualização da imagem do container.
|
||||||
|
|
||||||
## Desenvolvimento
|
## Desenvolvimento
|
||||||
@@ -126,9 +132,11 @@ Veja **[CONTRIBUTING.pt-BR.md](CONTRIBUTING.pt-BR.md)** e
|
|||||||
|
|
||||||
## Limites conhecidos
|
## Limites conhecidos
|
||||||
|
|
||||||
- O motor de detecção, o parser Zeek e a camada de armazenamento são stubs.
|
- A ingestão roda sob demanda: ainda não há ingestão contínua nem agendamento.
|
||||||
|
- Os alertas ficam em memória e se perdem quando o daemon reinicia.
|
||||||
|
- Hoje só `conn.log` e `dns.log` são lidos.
|
||||||
- Não há imagem de release publicada ainda.
|
- Não há imagem de release publicada ainda.
|
||||||
- NetFlow/IPFIX é um modo degradado por projeto; ele não substitui os logs de
|
- NetFlow/IPFIX está planejado como modo degradado; ele não substitui os logs de
|
||||||
protocolo do Zeek em todos os pilares.
|
protocolo do Zeek em todos os pilares.
|
||||||
- O projeto mira ambientes de container Linux (`linux/amd64`, `linux/arm64`).
|
- O projeto mira ambientes de container Linux (`linux/amd64`, `linux/arm64`).
|
||||||
|
|
||||||
@@ -138,10 +146,10 @@ Resumo do [ROADMAP](ROADMAP.pt-BR.md):
|
|||||||
|
|
||||||
| | |
|
| | |
|
||||||
|---|---|
|
|---|---|
|
||||||
| **Feito** | Workspace, stubs de CLI/API, dashboard web, containerização Docker, workflows de CI/release |
|
| **Feito** | CLI, API e dashboard web; implantação Docker; parser Zeek de `conn.log`/`dns.log`; armazenamento Parquet; pilares 1 a 4 (v1); autenticação; workflows de CI/release |
|
||||||
| **Próximo** | Implementação dos pilares 1 e 2 com fixtures determinísticas; parser Zeek real |
|
| **Próximo** | Ingestão contínua, alertas persistentes, rastreio de conexões longas ao vivo, Public Suffix List, allowlist e baseline |
|
||||||
| **Depois** | Particionamento Parquet completo, limpeza por TTL, pilares 3 e 4, fusão de evidências |
|
| **Depois** | Sessões UDP e mais parsers de protocolo, identidade e movimento lateral, entradas NetFlow/IPFIX e Suricata EVE, metadados de release assinados e SBOM |
|
||||||
| **Fora de plano** | Pontuação por IA opaca, serviço de nuvem obrigatório, Python no runtime distribuído |
|
| **Fora de plano** | Pontuação por IA opaca, serviço de nuvem obrigatório, Python no runtime distribuído, tratar fluxos como equivalentes a logs Zeek, shell desktop nativo |
|
||||||
|
|
||||||
## Licença
|
## Licença
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ are implemented in their **initial version (v1)** and validated against public t
|
|||||||
- **Pillar 3 (v1.0):** DNS information capacity (Shannon entropy $\times$ unique subdomain chars per UTC hour) to detect tunneling, with JSD in evidence.
|
- **Pillar 3 (v1.0):** DNS information capacity (Shannon entropy $\times$ unique subdomain chars per UTC hour) to detect tunneling, with JSD in evidence.
|
||||||
- **Pillar 4 (v1.0):** Per-host weighted noisy-OR fusion ($w_1=w_2=w_3=0.75$) with deterministic JSON evidence and priority ranking (`hosts:` output).
|
- **Pillar 4 (v1.0):** Per-host weighted noisy-OR fusion ($w_1=w_2=w_3=0.75$) with deterministic JSON evidence and priority ranking (`hosts:` output).
|
||||||
- In-memory alert reporting in `/api/alerts` and updated web interface.
|
- In-memory alert reporting in `/api/alerts` and updated web interface.
|
||||||
|
- Authentication: required login, MFA (mandatory for administrators, optional for analysts), sessions, API tokens, audit log, explicit transport modes and `acaua auth reset`.
|
||||||
- English/Portuguese documentation, CI/release workflows and `scripts/check.sh`.
|
- English/Portuguese documentation, CI/release workflows and `scripts/check.sh`.
|
||||||
- Deterministic test suite and validation scripts against IoT-23 and CTU-Normal captures.
|
- Deterministic test suite and validation scripts against IoT-23 and CTU-Normal captures.
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ estão implementados em sua **versão inicial (v1)** e validados contra tráfego
|
|||||||
- **Pilar 3 (v1.0):** Capacidade de informação DNS (entropia de Shannon $\times$ caracteres de subdomínio únicos por hora UTC) para detecção de túneis, com JSD na evidência.
|
- **Pilar 3 (v1.0):** Capacidade de informação DNS (entropia de Shannon $\times$ caracteres de subdomínio únicos por hora UTC) para detecção de túneis, com JSD na evidência.
|
||||||
- **Pilar 4 (v1.0):** Fusão noisy-OR ponderada por host ($w_1=w_2=w_3=0.75$) com evidência determinística em JSON e ordenação de prioridade (saída `hosts:`).
|
- **Pilar 4 (v1.0):** Fusão noisy-OR ponderada por host ($w_1=w_2=w_3=0.75$) com evidência determinística em JSON e ordenação de prioridade (saída `hosts:`).
|
||||||
- Relato de alertas em memória em `/api/alerts` e interface web atualizada.
|
- Relato de alertas em memória em `/api/alerts` e interface web atualizada.
|
||||||
|
- Autenticação: login exigido, MFA (obrigatório para administradores, opcional para analistas), sessões, tokens de API, log de auditoria, modos de transporte explícitos e `acaua auth reset`.
|
||||||
- Documentação em inglês/português, workflows de CI/release e `scripts/check.sh`.
|
- Documentação em inglês/português, workflows de CI/release e `scripts/check.sh`.
|
||||||
- Suíte determinística de testes e scripts de validação contra capturas do IoT-23 e CTU-Normal.
|
- Suíte determinística de testes e scripts de validação contra capturas do IoT-23 e CTU-Normal.
|
||||||
|
|
||||||
|
|||||||
+47
-3
@@ -22,9 +22,53 @@ reproduction when a private channel is available.
|
|||||||
memory or escape the configured data directory.
|
memory or escape the configured data directory.
|
||||||
- **Path handling:** dataset paths are resolved and confined to the configured
|
- **Path handling:** dataset paths are resolved and confined to the configured
|
||||||
root; symbolic links are not followed outside it.
|
root; symbolic links are not followed outside it.
|
||||||
- **API exposure:** `serve` binds to `127.0.0.1` by default. Exposing it on a
|
- **Authentication:** login is always required; MFA (TOTP) is mandatory for
|
||||||
network interface is an explicit operator decision and needs a reverse proxy
|
administrators and optional for analysts. The only routes open without a
|
||||||
with authentication.
|
credential are `GET /api/health`, `GET /api/auth/state`, `POST /api/auth/{bootstrap,login,mfa,password-change-required}` and the login assets (`/login.html`, `/login.js`, `/app.css`, `/logo.png`, `/i18n.js`, `/i18n-en.js`). Sessions, API tokens (`read`/`admin`) and an audit log are kept
|
||||||
|
in the data directory. A password or MFA change revokes admin tokens and keeps
|
||||||
|
read tokens. `/api/analyze` is admin-only.
|
||||||
|
- **Attempt limits:** wrong passwords count per username and client address
|
||||||
|
(an IPv4 address or an IPv6 /48), and an address also has its own overall limit;
|
||||||
|
counts fade by one every 15 minutes. On top of that each username has a budget of
|
||||||
|
100 failures in any 24 hours from addresses it has not logged in from, counted over
|
||||||
|
a true rolling window: a slot opens only when a failure turns 24 hours old. Once spent, attempts from unknown addresses are refused
|
||||||
|
before the password is evaluated, even with the right password. Usernames with no
|
||||||
|
account behave the same. An address with a completed login (after MFA, if
|
||||||
|
required) in the last 30 days skips the budget but not the per-address limit; each
|
||||||
|
account keeps at most 10, as hashes rather than addresses. A password or MFA change
|
||||||
|
from a live session keeps only the address that made it; promotion to administrator
|
||||||
|
and `acaua auth reset` clear the list.
|
||||||
|
**The limit that remains:** an attacker can stop logins from a *new* address for
|
||||||
|
a real user for the whole budget window, and for as long as they keep spending the
|
||||||
|
slots as they open. Known addresses, existing sessions and API tokens keep working,
|
||||||
|
and `acaua auth reset` clears the budget; an attacker still running can spend it
|
||||||
|
again. Up to 100 guesses a day per account remain possible, so long passwords
|
||||||
|
matter, and MFA remains recommended for analysts.
|
||||||
|
These limits trust the client address: a wrong `ACAUA_TRUSTED_PROXIES` makes every
|
||||||
|
client look like one address, which removes the cap and can share lockouts, and a
|
||||||
|
too-wide one lets clients forge `X-Forwarded-For`.
|
||||||
|
Crossing the budget writes one `login.budget_exhausted` audit event per account
|
||||||
|
per 24 hours; a username with no account writes none. The audit log has no rotation yet: failed logins add to it, so watch
|
||||||
|
its size on an exposed instance. Budgets of real accounts survive a restart;
|
||||||
|
per-address counts are in memory and a restart clears them. MFA codes and session
|
||||||
|
password checks use a separate persistent per-user count, reachable only past the
|
||||||
|
password or from a live session.
|
||||||
|
- **Browser headers:** every response has a CSP (`script-src 'self'`,
|
||||||
|
`frame-ancestors 'none'`), `X-Frame-Options: DENY`, `nosniff` and
|
||||||
|
`Referrer-Policy: no-referrer`. `style-src` allows `'unsafe-inline'`, which the
|
||||||
|
report's inline stylesheet and Paged.js need.
|
||||||
|
- **API exposure:** `serve` binds to `127.0.0.1` by default and refuses to start
|
||||||
|
without an explicit transport (`local`, `tls` or `proxy`). Publishing beyond
|
||||||
|
loopback is an operator decision and needs `tls` or `proxy`; `local` refuses a
|
||||||
|
non-loopback `--bind` unless `ACAUA_RUNTIME=container`, where `ACAUA_PUBLISHED`
|
||||||
|
is the control. In `proxy` mode the daemon port must be reachable only by the
|
||||||
|
proxy. A bare
|
||||||
|
`docker run -p` without `ACAUA_PUBLISHED` is not detected (login stays mandatory).
|
||||||
|
- **Secret key:** MFA secrets are sealed with a key stored in the data volume by
|
||||||
|
default, which does not protect against copying the volume; prefer a Docker
|
||||||
|
secret via `ACAUA_SECRET_KEY_FILE`.
|
||||||
|
- **Host access:** anyone with Docker access on the host can run
|
||||||
|
`acaua auth reset` and take over any account.
|
||||||
- **Evidence integrity:** alert evidence must be reproducible from the same
|
- **Evidence integrity:** alert evidence must be reproducible from the same
|
||||||
input and code version. Silent nondeterminism is a correctness and security
|
input and code version. Silent nondeterminism is a correctness and security
|
||||||
issue.
|
issue.
|
||||||
|
|||||||
+50
-3
@@ -22,9 +22,56 @@ mínima quando o canal privado estiver estabelecido.
|
|||||||
daemon, exaurir memória ou escapar do diretório de dados configurado.
|
daemon, exaurir memória ou escapar do diretório de dados configurado.
|
||||||
- **Manipulação de caminhos:** caminhos de dataset são resolvidos e confinados à
|
- **Manipulação de caminhos:** caminhos de dataset são resolvidos e confinados à
|
||||||
raiz configurada; symlinks externos não são seguidos.
|
raiz configurada; symlinks externos não são seguidos.
|
||||||
- **Exposição de API:** `serve` escuta em `127.0.0.1` por padrão. Expô-lo em uma
|
- **Autenticação:** o login é sempre exigido; o MFA (TOTP) é obrigatório para
|
||||||
interface de rede é decisão explícita do operador e exige um proxy reverso com
|
administradores e opcional para analistas. As únicas rotas abertas sem credencial
|
||||||
autenticação.
|
são `GET /api/health`, `GET /api/auth/state`, `POST /api/auth/{bootstrap,login,mfa,password-change-required}` e os arquivos da tela de login (`/login.html`, `/login.js`, `/app.css`, `/logo.png`, `/i18n.js`, `/i18n-en.js`). Sessões, tokens de API (`read`/`admin`) e um log de
|
||||||
|
auditoria ficam no diretório de dados. Trocar a senha ou o MFA revoga os tokens
|
||||||
|
admin e mantém os de leitura. `/api/analyze` é exclusivo de administrador.
|
||||||
|
- **Limites de tentativa:** senhas erradas contam por usuário e endereço do
|
||||||
|
cliente (um endereço IPv4 ou um /48 IPv6), e o endereço também tem um limite geral
|
||||||
|
próprio; a contagem cai uma unidade a cada 15 minutos. Além disso, cada usuário tem
|
||||||
|
uma cota de 100 falhas em quaisquer 24 horas vindas de endereços de onde ele ainda
|
||||||
|
não entrou, contada em janela móvel real: uma vaga só abre quando uma falha completa
|
||||||
|
24 horas. Esgotada a cota, tentativas de
|
||||||
|
endereços desconhecidos são recusadas antes de a senha ser avaliada, mesmo com a
|
||||||
|
senha certa. Usuários inexistentes se comportam igual. Um endereço com login
|
||||||
|
completo (depois do MFA, se exigido) nos últimos 30 dias não usa a cota, mas segue
|
||||||
|
sob o limite por endereço; cada conta guarda no máximo 10, como hashes e não como
|
||||||
|
endereços. Uma troca de senha ou de MFA feita de uma sessão ativa mantém só o
|
||||||
|
endereço que a fez; promoção a administrador e `acaua auth reset` apagam a lista.
|
||||||
|
**O limite que resta:** um atacante consegue impedir logins de um endereço *novo*
|
||||||
|
de um usuário real durante toda a janela da cota, e enquanto continuar gastando as
|
||||||
|
vagas à medida que abrem. Endereços conhecidos, sessões existentes e tokens de API
|
||||||
|
continuam funcionando, e `acaua auth reset` zera a cota; um atacante ainda ativo
|
||||||
|
pode gastá-la de novo. Continuam possíveis até 100 palpites por dia por conta,
|
||||||
|
então senhas longas importam, e o MFA continua recomendado para analistas.
|
||||||
|
Esses limites confiam no endereço do cliente: um `ACAUA_TRUSTED_PROXIES` errado faz
|
||||||
|
todos os clientes parecerem um só endereço, o que elimina o limite e pode
|
||||||
|
compartilhar bloqueios, e um amplo demais permite que clientes forjem
|
||||||
|
`X-Forwarded-For`.
|
||||||
|
Esgotar a cota grava um evento de auditoria `login.budget_exhausted` por conta a
|
||||||
|
cada 24 horas; um usuário inexistente não grava nenhum. O log de auditoria ainda não tem rotação: logins com falha o fazem
|
||||||
|
crescer, então acompanhe o tamanho dele em uma instância exposta. A cota de contas
|
||||||
|
reais sobrevive a um reinício; as contagens por endereço ficam em memória e um
|
||||||
|
reinício as apaga. Códigos de MFA e verificações de senha em sessão usam outra
|
||||||
|
contagem, por usuário e persistente, alcançável só depois da senha ou de dentro de
|
||||||
|
uma sessão.
|
||||||
|
- **Cabeçalhos do navegador:** toda resposta traz CSP (`script-src 'self'`,
|
||||||
|
`frame-ancestors 'none'`), `X-Frame-Options: DENY`, `nosniff` e
|
||||||
|
`Referrer-Policy: no-referrer`. O `style-src` permite `'unsafe-inline'`, exigido
|
||||||
|
pela folha de estilo embutida do relatório e pelo Paged.js.
|
||||||
|
- **Exposição de API:** `serve` escuta em `127.0.0.1` por padrão e recusa iniciar
|
||||||
|
sem transporte explícito (`local`, `tls` ou `proxy`). Publicar além do loopback
|
||||||
|
é decisão do operador e exige `tls` ou `proxy`; `local` recusa um `--bind` que não
|
||||||
|
seja loopback, salvo com `ACAUA_RUNTIME=container`, onde o controle é
|
||||||
|
`ACAUA_PUBLISHED`. No modo `proxy`, a porta do daemon deve ser acessível somente
|
||||||
|
pelo proxy. Um `docker run -p` direto, sem
|
||||||
|
`ACAUA_PUBLISHED`, não é detectado (o login continua obrigatório).
|
||||||
|
- **Chave secreta:** os segredos do MFA são selados com uma chave guardada por
|
||||||
|
padrão no volume de dados, o que não protege contra a cópia do volume; prefira
|
||||||
|
um Docker secret via `ACAUA_SECRET_KEY_FILE`.
|
||||||
|
- **Acesso ao host:** quem tem acesso ao Docker do host pode executar
|
||||||
|
`acaua auth reset` e assumir qualquer conta.
|
||||||
- **Integridade da evidência:** a evidência de um alerta deve ser reproduzível a
|
- **Integridade da evidência:** a evidência de um alerta deve ser reproduzível a
|
||||||
partir da mesma entrada e versão de código. Nãodeterminismo silencioso é falha de
|
partir da mesma entrada e versão de código. Nãodeterminismo silencioso é falha de
|
||||||
corretude e segurança.
|
corretude e segurança.
|
||||||
|
|||||||
@@ -0,0 +1,422 @@
|
|||||||
|
// The "Conta" view. Everything from the server goes in through textContent.
|
||||||
|
import { tr, LOC } from './i18n.js';
|
||||||
|
|
||||||
|
const $ = (selector) => document.querySelector(selector);
|
||||||
|
|
||||||
|
let api = null;
|
||||||
|
let session = { username: '', role: '' };
|
||||||
|
|
||||||
|
function el(tag, props = {}, children = []) {
|
||||||
|
const node = document.createElement(tag);
|
||||||
|
for (const [key, value] of Object.entries(props)) {
|
||||||
|
if (key === 'text') node.textContent = value;
|
||||||
|
else if (key === 'class') node.className = value;
|
||||||
|
else if (key === 'on') node.addEventListener('click', value);
|
||||||
|
else node.setAttribute(key, value);
|
||||||
|
}
|
||||||
|
for (const child of children) node.append(child);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
function when(unix) {
|
||||||
|
return unix ? new Date(unix * 1000).toLocaleString(LOC()) : '—';
|
||||||
|
}
|
||||||
|
|
||||||
|
function say(box, text, ok = false) {
|
||||||
|
box.textContent = text;
|
||||||
|
box.className = ok ? 'form-ok' : 'form-error';
|
||||||
|
box.hidden = !text;
|
||||||
|
}
|
||||||
|
|
||||||
|
function explain(error) {
|
||||||
|
if (!error.retryAfter) return error.message;
|
||||||
|
return `${error.message} ${tr('Tente de novo em {n} s.').replace('{n}', error.retryAfter)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fillRows(body, rows, columns, emptyText) {
|
||||||
|
body.replaceChildren(
|
||||||
|
...(rows.length
|
||||||
|
? rows
|
||||||
|
: [el('tr', {}, [el('td', { colspan: String(columns), class: 'empty-cell', text: emptyText })])]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Reauthentication ------------------------------------------------------
|
||||||
|
|
||||||
|
class ReauthCancelled extends Error {}
|
||||||
|
|
||||||
|
function promptReauth() {
|
||||||
|
const dialog = $('#reauthDlg');
|
||||||
|
const form = $('#reauthForm');
|
||||||
|
const error = $('#reauthError');
|
||||||
|
const password = $('#reauthPass');
|
||||||
|
const code = $('#reauthCode');
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const finish = (confirmed) => {
|
||||||
|
form.removeEventListener('submit', submit);
|
||||||
|
$('#reauthCancel').removeEventListener('click', cancel);
|
||||||
|
dialog.removeEventListener('cancel', cancel);
|
||||||
|
password.value = '';
|
||||||
|
code.value = '';
|
||||||
|
dialog.close();
|
||||||
|
if (confirmed) resolve();
|
||||||
|
else reject(new ReauthCancelled());
|
||||||
|
};
|
||||||
|
const cancel = (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
finish(false);
|
||||||
|
};
|
||||||
|
const submit = async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const button = form.querySelector('button[type="submit"]');
|
||||||
|
button.disabled = true;
|
||||||
|
say(error, '');
|
||||||
|
try {
|
||||||
|
await api('/api/auth/reauth', {
|
||||||
|
method: 'POST',
|
||||||
|
body: { password: password.value, code: code.value.trim() || null },
|
||||||
|
});
|
||||||
|
finish(true);
|
||||||
|
} catch (failure) {
|
||||||
|
say(error, explain(failure));
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
say(error, '');
|
||||||
|
form.addEventListener('submit', submit);
|
||||||
|
$('#reauthCancel').addEventListener('click', cancel);
|
||||||
|
dialog.addEventListener('cancel', cancel);
|
||||||
|
dialog.showModal();
|
||||||
|
password.focus();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a sensitive action, asking for password and code once if the server wants them. */
|
||||||
|
async function withReauth(action) {
|
||||||
|
try {
|
||||||
|
return await action();
|
||||||
|
} catch (error) {
|
||||||
|
if (error.code !== 'recent authentication required') throw error;
|
||||||
|
}
|
||||||
|
await promptReauth();
|
||||||
|
return action();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a panel's action and reports the outcome in its status line. */
|
||||||
|
async function attempt(box, action, done = '') {
|
||||||
|
say(box, '');
|
||||||
|
try {
|
||||||
|
await action();
|
||||||
|
if (done) say(box, done, true);
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof ReauthCancelled)) say(box, explain(error));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- One-time secrets ------------------------------------------------------
|
||||||
|
|
||||||
|
function bindSecret({ box, copy, download, fileName, status }) {
|
||||||
|
copy.addEventListener('click', async () => {
|
||||||
|
const label = copy.textContent;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(box.textContent);
|
||||||
|
copy.textContent = tr('Copiado');
|
||||||
|
window.setTimeout(() => { copy.textContent = label; }, 1400);
|
||||||
|
} catch {
|
||||||
|
say(status, tr('Não foi possível copiar. Selecione o texto e copie à mão.'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
download.addEventListener('click', () => {
|
||||||
|
const url = URL.createObjectURL(new Blob([`${box.textContent}\n`], { type: 'text/plain' }));
|
||||||
|
const link = el('a', { href: url, download: fileName });
|
||||||
|
link.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Own credentials -------------------------------------------------------
|
||||||
|
|
||||||
|
async function changePassword(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
const box = $('#pwStatus');
|
||||||
|
const form = event.currentTarget;
|
||||||
|
if ($('#pwNew').value !== $('#pwRepeat').value) {
|
||||||
|
say(box, tr('As senhas não coincidem.'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await attempt(box, async () => {
|
||||||
|
await api('/api/auth/password', {
|
||||||
|
method: 'POST',
|
||||||
|
body: { current: $('#pwCurrent').value, new: $('#pwNew').value },
|
||||||
|
});
|
||||||
|
form.reset();
|
||||||
|
await loadSessions();
|
||||||
|
}, tr('Senha trocada. As outras sessões foram encerradas.'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True while one-time recovery codes are on screen and not yet confirmed. */
|
||||||
|
let holdingCodes = false;
|
||||||
|
|
||||||
|
export function holdingOneTimeCodes() {
|
||||||
|
return holdingCodes;
|
||||||
|
}
|
||||||
|
|
||||||
|
function warnBeforeLeaving(event) {
|
||||||
|
event.preventDefault();
|
||||||
|
event.returnValue = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
function holdCodes() {
|
||||||
|
holdingCodes = true;
|
||||||
|
window.addEventListener('beforeunload', warnBeforeLeaving);
|
||||||
|
}
|
||||||
|
|
||||||
|
function releaseCodes() {
|
||||||
|
holdingCodes = false;
|
||||||
|
window.removeEventListener('beforeunload', warnBeforeLeaving);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The buttons follow the account: disabling needs an analyst with MFA on. */
|
||||||
|
function showMfaState() {
|
||||||
|
$('#mfaStart').textContent = session.mfa_enabled ? 'Cadastrar MFA de novo' : 'Ativar MFA';
|
||||||
|
$('#mfaDisable').hidden = session.role === 'admin' || !session.mfa_enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindMfa() {
|
||||||
|
const status = $('#mfaStatus');
|
||||||
|
$('#mfaStart').addEventListener('click', () => attempt(status, async () => {
|
||||||
|
const data = await withReauth(() => api('/api/auth/enroll/start', { method: 'POST', body: {} }));
|
||||||
|
$('#mfaQr').src = `data:image/png;base64,${data.qr_png_base64}`;
|
||||||
|
$('#mfaKey').value = data.manual_key;
|
||||||
|
$('#mfaCode').value = '';
|
||||||
|
$('#mfaEnroll').hidden = false;
|
||||||
|
$('#mfaCode').focus();
|
||||||
|
}));
|
||||||
|
$('#mfaEnroll').addEventListener('submit', (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
attempt(status, async () => {
|
||||||
|
// Activation ends this session while the reply is on its way: a request
|
||||||
|
// from elsewhere in the page can get a 401 and leave before it lands,
|
||||||
|
// taking the codes with it. So the page is held before the POST.
|
||||||
|
holdCodes();
|
||||||
|
let reply;
|
||||||
|
try {
|
||||||
|
reply = await withReauth(() => api('/api/auth/enroll/confirm', {
|
||||||
|
method: 'POST',
|
||||||
|
body: { code: $('#mfaCode').value.trim() },
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
releaseCodes();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
$('#mfaEnroll').hidden = true;
|
||||||
|
$('#mfaQr').removeAttribute('src');
|
||||||
|
$('#mfaKey').value = '';
|
||||||
|
$('#mfaActions').hidden = true;
|
||||||
|
$('#mfaRecoveryCodes').textContent = reply.recovery_codes.join('\n');
|
||||||
|
$('#mfaRecovery').hidden = false;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
bindSecret({
|
||||||
|
box: $('#mfaRecoveryCodes'),
|
||||||
|
copy: $('#mfaRecoveryCopy'),
|
||||||
|
download: $('#mfaRecoveryDownload'),
|
||||||
|
fileName: 'acaua-codigos-de-recuperacao.txt',
|
||||||
|
status,
|
||||||
|
});
|
||||||
|
// Activation ended every session of this user, this one included.
|
||||||
|
$('#mfaRecoveryDone').addEventListener('click', () => {
|
||||||
|
releaseCodes();
|
||||||
|
location.replace('/login.html');
|
||||||
|
});
|
||||||
|
$('#mfaDisable').addEventListener('click', () => {
|
||||||
|
if (!window.confirm(tr('Desativar o MFA desta conta?'))) return;
|
||||||
|
attempt(status, async () => {
|
||||||
|
await withReauth(() => api('/api/auth/mfa/disable', { method: 'POST', body: {} }));
|
||||||
|
session.mfa_enabled = false;
|
||||||
|
showMfaState();
|
||||||
|
}, tr('MFA desativado.'));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Sessions and tokens ---------------------------------------------------
|
||||||
|
|
||||||
|
async function loadSessions() {
|
||||||
|
const box = $('#sessionStatus');
|
||||||
|
const list = await api('/api/auth/sessions');
|
||||||
|
fillRows($('#sessionRows'), list.map((s) => el('tr', {}, [
|
||||||
|
el('td', { text: when(s.created_at) }),
|
||||||
|
el('td', { text: when(s.last_seen) }),
|
||||||
|
el('td', { text: when(s.expires_at) }),
|
||||||
|
el('td', { class: 'row-actions' }, [el('button', {
|
||||||
|
type: 'button',
|
||||||
|
class: 'btn small danger',
|
||||||
|
text: 'Encerrar',
|
||||||
|
on: () => attempt(box, async () => {
|
||||||
|
await api('/api/auth/sessions', { method: 'DELETE', body: { id: s.id } });
|
||||||
|
await loadSessions();
|
||||||
|
}),
|
||||||
|
})]),
|
||||||
|
])), 4, 'Nenhuma sessão ativa.');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadTokens() {
|
||||||
|
const box = $('#tokenStatus');
|
||||||
|
const list = await api('/api/auth/tokens');
|
||||||
|
fillRows($('#tokenRows'), list.map((token) => el('tr', {}, [
|
||||||
|
el('td', { class: 'mono', text: token.name }),
|
||||||
|
el('td', { text: token.scope === 'admin' ? 'Administração' : 'Leitura' }),
|
||||||
|
el('td', { text: when(token.expires_at) }),
|
||||||
|
el('td', { class: 'row-actions' }, [el('button', {
|
||||||
|
type: 'button',
|
||||||
|
class: 'btn small danger',
|
||||||
|
text: 'Revogar',
|
||||||
|
on: () => attempt(box, async () => {
|
||||||
|
await api('/api/auth/tokens', { method: 'DELETE', body: { id: token.id } });
|
||||||
|
await loadTokens();
|
||||||
|
}),
|
||||||
|
})]),
|
||||||
|
])), 4, 'Nenhum token criado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindTokens() {
|
||||||
|
const status = $('#tokenStatus');
|
||||||
|
$('#tokenForm').addEventListener('submit', (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const form = event.currentTarget;
|
||||||
|
attempt(status, async () => {
|
||||||
|
const days = Number($('#tokenDays').value);
|
||||||
|
const made = await withReauth(() => api('/api/auth/tokens', {
|
||||||
|
method: 'POST',
|
||||||
|
body: {
|
||||||
|
name: $('#tokenName').value,
|
||||||
|
scope: $('#tokenScope').value,
|
||||||
|
expires_at: Math.floor(Date.now() / 1000) + days * 86400,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
form.reset();
|
||||||
|
$('#tokenValue').textContent = made.token;
|
||||||
|
$('#tokenOnce').hidden = false;
|
||||||
|
await loadTokens();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
bindSecret({
|
||||||
|
box: $('#tokenValue'),
|
||||||
|
copy: $('#tokenCopy'),
|
||||||
|
download: $('#tokenDownload'),
|
||||||
|
fileName: 'acaua-token.txt',
|
||||||
|
status,
|
||||||
|
});
|
||||||
|
$('#tokenDone').addEventListener('click', () => {
|
||||||
|
$('#tokenValue').textContent = '';
|
||||||
|
$('#tokenOnce').hidden = true;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Administration --------------------------------------------------------
|
||||||
|
|
||||||
|
function roleSelect(user) {
|
||||||
|
const select = el('select', { name: 'role', 'aria-label': 'Papel' }, [
|
||||||
|
el('option', { value: 'analyst', text: 'Analista' }),
|
||||||
|
el('option', { value: 'admin', text: 'Administrador' }),
|
||||||
|
]);
|
||||||
|
select.value = user.role;
|
||||||
|
select.addEventListener('change', () => attempt($('#userStatus'), async () => {
|
||||||
|
try {
|
||||||
|
await withReauth(() => api('/api/admin/users', {
|
||||||
|
method: 'PATCH',
|
||||||
|
body: { id: user.id, role: select.value },
|
||||||
|
}));
|
||||||
|
} finally {
|
||||||
|
await loadUsers();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
return select;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadUsers() {
|
||||||
|
const box = $('#userStatus');
|
||||||
|
const list = await api('/api/admin/users');
|
||||||
|
fillRows($('#userRows'), list.map((user) => el('tr', {}, [
|
||||||
|
el('td', { class: 'mono', text: user.username }),
|
||||||
|
el('td', {}, [roleSelect(user)]),
|
||||||
|
el('td', { text: user.mfa_enabled ? 'Ativo' : 'Inativo' }),
|
||||||
|
el('td', { text: when(user.created_at) }),
|
||||||
|
el('td', { class: 'row-actions' }, [el('button', {
|
||||||
|
type: 'button',
|
||||||
|
class: 'btn small danger',
|
||||||
|
text: 'Excluir',
|
||||||
|
on: () => {
|
||||||
|
if (!window.confirm(tr('Excluir esta conta? As sessões e os tokens dela também acabam.'))) return;
|
||||||
|
attempt(box, async () => {
|
||||||
|
await withReauth(() => api('/api/admin/users', { method: 'DELETE', body: { id: user.id } }));
|
||||||
|
await loadUsers();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
})]),
|
||||||
|
])), 5, 'Nenhuma conta.');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAudit() {
|
||||||
|
const list = await api('/api/admin/audit?limit=100');
|
||||||
|
fillRows($('#auditRows'), list.slice().reverse().map((entry) => el('tr', {}, [
|
||||||
|
el('td', { class: 'mono', text: entry.ts }),
|
||||||
|
el('td', { class: 'mono', text: entry.action }),
|
||||||
|
el('td', { class: 'mono', text: entry.actor ?? '—' }),
|
||||||
|
el('td', { class: 'mono', text: entry.ip ?? '—' }),
|
||||||
|
el('td', { text: entry.ok ? 'Sim' : 'Não' }),
|
||||||
|
el('td', { class: 'mono', text: entry.detail ?? '—' }),
|
||||||
|
])), 6, 'Nenhum evento registrado.');
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindAdmin() {
|
||||||
|
$('#userForm').addEventListener('submit', (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const form = event.currentTarget;
|
||||||
|
attempt($('#userStatus'), async () => {
|
||||||
|
await withReauth(() => api('/api/admin/users', {
|
||||||
|
method: 'POST',
|
||||||
|
body: {
|
||||||
|
username: $('#userName').value,
|
||||||
|
password: $('#userPass').value,
|
||||||
|
role: $('#userRole').value,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
form.reset();
|
||||||
|
await Promise.all([loadUsers(), loadAudit()]);
|
||||||
|
}, tr('Conta criada.'));
|
||||||
|
});
|
||||||
|
$('#auditRefresh').addEventListener('click', () => attempt($('#auditStatus'), loadAudit));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Entry points ----------------------------------------------------------
|
||||||
|
|
||||||
|
export function refreshAccount() {
|
||||||
|
attempt($('#sessionStatus'), loadSessions);
|
||||||
|
attempt($('#tokenStatus'), loadTokens);
|
||||||
|
if (session.role === 'admin') {
|
||||||
|
attempt($('#userStatus'), loadUsers);
|
||||||
|
attempt($('#auditStatus'), loadAudit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function initAccount(client, current) {
|
||||||
|
api = client;
|
||||||
|
session = current;
|
||||||
|
const admin = session.role === 'admin';
|
||||||
|
$('#accountUser').textContent = session.username;
|
||||||
|
$('#accountRole').textContent = admin ? 'Administrador' : 'Analista';
|
||||||
|
$('#mfaPolicy').textContent = admin
|
||||||
|
? 'O MFA é obrigatório para administradores. Cadastrar de novo troca o segredo e os códigos de recuperação.'
|
||||||
|
: 'O MFA é opcional para analistas. Cadastrar de novo troca o segredo e os códigos de recuperação.';
|
||||||
|
showMfaState();
|
||||||
|
$('#tokenScopeAdmin').hidden = !admin;
|
||||||
|
$('#tokenScopeAdmin').disabled = !admin;
|
||||||
|
$('#adminPanels').hidden = !admin;
|
||||||
|
|
||||||
|
$('#passwordForm').addEventListener('submit', changePassword);
|
||||||
|
bindMfa();
|
||||||
|
bindTokens();
|
||||||
|
if (admin) bindAdmin();
|
||||||
|
}
|
||||||
@@ -225,6 +225,8 @@ input, select {
|
|||||||
}
|
}
|
||||||
html[data-theme="light"] input, html[data-theme="light"] select { background: rgba(255, 255, 255, 0.7); }
|
html[data-theme="light"] input, html[data-theme="light"] select { background: rgba(255, 255, 255, 0.7); }
|
||||||
input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(69, 214, 176, 0.12); }
|
input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(69, 214, 176, 0.12); }
|
||||||
|
/* The select background is translucent; the open dropdown does not inherit it and rendered white text on white in dark mode. */
|
||||||
|
select option, select optgroup { background-color: var(--panel-solid); color: var(--text); }
|
||||||
|
|
||||||
.btn {
|
.btn {
|
||||||
padding: 10px 14px;
|
padding: 10px 14px;
|
||||||
@@ -697,3 +699,69 @@ html[data-theme="light"] .host-detail-row td { background: rgba(20, 58, 64, 0.03
|
|||||||
.legend { display: none; }
|
.legend { display: none; }
|
||||||
.top-actions { justify-content: flex-start; }
|
.top-actions { justify-content: flex-start; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ---- Login and account ---- */
|
||||||
|
.auth-shell { width: min(460px, 100%); margin: 0 auto; padding: 40px 16px; display: grid; gap: 16px; }
|
||||||
|
.auth-brand { justify-content: center; }
|
||||||
|
.auth-card { margin-top: 0; }
|
||||||
|
.auth-step { display: grid; gap: 14px; }
|
||||||
|
.auth-step[hidden], .form-stack[hidden] { display: none; }
|
||||||
|
.auth-step h1 { font-size: 1.3rem; }
|
||||||
|
.auth-step .link-btn { justify-self: center; }
|
||||||
|
.auth-prefs { display: flex; justify-content: center; gap: 10px; }
|
||||||
|
.notice.notice-warn { margin: 0; }
|
||||||
|
.notice strong { white-space: normal; }
|
||||||
|
.form-error {
|
||||||
|
margin-bottom: 14px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--danger) 45%, transparent);
|
||||||
|
border-radius: 10px;
|
||||||
|
color: var(--danger);
|
||||||
|
font-size: 0.84rem;
|
||||||
|
}
|
||||||
|
.form-ok { color: var(--accent); font-size: 0.84rem; }
|
||||||
|
.qr { justify-self: center; display: block; margin: 0 auto; width: 200px; height: 200px; padding: 8px; border-radius: 10px; background: #ffffff; image-rendering: pixelated; }
|
||||||
|
.secret-box {
|
||||||
|
margin: 0;
|
||||||
|
padding: 12px 14px;
|
||||||
|
border: 1px solid var(--line-strong);
|
||||||
|
border-radius: 10px;
|
||||||
|
background: var(--panel-solid);
|
||||||
|
color: var(--text);
|
||||||
|
font-family: var(--mono);
|
||||||
|
font-size: 0.84rem;
|
||||||
|
line-height: 1.7;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-wrap: anywhere;
|
||||||
|
user-select: all;
|
||||||
|
}
|
||||||
|
.secret-actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.account-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; align-items: start; }
|
||||||
|
.account-grid > .panel { margin-top: 16px; }
|
||||||
|
.form-stack { display: grid; gap: 12px; }
|
||||||
|
.form-inline { display: flex; gap: 10px; align-items: flex-end; flex-wrap: wrap; margin-bottom: 14px; }
|
||||||
|
.form-inline .field { min-width: 150px; }
|
||||||
|
.data-table { width: 100%; border-collapse: collapse; }
|
||||||
|
.data-table th {
|
||||||
|
padding: 10px 12px;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.68rem;
|
||||||
|
font-weight: 600;
|
||||||
|
letter-spacing: 0.08em;
|
||||||
|
text-align: left;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
.data-table td { padding: 10px 12px; border-top: 1px solid var(--line); font-size: 0.82rem; vertical-align: middle; overflow-wrap: break-word; }
|
||||||
|
.data-table select { padding: 6px 8px; }
|
||||||
|
.data-table .row-actions { text-align: right; white-space: nowrap; }
|
||||||
|
.btn.danger { color: var(--danger); }
|
||||||
|
.btn.danger:hover { border-color: var(--danger); }
|
||||||
|
.user-chip { color: var(--muted); font-size: 0.8rem; }
|
||||||
|
.analysis-locked { margin: 0 0 14px; }
|
||||||
|
@media (max-width: 1120px) { .account-grid { grid-template-columns: minmax(0, 1fr); } }
|
||||||
|
.notice[hidden], .field-row[hidden], .btn[hidden] { display: none; }
|
||||||
|
.empty-cell { color: var(--muted); }
|
||||||
|
.form-inline .field.compact > span { font-size: 0.74rem; }
|
||||||
|
html[data-theme="light"] .btn.primary { color: #ffffff; }
|
||||||
|
.panel [role="status"] { margin: 0 0 12px; }
|
||||||
|
#tokenOnce { margin-bottom: 14px; }
|
||||||
+78
-7
@@ -1,4 +1,5 @@
|
|||||||
import { setLang, tr, LOC, currentLang } from './i18n.js';
|
import { setLang, tr, LOC, currentLang, serverMessage } from './i18n.js';
|
||||||
|
import { initAccount, refreshAccount, holdingOneTimeCodes } from './account.js';
|
||||||
|
|
||||||
const SVG_NS = 'http://www.w3.org/2000/svg';
|
const SVG_NS = 'http://www.w3.org/2000/svg';
|
||||||
const $ = (selector) => document.querySelector(selector);
|
const $ = (selector) => document.querySelector(selector);
|
||||||
@@ -53,6 +54,8 @@ const state = {
|
|||||||
expandedHosts: new Set(),
|
expandedHosts: new Set(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let session = { username: '', role: '', csrf: '' };
|
||||||
|
|
||||||
const VIEW_META = {
|
const VIEW_META = {
|
||||||
overview: {
|
overview: {
|
||||||
title: 'Visão geral',
|
title: 'Visão geral',
|
||||||
@@ -70,6 +73,10 @@ const VIEW_META = {
|
|||||||
title: 'Análise',
|
title: 'Análise',
|
||||||
sub: 'Ingestão de logs Zeek e relatório da execução',
|
sub: 'Ingestão de logs Zeek e relatório da execução',
|
||||||
},
|
},
|
||||||
|
account: {
|
||||||
|
title: 'Conta',
|
||||||
|
sub: 'Senha, MFA, sessões e tokens',
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
let themePreference = localStorage.getItem('acaua-theme') || 'auto';
|
let themePreference = localStorage.getItem('acaua-theme') || 'auto';
|
||||||
@@ -1128,6 +1135,7 @@ function renderReportSummary() {
|
|||||||
output.textContent = t('Nenhuma análise executada.');
|
output.textContent = t('Nenhuma análise executada.');
|
||||||
$('#gotoAlerts').hidden = true;
|
$('#gotoAlerts').hidden = true;
|
||||||
$('#gotoHosts').hidden = true;
|
$('#gotoHosts').hidden = true;
|
||||||
|
$('#openReport').hidden = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
reportSummary.hidden = false;
|
reportSummary.hidden = false;
|
||||||
@@ -1146,6 +1154,7 @@ function renderReportSummary() {
|
|||||||
reportStatus.textContent = report.status || '—';
|
reportStatus.textContent = report.status || '—';
|
||||||
$('#gotoAlerts').hidden = false;
|
$('#gotoAlerts').hidden = false;
|
||||||
$('#gotoHosts').hidden = false;
|
$('#gotoHosts').hidden = false;
|
||||||
|
$('#openReport').hidden = false;
|
||||||
|
|
||||||
const lines = [
|
const lines = [
|
||||||
message(
|
message(
|
||||||
@@ -1235,11 +1244,54 @@ function applyViewMeta() {
|
|||||||
document.title = `${t(meta.title)} · Acauã`;
|
document.title = `${t(meta.title)} · Acauã`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function goToLogin() {
|
||||||
|
// Recovery codes on screen exist nowhere else: their "done" button leaves.
|
||||||
|
if (!holdingOneTimeCodes()) location.replace('/login.html');
|
||||||
|
// The page is leaving: callers must not go on to render a failure.
|
||||||
|
return new Promise(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
async function fetchJson(path, options = {}) {
|
async function fetchJson(path, options = {}) {
|
||||||
const response = await fetch(path, options);
|
const method = (options.method || 'GET').toUpperCase();
|
||||||
|
const headers = { ...options.headers };
|
||||||
|
if (method !== 'GET' && method !== 'HEAD') headers['X-Acaua-CSRF'] = session.csrf;
|
||||||
|
const response = await fetch(path, { ...options, headers });
|
||||||
const body = await response.json().catch(() => ({}));
|
const body = await response.json().catch(() => ({}));
|
||||||
if (!response.ok) throw new Error(body.error || response.statusText);
|
if (response.ok) return body;
|
||||||
return body;
|
// A wrong password in a form is also a 401, but must stay on the page.
|
||||||
|
if (response.status === 401 && body.error === 'authentication required') return goToLogin();
|
||||||
|
const raw = body.error || response.statusText;
|
||||||
|
const error = new Error(serverMessage(raw));
|
||||||
|
error.code = raw;
|
||||||
|
error.retryAfter = response.headers.get('Retry-After');
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `fetchJson` with a JSON body, for the account screen. */
|
||||||
|
function accountApi(path, { method = 'GET', body } = {}) {
|
||||||
|
if (body === undefined) return fetchJson(path, { method });
|
||||||
|
return fetchJson(path, {
|
||||||
|
method,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function logout() {
|
||||||
|
// On failure the session is still alive: looking signed out would be a lie.
|
||||||
|
const button = $('#logoutBtn');
|
||||||
|
const status = $('#logoutStatus');
|
||||||
|
status.hidden = true;
|
||||||
|
button.disabled = true;
|
||||||
|
try {
|
||||||
|
await fetchJson('/api/auth/logout', { method: 'POST' });
|
||||||
|
await goToLogin();
|
||||||
|
} catch (error) {
|
||||||
|
status.textContent = `${tr('Não foi possível sair; a sessão continua ativa.')} ${error.message}`;
|
||||||
|
status.hidden = false;
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function call(command, args = {}) {
|
async function call(command, args = {}) {
|
||||||
@@ -1313,6 +1365,7 @@ async function refreshAll() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function analyzeDataset() {
|
async function analyzeDataset() {
|
||||||
|
if (session.role !== 'admin') return;
|
||||||
const path = datasetPath.value.trim();
|
const path = datasetPath.value.trim();
|
||||||
if (!path) {
|
if (!path) {
|
||||||
output.textContent = t('Nenhum dataset selecionado.');
|
output.textContent = t('Nenhum dataset selecionado.');
|
||||||
@@ -1334,9 +1387,12 @@ async function analyzeDataset() {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
reportSummary.hidden = true;
|
reportSummary.hidden = true;
|
||||||
reportStatus.textContent = '—';
|
reportStatus.textContent = '—';
|
||||||
output.textContent = message('Falha na análise: {n}', error.message);
|
output.textContent = error.code === 'analysis failed'
|
||||||
|
? error.message
|
||||||
|
: message('Falha na análise: {n}', error.message);
|
||||||
$('#gotoAlerts').hidden = true;
|
$('#gotoAlerts').hidden = true;
|
||||||
$('#gotoHosts').hidden = true;
|
$('#gotoHosts').hidden = true;
|
||||||
|
$('#openReport').hidden = true;
|
||||||
} finally {
|
} finally {
|
||||||
analyzeBtn.disabled = false;
|
analyzeBtn.disabled = false;
|
||||||
}
|
}
|
||||||
@@ -1414,6 +1470,7 @@ function showView(target, { updateHash = true } = {}) {
|
|||||||
if (target === 'overview') renderCharts();
|
if (target === 'overview') renderCharts();
|
||||||
if (target === 'alerts') renderAlerts();
|
if (target === 'alerts') renderAlerts();
|
||||||
if (target === 'hosts') renderHosts();
|
if (target === 'hosts') renderHosts();
|
||||||
|
if (target === 'account' && session.csrf) refreshAccount();
|
||||||
window.scrollTo({ top: 0, behavior: 'instant' });
|
window.scrollTo({ top: 0, behavior: 'instant' });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1422,10 +1479,23 @@ function initViewFromHash() {
|
|||||||
return VIEW_META[target] ? target : 'overview';
|
return VIEW_META[target] ? target : 'overview';
|
||||||
}
|
}
|
||||||
|
|
||||||
function init() {
|
async function init() {
|
||||||
applyTheme(themePreference);
|
applyTheme(themePreference);
|
||||||
langSel.value = localStorage.getItem('acaua-lang') || 'auto';
|
langSel.value = localStorage.getItem('acaua-lang') || 'auto';
|
||||||
setLang(langSel.value);
|
setLang(langSel.value);
|
||||||
|
const auth = await fetch('/api/auth/state').then((response) => response.json());
|
||||||
|
if (!auth.authenticated) {
|
||||||
|
await goToLogin();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
session = { username: auth.username, role: auth.role, csrf: auth.csrf, mfa_enabled: auth.mfa_enabled };
|
||||||
|
$('#topUser').textContent = session.username;
|
||||||
|
$('#logoutBtn').addEventListener('click', logout);
|
||||||
|
if (session.role !== 'admin') {
|
||||||
|
$('#analysisForm').hidden = true;
|
||||||
|
$('#analysisLocked').hidden = false;
|
||||||
|
}
|
||||||
|
initAccount(accountApi, session);
|
||||||
datasetPath.value = localStorage.getItem('acaua-last-path') || '';
|
datasetPath.value = localStorage.getItem('acaua-last-path') || '';
|
||||||
state.view = initViewFromHash();
|
state.view = initViewFromHash();
|
||||||
showView(state.view, { updateHash: false });
|
showView(state.view, { updateHash: false });
|
||||||
@@ -1561,6 +1631,7 @@ function init() {
|
|||||||
$('#seeAllAlerts').addEventListener('click', () => showView('alerts'));
|
$('#seeAllAlerts').addEventListener('click', () => showView('alerts'));
|
||||||
$('#gotoAlerts').addEventListener('click', () => showView('alerts'));
|
$('#gotoAlerts').addEventListener('click', () => showView('alerts'));
|
||||||
$('#gotoHosts').addEventListener('click', () => showView('hosts'));
|
$('#gotoHosts').addEventListener('click', () => showView('hosts'));
|
||||||
|
$('#openReport').addEventListener('click', () => window.open('/relatorio', '_blank', 'noopener'));
|
||||||
|
|
||||||
langSel.addEventListener('change', () => {
|
langSel.addEventListener('change', () => {
|
||||||
localStorage.setItem('acaua-lang', langSel.value);
|
localStorage.setItem('acaua-lang', langSel.value);
|
||||||
@@ -1588,4 +1659,4 @@ function init() {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
init();
|
init().catch((error) => console.error(error));
|
||||||
@@ -103,6 +103,8 @@ export const EN = {
|
|||||||
'A API de fusão lista apenas hosts com pelo menos um alerta. Hosts sem alerta não aparecem nesta tabela.': 'The fusion API only lists hosts with at least one alert. Hosts without alerts do not appear in this table.',
|
'A API de fusão lista apenas hosts com pelo menos um alerta. Hosts sem alerta não aparecem nesta tabela.': 'The fusion API only lists hosts with at least one alert. Hosts without alerts do not appear in this table.',
|
||||||
'Ver alertas': 'View alerts',
|
'Ver alertas': 'View alerts',
|
||||||
'Ver hosts': 'View hosts',
|
'Ver hosts': 'View hosts',
|
||||||
|
'Relatório': 'Report',
|
||||||
|
'Abre o relatório executivo da última análise em uma nova aba': 'Opens the executive report of the latest analysis in a new tab',
|
||||||
'Estado do serviço': 'Service status',
|
'Estado do serviço': 'Service status',
|
||||||
'Versão, dataset e armazenamento informados pela API local.': 'Version, dataset and storage reported by the local API.',
|
'Versão, dataset e armazenamento informados pela API local.': 'Version, dataset and storage reported by the local API.',
|
||||||
'{n} pilares ativos': '{n} active pillars',
|
'{n} pilares ativos': '{n} active pillars',
|
||||||
@@ -164,4 +166,142 @@ export const EN = {
|
|||||||
'Hosts por score de fusão': 'Hosts by fusion score',
|
'Hosts por score de fusão': 'Hosts by fusion score',
|
||||||
'Distribuição de alertas por pilar': 'Alert distribution per pillar',
|
'Distribuição de alertas por pilar': 'Alert distribution per pillar',
|
||||||
'Filtrar por pilar': 'Filter by pillar',
|
'Filtrar por pilar': 'Filter by pillar',
|
||||||
|
'Entrar · Acauã': 'Sign in · Acauã',
|
||||||
|
'Entrar': 'Sign in',
|
||||||
|
'Sair': 'Sign out',
|
||||||
|
'Conta': 'Account',
|
||||||
|
'senha, MFA e tokens': 'password, MFA and tokens',
|
||||||
|
'Senha, MFA, sessões e tokens': 'Password, MFA, sessions and tokens',
|
||||||
|
'Sua conta': 'Your account',
|
||||||
|
'Trocar a senha': 'Change password',
|
||||||
|
'Senha atual': 'Current password',
|
||||||
|
'Nova senha': 'New password',
|
||||||
|
'Repita a nova senha': 'Repeat the new password',
|
||||||
|
'Senha': 'Password',
|
||||||
|
'Pelo menos 12 caracteres. As outras sessões da conta são encerradas.': 'At least 12 characters. The account\'s other sessions are ended.',
|
||||||
|
'Cadastrar MFA': 'Enroll MFA',
|
||||||
|
'Desativar MFA': 'Disable MFA',
|
||||||
|
'Ativar MFA': 'Enable MFA',
|
||||||
|
'O MFA não está ativo nesta conta.': 'MFA is not enabled on this account.',
|
||||||
|
'Cadastrar MFA de novo': 'Enroll MFA again',
|
||||||
|
'Não foi possível sair; a sessão continua ativa.': 'Could not sign out; the session is still active.',
|
||||||
|
'Escaneie o QR no aplicativo autenticador ou digite a chave manual. Depois, informe o código gerado. Ao confirmar, todas as suas sessões terminam e você entra de novo.': 'Scan the QR with your authenticator app or type the manual key, then enter the generated code. Confirming ends all your sessions and you sign in again.',
|
||||||
|
'Escaneie o QR no aplicativo autenticador ou digite a chave manual. Depois, informe o código gerado.': 'Scan the QR with your authenticator app or type the manual key, then enter the generated code.',
|
||||||
|
'QR do cadastro de MFA': 'MFA enrollment QR',
|
||||||
|
'Chave manual': 'Manual key',
|
||||||
|
'Código de 6 dígitos': '6-digit code',
|
||||||
|
'Confirmar cadastro': 'Confirm enrollment',
|
||||||
|
'Guarde estes códigos agora: eles só aparecem esta vez e cada um funciona uma única vez. O código usado no cadastro já foi gasto: para entrar, espere o': 'Save these codes now: they appear only this once and each works a single time. The enrollment code is already spent: to sign in, wait for the',
|
||||||
|
'próximo': 'next',
|
||||||
|
'código (até 30 s) ou use um código de recuperação.': 'code (up to 30 s) or use a recovery code.',
|
||||||
|
'Copiar': 'Copy',
|
||||||
|
'Baixar': 'Download',
|
||||||
|
'Já guardei, ir para o login': 'Saved, go to sign in',
|
||||||
|
'Sessões': 'Sessions',
|
||||||
|
'Inclui esta sessão: encerrá-la leva de volta ao login.': 'Includes this session: ending it returns you to sign in.',
|
||||||
|
'Último uso': 'Last used',
|
||||||
|
'Expira': 'Expires',
|
||||||
|
'Ações': 'Actions',
|
||||||
|
'Tokens de API': 'API tokens',
|
||||||
|
'O valor do token só aparece na criação. Validade de até 365 dias.': 'The token value appears only at creation. Valid for up to 365 days.',
|
||||||
|
'Nome': 'Name',
|
||||||
|
'Escopo': 'Scope',
|
||||||
|
'Leitura': 'Read',
|
||||||
|
'Administração': 'Administration',
|
||||||
|
'Dias de validade': 'Days valid',
|
||||||
|
'Criar token': 'Create token',
|
||||||
|
'Copie este token agora: ele não aparece de novo.': 'Copy this token now: it will not appear again.',
|
||||||
|
'Já guardei': 'Saved',
|
||||||
|
'Contas e papéis': 'Accounts and roles',
|
||||||
|
'Criar, excluir ou mudar o papel de uma conta pede sua senha e seu código.': 'Creating, deleting or changing an account\'s role asks for your password and code.',
|
||||||
|
'Usuário': 'Username',
|
||||||
|
'Senha inicial': 'Initial password',
|
||||||
|
'Papel': 'Role',
|
||||||
|
'Analista': 'Analyst',
|
||||||
|
'Administrador': 'Administrator',
|
||||||
|
'Criar conta': 'Create account',
|
||||||
|
'MFA': 'MFA',
|
||||||
|
'Criada em': 'Created',
|
||||||
|
'Auditoria': 'Audit',
|
||||||
|
'Os 100 eventos mais recentes.': 'The 100 most recent events.',
|
||||||
|
'Atualizar': 'Refresh',
|
||||||
|
'Quando': 'When',
|
||||||
|
'Ação': 'Action',
|
||||||
|
'Quem': 'Who',
|
||||||
|
'IP': 'IP',
|
||||||
|
'Êxito': 'Success',
|
||||||
|
'Detalhe': 'Detail',
|
||||||
|
'Confirme sua identidade': 'Confirm your identity',
|
||||||
|
'Esta ação pede sua senha e, se o MFA estiver ativo, um código. Depois ela continua sozinha.': 'This action asks for your password and, if MFA is active, a code. It then continues on its own.',
|
||||||
|
'Código MFA ou de recuperação': 'MFA or recovery code',
|
||||||
|
'Cancelar': 'Cancel',
|
||||||
|
'Confirmar': 'Confirm',
|
||||||
|
'Só administradores podem executar análises. Você ainda pode ler os resultados.': 'Only administrators can run analyses. You can still read the results.',
|
||||||
|
'Não foi possível copiar. Selecione o texto e copie à mão.': 'Could not copy. Select the text and copy it by hand.',
|
||||||
|
'As senhas não coincidem.': 'The passwords do not match.',
|
||||||
|
'Senha trocada. As outras sessões foram encerradas.': 'Password changed. Your other sessions were ended.',
|
||||||
|
'Desativar o MFA desta conta?': 'Disable MFA for this account?',
|
||||||
|
'MFA desativado.': 'MFA disabled.',
|
||||||
|
'Nenhuma sessão ativa.': 'No active sessions.',
|
||||||
|
'Encerrar': 'End',
|
||||||
|
'Revogar': 'Revoke',
|
||||||
|
'Nenhum token criado.': 'No tokens created.',
|
||||||
|
'Excluir': 'Delete',
|
||||||
|
'Ativo': 'Active',
|
||||||
|
'Inativo': 'Inactive',
|
||||||
|
'Excluir esta conta? As sessões e os tokens dela também acabam.': 'Delete this account? Its sessions and tokens end too.',
|
||||||
|
'Nenhuma conta.': 'No accounts.',
|
||||||
|
'Sim': 'Yes',
|
||||||
|
'Não': 'No',
|
||||||
|
'Nenhum evento registrado.': 'No events recorded.',
|
||||||
|
'Conta criada.': 'Account created.',
|
||||||
|
'O MFA é obrigatório para administradores. Cadastrar de novo troca o segredo e os códigos de recuperação.': 'MFA is mandatory for administrators. Enrolling again replaces the secret and the recovery codes.',
|
||||||
|
'O MFA é opcional para analistas. Cadastrar de novo troca o segredo e os códigos de recuperação.': 'MFA is optional for analysts. Enrolling again replaces the secret and the recovery codes.',
|
||||||
|
'Tente de novo em {n} s.': 'Try again in {n} s.',
|
||||||
|
'Próximo código em {n} s.': 'Next code in {n} s.',
|
||||||
|
'Credenciais inválidas.': 'Invalid credentials.',
|
||||||
|
'Muitas tentativas.': 'Too many attempts.',
|
||||||
|
'A configuração inicial ainda não foi concluída.': 'Initial setup is not finished yet.',
|
||||||
|
'Código de configuração inválido.': 'Invalid setup code.',
|
||||||
|
'O último administrador precisa continuar existindo.': 'The last administrator must remain.',
|
||||||
|
'O MFA é obrigatório para administradores.': 'MFA is mandatory for administrators.',
|
||||||
|
'Nenhum cadastro de MFA em andamento.': 'No MFA enrollment in progress.',
|
||||||
|
'Este nome de usuário já está em uso.': 'This username is already in use.',
|
||||||
|
'Não encontrado.': 'Not found.',
|
||||||
|
'É preciso confirmar sua identidade de novo.': 'You need to confirm your identity again.',
|
||||||
|
'Sem permissão para esta ação.': 'You do not have permission for this action.',
|
||||||
|
'Erro interno do serviço.': 'Internal service error.',
|
||||||
|
'Sua sessão terminou. Entre de novo.': 'Your session ended. Sign in again.',
|
||||||
|
'Sessão desatualizada. Recarregue a página.': 'Stale session. Reload the page.',
|
||||||
|
'A análise falhou. Os detalhes ficam no log do servidor.': 'The analysis failed. Details are in the server log.',
|
||||||
|
'Esta senha é comum demais.': 'This password is too common.',
|
||||||
|
'A senha não pode repetir um único caractere.': 'The password must not repeat a single character.',
|
||||||
|
'A senha não pode ter só dígitos.': 'The password must not be only digits.',
|
||||||
|
'A nova senha precisa ser diferente da atual.': 'The new password must differ from the current one.',
|
||||||
|
'O nome de usuário não pode ter dois-pontos nem caracteres de controle.': 'The username must not contain colons or control characters.',
|
||||||
|
'O nome de usuário não pode começar nem terminar com espaço.': 'The username must not start or end with a space.',
|
||||||
|
'A validade do token precisa estar no futuro e em até 365 dias.': 'The token expiry must be in the future and within 365 days.',
|
||||||
|
'Esta conta já tem tokens de API demais.': 'This account already has too many API tokens.',
|
||||||
|
'A senha precisa ter pelo menos {n} caracteres.': 'The password must have at least {n} characters.',
|
||||||
|
'A senha pode ter no máximo {n} bytes.': 'The password can have at most {n} bytes.',
|
||||||
|
'O nome de usuário precisa ter de 1 a {n} caracteres.': 'The username must have 1 to {n} characters.',
|
||||||
|
'O nome do token precisa ter de 1 a {n} caracteres, sem caracteres de controle.': 'The token name must have 1 to {n} characters, without control characters.',
|
||||||
|
'Configuração inicial': 'Initial setup',
|
||||||
|
'Nenhum administrador existe ainda. O código de configuração está no log do contêiner (': 'No administrator exists yet. The setup code is in the container log (',
|
||||||
|
') e vale por 1 hora; ao reiniciar o serviço, um novo código é gerado se o anterior tiver expirado.': ') and is valid for 1 hour; restarting the service generates a new code if the previous one expired.',
|
||||||
|
'Código de configuração': 'Setup code',
|
||||||
|
'Usuário administrador': 'Administrator username',
|
||||||
|
'Pelo menos 12 caracteres. Em seguida você cadastra o MFA, obrigatório para administradores.': 'At least 12 characters. Next you enroll MFA, which is mandatory for administrators.',
|
||||||
|
'Criar administrador': 'Create administrator',
|
||||||
|
'Código de verificação': 'Verification code',
|
||||||
|
'Digite o código de 6 dígitos do aplicativo autenticador ou um código de recuperação.': 'Enter the 6-digit code from your authenticator app or a recovery code.',
|
||||||
|
'O código usado no cadastro já foi gasto. Para concluir o login, espere o': 'The enrollment code is already spent. To finish signing in, wait for the',
|
||||||
|
'Código': 'Code',
|
||||||
|
'Verificar': 'Verify',
|
||||||
|
'Voltar ao login': 'Back to sign in',
|
||||||
|
'Códigos de recuperação': 'Recovery codes',
|
||||||
|
'Guarde estes códigos agora: eles só aparecem esta vez e cada um funciona uma única vez.': 'Save these codes now: they appear only this once and each works a single time.',
|
||||||
|
'Já guardei os códigos': 'I saved the codes',
|
||||||
|
'Esta conta precisa de uma senha nova antes de continuar.': 'This account needs a new password before continuing.',
|
||||||
|
'Trocar a senha e entrar': 'Change password and sign in',
|
||||||
};
|
};
|
||||||
@@ -47,6 +47,51 @@ export function tr(text) {
|
|||||||
return lead + out + trail;
|
return lead + out + trail;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The server speaks fixed English messages; the interface shows them in the
|
||||||
|
// user's language. Unknown messages pass through as they came.
|
||||||
|
const SERVER_MESSAGES = {
|
||||||
|
'invalid credentials': 'Credenciais inválidas.',
|
||||||
|
'too many attempts': 'Muitas tentativas.',
|
||||||
|
'setup required': 'A configuração inicial ainda não foi concluída.',
|
||||||
|
'invalid setup code': 'Código de configuração inválido.',
|
||||||
|
'the last administrator must remain': 'O último administrador precisa continuar existindo.',
|
||||||
|
'MFA is mandatory for administrators': 'O MFA é obrigatório para administradores.',
|
||||||
|
'MFA is not enabled': 'O MFA não está ativo nesta conta.',
|
||||||
|
'no enrollment in progress': 'Nenhum cadastro de MFA em andamento.',
|
||||||
|
'username is already in use': 'Este nome de usuário já está em uso.',
|
||||||
|
'not found': 'Não encontrado.',
|
||||||
|
'recent authentication required': 'É preciso confirmar sua identidade de novo.',
|
||||||
|
forbidden: 'Sem permissão para esta ação.',
|
||||||
|
'internal error': 'Erro interno do serviço.',
|
||||||
|
'authentication required': 'Sua sessão terminou. Entre de novo.',
|
||||||
|
'invalid CSRF token': 'Sessão desatualizada. Recarregue a página.',
|
||||||
|
'analysis failed': 'A análise falhou. Os detalhes ficam no log do servidor.',
|
||||||
|
'password is too common': 'Esta senha é comum demais.',
|
||||||
|
'password must not repeat a single character': 'A senha não pode repetir um único caractere.',
|
||||||
|
'password must not be only digits': 'A senha não pode ter só dígitos.',
|
||||||
|
'new password must differ from the current one': 'A nova senha precisa ser diferente da atual.',
|
||||||
|
"username must not contain ':' or control characters": 'O nome de usuário não pode ter dois-pontos nem caracteres de controle.',
|
||||||
|
'username must not start or end with a space': 'O nome de usuário não pode começar nem terminar com espaço.',
|
||||||
|
'token expiry must be in the future and within 365 days': 'A validade do token precisa estar no futuro e em até 365 dias.',
|
||||||
|
'too many API tokens': 'Esta conta já tem tokens de API demais.',
|
||||||
|
};
|
||||||
|
const SERVER_PATTERNS = [
|
||||||
|
[/^password must be at least (\d+) characters$/, 'A senha precisa ter pelo menos {n} caracteres.'],
|
||||||
|
[/^password must be at most (\d+) bytes$/, 'A senha pode ter no máximo {n} bytes.'],
|
||||||
|
[/^username must have 1 to (\d+) characters$/, 'O nome de usuário precisa ter de 1 a {n} caracteres.'],
|
||||||
|
[/^token name must have 1 to (\d+) characters, without control characters$/, 'O nome do token precisa ter de 1 a {n} caracteres, sem caracteres de controle.'],
|
||||||
|
];
|
||||||
|
|
||||||
|
export function serverMessage(raw) {
|
||||||
|
const known = SERVER_MESSAGES[raw];
|
||||||
|
if (known) return tr(known);
|
||||||
|
for (const [re, template] of SERVER_PATTERNS) {
|
||||||
|
const match = String(raw).match(re);
|
||||||
|
if (match) return tr(template).replace('{n}', match[1]);
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
const original = new WeakMap();
|
const original = new WeakMap();
|
||||||
let observer = null;
|
let observer = null;
|
||||||
|
|
||||||
|
|||||||
+181
-1
@@ -36,6 +36,10 @@
|
|||||||
<span class="nav-icon">⌁</span>
|
<span class="nav-icon">⌁</span>
|
||||||
<span><span class="nav-label">Análise</span><span class="nav-sub">dataset Zeek</span></span>
|
<span><span class="nav-label">Análise</span><span class="nav-sub">dataset Zeek</span></span>
|
||||||
</button>
|
</button>
|
||||||
|
<button type="button" class="nav-item" data-target="account">
|
||||||
|
<span class="nav-icon">◉</span>
|
||||||
|
<span><span class="nav-label">Conta</span><span class="nav-sub">senha, MFA e tokens</span></span>
|
||||||
|
</button>
|
||||||
<button type="button" class="nav-item" data-target="settings">
|
<button type="button" class="nav-item" data-target="settings">
|
||||||
<span class="nav-icon">⚙</span>
|
<span class="nav-icon">⚙</span>
|
||||||
<span><span class="nav-label">Configurações</span><span class="nav-sub">idioma e tema</span></span>
|
<span><span class="nav-label">Configurações</span><span class="nav-sub">idioma e tema</span></span>
|
||||||
@@ -65,6 +69,9 @@
|
|||||||
<span id="lastUpdated" class="mono last-updated">—</span>
|
<span id="lastUpdated" class="mono last-updated">—</span>
|
||||||
<button id="refreshBtn" type="button" class="btn">Atualizar status</button>
|
<button id="refreshBtn" type="button" class="btn">Atualizar status</button>
|
||||||
<button id="settingsBtn" type="button" class="icon-btn" aria-label="Configurações" title="Configurações">⚙</button>
|
<button id="settingsBtn" type="button" class="icon-btn" aria-label="Configurações" title="Configurações">⚙</button>
|
||||||
|
<span id="topUser" class="mono user-chip"></span>
|
||||||
|
<span id="logoutStatus" class="form-error" role="alert" hidden></span>
|
||||||
|
<button id="logoutBtn" type="button" class="btn">Sair</button>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
@@ -264,7 +271,9 @@
|
|||||||
<span id="reportStatus" class="panel-tag">—</span>
|
<span id="reportStatus" class="panel-tag">—</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="field-row">
|
<p id="analysisLocked" class="notice notice-warn analysis-locked" hidden><span>Só administradores podem executar análises. Você ainda pode ler os resultados.</span></p>
|
||||||
|
|
||||||
|
<div id="analysisForm" class="field-row">
|
||||||
<label class="field">
|
<label class="field">
|
||||||
<span>Diretório de logs</span>
|
<span>Diretório de logs</span>
|
||||||
<input id="datasetPath" type="text" placeholder="/var/log/zeek/current" autocomplete="off" spellcheck="false">
|
<input id="datasetPath" type="text" placeholder="/var/log/zeek/current" autocomplete="off" spellcheck="false">
|
||||||
@@ -279,6 +288,7 @@
|
|||||||
<div class="report-actions">
|
<div class="report-actions">
|
||||||
<button id="gotoAlerts" type="button" class="btn" hidden>Ver alertas</button>
|
<button id="gotoAlerts" type="button" class="btn" hidden>Ver alertas</button>
|
||||||
<button id="gotoHosts" type="button" class="btn" hidden>Ver hosts</button>
|
<button id="gotoHosts" type="button" class="btn" hidden>Ver hosts</button>
|
||||||
|
<button id="openReport" type="button" class="btn primary" hidden title="Abre o relatório executivo da última análise em uma nova aba">Relatório</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -294,6 +304,160 @@
|
|||||||
</section>
|
</section>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<section class="view" id="account" hidden>
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head">
|
||||||
|
<div>
|
||||||
|
<h2>Sua conta</h2>
|
||||||
|
<p class="hint"><span id="accountUser" class="mono"></span> · <span id="accountRole"></span></p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="account-grid">
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>Trocar a senha</h2>
|
||||||
|
<p class="hint">Pelo menos 12 caracteres. As outras sessões da conta são encerradas.</p>
|
||||||
|
</div></div>
|
||||||
|
<form id="passwordForm" class="form-stack">
|
||||||
|
<label class="field"><span>Senha atual</span>
|
||||||
|
<input id="pwCurrent" type="password" autocomplete="current-password" required></label>
|
||||||
|
<label class="field"><span>Nova senha</span>
|
||||||
|
<input id="pwNew" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<label class="field"><span>Repita a nova senha</span>
|
||||||
|
<input id="pwRepeat" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<p id="pwStatus" role="status" hidden></p>
|
||||||
|
<div><button type="submit" class="btn primary">Trocar a senha</button></div>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>MFA</h2>
|
||||||
|
<p id="mfaPolicy" class="hint"></p>
|
||||||
|
</div></div>
|
||||||
|
<p id="mfaStatus" role="status" hidden></p>
|
||||||
|
<div id="mfaActions" class="secret-actions">
|
||||||
|
<button id="mfaStart" type="button" class="btn">Cadastrar MFA</button>
|
||||||
|
<button id="mfaDisable" type="button" class="btn danger" hidden>Desativar MFA</button>
|
||||||
|
</div>
|
||||||
|
<form id="mfaEnroll" class="form-stack" hidden>
|
||||||
|
<p class="hint">Escaneie o QR no aplicativo autenticador ou digite a chave manual. Depois, informe o código gerado. Ao confirmar, todas as suas sessões terminam e você entra de novo.</p>
|
||||||
|
<img id="mfaQr" class="qr" alt="QR do cadastro de MFA">
|
||||||
|
<label class="field"><span>Chave manual</span>
|
||||||
|
<input id="mfaKey" class="mono" type="text" readonly></label>
|
||||||
|
<label class="field"><span>Código de 6 dígitos</span>
|
||||||
|
<input id="mfaCode" type="text" inputmode="numeric" autocomplete="one-time-code" required></label>
|
||||||
|
<div><button type="submit" class="btn primary">Confirmar cadastro</button></div>
|
||||||
|
</form>
|
||||||
|
<div id="mfaRecovery" class="form-stack" hidden>
|
||||||
|
<p class="notice notice-warn"><span>Guarde estes códigos agora: eles só aparecem esta vez e cada um funciona uma única vez. O código usado no cadastro já foi gasto: para entrar, espere o <strong>próximo</strong> código (até 30 s) ou use um código de recuperação.</span></p>
|
||||||
|
<pre id="mfaRecoveryCodes" class="secret-box"></pre>
|
||||||
|
<div class="secret-actions">
|
||||||
|
<button id="mfaRecoveryCopy" type="button" class="btn">Copiar</button>
|
||||||
|
<button id="mfaRecoveryDownload" type="button" class="btn">Baixar</button>
|
||||||
|
<button id="mfaRecoveryDone" type="button" class="btn primary">Já guardei, ir para o login</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>Sessões</h2>
|
||||||
|
<p class="hint">Inclui esta sessão: encerrá-la leva de volta ao login.</p>
|
||||||
|
</div></div>
|
||||||
|
<p id="sessionStatus" role="status" hidden></p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="data-table">
|
||||||
|
<thead><tr><th scope="col">Início</th><th scope="col">Último uso</th><th scope="col">Expira</th><th scope="col"><span class="sr-only">Ações</span></th></tr></thead>
|
||||||
|
<tbody id="sessionRows"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>Tokens de API</h2>
|
||||||
|
<p class="hint">O valor do token só aparece na criação. Validade de até 365 dias.</p>
|
||||||
|
</div></div>
|
||||||
|
<form id="tokenForm" class="form-inline">
|
||||||
|
<label class="field"><span>Nome</span>
|
||||||
|
<input id="tokenName" type="text" autocomplete="off" spellcheck="false" required></label>
|
||||||
|
<label class="field compact"><span>Escopo</span>
|
||||||
|
<select id="tokenScope">
|
||||||
|
<option value="read">Leitura</option>
|
||||||
|
<option id="tokenScopeAdmin" value="admin">Administração</option>
|
||||||
|
</select></label>
|
||||||
|
<label class="field compact"><span>Dias de validade</span>
|
||||||
|
<input id="tokenDays" type="number" min="1" max="365" value="90" required></label>
|
||||||
|
<button type="submit" class="btn primary">Criar token</button>
|
||||||
|
</form>
|
||||||
|
<p id="tokenStatus" role="status" hidden></p>
|
||||||
|
<div id="tokenOnce" class="form-stack" hidden>
|
||||||
|
<p class="notice notice-warn"><span>Copie este token agora: ele não aparece de novo.</span></p>
|
||||||
|
<pre id="tokenValue" class="secret-box"></pre>
|
||||||
|
<div class="secret-actions">
|
||||||
|
<button id="tokenCopy" type="button" class="btn">Copiar</button>
|
||||||
|
<button id="tokenDownload" type="button" class="btn">Baixar</button>
|
||||||
|
<button id="tokenDone" type="button" class="btn primary">Já guardei</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="data-table">
|
||||||
|
<thead><tr><th scope="col">Nome</th><th scope="col">Escopo</th><th scope="col">Expira</th><th scope="col"><span class="sr-only">Ações</span></th></tr></thead>
|
||||||
|
<tbody id="tokenRows"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div id="adminPanels" hidden>
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head"><div>
|
||||||
|
<h2>Contas e papéis</h2>
|
||||||
|
<p class="hint">Criar, excluir ou mudar o papel de uma conta pede sua senha e seu código.</p>
|
||||||
|
</div></div>
|
||||||
|
<form id="userForm" class="form-inline">
|
||||||
|
<label class="field"><span>Usuário</span>
|
||||||
|
<input id="userName" type="text" autocomplete="off" spellcheck="false" required></label>
|
||||||
|
<label class="field"><span>Senha inicial</span>
|
||||||
|
<input id="userPass" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<label class="field compact"><span>Papel</span>
|
||||||
|
<select id="userRole">
|
||||||
|
<option value="analyst">Analista</option>
|
||||||
|
<option value="admin">Administrador</option>
|
||||||
|
</select></label>
|
||||||
|
<button type="submit" class="btn primary">Criar conta</button>
|
||||||
|
</form>
|
||||||
|
<p id="userStatus" role="status" hidden></p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="data-table">
|
||||||
|
<thead><tr><th scope="col">Usuário</th><th scope="col">Papel</th><th scope="col">MFA</th><th scope="col">Criada em</th><th scope="col"><span class="sr-only">Ações</span></th></tr></thead>
|
||||||
|
<tbody id="userRows"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="panel">
|
||||||
|
<div class="panel-head">
|
||||||
|
<div>
|
||||||
|
<h2>Auditoria</h2>
|
||||||
|
<p class="hint">Os 100 eventos mais recentes.</p>
|
||||||
|
</div>
|
||||||
|
<button id="auditRefresh" type="button" class="btn">Atualizar</button>
|
||||||
|
</div>
|
||||||
|
<p id="auditStatus" role="status" hidden></p>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table class="data-table">
|
||||||
|
<thead><tr><th scope="col">Quando</th><th scope="col">Ação</th><th scope="col">Quem</th><th scope="col">IP</th><th scope="col">Êxito</th><th scope="col">Detalhe</th></tr></thead>
|
||||||
|
<tbody id="auditRows"></tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<footer class="foot">
|
<footer class="foot">
|
||||||
<span>Acauã · pré-lançamento</span>
|
<span>Acauã · pré-lançamento</span>
|
||||||
<span class="mono">MIT OR Apache-2.0</span>
|
<span class="mono">MIT OR Apache-2.0</span>
|
||||||
@@ -329,6 +493,22 @@
|
|||||||
</form>
|
</form>
|
||||||
</dialog>
|
</dialog>
|
||||||
|
|
||||||
|
<dialog id="reauthDlg" aria-labelledby="reauthTitle">
|
||||||
|
<form id="reauthForm">
|
||||||
|
<div class="dialog-head"><h2 id="reauthTitle">Confirme sua identidade</h2></div>
|
||||||
|
<p class="hint">Esta ação pede sua senha e, se o MFA estiver ativo, um código. Depois ela continua sozinha.</p>
|
||||||
|
<p id="reauthError" role="alert" hidden></p>
|
||||||
|
<label class="field"><span>Senha</span>
|
||||||
|
<input id="reauthPass" type="password" autocomplete="current-password" required></label>
|
||||||
|
<label class="field"><span>Código MFA ou de recuperação</span>
|
||||||
|
<input id="reauthCode" type="text" autocomplete="one-time-code" spellcheck="false"></label>
|
||||||
|
<menu>
|
||||||
|
<button type="button" id="reauthCancel" class="btn">Cancelar</button>
|
||||||
|
<button type="submit" class="btn primary">Confirmar</button>
|
||||||
|
</menu>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
|
||||||
<script type="module" src="/app.js"></script>
|
<script type="module" src="/app.js"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="pt-BR">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Entrar · Acauã</title>
|
||||||
|
<link rel="icon" href="/logo.png">
|
||||||
|
<link rel="stylesheet" href="/app.css">
|
||||||
|
</head>
|
||||||
|
<body class="auth-page">
|
||||||
|
<main class="auth-shell">
|
||||||
|
<div class="brand auth-brand">
|
||||||
|
<img class="logo" src="/logo.png" alt="">
|
||||||
|
<div>
|
||||||
|
<strong>Acauã</strong>
|
||||||
|
<small>caça a ameaças em rede</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="panel auth-card">
|
||||||
|
<p id="authError" class="form-error" role="alert" hidden></p>
|
||||||
|
|
||||||
|
<form id="stSetup" class="auth-step" hidden>
|
||||||
|
<h1>Configuração inicial</h1>
|
||||||
|
<p class="hint">Nenhum administrador existe ainda. O código de configuração está no log do contêiner (<code>docker compose logs acaua</code>) e vale por 1 hora; ao reiniciar o serviço, um novo código é gerado se o anterior tiver expirado.</p>
|
||||||
|
<label class="field"><span>Código de configuração</span>
|
||||||
|
<input id="setupCode" type="text" autocomplete="off" spellcheck="false" required></label>
|
||||||
|
<label class="field"><span>Usuário administrador</span>
|
||||||
|
<input id="setupUser" type="text" autocomplete="username" spellcheck="false" required></label>
|
||||||
|
<label class="field"><span>Senha</span>
|
||||||
|
<input id="setupPass" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<p class="hint">Pelo menos 12 caracteres. Em seguida você cadastra o MFA, obrigatório para administradores.</p>
|
||||||
|
<button type="submit" class="btn primary">Criar administrador</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form id="stLogin" class="auth-step" hidden>
|
||||||
|
<h1>Entrar</h1>
|
||||||
|
<label class="field"><span>Usuário</span>
|
||||||
|
<input id="loginUser" type="text" autocomplete="username" spellcheck="false" required></label>
|
||||||
|
<label class="field"><span>Senha</span>
|
||||||
|
<input id="loginPass" type="password" autocomplete="current-password" required></label>
|
||||||
|
<button type="submit" class="btn primary">Entrar</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form id="stMfa" class="auth-step" hidden>
|
||||||
|
<h1>Código de verificação</h1>
|
||||||
|
<p class="hint">Digite o código de 6 dígitos do aplicativo autenticador ou um código de recuperação.</p>
|
||||||
|
<p id="mfaNext" class="notice notice-warn" hidden>
|
||||||
|
<span>O código usado no cadastro já foi gasto. Para concluir o login, espere o <strong>próximo</strong> código (até 30 s) ou use um código de recuperação.</span>
|
||||||
|
</p>
|
||||||
|
<p id="mfaCountdown" class="hint" hidden></p>
|
||||||
|
<label class="field"><span>Código</span>
|
||||||
|
<input id="mfaCode" type="text" autocomplete="one-time-code" spellcheck="false" required></label>
|
||||||
|
<button type="submit" class="btn primary">Verificar</button>
|
||||||
|
<button type="button" class="link-btn" data-restart>Voltar ao login</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<form id="stEnroll" class="auth-step" hidden>
|
||||||
|
<h1>Cadastrar MFA</h1>
|
||||||
|
<p class="hint">Escaneie o QR no aplicativo autenticador ou digite a chave manual. Depois, informe o código gerado.</p>
|
||||||
|
<img id="enrollQr" class="qr" alt="QR do cadastro de MFA">
|
||||||
|
<label class="field"><span>Chave manual</span>
|
||||||
|
<input id="enrollKey" class="mono" type="text" readonly></label>
|
||||||
|
<label class="field"><span>Código de 6 dígitos</span>
|
||||||
|
<input id="enrollCode" type="text" inputmode="numeric" autocomplete="one-time-code" required></label>
|
||||||
|
<button type="submit" class="btn primary">Confirmar cadastro</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div id="stRecovery" class="auth-step" hidden>
|
||||||
|
<h1>Códigos de recuperação</h1>
|
||||||
|
<p class="notice notice-warn"><span>Guarde estes códigos agora: eles só aparecem esta vez e cada um funciona uma única vez.</span></p>
|
||||||
|
<pre id="recoveryCodes" class="secret-box"></pre>
|
||||||
|
<div class="secret-actions">
|
||||||
|
<button id="recoveryCopy" type="button" class="btn">Copiar</button>
|
||||||
|
<button id="recoveryDownload" type="button" class="btn">Baixar</button>
|
||||||
|
</div>
|
||||||
|
<button id="recoveryDone" type="button" class="btn primary">Já guardei os códigos</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form id="stPassword" class="auth-step" hidden>
|
||||||
|
<h1>Trocar a senha</h1>
|
||||||
|
<p class="hint">Esta conta precisa de uma senha nova antes de continuar.</p>
|
||||||
|
<label class="field"><span>Senha atual</span>
|
||||||
|
<input id="pwCurrent" type="password" autocomplete="current-password" required></label>
|
||||||
|
<label class="field"><span>Nova senha</span>
|
||||||
|
<input id="pwNew" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<label class="field"><span>Repita a nova senha</span>
|
||||||
|
<input id="pwRepeat" type="password" autocomplete="new-password" minlength="12" required></label>
|
||||||
|
<button type="submit" class="btn primary">Trocar a senha e entrar</button>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="auth-prefs">
|
||||||
|
<label class="field compact"><span>Idioma</span>
|
||||||
|
<select id="langSel">
|
||||||
|
<option value="auto">Auto</option>
|
||||||
|
<option value="pt">Português</option>
|
||||||
|
<option value="en">English</option>
|
||||||
|
</select></label>
|
||||||
|
<label class="field compact"><span>Tema</span>
|
||||||
|
<select id="themeSel">
|
||||||
|
<option value="auto">Auto</option>
|
||||||
|
<option value="light">Claro</option>
|
||||||
|
<option value="dark">Escuro</option>
|
||||||
|
</select></label>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<script type="module" src="/login.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
// Public page: imports only the other public files. The pending token lives in
|
||||||
|
// this module's memory and nowhere else.
|
||||||
|
import { setLang, tr, serverMessage } from './i18n.js';
|
||||||
|
|
||||||
|
const $ = (selector) => document.querySelector(selector);
|
||||||
|
const STEPS = ['stSetup', 'stLogin', 'stMfa', 'stEnroll', 'stRecovery', 'stPassword'];
|
||||||
|
const errorBox = $('#authError');
|
||||||
|
|
||||||
|
let pending = null;
|
||||||
|
let setupRequired = false;
|
||||||
|
let countdown = null;
|
||||||
|
|
||||||
|
function showError(text) {
|
||||||
|
errorBox.textContent = text;
|
||||||
|
errorBox.hidden = !text;
|
||||||
|
}
|
||||||
|
|
||||||
|
function show(step) {
|
||||||
|
showError('');
|
||||||
|
for (const id of STEPS) document.getElementById(id).hidden = id !== step;
|
||||||
|
document.getElementById(step).querySelector('input:not([readonly])')?.focus();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function post(path, body, headers = {}) {
|
||||||
|
const response = await fetch(path, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json', ...headers },
|
||||||
|
body: JSON.stringify(body ?? {}),
|
||||||
|
});
|
||||||
|
const data = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = new Error(serverMessage(data.error || response.statusText));
|
||||||
|
error.retryAfter = response.headers.get('Retry-After');
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
function explain(error) {
|
||||||
|
if (!error.retryAfter) return error.message;
|
||||||
|
return `${error.message} ${tr('Tente de novo em {n} s.').replace('{n}', error.retryAfter)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Runs a form action, showing a failure and keeping the button from doubling it. */
|
||||||
|
function onSubmit(form, action) {
|
||||||
|
form.addEventListener('submit', async (event) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const button = form.querySelector('button[type="submit"]');
|
||||||
|
button.disabled = true;
|
||||||
|
showError('');
|
||||||
|
try {
|
||||||
|
await action();
|
||||||
|
} catch (error) {
|
||||||
|
showError(explain(error));
|
||||||
|
} finally {
|
||||||
|
button.disabled = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function restart(notice = '') {
|
||||||
|
pending = null;
|
||||||
|
stopCountdown();
|
||||||
|
for (const input of document.querySelectorAll('input:not(#loginUser)')) input.value = '';
|
||||||
|
show(setupRequired ? 'stSetup' : 'stLogin');
|
||||||
|
showError(notice);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopCountdown() {
|
||||||
|
if (countdown) window.clearInterval(countdown);
|
||||||
|
countdown = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function startCountdown() {
|
||||||
|
const out = $('#mfaCountdown');
|
||||||
|
const tick = () => {
|
||||||
|
const left = 30 - (Math.floor(Date.now() / 1000) % 30);
|
||||||
|
out.textContent = tr('Próximo código em {n} s.').replace('{n}', String(left));
|
||||||
|
};
|
||||||
|
stopCountdown();
|
||||||
|
out.hidden = false;
|
||||||
|
tick();
|
||||||
|
countdown = window.setInterval(tick, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function beginEnroll() {
|
||||||
|
const data = await post('/api/auth/enroll/start', {}, { 'X-Acaua-Pending': pending });
|
||||||
|
$('#enrollQr').src = `data:image/png;base64,${data.qr_png_base64}`;
|
||||||
|
$('#enrollKey').value = data.manual_key;
|
||||||
|
$('#enrollCode').value = '';
|
||||||
|
show('stEnroll');
|
||||||
|
}
|
||||||
|
|
||||||
|
function advance(reply) {
|
||||||
|
if (reply.step === 'session') {
|
||||||
|
location.replace('/');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
pending = reply.pending;
|
||||||
|
if (reply.step === 'mfa_required') {
|
||||||
|
$('#mfaCode').value = '';
|
||||||
|
$('#mfaNext').hidden = true;
|
||||||
|
$('#mfaCountdown').hidden = true;
|
||||||
|
show('stMfa');
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
if (reply.step === 'mfa_enroll_required') return beginEnroll();
|
||||||
|
if (reply.step === 'password_change_required') {
|
||||||
|
show('stPassword');
|
||||||
|
return Promise.resolve();
|
||||||
|
}
|
||||||
|
throw new Error(serverMessage('internal error'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function showRecovery(codes) {
|
||||||
|
$('#recoveryCodes').textContent = codes.join('\n');
|
||||||
|
show('stRecovery');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function copySecret(button, text) {
|
||||||
|
const label = button.textContent;
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
button.textContent = tr('Copiado');
|
||||||
|
window.setTimeout(() => { button.textContent = label; }, 1400);
|
||||||
|
} catch {
|
||||||
|
showError(tr('Não foi possível copiar. Selecione o texto e copie à mão.'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function download(name, text) {
|
||||||
|
const url = URL.createObjectURL(new Blob([`${text}\n`], { type: 'text/plain' }));
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = name;
|
||||||
|
link.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
function applyTheme(pref) {
|
||||||
|
const light = window.matchMedia('(prefers-color-scheme: light)').matches;
|
||||||
|
document.documentElement.dataset.theme = pref === 'auto' ? (light ? 'light' : 'dark') : pref;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bindPrefs() {
|
||||||
|
const lang = $('#langSel');
|
||||||
|
const theme = $('#themeSel');
|
||||||
|
lang.value = localStorage.getItem('acaua-lang') || 'auto';
|
||||||
|
theme.value = localStorage.getItem('acaua-theme') || 'auto';
|
||||||
|
setLang(lang.value);
|
||||||
|
applyTheme(theme.value);
|
||||||
|
lang.addEventListener('change', () => {
|
||||||
|
localStorage.setItem('acaua-lang', lang.value);
|
||||||
|
setLang(lang.value);
|
||||||
|
});
|
||||||
|
theme.addEventListener('change', () => {
|
||||||
|
localStorage.setItem('acaua-theme', theme.value);
|
||||||
|
applyTheme(theme.value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function init() {
|
||||||
|
bindPrefs();
|
||||||
|
|
||||||
|
onSubmit($('#stSetup'), async () => {
|
||||||
|
pending = (await post('/api/auth/bootstrap', {
|
||||||
|
code: $('#setupCode').value.trim(),
|
||||||
|
username: $('#setupUser').value,
|
||||||
|
password: $('#setupPass').value,
|
||||||
|
})).pending;
|
||||||
|
setupRequired = false;
|
||||||
|
$('#loginUser').value = $('#setupUser').value;
|
||||||
|
$('#setupPass').value = '';
|
||||||
|
await beginEnroll();
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit($('#stLogin'), async () => {
|
||||||
|
const reply = await post('/api/auth/login', {
|
||||||
|
username: $('#loginUser').value,
|
||||||
|
password: $('#loginPass').value,
|
||||||
|
});
|
||||||
|
await advance(reply);
|
||||||
|
$('#loginPass').value = '';
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit($('#stMfa'), async () => {
|
||||||
|
const reply = await post('/api/auth/mfa', { pending, code: $('#mfaCode').value.trim() });
|
||||||
|
stopCountdown();
|
||||||
|
await advance(reply);
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit($('#stEnroll'), async () => {
|
||||||
|
const reply = await post(
|
||||||
|
'/api/auth/enroll/confirm',
|
||||||
|
{ code: $('#enrollCode').value.trim() },
|
||||||
|
{ 'X-Acaua-Pending': pending },
|
||||||
|
);
|
||||||
|
showRecovery(reply.recovery_codes);
|
||||||
|
});
|
||||||
|
|
||||||
|
onSubmit($('#stPassword'), async () => {
|
||||||
|
if ($('#pwNew').value !== $('#pwRepeat').value) throw new Error(tr('As senhas não coincidem.'));
|
||||||
|
await post('/api/auth/password-change-required', {
|
||||||
|
ticket: pending,
|
||||||
|
current: $('#pwCurrent').value,
|
||||||
|
new: $('#pwNew').value,
|
||||||
|
});
|
||||||
|
location.replace('/');
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll('[data-restart]').forEach((button) => {
|
||||||
|
button.addEventListener('click', () => restart());
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#recoveryCopy').addEventListener('click', (event) => {
|
||||||
|
copySecret(event.currentTarget, $('#recoveryCodes').textContent);
|
||||||
|
});
|
||||||
|
$('#recoveryDownload').addEventListener('click', () => {
|
||||||
|
download('acaua-codigos-de-recuperacao.txt', $('#recoveryCodes').textContent);
|
||||||
|
});
|
||||||
|
$('#recoveryDone').addEventListener('click', () => {
|
||||||
|
$('#recoveryCodes').textContent = '';
|
||||||
|
$('#mfaCode').value = '';
|
||||||
|
$('#mfaNext').hidden = false;
|
||||||
|
startCountdown();
|
||||||
|
show('stMfa');
|
||||||
|
});
|
||||||
|
|
||||||
|
const state = await fetch('/api/auth/state').then((r) => r.json());
|
||||||
|
if (state.authenticated) {
|
||||||
|
location.replace('/');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setupRequired = state.setup_required;
|
||||||
|
restart();
|
||||||
|
}
|
||||||
|
|
||||||
|
init().catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
showError(serverMessage('internal error'));
|
||||||
|
});
|
||||||
Vendored
+4
@@ -6,3 +6,7 @@ the interface: the UI stays vanilla HTML, CSS and JavaScript, like Guará and
|
|||||||
Sabiá.
|
Sabiá.
|
||||||
|
|
||||||
Document every vendored file with its project URL, version and license.
|
Document every vendored file with its project URL, version and license.
|
||||||
|
|
||||||
|
| File | Project | Version | License |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| `paged.polyfill.min.js` | Paged.js, https://gitlab.coko.foundation/pagedjs/pagedjs (paginates the executive report at `/relatorio`) | 0.4.3 | MIT |
|
||||||
+4
@@ -0,0 +1,4 @@
|
|||||||
|
/**
|
||||||
|
* @license Paged.js v0.4.3 | MIT | https://gitlab.coko.foundation/pagedjs/pagedjs
|
||||||
|
*/
|
||||||
|
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PagedPolyfill=t()}(this,(function(){"use strict";function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var t,n,r={exports:{}},a={exports:{}};var i,o,s,l,d=function(){},p=d(),c=function(e){return e!==p&&null!==e};function u(){return l||(l=1,s=(n?t:(n=1,t=function(){try{return Object.keys("primitive"),!0}catch(e){return!1}}))()?Object.keys:function(){if(o)return i;o=1;var e=c,t=Object.keys;return i=function(n){return t(e(n)?Object(n):n)}}()),s}var m,h,g=c,f=function(e){if(!g(e))throw new TypeError("Cannot use null or undefined");return e};var y,b,S=function(){var e,t=Object.assign;return"function"==typeof t&&(t(e={foo:"raz"},{bar:"dwa"},{trzy:"trzy"}),e.foo+e.bar+e.trzy==="razdwatrzy")}()?Object.assign:function(){if(h)return m;h=1;var e=u(),t=f,n=Math.max;return m=function(r,a){var i,o,s,l=n(arguments.length,2);for(r=Object(t(r)),s=function(e){try{r[e]=a[e]}catch(e){i||(i=e)}},o=1;o<l;++o)e(a=arguments[o]).forEach(s);if(void 0!==i)throw i;return r},m}(),v=c,x=Array.prototype.forEach,k=Object.create,w="razdwatrzy";var C,T="function"==typeof w.contains&&!0===w.contains("dwa")&&!1===w.contains("foo")?String.prototype.contains:function(){if(b)return y;b=1;var e=String.prototype.indexOf;return y=function(t){return e.call(this,t,arguments[1])>-1},y}(),_=S,z=function(e){var t=k(null);return x.call(arguments,(function(e){v(e)&&function(e,t){var n;for(n in e)t[n]=e[n]}(Object(e),t)})),t},O=function(e){return"function"==typeof e},A=T;C=a.exports=function(e,t){var n,r,a,i,o;return arguments.length<2||"string"!=typeof e?(i=t,t=e,e=null):i=arguments[2],null==e?(n=a=!0,r=!1):(n=A.call(e,"c"),r=A.call(e,"e"),a=A.call(e,"w")),o={value:t,configurable:n,enumerable:r,writable:a},i?_(z(i),o):o},C.gs=function(e,t,n){var r,a,i,o;return"string"!=typeof e?(i=n,n=t,t=e,e=null):i=arguments[3],null==t?t=void 0:O(t)?null==n?n=void 0:O(n)||(i=n,n=void 0):(i=t,t=n=void 0),null==e?(r=!0,a=!1):(r=A.call(e,"c"),a=A.call(e,"e")),o={get:t,set:n,configurable:r,enumerable:a},i?_(z(i),o):o};var E=a.exports,j=function(e){if("function"!=typeof e)throw new TypeError(e+" is not a function");return e};!function(e,t){var n,r,a,i,o,s,l,d=E,p=j,c=Function.prototype.apply,u=Function.prototype.call,m=Object.create,h=Object.defineProperty,g=Object.defineProperties,f=Object.prototype.hasOwnProperty,y={configurable:!0,enumerable:!1,writable:!0};n=function(e,t){var n;return p(t),f.call(this,"__ee__")?n=this.__ee__:(n=y.value=m(null),h(this,"__ee__",y),y.value=null),n[e]?"object"==typeof n[e]?n[e].push(t):n[e]=[n[e],t]:n[e]=t,this},r=function(e,t){var r,i;return p(t),i=this,n.call(this,e,r=function(){a.call(i,e,r),c.call(t,this,arguments)}),r.__eeOnceListener__=t,this},a=function(e,t){var n,r,a,i;if(p(t),!f.call(this,"__ee__"))return this;if(!(n=this.__ee__)[e])return this;if("object"==typeof(r=n[e]))for(i=0;a=r[i];++i)a!==t&&a.__eeOnceListener__!==t||(2===r.length?n[e]=r[i?0:1]:r.splice(i,1));else r!==t&&r.__eeOnceListener__!==t||delete n[e];return this},i=function(e){var t,n,r,a,i;if(f.call(this,"__ee__")&&(a=this.__ee__[e]))if("object"==typeof a){for(n=arguments.length,i=new Array(n-1),t=1;t<n;++t)i[t-1]=arguments[t];for(a=a.slice(),t=0;r=a[t];++t)c.call(r,this,i)}else switch(arguments.length){case 1:u.call(a,this);break;case 2:u.call(a,this,arguments[1]);break;case 3:u.call(a,this,arguments[1],arguments[2]);break;default:for(n=arguments.length,i=new Array(n-1),t=1;t<n;++t)i[t-1]=arguments[t];c.call(a,this,i)}},o={on:n,once:r,off:a,emit:i},s={on:d(n),once:d(r),off:d(a),emit:d(i)},l=g({},s),e.exports=t=function(e){return null==e?m(l):g(Object(e),s)},t.methods=o}(r,r.exports);var W=r.exports,L=e(W);class B{constructor(e){this.context=e||this,this.hooks=[]}register(){for(var e=0;e<arguments.length;++e)if("function"==typeof arguments[e])this.hooks.push(arguments[e]);else for(var t=0;t<arguments[e].length;++t)this.hooks.push(arguments[e][t])}trigger(){var e=arguments,t=this.context,n=[];return this.hooks.forEach((function(r){var a=r.apply(t,e);a&&"function"==typeof a.then?n.push(a):n.push(new Promise(((e,t)=>{e(a)})))})),Promise.all(n)}triggerSync(){var e=arguments,t=this.context,n=[];return this.hooks.forEach((function(r){var a=r.apply(t,e);n.push(a)})),n}list(){return this.hooks}clear(){return this.hooks=[]}}function P(e){if(!e)return;let t;if(void 0!==e.getBoundingClientRect)t=e.getBoundingClientRect();else{let n=document.createRange();n.selectNode(e),t=n.getBoundingClientRect()}return t}function q(e){if(!e)return;let t;if(void 0!==e.getClientRects)t=e.getClientRects();else{let n=document.createRange();n.selectNode(e),t=n.getClientRects()}return t}function M(){var e=(new Date).getTime();return"undefined"!=typeof performance&&"function"==typeof performance.now&&(e+=performance.now()),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replaceLine truncated
|
||||||
@@ -15,12 +15,20 @@ path = "src/main.rs"
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
acaua-core = { path = "../acaua-core" }
|
acaua-core = { path = "../acaua-core" }
|
||||||
axum = "0.8"
|
axum = "0.8"
|
||||||
|
axum-server = { version = "0.8.0", features = ["tls-rustls"] }
|
||||||
clap = { version = "4", features = ["derive"] }
|
clap = { version = "4", features = ["derive"] }
|
||||||
|
ipnet = "2"
|
||||||
mime_guess = "2"
|
mime_guess = "2"
|
||||||
rust-embed = "8"
|
rust-embed = "8"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal"] }
|
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "signal", "sync"] }
|
||||||
tower-http = { version = "0.6", features = ["compression-gzip", "cors", "trace"] }
|
tower-http = { version = "0.6", features = ["compression-gzip", "trace"] }
|
||||||
tracing = "0.1"
|
tracing = "0.1"
|
||||||
tracing-subscriber = "0.3"
|
tracing-subscriber = "0.3"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
http-body-util = "0.1"
|
||||||
|
tempfile = "3"
|
||||||
|
totp-rs = { version = "6.0.0", features = ["otpauth"] }
|
||||||
|
tower = { version = "0.5", features = ["util"] }
|
||||||
@@ -0,0 +1,979 @@
|
|||||||
|
//! The HTTP face of authentication: the global gate and the `/api/auth` and
|
||||||
|
//! `/api/admin` handlers. Decisions about accounts stay in `acaua_core::auth`.
|
||||||
|
//!
|
||||||
|
//! The session token travels only in the cookie, and that cookie is only ever
|
||||||
|
//! built from a `NewSession` the core issued. Request structs here hold
|
||||||
|
//! passwords and codes, so none of them derives `Debug`.
|
||||||
|
|
||||||
|
use crate::web::{access_of, is_public, is_public_asset, Access, AppState};
|
||||||
|
use acaua_core::auth::{
|
||||||
|
csrf_matches, csrf_token, AuthService, LoginAttempt, LoginStep, NewSession, PendingMfa,
|
||||||
|
Principal, Role, Scope, TotpEnrollment, Via,
|
||||||
|
};
|
||||||
|
use acaua_core::{AcauaError, AuthFailure};
|
||||||
|
use axum::extract::rejection::JsonRejection;
|
||||||
|
use axum::extract::{ConnectInfo, FromRequest, FromRequestParts, Query, Request, State};
|
||||||
|
use axum::http::request::Parts;
|
||||||
|
use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode};
|
||||||
|
use axum::middleware::Next;
|
||||||
|
use axum::response::{IntoResponse, Response};
|
||||||
|
use axum::{Extension, Json};
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
pub const MAX_BODY_BYTES: usize = 64 * 1024;
|
||||||
|
pub const ARGON2_CONCURRENCY: usize = 8;
|
||||||
|
const SESSION_COOKIE: &str = "acaua_session";
|
||||||
|
const CSRF_HEADER: &str = "x-acaua-csrf";
|
||||||
|
const PENDING_HEADER: &str = "x-acaua-pending";
|
||||||
|
const LOGIN_PAGE: &str = "/login.html";
|
||||||
|
const AUDIT_DEFAULT: usize = 200;
|
||||||
|
const AUDIT_MAX: usize = 1000;
|
||||||
|
/// The longest a login waits for a hashing permit.
|
||||||
|
const LOGIN_QUEUE_WAIT: Duration = Duration::from_secs(30);
|
||||||
|
|
||||||
|
/// A clock before 1970 fails closed: everything looks expired.
|
||||||
|
pub fn unix_now() -> u64 {
|
||||||
|
SystemTime::now()
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.map(|d| d.as_secs())
|
||||||
|
.unwrap_or(u64::MAX)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Errors ---------------------------------------------------------------
|
||||||
|
|
||||||
|
pub enum ApiError {
|
||||||
|
Core(AcauaError),
|
||||||
|
Fixed(StatusCode, &'static str),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<AcauaError> for ApiError {
|
||||||
|
fn from(e: AcauaError) -> Self {
|
||||||
|
ApiError::Core(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<AuthFailure> for ApiError {
|
||||||
|
fn from(f: AuthFailure) -> Self {
|
||||||
|
ApiError::Core(f.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn internal() -> ApiError {
|
||||||
|
ApiError::Fixed(StatusCode::INTERNAL_SERVER_ERROR, "internal error")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn error_response(status: StatusCode, message: &str) -> Response {
|
||||||
|
(status, Json(serde_json::json!({ "error": message }))).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failure_response(f: &AuthFailure) -> Response {
|
||||||
|
use AuthFailure as F;
|
||||||
|
let (status, message) = match f {
|
||||||
|
F::InvalidCredentials => (StatusCode::UNAUTHORIZED, "invalid credentials"),
|
||||||
|
F::Throttled { retry_after_secs } => {
|
||||||
|
let mut r = error_response(StatusCode::TOO_MANY_REQUESTS, "too many attempts");
|
||||||
|
r.headers_mut()
|
||||||
|
.insert(header::RETRY_AFTER, HeaderValue::from(*retry_after_secs));
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
F::SetupRequired => (StatusCode::CONFLICT, "setup required"),
|
||||||
|
F::BootstrapInvalid => (StatusCode::UNAUTHORIZED, "invalid setup code"),
|
||||||
|
F::LastAdmin => (StatusCode::CONFLICT, "the last administrator must remain"),
|
||||||
|
F::MfaMandatory => (StatusCode::CONFLICT, "MFA is mandatory for administrators"),
|
||||||
|
F::MfaNotEnabled => (StatusCode::CONFLICT, "MFA is not enabled"),
|
||||||
|
F::EnrollmentNotStarted => (StatusCode::CONFLICT, "no enrollment in progress"),
|
||||||
|
F::UsernameTaken => (StatusCode::CONFLICT, "username is already in use"),
|
||||||
|
F::UserNotFound | F::NotFound => (StatusCode::NOT_FOUND, "not found"),
|
||||||
|
F::ReauthRequired => (StatusCode::FORBIDDEN, "recent authentication required"),
|
||||||
|
F::Forbidden => (StatusCode::FORBIDDEN, "forbidden"),
|
||||||
|
other => {
|
||||||
|
tracing::error!(error = %other, "authentication backend failure");
|
||||||
|
(StatusCode::INTERNAL_SERVER_ERROR, "internal error")
|
||||||
|
}
|
||||||
|
};
|
||||||
|
error_response(status, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoResponse for ApiError {
|
||||||
|
fn into_response(self) -> Response {
|
||||||
|
match self {
|
||||||
|
ApiError::Fixed(status, message) => error_response(status, message),
|
||||||
|
ApiError::Core(AcauaError::Auth(f)) => failure_response(&f),
|
||||||
|
// Written by the core's validators; never echoes the input.
|
||||||
|
ApiError::Core(AcauaError::InvalidInput(message)) => {
|
||||||
|
error_response(StatusCode::BAD_REQUEST, &message)
|
||||||
|
}
|
||||||
|
ApiError::Core(other) => {
|
||||||
|
tracing::error!(error = %other, "request failed");
|
||||||
|
error_response(StatusCode::INTERNAL_SERVER_ERROR, "internal error")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Json`, with fixed refusals: a parser message could quote the input.
|
||||||
|
pub struct JsonBody<T>(pub T);
|
||||||
|
|
||||||
|
impl<S: Send + Sync, T: DeserializeOwned> FromRequest<S> for JsonBody<T> {
|
||||||
|
type Rejection = ApiError;
|
||||||
|
|
||||||
|
async fn from_request(req: Request, state: &S) -> Result<Self, ApiError> {
|
||||||
|
Json::<T>::from_request(req, state)
|
||||||
|
.await
|
||||||
|
.map(|Json(v)| JsonBody(v))
|
||||||
|
.map_err(|e: JsonRejection| {
|
||||||
|
let status = e.status();
|
||||||
|
let message = match status {
|
||||||
|
StatusCode::PAYLOAD_TOO_LARGE => "request body too large",
|
||||||
|
StatusCode::UNSUPPORTED_MEDIA_TYPE => "expected application/json",
|
||||||
|
_ => "invalid request",
|
||||||
|
};
|
||||||
|
ApiError::Fixed(status, message)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Blocking work --------------------------------------------------------
|
||||||
|
|
||||||
|
/// Store and audit calls take a file lock and fsync.
|
||||||
|
pub async fn blocking<T, F>(f: F) -> Result<T, ApiError>
|
||||||
|
where
|
||||||
|
T: Send + 'static,
|
||||||
|
F: FnOnce() -> Result<T, AcauaError> + Send + 'static,
|
||||||
|
{
|
||||||
|
match tokio::task::spawn_blocking(f).await {
|
||||||
|
Ok(result) => result.map_err(ApiError::Core),
|
||||||
|
Err(_) => Err(internal()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// As `blocking`, for calls that run Argon2: its memory cost multiplies with
|
||||||
|
/// concurrency, so only a few run at a time.
|
||||||
|
async fn hashing<T, F>(state: &AppState, f: F) -> Result<T, ApiError>
|
||||||
|
where
|
||||||
|
T: Send + 'static,
|
||||||
|
F: FnOnce() -> Result<T, AcauaError> + Send + 'static,
|
||||||
|
{
|
||||||
|
// The permit moves into the closure: a dropped request cancels this future
|
||||||
|
// but not the blocking task, whose Argon2 run must keep its slot to the end.
|
||||||
|
let permit = state
|
||||||
|
.argon2
|
||||||
|
.clone()
|
||||||
|
.acquire_owned()
|
||||||
|
.await
|
||||||
|
.map_err(|_| internal())?;
|
||||||
|
blocking(move || {
|
||||||
|
let _permit = permit;
|
||||||
|
f()
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Credentials ----------------------------------------------------------
|
||||||
|
|
||||||
|
/// The client address `Transport` allows us to believe.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct ClientIp(IpAddr);
|
||||||
|
|
||||||
|
/// A session token proved valid by the gate. No `Debug`: it is a credential.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SessionToken(String);
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct PendingToken(String);
|
||||||
|
|
||||||
|
/// The `Principal` the gate authenticated. The only way a handler gets one.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Auth(pub Principal);
|
||||||
|
|
||||||
|
impl<S: Send + Sync> FromRequestParts<S> for Auth {
|
||||||
|
type Rejection = ApiError;
|
||||||
|
|
||||||
|
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, ApiError> {
|
||||||
|
parts
|
||||||
|
.extensions
|
||||||
|
.get::<Auth>()
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(unauthenticated)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unauthenticated() -> ApiError {
|
||||||
|
ApiError::Fixed(StatusCode::UNAUTHORIZED, "authentication required")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn forbidden() -> ApiError {
|
||||||
|
AuthFailure::Forbidden.into()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session_cookie_value(headers: &HeaderMap) -> Option<String> {
|
||||||
|
headers
|
||||||
|
.get_all(header::COOKIE)
|
||||||
|
.iter()
|
||||||
|
.filter_map(|v| v.to_str().ok())
|
||||||
|
.flat_map(|v| v.split(';'))
|
||||||
|
.find_map(|pair| {
|
||||||
|
let (name, value) = pair.trim().split_once('=')?;
|
||||||
|
(name == SESSION_COOKIE && !value.is_empty()).then(|| value.to_string())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Credential {
|
||||||
|
Bearer(String),
|
||||||
|
Cookie(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An `Authorization` header decides alone: a bad one never falls back to the
|
||||||
|
/// cookie. Only API tokens are valid there, so a session cannot skip CSRF.
|
||||||
|
fn credential(headers: &HeaderMap) -> Result<Option<Credential>, ApiError> {
|
||||||
|
if let Some(value) = headers.get(header::AUTHORIZATION) {
|
||||||
|
let text = value.to_str().map_err(|_| unauthenticated())?;
|
||||||
|
return match text.split_once(' ') {
|
||||||
|
Some((scheme, token)) if scheme.eq_ignore_ascii_case("bearer") => {
|
||||||
|
Ok(Some(Credential::Bearer(token.trim().to_string())))
|
||||||
|
}
|
||||||
|
_ => Err(unauthenticated()),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Ok(session_cookie_value(headers).map(Credential::Cookie))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_safe(method: &Method) -> bool {
|
||||||
|
matches!(*method, Method::GET | Method::HEAD)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn require_admin(p: &Principal) -> Result<(), ApiError> {
|
||||||
|
if p.role == Role::Admin && p.scope == Scope::Admin {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(forbidden())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A refused request. Browsers navigating to a page go to the login; the rest
|
||||||
|
/// get the same 401, so unknown paths cannot be told from protected ones.
|
||||||
|
fn deny(method: &Method, path: &str, headers: &HeaderMap) -> Response {
|
||||||
|
let wants_html = headers
|
||||||
|
.get(header::ACCEPT)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.is_some_and(|v| v.contains("text/html"));
|
||||||
|
if is_safe(method) && wants_html && !path.starts_with("/api/") {
|
||||||
|
let mut r = StatusCode::SEE_OTHER.into_response();
|
||||||
|
r.headers_mut()
|
||||||
|
.insert(header::LOCATION, HeaderValue::from_static(LOGIN_PAGE));
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
unauthenticated().into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wraps the whole router, fallback included, so anything not listed in
|
||||||
|
/// `PUBLIC_ROUTES` needs a credential from the moment it exists.
|
||||||
|
pub async fn require_auth(State(state): State<AppState>, mut req: Request, next: Next) -> Response {
|
||||||
|
let method = req.method().clone();
|
||||||
|
let path = req.uri().path().to_string();
|
||||||
|
let peer = req
|
||||||
|
.extensions()
|
||||||
|
.get::<ConnectInfo<SocketAddr>>()
|
||||||
|
.map(|c| c.0.ip())
|
||||||
|
.unwrap_or(IpAddr::V4(Ipv4Addr::UNSPECIFIED));
|
||||||
|
let ip = state.transport.client_ip(peer, req.headers());
|
||||||
|
req.extensions_mut().insert(ClientIp(ip));
|
||||||
|
|
||||||
|
let mut response = if is_public(&method, &path) {
|
||||||
|
next.run(req).await
|
||||||
|
} else {
|
||||||
|
match gate(&state, &method, &path, &mut req).await {
|
||||||
|
Ok(()) => next.run(req).await,
|
||||||
|
Err(Refusal::Unauthenticated) => deny(&method, &path, req.headers()),
|
||||||
|
Err(Refusal::Other(e)) => e.into_response(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if !is_public_asset(&method, &path) {
|
||||||
|
response
|
||||||
|
.headers_mut()
|
||||||
|
.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
|
||||||
|
}
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Refusal {
|
||||||
|
Unauthenticated,
|
||||||
|
Other(ApiError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ApiError> for Refusal {
|
||||||
|
fn from(e: ApiError) -> Self {
|
||||||
|
Refusal::Other(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn gate(
|
||||||
|
state: &AppState,
|
||||||
|
method: &Method,
|
||||||
|
path: &str,
|
||||||
|
req: &mut Request,
|
||||||
|
) -> Result<(), Refusal> {
|
||||||
|
let access = access_of(method, path);
|
||||||
|
|
||||||
|
if access == Access::SessionOrPending {
|
||||||
|
if let Some(value) = req.headers().get(PENDING_HEADER) {
|
||||||
|
let token = value
|
||||||
|
.to_str()
|
||||||
|
.map_err(|_| Refusal::Unauthenticated)?
|
||||||
|
.to_string();
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let checked = token.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
authenticated(blocking(move || auth.pending_user(&checked, now)).await)?;
|
||||||
|
// A custom header is never sent by a cross-site form: no CSRF here.
|
||||||
|
req.extensions_mut().insert(PendingToken(token));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let cred = credential(req.headers())
|
||||||
|
.map_err(|_| Refusal::Unauthenticated)?
|
||||||
|
.ok_or(Refusal::Unauthenticated)?;
|
||||||
|
let now = unix_now();
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let principal = match &cred {
|
||||||
|
Credential::Bearer(token) => {
|
||||||
|
let token = token.clone();
|
||||||
|
authenticated(blocking(move || auth.authenticate_token(&token, now)).await)?
|
||||||
|
}
|
||||||
|
Credential::Cookie(token) => {
|
||||||
|
let token = token.clone();
|
||||||
|
authenticated(blocking(move || auth.authenticate_session(&token, now)).await)?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if let Credential::Cookie(token) = &cred {
|
||||||
|
if !is_safe(method) {
|
||||||
|
let sent = req
|
||||||
|
.headers()
|
||||||
|
.get(CSRF_HEADER)
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.unwrap_or("");
|
||||||
|
if !csrf_matches(token, sent) {
|
||||||
|
return Err(ApiError::Fixed(StatusCode::FORBIDDEN, "invalid CSRF token").into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if principal.via == Via::Token && !is_safe(method) && principal.scope != Scope::Admin {
|
||||||
|
return Err(forbidden().into());
|
||||||
|
}
|
||||||
|
match access {
|
||||||
|
Access::Authenticated => {}
|
||||||
|
Access::Session | Access::SessionOrPending => {
|
||||||
|
if principal.via != Via::Session {
|
||||||
|
return Err(forbidden().into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Access::Admin => require_admin(&principal)?,
|
||||||
|
Access::AdminRecentSession => {
|
||||||
|
require_admin(&principal)?;
|
||||||
|
if principal.via != Via::Session {
|
||||||
|
return Err(forbidden().into());
|
||||||
|
}
|
||||||
|
if !principal.recent_auth {
|
||||||
|
return Err(ApiError::from(AuthFailure::ReauthRequired).into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Credential::Cookie(token) = cred {
|
||||||
|
req.extensions_mut().insert(SessionToken(token));
|
||||||
|
}
|
||||||
|
req.extensions_mut().insert(Auth(principal));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A rejected credential is a plain 401. A backend failure stays a 500: it
|
||||||
|
/// still refuses, but must not look like a logout.
|
||||||
|
fn authenticated<T>(result: Result<T, ApiError>) -> Result<T, Refusal> {
|
||||||
|
result.map_err(|e| match e {
|
||||||
|
ApiError::Core(AcauaError::Auth(AuthFailure::InvalidCredentials)) => {
|
||||||
|
Refusal::Unauthenticated
|
||||||
|
}
|
||||||
|
other => Refusal::Other(other),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Cookies and login replies --------------------------------------------
|
||||||
|
|
||||||
|
fn with_cookie(mut response: Response, cookie: String) -> Response {
|
||||||
|
match HeaderValue::from_str(&cookie) {
|
||||||
|
Ok(value) => {
|
||||||
|
response.headers_mut().append(header::SET_COOKIE, value);
|
||||||
|
response
|
||||||
|
}
|
||||||
|
Err(_) => internal().into_response(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cookie_attrs(state: &AppState) -> &'static str {
|
||||||
|
if state.transport.cookie_secure() {
|
||||||
|
"; Path=/; HttpOnly; SameSite=Strict; Secure"
|
||||||
|
} else {
|
||||||
|
"; Path=/; HttpOnly; SameSite=Strict"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clear_cookie(state: &AppState, response: Response) -> Response {
|
||||||
|
let attrs = cookie_attrs(state);
|
||||||
|
with_cookie(response, format!("{SESSION_COOKIE}=; Max-Age=0{attrs}"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session reply. The token leaves the server only as this cookie.
|
||||||
|
fn session_reply(state: &AppState, session: &NewSession) -> Response {
|
||||||
|
let attrs = cookie_attrs(state);
|
||||||
|
let max_age = session.expires_at.saturating_sub(unix_now());
|
||||||
|
let reply = Json(serde_json::json!({
|
||||||
|
"step": "session",
|
||||||
|
"expires_at": session.expires_at,
|
||||||
|
}));
|
||||||
|
with_cookie(
|
||||||
|
reply.into_response(),
|
||||||
|
format!(
|
||||||
|
"{SESSION_COOKIE}={}; Max-Age={max_age}{attrs}",
|
||||||
|
session.token
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pending_reply(step: &str, pending: &PendingMfa) -> Response {
|
||||||
|
Json(serde_json::json!({
|
||||||
|
"step": step,
|
||||||
|
"pending": pending.token,
|
||||||
|
"expires_at": pending.expires_at,
|
||||||
|
}))
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step_reply(state: &AppState, step: &acaua_core::auth::LoginStep) -> Response {
|
||||||
|
use acaua_core::auth::LoginStep as L;
|
||||||
|
match step {
|
||||||
|
L::Session(s) => session_reply(state, s),
|
||||||
|
L::MfaRequired(p) => pending_reply("mfa_required", p),
|
||||||
|
L::MfaEnrollRequired(p) => pending_reply("mfa_enroll_required", p),
|
||||||
|
L::PasswordChangeRequired(p) => pending_reply("password_change_required", p),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Public handlers ------------------------------------------------------
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct StateReply {
|
||||||
|
setup_required: bool,
|
||||||
|
authenticated: bool,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
username: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
role: Option<Role>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
mfa_enabled: Option<bool>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
csrf: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn auth_state(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
) -> Result<Json<StateReply>, ApiError> {
|
||||||
|
let token = session_cookie_value(&headers);
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
blocking(move || {
|
||||||
|
let setup_required = !auth.has_admin()?;
|
||||||
|
let session = token.and_then(|t| {
|
||||||
|
let p = auth.authenticate_session(&t, now).ok()?;
|
||||||
|
Some((p, csrf_token(&t)))
|
||||||
|
});
|
||||||
|
Ok(Json(match session {
|
||||||
|
Some((p, csrf)) => StateReply {
|
||||||
|
setup_required,
|
||||||
|
authenticated: true,
|
||||||
|
mfa_enabled: Some(auth.mfa_enabled(&p.user_id)?),
|
||||||
|
username: Some(p.username),
|
||||||
|
role: Some(p.role),
|
||||||
|
csrf: Some(csrf),
|
||||||
|
},
|
||||||
|
None => StateReply {
|
||||||
|
setup_required,
|
||||||
|
authenticated: false,
|
||||||
|
username: None,
|
||||||
|
role: None,
|
||||||
|
mfa_enabled: None,
|
||||||
|
csrf: None,
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct BootstrapBody {
|
||||||
|
code: String,
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn bootstrap(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ClientIp(ip)): Extension<ClientIp>,
|
||||||
|
JsonBody(b): JsonBody<BootstrapBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
let pending = hashing(&state, move || {
|
||||||
|
auth.complete_bootstrap(&b.code, &b.username, &b.password, ip, now)
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(pending_reply("mfa_enroll_required", &pending))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct LoginBody {
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn login(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ClientIp(ip)): Extension<ClientIp>,
|
||||||
|
JsonBody(b): JsonBody<LoginBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let now = unix_now();
|
||||||
|
// Whatever can be refused without Argon2 is, before the queue for a permit,
|
||||||
|
// or a flood of hopeless attempts would stand in front of the owner.
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let username = b.username;
|
||||||
|
let queued = blocking(move || {
|
||||||
|
let attempt = auth.login_begin(&username, ip, now)?;
|
||||||
|
Ok(QueuedLogin {
|
||||||
|
auth,
|
||||||
|
attempt: Some(attempt),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let step = finish_queued(&state, queued, b.password, LOGIN_QUEUE_WAIT).await?;
|
||||||
|
Ok(step_reply(&state, &step))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Evaluates a queued login once a permit is free. Past `wait` it is refused
|
||||||
|
/// like any other throttled attempt, and gives back what it reserved.
|
||||||
|
pub(crate) async fn finish_queued(
|
||||||
|
state: &AppState,
|
||||||
|
mut queued: QueuedLogin,
|
||||||
|
password: String,
|
||||||
|
wait: Duration,
|
||||||
|
) -> Result<LoginStep, ApiError> {
|
||||||
|
// Only the queue is timed: once the hash runs, it runs to its answer. Leaving
|
||||||
|
// here drops `queued`, which gives back what the attempt reserved.
|
||||||
|
let permit = match tokio::time::timeout(wait, state.argon2.clone().acquire_owned()).await {
|
||||||
|
Ok(permit) => permit.map_err(|_| internal())?,
|
||||||
|
Err(_) => {
|
||||||
|
return Err(AuthFailure::Throttled {
|
||||||
|
retry_after_secs: wait.as_secs().max(1),
|
||||||
|
}
|
||||||
|
.into())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
blocking(move || {
|
||||||
|
let _permit = permit;
|
||||||
|
let attempt = queued
|
||||||
|
.attempt
|
||||||
|
.take()
|
||||||
|
.ok_or(AuthFailure::InvalidCredentials)?;
|
||||||
|
// The clock now, not at arrival: the queue took time.
|
||||||
|
queued.auth.login_finish(attempt, &password, unix_now())
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A login between its checks and its evaluation. A client that disconnects
|
||||||
|
/// while queued made no guess, so what it reserved goes back.
|
||||||
|
pub(crate) struct QueuedLogin {
|
||||||
|
pub(crate) auth: Arc<AuthService>,
|
||||||
|
pub(crate) attempt: Option<LoginAttempt>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for QueuedLogin {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if let Some(attempt) = self.attempt.take() {
|
||||||
|
self.auth.login_abandon(attempt);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct MfaBody {
|
||||||
|
pending: String,
|
||||||
|
code: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn mfa(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
JsonBody(b): JsonBody<MfaBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
let step = blocking(move || auth.confirm_mfa(&b.pending, &b.code, now)).await?;
|
||||||
|
Ok(step_reply(&state, &step))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct RequiredPasswordBody {
|
||||||
|
ticket: String,
|
||||||
|
current: String,
|
||||||
|
new: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn password_change_required(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
JsonBody(b): JsonBody<RequiredPasswordBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
let session = hashing(&state, move || {
|
||||||
|
auth.change_required_password(&b.ticket, &b.current, &b.new, now)
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(session_reply(&state, &session))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Session handlers -----------------------------------------------------
|
||||||
|
|
||||||
|
fn ok_reply() -> Response {
|
||||||
|
Json(serde_json::json!({ "ok": true })).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session behind a `Via::Session` principal.
|
||||||
|
fn session_token(parts: &axum::http::Extensions) -> Result<String, ApiError> {
|
||||||
|
parts
|
||||||
|
.get::<SessionToken>()
|
||||||
|
.map(|t| t.0.clone())
|
||||||
|
.ok_or_else(unauthenticated)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn logout(State(state): State<AppState>, req: Request) -> Result<Response, ApiError> {
|
||||||
|
let token = session_token(req.extensions())?;
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
blocking(move || auth.logout(&token, now)).await?;
|
||||||
|
Ok(clear_cookie(&state, ok_reply()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct ReauthBody {
|
||||||
|
password: String,
|
||||||
|
code: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn reauth(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
Extension(SessionToken(token)): Extension<SessionToken>,
|
||||||
|
JsonBody(b): JsonBody<ReauthBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
hashing(&state, move || {
|
||||||
|
auth.reauthenticate(&p.user_id, &token, &b.password, b.code.as_deref(), now)
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(ok_reply())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct PasswordBody {
|
||||||
|
current: String,
|
||||||
|
new: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn change_password(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
Extension(SessionToken(token)): Extension<SessionToken>,
|
||||||
|
Extension(ClientIp(ip)): Extension<ClientIp>,
|
||||||
|
JsonBody(b): JsonBody<PasswordBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
hashing(&state, move || {
|
||||||
|
auth.change_password(&p.user_id, &b.current, &b.new, Some(&token), Some(ip), now)
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(ok_reply())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Who is enrolling: the first-login pending token, or a session that
|
||||||
|
/// reauthenticated recently.
|
||||||
|
pub enum EnrollActor {
|
||||||
|
Pending(String),
|
||||||
|
Session(Principal),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<S: Send + Sync> FromRequestParts<S> for EnrollActor {
|
||||||
|
type Rejection = ApiError;
|
||||||
|
|
||||||
|
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, ApiError> {
|
||||||
|
if let Some(PendingToken(token)) = parts.extensions.get::<PendingToken>() {
|
||||||
|
return Ok(EnrollActor::Pending(token.clone()));
|
||||||
|
}
|
||||||
|
let Auth(p) = parts
|
||||||
|
.extensions
|
||||||
|
.get::<Auth>()
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(unauthenticated)?;
|
||||||
|
if !p.recent_auth {
|
||||||
|
return Err(AuthFailure::ReauthRequired.into());
|
||||||
|
}
|
||||||
|
Ok(EnrollActor::Session(p))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Serialize)]
|
||||||
|
pub struct EnrollReply {
|
||||||
|
uri: String,
|
||||||
|
qr_png_base64: String,
|
||||||
|
manual_key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<TotpEnrollment> for EnrollReply {
|
||||||
|
fn from(e: TotpEnrollment) -> Self {
|
||||||
|
Self {
|
||||||
|
uri: e.uri,
|
||||||
|
qr_png_base64: e.qr_png_base64,
|
||||||
|
manual_key: e.manual_key,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn enroll_start(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
actor: EnrollActor,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
let enrollment = blocking(move || match actor {
|
||||||
|
EnrollActor::Pending(token) => auth.start_enrollment_pending(&token, now),
|
||||||
|
EnrollActor::Session(p) => auth.start_enrollment(&p.user_id, now),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(Json(EnrollReply::from(enrollment)).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct CodeBody {
|
||||||
|
code: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn enroll_confirm(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Extension(ClientIp(ip)): Extension<ClientIp>,
|
||||||
|
actor: EnrollActor,
|
||||||
|
JsonBody(b): JsonBody<CodeBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
let from_session = matches!(actor, EnrollActor::Session(_));
|
||||||
|
let codes = blocking(move || match actor {
|
||||||
|
EnrollActor::Pending(token) => auth.confirm_enrollment_pending(&token, &b.code, now),
|
||||||
|
EnrollActor::Session(p) => auth.confirm_enrollment(&p.user_id, &b.code, Some(ip), now),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
let reply = Json(serde_json::json!({ "recovery_codes": codes })).into_response();
|
||||||
|
// Activation ends every session of the user, this one too.
|
||||||
|
Ok(if from_session {
|
||||||
|
clear_cookie(&state, reply)
|
||||||
|
} else {
|
||||||
|
reply
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn mfa_disable(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
Extension(SessionToken(token)): Extension<SessionToken>,
|
||||||
|
Extension(ClientIp(ip)): Extension<ClientIp>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
if !p.recent_auth {
|
||||||
|
return Err(AuthFailure::ReauthRequired.into());
|
||||||
|
}
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
blocking(move || auth.disable_mfa(&p.username, &p.user_id, Some(&token), Some(ip), now))
|
||||||
|
.await?;
|
||||||
|
Ok(ok_reply())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct OwnerQuery {
|
||||||
|
user_id: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The core's listings take no actor: the check lives here.
|
||||||
|
fn listing_target(p: &Principal, asked: Option<String>) -> Result<String, ApiError> {
|
||||||
|
match asked {
|
||||||
|
Some(id) if id != p.user_id => {
|
||||||
|
require_admin(p)?;
|
||||||
|
Ok(id)
|
||||||
|
}
|
||||||
|
_ => Ok(p.user_id.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn sessions_list(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
Query(q): Query<OwnerQuery>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let target = listing_target(&p, q.user_id)?;
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
let list = blocking(move || auth.list_sessions(&target, now)).await?;
|
||||||
|
Ok(Json(list).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct IdBody {
|
||||||
|
id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn sessions_revoke(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
JsonBody(b): JsonBody<IdBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
blocking(move || auth.revoke_session(&p, &b.id, now)).await?;
|
||||||
|
Ok(ok_reply())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn tokens_list(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
Query(q): Query<OwnerQuery>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let target = listing_target(&p, q.user_id)?;
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
let list = blocking(move || auth.list_tokens(&target, now)).await?;
|
||||||
|
Ok(Json(list).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct TokenBody {
|
||||||
|
name: String,
|
||||||
|
scope: Scope,
|
||||||
|
expires_at: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn tokens_create(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
JsonBody(b): JsonBody<TokenBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
let made =
|
||||||
|
blocking(move || auth.create_api_token(&p, &b.name, b.scope, b.expires_at, now)).await?;
|
||||||
|
Ok(Json(serde_json::json!({
|
||||||
|
"id": made.id,
|
||||||
|
"name": made.name,
|
||||||
|
"token": made.token,
|
||||||
|
"scope": made.scope,
|
||||||
|
"expires_at": made.expires_at,
|
||||||
|
}))
|
||||||
|
.into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn tokens_revoke(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
JsonBody(b): JsonBody<IdBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
blocking(move || auth.revoke_token(&p, &b.id, now)).await?;
|
||||||
|
Ok(ok_reply())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Admin handlers (the gate already ran its admin check) ----------------
|
||||||
|
|
||||||
|
pub async fn users_list(State(state): State<AppState>) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let list = blocking(move || auth.list_users()).await?;
|
||||||
|
Ok(Json(list).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct NewUserBody {
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
role: Role,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn users_create(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
JsonBody(b): JsonBody<NewUserBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
let id = hashing(&state, move || {
|
||||||
|
auth.create_user(&p.username, &b.username, &b.password, b.role, now)
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(Json(serde_json::json!({ "id": id })).into_response())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct RoleBody {
|
||||||
|
id: String,
|
||||||
|
role: Role,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn users_set_role(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
JsonBody(b): JsonBody<RoleBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
blocking(move || auth.set_role(&p.username, &b.id, b.role, now)).await?;
|
||||||
|
Ok(ok_reply())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn users_delete(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Auth(p): Auth,
|
||||||
|
JsonBody(b): JsonBody<IdBody>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let now = unix_now();
|
||||||
|
blocking(move || auth.delete_user(&p.username, &b.id, now)).await?;
|
||||||
|
Ok(ok_reply())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize)]
|
||||||
|
pub struct AuditQuery {
|
||||||
|
limit: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn audit(
|
||||||
|
State(state): State<AppState>,
|
||||||
|
Query(q): Query<AuditQuery>,
|
||||||
|
) -> Result<Response, ApiError> {
|
||||||
|
let limit = q.limit.unwrap_or(AUDIT_DEFAULT).clamp(1, AUDIT_MAX);
|
||||||
|
let auth = state.auth.clone();
|
||||||
|
let list = blocking(move || auth.audit_tail(limit)).await?;
|
||||||
|
Ok(Json(list).into_response())
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
mod auth_http;
|
||||||
|
mod transport;
|
||||||
mod web;
|
mod web;
|
||||||
|
|
||||||
use acaua_core::{doctor, update, zeek};
|
use acaua_core::{doctor, update, zeek};
|
||||||
@@ -35,6 +37,24 @@ enum Command {
|
|||||||
json: bool,
|
json: bool,
|
||||||
},
|
},
|
||||||
Update,
|
Update,
|
||||||
|
/// Local account recovery. Never starts the daemon.
|
||||||
|
Auth {
|
||||||
|
#[command(subcommand)]
|
||||||
|
action: AuthAction,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum AuthAction {
|
||||||
|
/// Resets an account: removes MFA, sessions and tokens, prints a temporary
|
||||||
|
/// password once. The next login changes the password; an administrator
|
||||||
|
/// also enrolls MFA again.
|
||||||
|
Reset {
|
||||||
|
#[arg(long)]
|
||||||
|
username: String,
|
||||||
|
#[arg(long, default_value = ".acaua")]
|
||||||
|
data_dir: PathBuf,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
@@ -49,6 +69,18 @@ async fn main() {
|
|||||||
async fn run(cli: Cli) -> acaua_core::Result<()> {
|
async fn run(cli: Cli) -> acaua_core::Result<()> {
|
||||||
match cli.command {
|
match cli.command {
|
||||||
Command::Serve { bind, data_dir } => web::serve(&bind, data_dir).await,
|
Command::Serve { bind, data_dir } => web::serve(&bind, data_dir).await,
|
||||||
|
Command::Auth {
|
||||||
|
action: AuthAction::Reset { username, data_dir },
|
||||||
|
} => {
|
||||||
|
let key = web::secret_key_file(&|name| std::env::var(name).ok());
|
||||||
|
let auth = acaua_core::auth::AuthService::open(&data_dir, key.as_deref())?;
|
||||||
|
let temp = auth.reset_account(&username, auth_http::unix_now())?;
|
||||||
|
println!("Senha temporária (exibida uma única vez): {temp}");
|
||||||
|
println!(
|
||||||
|
"O próximo login exige troca de senha e, para administradores, novo cadastro de MFA."
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Command::Analyze {
|
Command::Analyze {
|
||||||
directory,
|
directory,
|
||||||
data_dir,
|
data_dir,
|
||||||
|
|||||||
@@ -0,0 +1,335 @@
|
|||||||
|
//! How requests reach the daemon: this decides which client address can be
|
||||||
|
//! believed and whether cookies may be marked `Secure`.
|
||||||
|
|
||||||
|
use acaua_core::{AcauaError, Result};
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use ipnet::IpNet;
|
||||||
|
use std::net::{IpAddr, SocketAddr};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub enum Transport {
|
||||||
|
Local,
|
||||||
|
Tls { cert: PathBuf, key: PathBuf },
|
||||||
|
Proxy { trusted: Vec<IpNet> },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Transport {
|
||||||
|
/// Reads the mode from the environment. There is no default: a daemon
|
||||||
|
/// that guesses how it is exposed can end up serving plain HTTP on a
|
||||||
|
/// network by accident.
|
||||||
|
pub fn from_env(env: &impl Fn(&str) -> Option<String>) -> Result<Transport> {
|
||||||
|
let get = |name: &str| env(name).filter(|v| !v.trim().is_empty());
|
||||||
|
let required = |mode: &str, name: &str| {
|
||||||
|
get(name).ok_or_else(|| {
|
||||||
|
AcauaError::InvalidInput(format!("ACAUA_TRANSPORT={mode} requires {name}"))
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let mode = get("ACAUA_TRANSPORT").ok_or_else(|| {
|
||||||
|
AcauaError::InvalidInput(
|
||||||
|
"ACAUA_TRANSPORT is not set; choose one of: local, tls, proxy".into(),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
match mode.trim() {
|
||||||
|
"local" => {
|
||||||
|
if let Some(published) = env("ACAUA_PUBLISHED") {
|
||||||
|
let loopback = published
|
||||||
|
.trim()
|
||||||
|
.parse::<SocketAddr>()
|
||||||
|
.is_ok_and(|addr| addr.ip().to_canonical().is_loopback());
|
||||||
|
if !loopback {
|
||||||
|
return Err(AcauaError::InvalidInput(format!(
|
||||||
|
"ACAUA_TRANSPORT=local refuses ACAUA_PUBLISHED={published}: \
|
||||||
|
the dashboard would be reachable over plain HTTP from the network. \
|
||||||
|
Publish on 127.0.0.1 or [::1], or set ACAUA_TRANSPORT to tls or proxy"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Transport::Local)
|
||||||
|
}
|
||||||
|
"tls" => Ok(Transport::Tls {
|
||||||
|
cert: required("tls", "ACAUA_TLS_CERT")?.into(),
|
||||||
|
key: required("tls", "ACAUA_TLS_KEY")?.into(),
|
||||||
|
}),
|
||||||
|
"proxy" => {
|
||||||
|
let list = required("proxy", "ACAUA_TRUSTED_PROXIES")?;
|
||||||
|
let mut trusted = Vec::new();
|
||||||
|
for item in list.split(',').map(str::trim).filter(|i| !i.is_empty()) {
|
||||||
|
let net = item.parse::<IpNet>().map_err(|_| {
|
||||||
|
AcauaError::InvalidInput(format!(
|
||||||
|
"ACAUA_TRUSTED_PROXIES: `{item}` is not a CIDR such as 10.0.0.0/8"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
trusted.push(net);
|
||||||
|
}
|
||||||
|
if trusted.is_empty() {
|
||||||
|
return Err(AcauaError::InvalidInput(
|
||||||
|
"ACAUA_TRANSPORT=proxy requires ACAUA_TRUSTED_PROXIES".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(Transport::Proxy { trusted })
|
||||||
|
}
|
||||||
|
other => Err(AcauaError::InvalidInput(format!(
|
||||||
|
"ACAUA_TRANSPORT=`{other}` is not valid; choose one of: local, tls, proxy"
|
||||||
|
))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `local` means plain HTTP for this machine only. In a container the
|
||||||
|
/// daemon must listen on all interfaces to be published at all, so there
|
||||||
|
/// `ACAUA_PUBLISHED` decides (see `from_env`); elsewhere the bind does.
|
||||||
|
pub fn check_bind(&self, bind: &str, env: &impl Fn(&str) -> Option<String>) -> Result<()> {
|
||||||
|
if !matches!(self, Transport::Local) || env("ACAUA_RUNTIME").as_deref() == Some("container")
|
||||||
|
{
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let loopback = match bind.parse::<SocketAddr>() {
|
||||||
|
Ok(addr) => addr.ip().to_canonical().is_loopback(),
|
||||||
|
Err(_) => bind
|
||||||
|
.rsplit_once(':')
|
||||||
|
.is_some_and(|(host, _)| host.eq_ignore_ascii_case("localhost")),
|
||||||
|
};
|
||||||
|
if loopback {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
Err(AcauaError::InvalidInput(format!(
|
||||||
|
"ACAUA_TRANSPORT=local refuses --bind {bind}: the dashboard would be reachable \
|
||||||
|
over plain HTTP from the network. Bind to 127.0.0.1 or [::1], or set \
|
||||||
|
ACAUA_TRANSPORT to tls or proxy"
|
||||||
|
)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Browsers should be pinned to HTTPS only when HTTPS is what they use.
|
||||||
|
pub fn hsts(&self) -> bool {
|
||||||
|
!matches!(self, Transport::Local)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The address to throttle and audit. `X-Forwarded-For` counts only when
|
||||||
|
/// the peer is a trusted proxy, and then the answer is the rightmost hop
|
||||||
|
/// that is not itself trusted: everything left of it is client-supplied.
|
||||||
|
pub fn client_ip(&self, peer: IpAddr, headers: &HeaderMap) -> IpAddr {
|
||||||
|
let peer = peer.to_canonical();
|
||||||
|
let Transport::Proxy { trusted } = self else {
|
||||||
|
return peer;
|
||||||
|
};
|
||||||
|
let is_trusted = |ip: &IpAddr| trusted.iter().any(|net| net.contains(ip));
|
||||||
|
if !is_trusted(&peer) {
|
||||||
|
return peer;
|
||||||
|
}
|
||||||
|
let mut hops: Vec<&str> = Vec::new();
|
||||||
|
for value in headers.get_all("x-forwarded-for") {
|
||||||
|
let Ok(text) = value.to_str() else {
|
||||||
|
return peer;
|
||||||
|
};
|
||||||
|
hops.extend(text.split(','));
|
||||||
|
}
|
||||||
|
for hop in hops.iter().rev() {
|
||||||
|
let Ok(ip) = hop.trim().parse::<IpAddr>() else {
|
||||||
|
return peer;
|
||||||
|
};
|
||||||
|
let ip = ip.to_canonical();
|
||||||
|
if !is_trusted(&ip) {
|
||||||
|
return ip;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
peer
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn cookie_secure(&self) -> bool {
|
||||||
|
!matches!(self, Transport::Local)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn proxy() -> Transport {
|
||||||
|
Transport::Proxy {
|
||||||
|
trusted: vec!["10.0.0.0/8".parse().unwrap()],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xff(value: &str) -> HeaderMap {
|
||||||
|
let mut h = HeaderMap::new();
|
||||||
|
h.insert("x-forwarded-for", value.parse().unwrap());
|
||||||
|
h
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ip(s: &str) -> IpAddr {
|
||||||
|
s.parse().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_mode_refuses_a_network_bind_outside_a_container() {
|
||||||
|
let bare = |_: &str| None;
|
||||||
|
let local = Transport::Local;
|
||||||
|
for ok in [
|
||||||
|
"127.0.0.1:8787",
|
||||||
|
"[::1]:8787",
|
||||||
|
"localhost:8787",
|
||||||
|
"127.9.9.9:1",
|
||||||
|
] {
|
||||||
|
assert!(local.check_bind(ok, &bare).is_ok(), "{ok}");
|
||||||
|
}
|
||||||
|
for bad in [
|
||||||
|
"0.0.0.0:8787",
|
||||||
|
"[::]:8787",
|
||||||
|
"192.0.2.1:8787",
|
||||||
|
"example.org:80",
|
||||||
|
"nonsense",
|
||||||
|
] {
|
||||||
|
let err = local.check_bind(bad, &bare).unwrap_err().to_string();
|
||||||
|
assert!(err.contains("--bind"), "{err}");
|
||||||
|
}
|
||||||
|
// In the image ACAUA_PUBLISHED is the control, not the bind.
|
||||||
|
let container = |n: &str| (n == "ACAUA_RUNTIME").then(|| "container".to_string());
|
||||||
|
assert!(local.check_bind("0.0.0.0:8787", &container).is_ok());
|
||||||
|
let other = |n: &str| (n == "ACAUA_RUNTIME").then(|| "host".to_string());
|
||||||
|
assert!(local.check_bind("0.0.0.0:8787", &other).is_err());
|
||||||
|
// Other modes protect the network themselves.
|
||||||
|
assert!(proxy().check_bind("0.0.0.0:8787", &bare).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn forwarded_for_counts_only_from_a_trusted_proxy() {
|
||||||
|
let forged = xff("203.0.113.9");
|
||||||
|
assert_eq!(
|
||||||
|
Transport::Local.client_ip(ip("192.0.2.1"), &forged),
|
||||||
|
ip("192.0.2.1")
|
||||||
|
);
|
||||||
|
let tls = Transport::Tls {
|
||||||
|
cert: "c".into(),
|
||||||
|
key: "k".into(),
|
||||||
|
};
|
||||||
|
assert_eq!(tls.client_ip(ip("192.0.2.1"), &forged), ip("192.0.2.1"));
|
||||||
|
assert_eq!(
|
||||||
|
proxy().client_ip(ip("192.0.2.1"), &forged),
|
||||||
|
ip("192.0.2.1"),
|
||||||
|
"untrusted peer"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
proxy().client_ip(ip("10.0.0.1"), &forged),
|
||||||
|
ip("203.0.113.9")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rightmost_untrusted_hop_wins_over_a_forged_left_side() {
|
||||||
|
let h = xff("1.1.1.1, 203.0.113.9, 10.0.0.2");
|
||||||
|
assert_eq!(proxy().client_ip(ip("10.0.0.1"), &h), ip("203.0.113.9"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_or_missing_header_falls_back_to_the_peer() {
|
||||||
|
for h in [xff("not-an-ip"), HeaderMap::new(), xff("10.0.0.2")] {
|
||||||
|
assert_eq!(proxy().client_ip(ip("10.0.0.1"), &h), ip("10.0.0.1"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option<String> + 'a {
|
||||||
|
move |k| {
|
||||||
|
pairs
|
||||||
|
.iter()
|
||||||
|
.find(|(name, _)| *name == k)
|
||||||
|
.map(|(_, v)| (*v).to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn err(pairs: &[(&str, &str)]) -> String {
|
||||||
|
Transport::from_env(&env(pairs)).unwrap_err().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn missing_or_invalid_mode_fails() {
|
||||||
|
assert!(err(&[]).contains("ACAUA_TRANSPORT"));
|
||||||
|
let bad = err(&[("ACAUA_TRANSPORT", "xyz")]);
|
||||||
|
assert!(bad.contains("xyz") && bad.contains("local"), "{bad}");
|
||||||
|
assert!(err(&[("ACAUA_TRANSPORT", "")]).contains("ACAUA_TRANSPORT"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn local_refuses_non_loopback_publish() {
|
||||||
|
let local = |published: &'static str| {
|
||||||
|
Transport::from_env(&env(&[
|
||||||
|
("ACAUA_TRANSPORT", "local"),
|
||||||
|
("ACAUA_PUBLISHED", published),
|
||||||
|
]))
|
||||||
|
};
|
||||||
|
for bad in [
|
||||||
|
"0.0.0.0:8787",
|
||||||
|
"192.168.1.5:8787",
|
||||||
|
"[::]:8787",
|
||||||
|
"garbage",
|
||||||
|
"",
|
||||||
|
] {
|
||||||
|
let e = local(bad).unwrap_err().to_string();
|
||||||
|
assert!(e.contains("ACAUA_PUBLISHED"), "{bad}: {e}");
|
||||||
|
}
|
||||||
|
for ok in ["127.0.0.1:8787", "[::1]:8787", "127.0.0.2:80"] {
|
||||||
|
assert!(matches!(local(ok), Ok(Transport::Local)), "{ok}");
|
||||||
|
}
|
||||||
|
assert!(matches!(
|
||||||
|
Transport::from_env(&env(&[("ACAUA_TRANSPORT", "local")])),
|
||||||
|
Ok(Transport::Local)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tls_requires_cert_and_key() {
|
||||||
|
assert!(err(&[("ACAUA_TRANSPORT", "tls")]).contains("ACAUA_TLS_CERT"));
|
||||||
|
assert!(
|
||||||
|
err(&[("ACAUA_TRANSPORT", "tls"), ("ACAUA_TLS_CERT", "/c.pem")])
|
||||||
|
.contains("ACAUA_TLS_KEY")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
err(&[("ACAUA_TRANSPORT", "tls"), ("ACAUA_TLS_KEY", "/k.pem")])
|
||||||
|
.contains("ACAUA_TLS_CERT")
|
||||||
|
);
|
||||||
|
let t = Transport::from_env(&env(&[
|
||||||
|
("ACAUA_TRANSPORT", "tls"),
|
||||||
|
("ACAUA_TLS_CERT", "/c.pem"),
|
||||||
|
("ACAUA_TLS_KEY", "/k.pem"),
|
||||||
|
]))
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(t, Transport::Tls { cert, key }
|
||||||
|
if cert.as_path() == std::path::Path::new("/c.pem") && key.as_path() == std::path::Path::new("/k.pem")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn proxy_requires_trusted_list() {
|
||||||
|
let base = ("ACAUA_TRANSPORT", "proxy");
|
||||||
|
assert!(err(&[base]).contains("ACAUA_TRUSTED_PROXIES"));
|
||||||
|
assert!(err(&[base, ("ACAUA_TRUSTED_PROXIES", " , ")]).contains("ACAUA_TRUSTED_PROXIES"));
|
||||||
|
let bad = err(&[base, ("ACAUA_TRUSTED_PROXIES", "10.0.0.0/8,nope")]);
|
||||||
|
assert!(bad.contains("nope"), "{bad}");
|
||||||
|
let t = Transport::from_env(&env(&[
|
||||||
|
base,
|
||||||
|
("ACAUA_TRUSTED_PROXIES", "10.0.0.0/8, 172.18.0.2/32"),
|
||||||
|
]))
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(t, Transport::Proxy { trusted } if trusted.len() == 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hsts_only_in_tls_and_proxy() {
|
||||||
|
assert!(!Transport::Local.hsts());
|
||||||
|
assert!(proxy().hsts());
|
||||||
|
assert!(Transport::Tls {
|
||||||
|
cert: "c".into(),
|
||||||
|
key: "k".into()
|
||||||
|
}
|
||||||
|
.hsts());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_local_cookies_lack_secure() {
|
||||||
|
assert!(!Transport::Local.cookie_secure());
|
||||||
|
assert!(proxy().cookie_secure());
|
||||||
|
assert!(Transport::Tls {
|
||||||
|
cert: "c".into(),
|
||||||
|
key: "k".into()
|
||||||
|
}
|
||||||
|
.cookie_secure());
|
||||||
|
}
|
||||||
|
}
|
||||||
+388
-65
@@ -1,21 +1,31 @@
|
|||||||
|
use crate::auth_http::{self, blocking, require_auth, ApiError, JsonBody};
|
||||||
|
use crate::transport::Transport;
|
||||||
|
use acaua_core::auth::AuthService;
|
||||||
use acaua_core::fusion::Alert;
|
use acaua_core::fusion::Alert;
|
||||||
use acaua_core::storage::{DatasetSummary, Storage};
|
use acaua_core::storage::{DatasetSummary, Storage};
|
||||||
use acaua_core::update::UpdateStatus;
|
use acaua_core::update::UpdateStatus;
|
||||||
use acaua_core::zeek::{self, AnalysisReport};
|
use acaua_core::zeek::{self, AnalysisReport};
|
||||||
use acaua_core::{update, Result};
|
use acaua_core::{update, AcauaError, Result};
|
||||||
use axum::body::Body;
|
use axum::body::Body;
|
||||||
use axum::extract::State;
|
use axum::extract::Request;
|
||||||
use axum::http::{header, StatusCode, Uri};
|
use axum::extract::{DefaultBodyLimit, Query, State};
|
||||||
|
use axum::http::{header, HeaderValue, Method, StatusCode, Uri};
|
||||||
|
use axum::middleware::{from_fn, from_fn_with_state, Next};
|
||||||
use axum::response::{IntoResponse, Response};
|
use axum::response::{IntoResponse, Response};
|
||||||
use axum::routing::{get, post};
|
use axum::routing::{delete, get, patch, post, MethodRouter};
|
||||||
use axum::{Json, Router};
|
use axum::{Json, Router};
|
||||||
|
use axum_server::tls_rustls::RustlsConfig;
|
||||||
|
use axum_server::Handle;
|
||||||
use rust_embed::RustEmbed;
|
use rust_embed::RustEmbed;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::net::SocketAddr;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
use std::sync::Arc;
|
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||||
|
use std::time::Duration;
|
||||||
use tokio::net::TcpListener;
|
use tokio::net::TcpListener;
|
||||||
|
use tokio::sync::Semaphore;
|
||||||
use tower_http::compression::CompressionLayer;
|
use tower_http::compression::CompressionLayer;
|
||||||
use tower_http::cors::CorsLayer;
|
|
||||||
use tower_http::trace::TraceLayer;
|
use tower_http::trace::TraceLayer;
|
||||||
|
|
||||||
const LOGO: &[u8] = include_bytes!("../../../logo.png");
|
const LOGO: &[u8] = include_bytes!("../../../logo.png");
|
||||||
@@ -25,15 +35,259 @@ const LOGO: &[u8] = include_bytes!("../../../logo.png");
|
|||||||
struct Assets;
|
struct Assets;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct AppState {
|
pub struct AppState {
|
||||||
storage: Arc<Storage>,
|
storage: Arc<Storage>,
|
||||||
last_report: Arc<std::sync::Mutex<Option<AnalysisReport>>>,
|
last_report: Arc<Mutex<Option<AnalysisReport>>>,
|
||||||
|
pub auth: Arc<AuthService>,
|
||||||
|
pub transport: Arc<Transport>,
|
||||||
|
pub argon2: Arc<Semaphore>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AppState {
|
||||||
|
pub fn new(storage: Arc<Storage>, auth: Arc<AuthService>, transport: Transport) -> Self {
|
||||||
|
Self {
|
||||||
|
storage,
|
||||||
|
last_report: Arc::new(Mutex::new(None)),
|
||||||
|
auth,
|
||||||
|
transport: Arc::new(transport),
|
||||||
|
argon2: Arc::new(Semaphore::new(auth_http::ARGON2_CONCURRENCY)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The report is replaced whole, so a poisoned lock still holds a valid one.
|
||||||
|
fn report(&self) -> MutexGuard<'_, Option<AnalysisReport>> {
|
||||||
|
self.last_report
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(PoisonError::into_inner)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum Verb {
|
||||||
|
Get,
|
||||||
|
Post,
|
||||||
|
Patch,
|
||||||
|
Delete,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Verb {
|
||||||
|
/// `HEAD` follows `GET`, as in the router.
|
||||||
|
fn matches(self, method: &Method) -> bool {
|
||||||
|
match self {
|
||||||
|
Verb::Get => *method == Method::GET || *method == Method::HEAD,
|
||||||
|
Verb::Post => *method == Method::POST,
|
||||||
|
Verb::Patch => *method == Method::PATCH,
|
||||||
|
Verb::Delete => *method == Method::DELETE,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a non-public route asks of the caller. There is no public level on
|
||||||
|
/// purpose: a route is public only by being written into `PUBLIC_ROUTES`.
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||||
|
pub enum Access {
|
||||||
|
/// Any session or token; a read token still cannot mutate.
|
||||||
|
Authenticated,
|
||||||
|
/// A browser session: an API token, whatever its scope, is refused.
|
||||||
|
Session,
|
||||||
|
/// As `Session`, or the pending token of a first login.
|
||||||
|
SessionOrPending,
|
||||||
|
/// Administrator role, and Admin scope when through a token.
|
||||||
|
Admin,
|
||||||
|
/// Administrator in a session that reauthenticated recently, never a
|
||||||
|
/// token: otherwise a hijacked session could create an admin outliving it.
|
||||||
|
AdminRecentSession,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RouteDef {
|
||||||
|
pub verb: Verb,
|
||||||
|
pub path: &'static str,
|
||||||
|
pub access: Access,
|
||||||
|
handler: fn() -> MethodRouter<AppState>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn route(
|
||||||
|
verb: Verb,
|
||||||
|
path: &'static str,
|
||||||
|
access: Access,
|
||||||
|
handler: fn() -> MethodRouter<AppState>,
|
||||||
|
) -> RouteDef {
|
||||||
|
RouteDef {
|
||||||
|
verb,
|
||||||
|
path,
|
||||||
|
access,
|
||||||
|
handler,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one source of routes: `build_app` registers exactly these. Access for
|
||||||
|
/// entries also in `PUBLIC_ROUTES` is never consulted.
|
||||||
|
pub const ALL_ROUTES: &[RouteDef] = {
|
||||||
|
use auth_http as a;
|
||||||
|
use Access::{Admin, AdminRecentSession, Authenticated, Session, SessionOrPending};
|
||||||
|
use Verb::{Delete, Get, Patch, Post};
|
||||||
|
&[
|
||||||
|
route(Get, "/api/health", Authenticated, || get(health)),
|
||||||
|
route(Get, "/login.html", Authenticated, || get(asset)),
|
||||||
|
route(Get, "/login.js", Authenticated, || get(asset)),
|
||||||
|
route(Get, "/app.css", Authenticated, || get(asset)),
|
||||||
|
route(Get, "/logo.png", Authenticated, || get(logo)),
|
||||||
|
route(Get, "/i18n.js", Authenticated, || get(asset)),
|
||||||
|
route(Get, "/i18n-en.js", Authenticated, || get(asset)),
|
||||||
|
route(Get, "/api/auth/state", Authenticated, || get(a::auth_state)),
|
||||||
|
route(Post, "/api/auth/bootstrap", Authenticated, || {
|
||||||
|
post(a::bootstrap)
|
||||||
|
}),
|
||||||
|
route(Post, "/api/auth/login", Authenticated, || post(a::login)),
|
||||||
|
route(Post, "/api/auth/mfa", Authenticated, || post(a::mfa)),
|
||||||
|
route(
|
||||||
|
Post,
|
||||||
|
"/api/auth/password-change-required",
|
||||||
|
Authenticated,
|
||||||
|
|| post(a::password_change_required),
|
||||||
|
),
|
||||||
|
route(Post, "/api/auth/logout", Session, || post(a::logout)),
|
||||||
|
route(Post, "/api/auth/reauth", Session, || post(a::reauth)),
|
||||||
|
route(Post, "/api/auth/password", Session, || {
|
||||||
|
post(a::change_password)
|
||||||
|
}),
|
||||||
|
route(Post, "/api/auth/mfa/disable", Session, || {
|
||||||
|
post(a::mfa_disable)
|
||||||
|
}),
|
||||||
|
route(Post, "/api/auth/enroll/start", SessionOrPending, || {
|
||||||
|
post(a::enroll_start)
|
||||||
|
}),
|
||||||
|
route(Post, "/api/auth/enroll/confirm", SessionOrPending, || {
|
||||||
|
post(a::enroll_confirm)
|
||||||
|
}),
|
||||||
|
route(Get, "/api/auth/sessions", Authenticated, || {
|
||||||
|
get(a::sessions_list)
|
||||||
|
}),
|
||||||
|
route(Delete, "/api/auth/sessions", Authenticated, || {
|
||||||
|
delete(a::sessions_revoke)
|
||||||
|
}),
|
||||||
|
route(Get, "/api/auth/tokens", Authenticated, || {
|
||||||
|
get(a::tokens_list)
|
||||||
|
}),
|
||||||
|
route(Post, "/api/auth/tokens", Session, || post(a::tokens_create)),
|
||||||
|
route(Delete, "/api/auth/tokens", Authenticated, || {
|
||||||
|
delete(a::tokens_revoke)
|
||||||
|
}),
|
||||||
|
route(Get, "/api/admin/users", Admin, || get(a::users_list)),
|
||||||
|
route(Post, "/api/admin/users", AdminRecentSession, || {
|
||||||
|
post(a::users_create)
|
||||||
|
}),
|
||||||
|
route(Patch, "/api/admin/users", AdminRecentSession, || {
|
||||||
|
patch(a::users_set_role)
|
||||||
|
}),
|
||||||
|
route(Delete, "/api/admin/users", AdminRecentSession, || {
|
||||||
|
delete(a::users_delete)
|
||||||
|
}),
|
||||||
|
route(Get, "/api/admin/audit", Admin, || get(a::audit)),
|
||||||
|
route(Post, "/api/analyze", Admin, || post(analyze)),
|
||||||
|
route(Get, "/api/status", Authenticated, || get(status)),
|
||||||
|
route(Get, "/api/alerts", Authenticated, || get(alerts)),
|
||||||
|
route(Get, "/api/update", Authenticated, || get(update_check)),
|
||||||
|
route(Get, "/relatorio", Authenticated, || get(report_page)),
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Everything reachable without a credential. Exact matches only.
|
||||||
|
pub const PUBLIC_ROUTES: &[(Verb, &str)] = &[
|
||||||
|
(Verb::Get, "/api/health"),
|
||||||
|
(Verb::Get, "/login.html"),
|
||||||
|
(Verb::Get, "/login.js"),
|
||||||
|
(Verb::Get, "/app.css"),
|
||||||
|
(Verb::Get, "/logo.png"),
|
||||||
|
(Verb::Get, "/i18n.js"),
|
||||||
|
(Verb::Get, "/i18n-en.js"),
|
||||||
|
(Verb::Get, "/api/auth/state"),
|
||||||
|
(Verb::Post, "/api/auth/bootstrap"),
|
||||||
|
(Verb::Post, "/api/auth/login"),
|
||||||
|
(Verb::Post, "/api/auth/mfa"),
|
||||||
|
(Verb::Post, "/api/auth/password-change-required"),
|
||||||
|
];
|
||||||
|
|
||||||
|
pub fn is_public(method: &Method, path: &str) -> bool {
|
||||||
|
PUBLIC_ROUTES
|
||||||
|
.iter()
|
||||||
|
.any(|(verb, p)| *p == path && verb.matches(method))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The public files: shared, cacheable, and holding nothing per-user.
|
||||||
|
pub fn is_public_asset(method: &Method, path: &str) -> bool {
|
||||||
|
!path.starts_with("/api/") && is_public(method, path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Paths outside the table (the asset fallback) need a credential too.
|
||||||
|
pub fn access_of(method: &Method, path: &str) -> Access {
|
||||||
|
ALL_ROUTES
|
||||||
|
.iter()
|
||||||
|
.find(|r| r.path == path && r.verb.matches(method))
|
||||||
|
.map_or(Access::Authenticated, |r| r.access)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn build_app(state: AppState) -> Router {
|
||||||
|
let mut router = Router::new();
|
||||||
|
for r in ALL_ROUTES {
|
||||||
|
router = router.route(r.path, (r.handler)());
|
||||||
|
}
|
||||||
|
router
|
||||||
|
.fallback(asset)
|
||||||
|
// Bounds every `Json` extractor before anything looks at the input.
|
||||||
|
.layer(DefaultBodyLimit::max(auth_http::MAX_BODY_BYTES))
|
||||||
|
.layer(from_fn_with_state(state.clone(), require_auth))
|
||||||
|
.layer(from_fn_with_state(state.clone(), hsts))
|
||||||
|
.layer(from_fn(security_headers))
|
||||||
|
.with_state(state)
|
||||||
|
.layer(CompressionLayer::new())
|
||||||
|
.layer(TraceLayer::new_for_http())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds `Strict-Transport-Security` when the transport is HTTPS. It sits
|
||||||
|
/// outside `require_auth`, so refusals carry it too.
|
||||||
|
async fn hsts(State(state): State<AppState>, req: Request, next: Next) -> Response {
|
||||||
|
let mut response = next.run(req).await;
|
||||||
|
if state.transport.hsts() {
|
||||||
|
response.headers_mut().insert(
|
||||||
|
header::STRICT_TRANSPORT_SECURITY,
|
||||||
|
HeaderValue::from_static("max-age=31536000"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
response
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `style-src 'unsafe-inline'` is the narrowest that works: the report carries
|
||||||
|
/// its stylesheet inline and Paged.js adds `<style>` elements while it paginates.
|
||||||
|
/// Scripts stay same-origin only. `data:` images are the report's embedded logo
|
||||||
|
/// and the MFA QR code.
|
||||||
|
pub(crate) const CSP: &str = "default-src 'none'; script-src 'self'; \
|
||||||
|
style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; \
|
||||||
|
connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'";
|
||||||
|
|
||||||
|
/// On every response, refusals included.
|
||||||
|
async fn security_headers(req: Request, next: Next) -> Response {
|
||||||
|
let mut response = next.run(req).await;
|
||||||
|
let headers = response.headers_mut();
|
||||||
|
headers.insert(
|
||||||
|
header::CONTENT_SECURITY_POLICY,
|
||||||
|
HeaderValue::from_static(CSP),
|
||||||
|
);
|
||||||
|
headers.insert(header::X_FRAME_OPTIONS, HeaderValue::from_static("DENY"));
|
||||||
|
headers.insert(
|
||||||
|
header::X_CONTENT_TYPE_OPTIONS,
|
||||||
|
HeaderValue::from_static("nosniff"),
|
||||||
|
);
|
||||||
|
headers.insert(
|
||||||
|
header::REFERRER_POLICY,
|
||||||
|
HeaderValue::from_static("no-referrer"),
|
||||||
|
);
|
||||||
|
response
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct Health {
|
struct Health {
|
||||||
status: &'static str,
|
status: &'static str,
|
||||||
version: &'static str,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
@@ -53,27 +307,40 @@ struct AnalyzeRequest {
|
|||||||
path: String,
|
path: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn health() -> Json<Health> {
|
/// The detail (paths, command output) goes to the log, not to the caller.
|
||||||
Json(Health {
|
fn failure(status: StatusCode, message: &str, detail: &acaua_core::AcauaError) -> Response {
|
||||||
status: "ok",
|
tracing::error!(error = %detail, "{message}");
|
||||||
version: env!("CARGO_PKG_VERSION"),
|
(
|
||||||
})
|
status,
|
||||||
|
Json(ErrorBody {
|
||||||
|
error: message.to_string(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn status(State(state): State<AppState>) -> Json<Status> {
|
async fn health() -> Json<Health> {
|
||||||
Json(Status {
|
Json(Health { status: "ok" })
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn status(State(state): State<AppState>) -> std::result::Result<Json<Status>, ApiError> {
|
||||||
|
let storage = state.storage.clone();
|
||||||
|
let dataset = blocking(move || {
|
||||||
|
Ok(storage
|
||||||
|
.summary()
|
||||||
|
.unwrap_or_else(|_| DatasetSummary::empty()))
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
Ok(Json(Status {
|
||||||
version: env!("CARGO_PKG_VERSION"),
|
version: env!("CARGO_PKG_VERSION"),
|
||||||
mode: "serve",
|
mode: "serve",
|
||||||
dataset: state
|
dataset,
|
||||||
.storage
|
}))
|
||||||
.summary()
|
|
||||||
.unwrap_or_else(|_| DatasetSummary::empty()),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn alerts(State(state): State<AppState>) -> Json<Vec<Alert>> {
|
async fn alerts(State(state): State<AppState>) -> Json<Vec<Alert>> {
|
||||||
let report_lock = state.last_report.lock().unwrap();
|
let list = state
|
||||||
let list = report_lock
|
.report()
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|r| r.alerts.clone())
|
.map(|r| r.alerts.clone())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
@@ -82,36 +349,50 @@ async fn alerts(State(state): State<AppState>) -> Json<Vec<Alert>> {
|
|||||||
|
|
||||||
async fn analyze(
|
async fn analyze(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
Json(request): Json<AnalyzeRequest>,
|
JsonBody(request): JsonBody<AnalyzeRequest>,
|
||||||
) -> std::result::Result<Json<AnalysisReport>, (StatusCode, Json<ErrorBody>)> {
|
) -> Response {
|
||||||
zeek::analyze_dir(&request.path, state.storage.root())
|
let root = state.storage.root().to_path_buf();
|
||||||
.map(|report| {
|
let outcome =
|
||||||
if let Ok(mut lock) = state.last_report.lock() {
|
tokio::task::spawn_blocking(move || zeek::analyze_dir(&request.path, &root)).await;
|
||||||
*lock = Some(report.clone());
|
match outcome {
|
||||||
|
Ok(Ok(report)) => {
|
||||||
|
*state.report() = Some(report.clone());
|
||||||
|
Json(report).into_response()
|
||||||
|
}
|
||||||
|
Ok(Err(error)) => failure(StatusCode::BAD_REQUEST, "analysis failed", &error),
|
||||||
|
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||||
}
|
}
|
||||||
Json(report)
|
|
||||||
})
|
|
||||||
.map_err(|error| {
|
|
||||||
(
|
|
||||||
StatusCode::BAD_REQUEST,
|
|
||||||
Json(ErrorBody {
|
|
||||||
error: error.to_string(),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn update_check() -> std::result::Result<Json<UpdateStatus>, (StatusCode, Json<ErrorBody>)> {
|
/// Executive report of the latest analysis (`?tlp=` picks the TLP label).
|
||||||
update::check(env!("CARGO_PKG_VERSION"))
|
async fn report_page(
|
||||||
.map(Json)
|
State(state): State<AppState>,
|
||||||
.map_err(|error| {
|
Query(query): Query<HashMap<String, String>>,
|
||||||
(
|
) -> Response {
|
||||||
StatusCode::BAD_GATEWAY,
|
let lock = state.report();
|
||||||
Json(ErrorBody {
|
let Some(report) = lock.as_ref() else {
|
||||||
error: error.to_string(),
|
return (
|
||||||
}),
|
StatusCode::NOT_FOUND,
|
||||||
|
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
|
||||||
|
"<!doctype html><meta charset=\"utf-8\"><title>Acauã</title><p>Nenhuma análise executada. Rode uma análise no painel e abra o relatório de novo.</p>",
|
||||||
)
|
)
|
||||||
})
|
.into_response();
|
||||||
|
};
|
||||||
|
let options = acaua_core::report::ReportOptions {
|
||||||
|
tlp: query.get("tlp").cloned().unwrap_or_else(|| "AMBER".into()),
|
||||||
|
issued_at: None,
|
||||||
|
};
|
||||||
|
let html = acaua_core::report::render_html_with(report, &options);
|
||||||
|
([(header::CONTENT_TYPE, "text/html; charset=utf-8")], html).into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_check() -> Response {
|
||||||
|
let outcome = tokio::task::spawn_blocking(|| update::check(env!("CARGO_PKG_VERSION"))).await;
|
||||||
|
match outcome {
|
||||||
|
Ok(Ok(status)) => Json::<UpdateStatus>(status).into_response(),
|
||||||
|
Ok(Err(error)) => failure(StatusCode::BAD_GATEWAY, "update check failed", &error),
|
||||||
|
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn logo() -> impl IntoResponse {
|
async fn logo() -> impl IntoResponse {
|
||||||
@@ -154,29 +435,71 @@ async fn shutdown_signal() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Path of an external secret key (a Docker secret), from `ACAUA_SECRET_KEY_FILE`.
|
||||||
|
/// An unset or empty variable means the key lives in the data directory.
|
||||||
|
pub(crate) fn secret_key_file(get: &dyn Fn(&str) -> Option<String>) -> Option<PathBuf> {
|
||||||
|
get("ACAUA_SECRET_KEY_FILE")
|
||||||
|
.filter(|value| !value.trim().is_empty())
|
||||||
|
.map(PathBuf::from)
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn serve(bind: &str, data_dir: PathBuf) -> Result<()> {
|
pub async fn serve(bind: &str, data_dir: PathBuf) -> Result<()> {
|
||||||
|
// Decide the exposure before touching the data directory or printing a
|
||||||
|
// setup code: a refusal must leave nothing behind.
|
||||||
|
let transport = Transport::from_env(&|name| std::env::var(name).ok())?;
|
||||||
|
transport.check_bind(bind, &|name| std::env::var(name).ok())?;
|
||||||
let _ = tracing_subscriber::fmt().try_init();
|
let _ = tracing_subscriber::fmt().try_init();
|
||||||
std::fs::create_dir_all(&data_dir)?;
|
std::fs::create_dir_all(&data_dir)?;
|
||||||
let state = AppState {
|
let auth = Arc::new(AuthService::open(
|
||||||
storage: Arc::new(Storage::open(&data_dir)?),
|
&data_dir,
|
||||||
last_report: Arc::new(std::sync::Mutex::new(None)),
|
secret_key_file(&|name| std::env::var(name).ok()).as_deref(),
|
||||||
|
)?);
|
||||||
|
if let Some(code) = auth.ensure_bootstrap(auth_http::unix_now())? {
|
||||||
|
eprintln!("Acauã: código de configuração inicial (válido por 1 hora): {code}");
|
||||||
|
}
|
||||||
|
let tls = match &transport {
|
||||||
|
Transport::Tls { cert, key } => Some((cert.clone(), key.clone())),
|
||||||
|
_ => None,
|
||||||
};
|
};
|
||||||
let app = Router::new()
|
let state = AppState::new(Arc::new(Storage::open(&data_dir)?), auth, transport);
|
||||||
.route("/api/health", get(health))
|
let service = build_app(state).into_make_service_with_connect_info::<SocketAddr>();
|
||||||
.route("/api/status", get(status))
|
match tls {
|
||||||
.route("/api/alerts", get(alerts))
|
None => {
|
||||||
.route("/api/analyze", post(analyze))
|
|
||||||
.route("/api/update", get(update_check))
|
|
||||||
.route("/logo.png", get(logo))
|
|
||||||
.fallback(asset)
|
|
||||||
.with_state(state)
|
|
||||||
.layer(CompressionLayer::new())
|
|
||||||
.layer(CorsLayer::new())
|
|
||||||
.layer(TraceLayer::new_for_http());
|
|
||||||
let listener = TcpListener::bind(bind).await?;
|
let listener = TcpListener::bind(bind).await?;
|
||||||
println!("Acauã listening on http://{bind}");
|
println!("Acauã listening on http://{bind}");
|
||||||
axum::serve(listener, app)
|
axum::serve(listener, service)
|
||||||
.with_graceful_shutdown(shutdown_signal())
|
.with_graceful_shutdown(shutdown_signal())
|
||||||
.await?;
|
.await?;
|
||||||
|
}
|
||||||
|
Some((cert, key)) => {
|
||||||
|
let addr: SocketAddr = bind.parse().map_err(|_| {
|
||||||
|
AcauaError::InvalidInput(format!(
|
||||||
|
"--bind `{bind}` must be an IP:port when ACAUA_TRANSPORT=tls"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
let config = RustlsConfig::from_pem_file(&cert, &key)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
AcauaError::InvalidInput(format!(
|
||||||
|
"cannot load ACAUA_TLS_CERT/ACAUA_TLS_KEY: {e}"
|
||||||
|
))
|
||||||
|
})?;
|
||||||
|
let handle = Handle::new();
|
||||||
|
let stopper = handle.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
shutdown_signal().await;
|
||||||
|
stopper.graceful_shutdown(Some(Duration::from_secs(10)));
|
||||||
|
});
|
||||||
|
println!("Acauã listening on https://{bind}");
|
||||||
|
axum_server::bind_rustls(addr, config)
|
||||||
|
.handle(handle)
|
||||||
|
.serve(service)
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
#[path = "web_tests.rs"]
|
||||||
|
mod tests;
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -19,6 +19,13 @@ chrono = { version = "0.4", default-features = false, features = ["std"] }
|
|||||||
# never enable `bundled`, `parquet`, `json` or `extensions-full`, which compile
|
# never enable `bundled`, `parquet`, `json` or `extensions-full`, which compile
|
||||||
# DuckDB from source. Parquet, JSON and ICU are already inside libduckdb.so.
|
# DuckDB from source. Parquet, JSON and ICU are already inside libduckdb.so.
|
||||||
duckdb = "~1.10506.1"
|
duckdb = "~1.10506.1"
|
||||||
|
aes-gcm = "0.10"
|
||||||
|
base64 = "0.22"
|
||||||
|
fs2 = "0.4"
|
||||||
|
argon2 = "0.6.0"
|
||||||
|
totp-rs = { version = "6.0.0", features = ["qr", "otpauth"] }
|
||||||
|
unicode-normalization = "0.1"
|
||||||
|
subtle = "2"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
tempfile = "3"
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
@@ -0,0 +1,203 @@
|
|||||||
|
use super::{set_mode, DirLock, AUDIT_FILE};
|
||||||
|
use crate::error::{AcauaError, Result};
|
||||||
|
|
||||||
|
/// Action of the synthetic entry `tail` emits for an unparseable line.
|
||||||
|
pub const CORRUPT_ACTION: &str = "audit.corrupt_line";
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::fs::{self, OpenOptions};
|
||||||
|
use std::io::{Read, Seek, SeekFrom, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use time::format_description::well_known::Rfc3339;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
|
||||||
|
/// What happened. Deliberately has no field for passwords, tokens, codes or
|
||||||
|
/// keys: callers can only describe the event, never attach a secret.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct AuditEvent {
|
||||||
|
/// Machine-readable action, e.g. `login`, `token.create`.
|
||||||
|
pub action: String,
|
||||||
|
pub actor: Option<String>,
|
||||||
|
pub ip: Option<String>,
|
||||||
|
pub ok: bool,
|
||||||
|
/// Short non-secret note.
|
||||||
|
pub detail: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct AuditEntry {
|
||||||
|
pub ts: String,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub event: AuditEvent,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct AuditLog {
|
||||||
|
dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuditLog {
|
||||||
|
pub fn open(dir: &Path) -> AuditLog {
|
||||||
|
AuditLog {
|
||||||
|
dir: dir.to_path_buf(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record(&self, event: AuditEvent) -> Result<()> {
|
||||||
|
let _lock = DirLock::acquire(&self.dir, true)?;
|
||||||
|
let ts = OffsetDateTime::now_utc()
|
||||||
|
.format(&Rfc3339)
|
||||||
|
.map_err(|e| AcauaError::InvalidInput(e.to_string()))?;
|
||||||
|
let mut line = serde_json::to_vec(&AuditEntry { ts, event })?;
|
||||||
|
line.push(b'\n');
|
||||||
|
let mut opts = OpenOptions::new();
|
||||||
|
opts.read(true).append(true).create(true);
|
||||||
|
set_mode(&mut opts, 0o600);
|
||||||
|
let path = self.dir.join(AUDIT_FILE);
|
||||||
|
// A crash can leave an unterminated fragment; close it so the new
|
||||||
|
// entry starts on its own line. `tail` reports the fragment.
|
||||||
|
let mut file = opts.open(&path)?;
|
||||||
|
if file.metadata()?.len() > 0 {
|
||||||
|
let mut last = [0u8; 1];
|
||||||
|
file.seek(SeekFrom::End(-1))?;
|
||||||
|
file.read_exact(&mut last)?;
|
||||||
|
if last[0] != b'\n' {
|
||||||
|
line.insert(0, b'\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file.write_all(&line)?;
|
||||||
|
file.sync_all()?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Last `limit` entries, oldest first.
|
||||||
|
pub fn tail(&self, limit: usize) -> Result<Vec<AuditEntry>> {
|
||||||
|
let _lock = DirLock::acquire(&self.dir, false)?;
|
||||||
|
let raw = match fs::read(self.dir.join(AUDIT_FILE)) {
|
||||||
|
Ok(raw) => raw,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
};
|
||||||
|
// Bytes, not str: a torn write may cut a multi-byte character.
|
||||||
|
let lines: Vec<&[u8]> = raw
|
||||||
|
.split(|b| *b == b'\n')
|
||||||
|
.filter(|l| !l.iter().all(u8::is_ascii_whitespace))
|
||||||
|
.collect();
|
||||||
|
let start = lines.len().saturating_sub(limit);
|
||||||
|
// A torn line does not fail the read: it is surfaced as a visible
|
||||||
|
// `audit.corrupt_line` entry (ok = false) at its position.
|
||||||
|
Ok(lines[start..]
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, l)| {
|
||||||
|
serde_json::from_slice(l).unwrap_or_else(|_| AuditEntry {
|
||||||
|
ts: String::new(),
|
||||||
|
event: AuditEvent {
|
||||||
|
action: CORRUPT_ACTION.into(),
|
||||||
|
ok: false,
|
||||||
|
detail: Some(format!("unparseable audit line #{}", start + i + 1)),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audit_appends_and_never_serializes_secret() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let log = AuditLog::open(dir.path());
|
||||||
|
assert!(log.tail(5).unwrap().is_empty());
|
||||||
|
for i in 0..3 {
|
||||||
|
log.record(AuditEvent {
|
||||||
|
action: format!("a{i}"),
|
||||||
|
actor: Some("ana".into()),
|
||||||
|
ok: i % 2 == 0,
|
||||||
|
..Default::default()
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
let all = log.tail(10).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
all.iter()
|
||||||
|
.map(|e| e.event.action.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
["a0", "a1", "a2"]
|
||||||
|
);
|
||||||
|
let last = log.tail(2).unwrap();
|
||||||
|
assert_eq!(last[0].event.action, "a1");
|
||||||
|
assert!(!all[0].ts.is_empty());
|
||||||
|
|
||||||
|
let raw = fs::read_to_string(dir.path().join(AUDIT_FILE)).unwrap();
|
||||||
|
assert_eq!(raw.lines().count(), 3);
|
||||||
|
for key in ["password", "secret", "token", "code", "key"] {
|
||||||
|
assert!(
|
||||||
|
!raw.contains(&format!("\"{key}\"")),
|
||||||
|
"unexpected field {key}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mode = fs::metadata(dir.path().join(AUDIT_FILE))
|
||||||
|
.unwrap()
|
||||||
|
.permissions()
|
||||||
|
.mode();
|
||||||
|
assert_eq!(mode & 0o777, 0o600);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn torn_line_is_reported_and_next_record_is_separate() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let log = AuditLog::open(dir.path());
|
||||||
|
let ev = |a: &str| AuditEvent {
|
||||||
|
action: a.into(),
|
||||||
|
ok: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
log.record(ev("a0")).unwrap();
|
||||||
|
let path = dir.path().join(AUDIT_FILE);
|
||||||
|
let mut f = OpenOptions::new().append(true).open(&path).unwrap();
|
||||||
|
f.write_all(br#"{"ts":"2026-01-01T00:0"#).unwrap();
|
||||||
|
drop(f);
|
||||||
|
// Reading over the fragment works and flags it.
|
||||||
|
let t = log.tail(10).unwrap();
|
||||||
|
assert_eq!(t.len(), 2);
|
||||||
|
assert_eq!(t[1].event.action, CORRUPT_ACTION);
|
||||||
|
assert!(!t[1].event.ok);
|
||||||
|
// The next record must not join the fragment.
|
||||||
|
log.record(ev("a1")).unwrap();
|
||||||
|
let t = log.tail(10).unwrap();
|
||||||
|
let actions: Vec<_> = t.iter().map(|e| e.event.action.as_str()).collect();
|
||||||
|
assert_eq!(actions, ["a0", CORRUPT_ACTION, "a1"]);
|
||||||
|
assert!(t[2].event.ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn torn_multibyte_character_does_not_fail_tail() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let log = AuditLog::open(dir.path());
|
||||||
|
let ev = |a: &str| AuditEvent {
|
||||||
|
action: a.into(),
|
||||||
|
ok: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
log.record(ev("a0")).unwrap();
|
||||||
|
let path = dir.path().join(AUDIT_FILE);
|
||||||
|
// "é" is 0xC3 0xA9; cut after the first byte.
|
||||||
|
let mut f = OpenOptions::new().append(true).open(&path).unwrap();
|
||||||
|
f.write_all(b"{\"ts\":\"x\",\"action\":\"caf\xC3").unwrap();
|
||||||
|
drop(f);
|
||||||
|
let t = log.tail(10).unwrap();
|
||||||
|
assert_eq!(t.len(), 2);
|
||||||
|
assert_eq!(t[0].event.action, "a0");
|
||||||
|
assert_eq!(t[1].event.action, CORRUPT_ACTION);
|
||||||
|
log.record(ev("a1")).unwrap();
|
||||||
|
let t = log.tail(10).unwrap();
|
||||||
|
let actions: Vec<_> = t.iter().map(|e| e.event.action.as_str()).collect();
|
||||||
|
assert_eq!(actions, ["a0", CORRUPT_ACTION, "a1"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,412 @@
|
|||||||
|
//! Password hashing, TOTP and recovery codes. Crypto comes from audited
|
||||||
|
//! crates (`argon2`, `totp-rs`); nothing here is hand-rolled.
|
||||||
|
|
||||||
|
use super::secrets::{hash_token, random_token};
|
||||||
|
use crate::error::{AcauaError, Result};
|
||||||
|
use aes_gcm::aead::{rand_core::RngCore, OsRng};
|
||||||
|
use argon2::password_hash::{PasswordHasher, PasswordVerifier};
|
||||||
|
use argon2::{Algorithm, Argon2, Params, Version};
|
||||||
|
use std::collections::HashSet;
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
use totp_rs::{Algorithm as TotpAlgorithm, Builder as TotpBuilder, Totp};
|
||||||
|
use unicode_normalization::UnicodeNormalization;
|
||||||
|
|
||||||
|
/// Minimum password length, in characters.
|
||||||
|
pub const PASSWORD_MIN_CHARS: usize = 12;
|
||||||
|
/// Maximum password length, in bytes (bounds Argon2 work per request).
|
||||||
|
pub const PASSWORD_MAX_BYTES: usize = 256;
|
||||||
|
|
||||||
|
/// Argon2id cost: m=19456 KiB, t=2, p=1 (OWASP minimum profile).
|
||||||
|
const ARGON_M_KIB: u32 = 19_456;
|
||||||
|
const ARGON_T: u32 = 2;
|
||||||
|
const ARGON_P: u32 = 1;
|
||||||
|
|
||||||
|
const TOTP_SECRET_BYTES: usize = 20;
|
||||||
|
const TOTP_DIGITS: u8 = 6;
|
||||||
|
const TOTP_STEP_SECS: u64 = 30;
|
||||||
|
const TOTP_SKEW: u16 = 1;
|
||||||
|
const TOTP_ISSUER: &str = "Acauã";
|
||||||
|
|
||||||
|
const RECOVERY_CODE_COUNT: usize = 10;
|
||||||
|
const RECOVERY_CODE_BYTES: usize = 10; // 80 bits
|
||||||
|
|
||||||
|
/// SecLists 10k-most-common (MIT). Untrusted data: only a word list.
|
||||||
|
static COMMON_PASSWORDS_RAW: &str = include_str!("common-passwords.txt");
|
||||||
|
|
||||||
|
fn common_passwords() -> &'static HashSet<String> {
|
||||||
|
static SET: OnceLock<HashSet<String>> = OnceLock::new();
|
||||||
|
SET.get_or_init(|| {
|
||||||
|
COMMON_PASSWORDS_RAW
|
||||||
|
.lines()
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||||
|
.map(str::to_lowercase)
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_common(password: &str) -> bool {
|
||||||
|
let lower = password.to_lowercase();
|
||||||
|
let set = common_passwords();
|
||||||
|
if set.contains(&lower) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
// Common word plus a numeric suffix ("password1234") is no better.
|
||||||
|
let base = lower.trim_end_matches(|c: char| c.is_ascii_digit());
|
||||||
|
!base.is_empty() && base.len() != lower.len() && set.contains(base)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// NFC form: the same password typed on different keyboards or systems must
|
||||||
|
/// produce the same bytes. Every password path goes through this.
|
||||||
|
pub(super) fn normalize(password: &str) -> String {
|
||||||
|
password.nfc().collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rejects short, oversized, common, single-character and all-digit passwords.
|
||||||
|
/// No composition rules. The checks apply to the NFC form. Error messages
|
||||||
|
/// never echo the password.
|
||||||
|
pub fn validate_password(password: &str) -> Result<()> {
|
||||||
|
let password = normalize(password);
|
||||||
|
let password = password.as_str();
|
||||||
|
if password.len() > PASSWORD_MAX_BYTES {
|
||||||
|
return Err(AcauaError::InvalidInput(format!(
|
||||||
|
"password must be at most {PASSWORD_MAX_BYTES} bytes"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if password.chars().count() < PASSWORD_MIN_CHARS {
|
||||||
|
return Err(AcauaError::InvalidInput(format!(
|
||||||
|
"password must be at least {PASSWORD_MIN_CHARS} characters"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
if is_common(password) {
|
||||||
|
return Err(AcauaError::InvalidInput(
|
||||||
|
"password is too common".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut chars = password.chars();
|
||||||
|
if let Some(first) = chars.next() {
|
||||||
|
if chars.all(|c| c == first) {
|
||||||
|
return Err(AcauaError::InvalidInput(
|
||||||
|
"password must not repeat a single character".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if password.chars().all(char::is_numeric) {
|
||||||
|
return Err(AcauaError::InvalidInput(
|
||||||
|
"password must not be only digits".to_string(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn argon2() -> Result<Argon2<'static>> {
|
||||||
|
let params = Params::new(ARGON_M_KIB, ARGON_T, ARGON_P, None).map_err(|_| hash_failure())?;
|
||||||
|
Ok(Argon2::new(Algorithm::Argon2id, Version::V0x13, params))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hash_failure() -> AcauaError {
|
||||||
|
AcauaError::CommandFailed {
|
||||||
|
cmd: "argon2".to_string(),
|
||||||
|
detail: "password hashing failed".to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Argon2id (m=19456 KiB, t=2, p=1) hash in PHC string format, random salt.
|
||||||
|
pub fn hash_password(password: &str) -> Result<String> {
|
||||||
|
let password = normalize(password);
|
||||||
|
if password.len() > PASSWORD_MAX_BYTES {
|
||||||
|
return Err(AcauaError::InvalidInput(format!(
|
||||||
|
"password must be at most {PASSWORD_MAX_BYTES} bytes"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
let hash = argon2()?
|
||||||
|
.hash_password(password.as_bytes())
|
||||||
|
.map_err(|_| hash_failure())?;
|
||||||
|
Ok(hash.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dummy_hash() -> Option<&'static str> {
|
||||||
|
static DUMMY: OnceLock<Option<String>> = OnceLock::new();
|
||||||
|
DUMMY
|
||||||
|
.get_or_init(|| hash_password(&random_token(24)).ok())
|
||||||
|
.as_deref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verifies a candidate. With `hash == None` (unknown user) a dummy hash is
|
||||||
|
/// still verified so timing does not reveal whether the user exists; the
|
||||||
|
/// result is then always `false`. A malformed stored hash also yields `false`.
|
||||||
|
pub fn verify_password(hash: Option<&str>, candidate: &str) -> bool {
|
||||||
|
// Oversized input is refused before any Argon2 work.
|
||||||
|
let candidate = normalize(candidate);
|
||||||
|
if candidate.len() > PASSWORD_MAX_BYTES {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Ok(engine) = argon2() else { return false };
|
||||||
|
let (stored, real) = match hash {
|
||||||
|
Some(h) => (h, true),
|
||||||
|
None => match dummy_hash() {
|
||||||
|
Some(d) => (d, false),
|
||||||
|
None => return false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let Ok(parsed) = argon2::password_hash::phc::PasswordHash::from_str(stored) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let ok = engine
|
||||||
|
.verify_password(candidate.as_bytes(), &parsed)
|
||||||
|
.is_ok();
|
||||||
|
ok && real
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 160-bit random TOTP secret from the OS CSPRNG.
|
||||||
|
pub fn new_totp_secret() -> Vec<u8> {
|
||||||
|
let mut buf = vec![0u8; TOTP_SECRET_BYTES];
|
||||||
|
OsRng.fill_bytes(&mut buf);
|
||||||
|
buf
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn build_totp(secret: &[u8], account: &str) -> Result<Totp> {
|
||||||
|
TotpBuilder::new()
|
||||||
|
.with_algorithm(TotpAlgorithm::SHA1)
|
||||||
|
.with_digits(TOTP_DIGITS)
|
||||||
|
.with_skew(TOTP_SKEW)
|
||||||
|
.with_step_duration(TOTP_STEP_SECS)
|
||||||
|
.with_secret(secret.to_vec())
|
||||||
|
.with_account_name(account)
|
||||||
|
.with_issuer(Some(TOTP_ISSUER))
|
||||||
|
.build()
|
||||||
|
.map_err(|_| AcauaError::InvalidInput("invalid TOTP secret or account name".to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `otpauth://` URI and the QR code as base64 PNG.
|
||||||
|
pub fn totp_uri_and_qr(secret: &[u8], account: &str) -> Result<(String, String)> {
|
||||||
|
let totp = build_totp(secret, account)?;
|
||||||
|
let fail = |_| AcauaError::InvalidInput("could not encode TOTP enrolment".to_string());
|
||||||
|
let uri = totp.to_url().map_err(fail)?;
|
||||||
|
let qr = totp.to_qr_base64().map_err(fail)?;
|
||||||
|
Ok((uri, qr))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks a code at `unix` (SHA-1, 6 digits, 30 s, +-1 step). Returns the
|
||||||
|
/// accepted step, or `None` if invalid or not newer than `last_step`
|
||||||
|
/// (a step is never accepted twice).
|
||||||
|
pub fn verify_totp(secret: &[u8], code: &str, unix: u64, last_step: Option<u64>) -> Option<u64> {
|
||||||
|
let totp = build_totp(secret, "acaua").ok()?;
|
||||||
|
let step = totp.check(code.trim(), unix)?;
|
||||||
|
match last_step {
|
||||||
|
Some(last) if step <= last => None,
|
||||||
|
_ => Some(step),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Canonical form used for hashing: alphanumerics only, lowercase.
|
||||||
|
fn canonical_recovery(code: &str) -> String {
|
||||||
|
code.chars()
|
||||||
|
.filter(char::is_ascii_alphanumeric)
|
||||||
|
.map(|c| c.to_ascii_lowercase())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hash stored for a recovery code (case and separators ignored).
|
||||||
|
pub fn hash_recovery_code(code: &str) -> String {
|
||||||
|
hash_token(&canonical_recovery(code))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ten single-use 80-bit codes: `(display texts, SHA-256 hashes)`. Codes are
|
||||||
|
/// 20 hex digits in groups of five; only the hashes should be persisted.
|
||||||
|
pub fn new_recovery_codes() -> (Vec<String>, Vec<String>) {
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
let mut texts = Vec::with_capacity(RECOVERY_CODE_COUNT);
|
||||||
|
let mut hashes = Vec::with_capacity(RECOVERY_CODE_COUNT);
|
||||||
|
while texts.len() < RECOVERY_CODE_COUNT {
|
||||||
|
let mut raw = [0u8; RECOVERY_CODE_BYTES];
|
||||||
|
OsRng.fill_bytes(&mut raw);
|
||||||
|
let hex: String = raw.iter().map(|b| format!("{b:02x}")).collect();
|
||||||
|
if !seen.insert(hex.clone()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let text = format!(
|
||||||
|
"{}-{}-{}-{}",
|
||||||
|
&hex[0..5],
|
||||||
|
&hex[5..10],
|
||||||
|
&hex[10..15],
|
||||||
|
&hex[15..20]
|
||||||
|
);
|
||||||
|
hashes.push(hash_recovery_code(&text));
|
||||||
|
texts.push(text);
|
||||||
|
}
|
||||||
|
(texts, hashes)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_short_common_and_oversized_password() {
|
||||||
|
assert!(validate_password("abcdefghijk").is_err(), "11 chars");
|
||||||
|
assert!(validate_password("password1234").is_err(), "common");
|
||||||
|
assert!(
|
||||||
|
validate_password("PASSWORD1234").is_err(),
|
||||||
|
"common, case-insensitive"
|
||||||
|
);
|
||||||
|
assert!(validate_password(&"a1".repeat(129)).is_err(), "258 bytes");
|
||||||
|
assert!(validate_password(&"x".repeat(257)).is_err(), "257 bytes");
|
||||||
|
assert!(validate_password("correct horse battery staple").is_ok());
|
||||||
|
assert!(validate_password("ação de graças tardia").is_ok());
|
||||||
|
// 12 chars but more than 12 bytes: length counts characters.
|
||||||
|
assert!(validate_password("ããããããããããàã").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn password_roundtrip_and_params() {
|
||||||
|
let h = hash_password("correct horse battery staple").unwrap();
|
||||||
|
assert!(h.starts_with("$argon2id$v=19$m=19456,t=2,p=1$"), "{h}");
|
||||||
|
assert!(verify_password(Some(&h), "correct horse battery staple"));
|
||||||
|
assert!(!verify_password(Some(&h), "correct horse battery stapl"));
|
||||||
|
assert!(!verify_password(Some("not a phc string"), "x"));
|
||||||
|
assert_ne!(
|
||||||
|
h,
|
||||||
|
hash_password("correct horse battery staple").unwrap(),
|
||||||
|
"salted"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verify_password_handles_missing_user() {
|
||||||
|
assert!(!verify_password(None, "x"));
|
||||||
|
assert!(!verify_password(None, "correct horse battery staple"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rejects_repeated_character_and_all_digit_passwords() {
|
||||||
|
assert!(validate_password("aaaaaaaaaaaaaaaa").is_err(), "repeated");
|
||||||
|
assert!(validate_password("ãããããããããããããããã").is_err(), "repeated");
|
||||||
|
// Same repeated character, decomposed: must still be caught after NFC.
|
||||||
|
assert!(validate_password(&"a\u{0303}".repeat(14)).is_err());
|
||||||
|
assert!(validate_password("190283746501928").is_err(), "digits");
|
||||||
|
assert!(validate_password("١٢٣٤٥٦٧٨٩٠١٢٣").is_err(), "other digits");
|
||||||
|
assert!(validate_password("190283746501928x").is_ok());
|
||||||
|
assert!(validate_password("abababababababab").is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn password_is_nfc_normalized_everywhere() {
|
||||||
|
let composed = "maçã açaí pitanga";
|
||||||
|
let decomposed = "mac\u{0327}a\u{0303} ac\u{0327}ai\u{0301} pitanga";
|
||||||
|
assert_ne!(composed, decomposed);
|
||||||
|
let h = hash_password(decomposed).unwrap();
|
||||||
|
assert!(verify_password(Some(&h), composed));
|
||||||
|
let h = hash_password(composed).unwrap();
|
||||||
|
assert!(verify_password(Some(&h), decomposed));
|
||||||
|
// Length counts the normalized form: 11 composed characters.
|
||||||
|
assert!(validate_password("e\u{0301}xyzuvwklm1").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rfc_secret() -> &'static [u8] {
|
||||||
|
b"12345678901234567890"
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn totp_rfc6238_vector() {
|
||||||
|
// RFC 6238 appendix B, T=59 -> 94287082 (8 digits) -> 287082 (6).
|
||||||
|
assert_eq!(verify_totp(rfc_secret(), "287082", 59, None), Some(1));
|
||||||
|
assert_eq!(verify_totp(rfc_secret(), "287083", 59, None), None);
|
||||||
|
assert_eq!(verify_totp(rfc_secret(), "28708", 59, None), None);
|
||||||
|
assert_eq!(verify_totp(rfc_secret(), "2870820", 59, None), None);
|
||||||
|
assert_eq!(verify_totp(rfc_secret(), "abcdef", 59, None), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn totp_window_and_replay() {
|
||||||
|
// "287082" is the code for step 1. Steps 0 and 2 are +-1 of it.
|
||||||
|
assert_eq!(
|
||||||
|
verify_totp(rfc_secret(), "287082", 0, None),
|
||||||
|
Some(1),
|
||||||
|
"-1 step"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
verify_totp(rfc_secret(), "287082", 89, None),
|
||||||
|
Some(1),
|
||||||
|
"+1 step"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
verify_totp(rfc_secret(), "287082", 30 * 3, None),
|
||||||
|
None,
|
||||||
|
"+2 steps"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
verify_totp(rfc_secret(), "287082", 30 * 4, None),
|
||||||
|
None,
|
||||||
|
"+3 steps"
|
||||||
|
);
|
||||||
|
// Step 1 at unix 1000 would be -32 steps; use a larger base to test -2.
|
||||||
|
assert_eq!(verify_totp(rfc_secret(), "287082", 30 * 101, None), None);
|
||||||
|
assert_eq!(
|
||||||
|
verify_totp(rfc_secret(), "287082", 59, Some(1)),
|
||||||
|
None,
|
||||||
|
"replay"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
verify_totp(rfc_secret(), "287082", 59, Some(2)),
|
||||||
|
None,
|
||||||
|
"older than last"
|
||||||
|
);
|
||||||
|
assert_eq!(verify_totp(rfc_secret(), "287082", 59, Some(0)), Some(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn totp_rejects_future_steps_beyond_tolerance() {
|
||||||
|
let totp = build_totp(rfc_secret(), "a").unwrap();
|
||||||
|
let code_step_5 = totp.generate(5 * 30).to_string();
|
||||||
|
assert_eq!(
|
||||||
|
verify_totp(rfc_secret(), &code_step_5, 4 * 30, None),
|
||||||
|
Some(5),
|
||||||
|
"+1 ahead"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
verify_totp(rfc_secret(), &code_step_5, 3 * 30, None),
|
||||||
|
None,
|
||||||
|
"2 ahead"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn totp_uri_and_qr_shape() {
|
||||||
|
let secret = new_totp_secret();
|
||||||
|
assert_eq!(secret.len(), 20);
|
||||||
|
assert_ne!(secret, new_totp_secret());
|
||||||
|
let (uri, qr) = totp_uri_and_qr(&secret, "ana@example.org").unwrap();
|
||||||
|
assert!(uri.starts_with("otpauth://totp/"), "{uri}");
|
||||||
|
// SHA1 / 6 digits / 30 s are the otpauth defaults, so they are omitted.
|
||||||
|
assert!(uri.contains("secret=") && !uri.contains("algorithm=SHA256"));
|
||||||
|
assert!(uri.contains("issuer="), "{uri}");
|
||||||
|
use base64::{engine::general_purpose::STANDARD, Engine};
|
||||||
|
let png = STANDARD.decode(qr).unwrap();
|
||||||
|
assert_eq!(&png[..4], b"\x89PNG");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recovery_codes_unique_and_hashed() {
|
||||||
|
let (codes, hashes) = new_recovery_codes();
|
||||||
|
assert_eq!(codes.len(), 10);
|
||||||
|
assert_eq!(hashes.len(), 10);
|
||||||
|
let uniq: std::collections::HashSet<_> = codes.iter().collect();
|
||||||
|
assert_eq!(uniq.len(), 10);
|
||||||
|
let uh: std::collections::HashSet<_> = hashes.iter().collect();
|
||||||
|
assert_eq!(uh.len(), 10);
|
||||||
|
for (c, h) in codes.iter().zip(&hashes) {
|
||||||
|
assert_ne!(c, h);
|
||||||
|
assert_eq!(h, &hash_recovery_code(c));
|
||||||
|
assert_eq!(h.len(), 64);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recovery_hash_ignores_case_and_separators() {
|
||||||
|
let (codes, hashes) = new_recovery_codes();
|
||||||
|
let mangled = codes[0].replace('-', " ").to_uppercase();
|
||||||
|
assert_eq!(hash_recovery_code(&mangled), hashes[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
//! Authentication foundation: encrypted secrets, atomic state, audit log.
|
||||||
|
//!
|
||||||
|
//! Layout: `<data_dir>/auth/{state.json,secret.key,audit.jsonl,.lock}`.
|
||||||
|
|
||||||
|
pub mod audit;
|
||||||
|
pub mod credentials;
|
||||||
|
pub mod secrets;
|
||||||
|
pub mod service;
|
||||||
|
pub mod store;
|
||||||
|
pub mod throttle;
|
||||||
|
pub mod tokens;
|
||||||
|
|
||||||
|
pub use audit::{AuditEntry, AuditEvent, AuditLog};
|
||||||
|
pub use secrets::{hash_token, random_token, Secrets};
|
||||||
|
pub use service::{
|
||||||
|
AuthService, LoginAttempt, LoginStep, NewSession, PendingMfa, TotpEnrollment, UserView,
|
||||||
|
};
|
||||||
|
pub use store::{
|
||||||
|
ApiToken, AuthState, AuthStore, Bootstrap, KnownAddress, Role, Scope, Session, User,
|
||||||
|
};
|
||||||
|
pub use tokens::{csrf_matches, csrf_token, NewToken, Principal, SessionView, TokenView, Via};
|
||||||
|
|
||||||
|
use crate::error::Result;
|
||||||
|
use fs2::FileExt;
|
||||||
|
use std::fs::{self, File, OpenOptions};
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
pub(crate) const STATE_FILE: &str = "state.json";
|
||||||
|
pub(crate) const KEY_FILE: &str = "secret.key";
|
||||||
|
pub(crate) const AUDIT_FILE: &str = "audit.jsonl";
|
||||||
|
pub(crate) const LOCK_FILE: &str = ".lock";
|
||||||
|
|
||||||
|
/// Advisory inter-process lock on `<dir>/.lock`, released on drop.
|
||||||
|
pub(crate) struct DirLock {
|
||||||
|
_file: File,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DirLock {
|
||||||
|
pub(crate) fn acquire(dir: &Path, exclusive: bool) -> Result<Self> {
|
||||||
|
ensure_dir(dir)?;
|
||||||
|
let mut opts = OpenOptions::new();
|
||||||
|
opts.read(true).write(true).create(true).truncate(false);
|
||||||
|
set_mode(&mut opts, 0o600);
|
||||||
|
let file = opts.open(dir.join(LOCK_FILE))?;
|
||||||
|
if exclusive {
|
||||||
|
FileExt::lock_exclusive(&file)?;
|
||||||
|
} else {
|
||||||
|
FileExt::lock_shared(&file)?;
|
||||||
|
}
|
||||||
|
Ok(Self { _file: file })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn ensure_dir(dir: &Path) -> Result<()> {
|
||||||
|
if !dir.is_dir() {
|
||||||
|
fs::create_dir_all(dir)?;
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
pub(crate) fn set_mode(opts: &mut OpenOptions, mode: u32) {
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
opts.mode(mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
pub(crate) fn set_mode(_opts: &mut OpenOptions, _mode: u32) {}
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
use super::{set_mode, DirLock, KEY_FILE, STATE_FILE};
|
||||||
|
use crate::error::{AcauaError, AuthFailure, Result};
|
||||||
|
use aes_gcm::aead::{rand_core::RngCore, Aead, AeadCore, KeyInit, OsRng};
|
||||||
|
use aes_gcm::{Aes256Gcm, Key, Nonce};
|
||||||
|
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
|
||||||
|
use base64::Engine;
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
use std::fs::{self, OpenOptions};
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
const KEY_LEN: usize = 32;
|
||||||
|
const NONCE_LEN: usize = 12;
|
||||||
|
|
||||||
|
/// AES-256-GCM sealing of small secrets (TOTP seeds and similar).
|
||||||
|
pub struct Secrets {
|
||||||
|
cipher: Aes256Gcm,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Secrets {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.write_str("Secrets(<redacted>)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Secrets {
|
||||||
|
/// Loads the key from `key_file` (e.g. a Docker secret) or from
|
||||||
|
/// `<auth_dir>/secret.key`. A new key is generated only when no auth state
|
||||||
|
/// exists yet; a missing key next to existing state is an error.
|
||||||
|
pub fn open(auth_dir: &Path, key_file: Option<&Path>) -> Result<Secrets> {
|
||||||
|
if let Some(path) = key_file {
|
||||||
|
let raw = fs::read(path).map_err(|e| {
|
||||||
|
if e.kind() == std::io::ErrorKind::NotFound {
|
||||||
|
AcauaError::Auth(AuthFailure::KeyMissing)
|
||||||
|
} else {
|
||||||
|
AcauaError::Io(e)
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
return Self::from_bytes(&raw);
|
||||||
|
}
|
||||||
|
let path = auth_dir.join(KEY_FILE);
|
||||||
|
match fs::read(&path) {
|
||||||
|
Ok(raw) => Self::from_bytes(&raw),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||||
|
if auth_dir.join(STATE_FILE).exists() {
|
||||||
|
return Err(AuthFailure::KeyMissing.into());
|
||||||
|
}
|
||||||
|
Self::create_key(auth_dir, &path)
|
||||||
|
}
|
||||||
|
Err(e) => Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// First-run key creation, serialized by the dir lock. The key appears
|
||||||
|
/// atomically (temp file, fsync, hard link that never overwrites).
|
||||||
|
fn create_key(auth_dir: &Path, path: &Path) -> Result<Secrets> {
|
||||||
|
let _lock = DirLock::acquire(auth_dir, true)?;
|
||||||
|
// Recheck under the lock: another process may have won the race.
|
||||||
|
match fs::read(path) {
|
||||||
|
Ok(raw) => return Self::from_bytes(&raw),
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
}
|
||||||
|
if auth_dir.join(STATE_FILE).exists() {
|
||||||
|
return Err(AuthFailure::KeyMissing.into());
|
||||||
|
}
|
||||||
|
let mut key = [0u8; KEY_LEN];
|
||||||
|
OsRng.fill_bytes(&mut key);
|
||||||
|
let tmp = auth_dir.join(format!("{KEY_FILE}.tmp"));
|
||||||
|
let _ = fs::remove_file(&tmp);
|
||||||
|
let mut opts = OpenOptions::new();
|
||||||
|
opts.write(true).create_new(true);
|
||||||
|
set_mode(&mut opts, 0o600);
|
||||||
|
let mut file = opts.open(&tmp)?;
|
||||||
|
let written = file
|
||||||
|
.write_all(STANDARD.encode(key).as_bytes())
|
||||||
|
.and_then(|_| file.sync_all());
|
||||||
|
drop(file);
|
||||||
|
let linked = written.and_then(|_| fs::hard_link(&tmp, path));
|
||||||
|
let _ = fs::remove_file(&tmp);
|
||||||
|
linked?;
|
||||||
|
if let Ok(d) = fs::File::open(auth_dir) {
|
||||||
|
let _ = d.sync_all();
|
||||||
|
}
|
||||||
|
Self::from_bytes(&key)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accepts the key as raw 32 bytes or as base64 text (whitespace trimmed).
|
||||||
|
fn from_bytes(raw: &[u8]) -> Result<Secrets> {
|
||||||
|
let key: Vec<u8> = if raw.len() == KEY_LEN {
|
||||||
|
raw.to_vec()
|
||||||
|
} else {
|
||||||
|
let text = std::str::from_utf8(raw)
|
||||||
|
.map_err(|_| AuthFailure::KeyInvalid("not raw 32 bytes nor base64 text"))?;
|
||||||
|
STANDARD
|
||||||
|
.decode(text.trim())
|
||||||
|
.map_err(|_| AuthFailure::KeyInvalid("not raw 32 bytes nor base64 text"))?
|
||||||
|
};
|
||||||
|
if key.len() != KEY_LEN {
|
||||||
|
return Err(AuthFailure::KeyInvalid("must be 32 bytes").into());
|
||||||
|
}
|
||||||
|
Ok(Secrets {
|
||||||
|
cipher: Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns base64(nonce || ciphertext+tag) with a fresh random nonce.
|
||||||
|
pub fn seal(&self, plain: &[u8]) -> Result<String> {
|
||||||
|
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
|
||||||
|
let ct = self
|
||||||
|
.cipher
|
||||||
|
.encrypt(&nonce, plain)
|
||||||
|
.map_err(|_| AuthFailure::SealInvalid)?;
|
||||||
|
let mut out = nonce.to_vec();
|
||||||
|
out.extend_from_slice(&ct);
|
||||||
|
Ok(STANDARD.encode(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open_sealed(&self, sealed: &str) -> Result<Vec<u8>> {
|
||||||
|
let raw = STANDARD
|
||||||
|
.decode(sealed.trim())
|
||||||
|
.map_err(|_| AuthFailure::SealInvalid)?;
|
||||||
|
if raw.len() < NONCE_LEN + 16 {
|
||||||
|
return Err(AuthFailure::SealInvalid.into());
|
||||||
|
}
|
||||||
|
let (nonce, ct) = raw.split_at(NONCE_LEN);
|
||||||
|
self.cipher
|
||||||
|
.decrypt(Nonce::from_slice(nonce), ct)
|
||||||
|
.map_err(|_| AuthFailure::SealInvalid.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// URL-safe base64 (no padding) of `bytes` random bytes from the OS CSPRNG.
|
||||||
|
/// An OS RNG failure is unrecoverable and aborts, as in `OsRng::fill_bytes`.
|
||||||
|
pub fn random_token(bytes: usize) -> String {
|
||||||
|
let mut buf = vec![0u8; bytes];
|
||||||
|
OsRng.fill_bytes(&mut buf);
|
||||||
|
URL_SAFE_NO_PAD.encode(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hex SHA-256 of a token; only this digest is ever stored.
|
||||||
|
pub fn hash_token(token: &str) -> String {
|
||||||
|
Sha256::digest(token.as_bytes())
|
||||||
|
.iter()
|
||||||
|
.map(|b| format!("{b:02x}"))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn seal_roundtrip_and_tamper_rejected() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let s = Secrets::open(dir.path(), None).unwrap();
|
||||||
|
let sealed = s.seal(b"totp-seed").unwrap();
|
||||||
|
assert_ne!(sealed, s.seal(b"totp-seed").unwrap(), "nonce must vary");
|
||||||
|
assert_eq!(s.open_sealed(&sealed).unwrap(), b"totp-seed");
|
||||||
|
|
||||||
|
let mut raw = STANDARD.decode(&sealed).unwrap();
|
||||||
|
let last = raw.len() - 1;
|
||||||
|
raw[last] ^= 1;
|
||||||
|
assert!(s.open_sealed(&STANDARD.encode(raw)).is_err());
|
||||||
|
assert!(s.open_sealed("not base64!").is_err());
|
||||||
|
assert!(s.open_sealed("").is_err());
|
||||||
|
let other = Secrets::open(tempfile::tempdir().unwrap().path(), None).unwrap();
|
||||||
|
assert!(other.open_sealed(&sealed).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn key_file_created_0600_and_missing_key_with_state_fails() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let a = Secrets::open(dir.path(), None).unwrap();
|
||||||
|
let mode = fs::metadata(dir.path().join(KEY_FILE))
|
||||||
|
.unwrap()
|
||||||
|
.permissions()
|
||||||
|
.mode();
|
||||||
|
assert_eq!(mode & 0o777, 0o600);
|
||||||
|
// Reopen yields the same key.
|
||||||
|
let sealed = a.seal(b"x").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
Secrets::open(dir.path(), None)
|
||||||
|
.unwrap()
|
||||||
|
.open_sealed(&sealed)
|
||||||
|
.unwrap(),
|
||||||
|
b"x"
|
||||||
|
);
|
||||||
|
|
||||||
|
let dir2 = tempfile::tempdir().unwrap();
|
||||||
|
fs::write(dir2.path().join(STATE_FILE), r#"{"version":1}"#).unwrap();
|
||||||
|
let err = Secrets::open(dir2.path(), None).unwrap_err();
|
||||||
|
assert!(matches!(err, AcauaError::Auth(AuthFailure::KeyMissing)));
|
||||||
|
assert!(
|
||||||
|
!dir2.path().join(KEY_FILE).exists(),
|
||||||
|
"must not recreate the key"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn concurrent_first_open_agrees_on_one_key() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join("auth");
|
||||||
|
let sealed: Vec<(String, Secrets)> = std::thread::scope(|sc| {
|
||||||
|
let hs: Vec<_> = (0..8)
|
||||||
|
.map(|_| {
|
||||||
|
sc.spawn(|| {
|
||||||
|
let s = Secrets::open(&path, None).unwrap();
|
||||||
|
(s.seal(b"v").unwrap(), s)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
hs.into_iter().map(|h| h.join().unwrap()).collect()
|
||||||
|
});
|
||||||
|
let reopened = Secrets::open(&path, None).unwrap();
|
||||||
|
for (sl, s) in &sealed {
|
||||||
|
assert_eq!(reopened.open_sealed(sl).unwrap(), b"v");
|
||||||
|
assert_eq!(s.open_sealed(sl).unwrap(), b"v");
|
||||||
|
}
|
||||||
|
assert!(!path.join("secret.key.tmp").exists());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn external_key_file_is_used_and_validated() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let kf = dir.path().join("docker-secret");
|
||||||
|
fs::write(&kf, format!("{}\n", STANDARD.encode([7u8; 32]))).unwrap();
|
||||||
|
let s = Secrets::open(dir.path(), Some(&kf)).unwrap();
|
||||||
|
assert_eq!(s.open_sealed(&s.seal(b"a").unwrap()).unwrap(), b"a");
|
||||||
|
assert!(!dir.path().join(KEY_FILE).exists());
|
||||||
|
|
||||||
|
fs::write(&kf, "short").unwrap();
|
||||||
|
assert!(Secrets::open(dir.path(), Some(&kf)).is_err());
|
||||||
|
let missing = dir.path().join("nope");
|
||||||
|
assert!(Secrets::open(dir.path(), Some(&missing)).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tokens_are_random_and_hash_is_stable() {
|
||||||
|
assert_ne!(random_token(32), random_token(32));
|
||||||
|
assert_eq!(random_token(32).len(), 43);
|
||||||
|
assert_eq!(
|
||||||
|
hash_token("abc"),
|
||||||
|
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
format!(
|
||||||
|
"{:?}",
|
||||||
|
Secrets::open(tempfile::tempdir().unwrap().path(), None).unwrap()
|
||||||
|
),
|
||||||
|
"Secrets(<redacted>)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,384 @@
|
|||||||
|
use super::{set_mode, DirLock, STATE_FILE};
|
||||||
|
use crate::error::{AcauaError, AuthFailure, Result};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::fs::{self, File, OpenOptions};
|
||||||
|
use std::io::Write;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
pub const STATE_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
// Later tasks add fields; `#[serde(default)]` keeps older files readable.
|
||||||
|
// Unknown fields are ignored on read (and so dropped on rewrite).
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Role {
|
||||||
|
Admin,
|
||||||
|
/// The default is the least-privileged role.
|
||||||
|
#[default]
|
||||||
|
Analyst,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct User {
|
||||||
|
pub id: String,
|
||||||
|
pub username: String,
|
||||||
|
/// Unix seconds, like every timestamp here.
|
||||||
|
pub created_at: u64,
|
||||||
|
pub role: Role,
|
||||||
|
/// Argon2id PHC string.
|
||||||
|
pub password_hash: String,
|
||||||
|
/// Active TOTP secret, sealed with `Secrets`.
|
||||||
|
pub totp_sealed: Option<String>,
|
||||||
|
/// Secret awaiting its first code, sealed. Not usable to log in.
|
||||||
|
pub totp_pending_sealed: Option<String>,
|
||||||
|
/// Newest accepted TOTP step; a step is never accepted twice.
|
||||||
|
pub totp_last_step: Option<u64>,
|
||||||
|
/// SHA-256 hex of each unused recovery code.
|
||||||
|
pub recovery_hashes: Vec<String>,
|
||||||
|
/// MFA and session-password failures since the last completed login; one
|
||||||
|
/// is forgotten per 900 s. Wrong login passwords are not counted here: see
|
||||||
|
/// `throttle::LoginThrottle`.
|
||||||
|
pub failed_attempts: u32,
|
||||||
|
/// Start of the current decay period of `failed_attempts`.
|
||||||
|
pub failed_at: u64,
|
||||||
|
/// No MFA code or session password is evaluated before this instant.
|
||||||
|
pub locked_until: u64,
|
||||||
|
/// Changes when the password changes and at each completed login, which
|
||||||
|
/// voids the pending MFA tokens issued before it.
|
||||||
|
pub auth_epoch: u64,
|
||||||
|
/// Set by `reset_account`: no ordinary session until the password changes.
|
||||||
|
pub must_change_password: bool,
|
||||||
|
/// Addresses of recent completed logins, for `throttle`'s budget exception.
|
||||||
|
/// Hashes only: never a raw address.
|
||||||
|
pub known_addresses: Vec<KnownAddress>,
|
||||||
|
/// Instants of evaluated login failures from unknown addresses in the last
|
||||||
|
/// 24 hours, at most 100. The daemon's memory leads this by at most a minute.
|
||||||
|
pub budget_times: Vec<u64>,
|
||||||
|
/// When `login.budget_exhausted` was last audited for this account.
|
||||||
|
pub budget_audited_at: u64,
|
||||||
|
/// Moved by `reset_account`, which may run in another process: the daemon
|
||||||
|
/// drops what it holds in memory for this account when this changes.
|
||||||
|
pub budget_generation: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A hashed address prefix and when a login from it last completed.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct KnownAddress {
|
||||||
|
pub hash: String,
|
||||||
|
pub last_seen: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for User {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("User")
|
||||||
|
.field("id", &self.id)
|
||||||
|
.field("username", &self.username)
|
||||||
|
.field("role", &self.role)
|
||||||
|
.field("mfa", &self.totp_sealed.is_some())
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Session {
|
||||||
|
pub id: String,
|
||||||
|
pub user_id: String,
|
||||||
|
/// SHA-256 hex of the session token; the token itself is never stored.
|
||||||
|
pub token_hash: String,
|
||||||
|
pub created_at: u64,
|
||||||
|
pub last_seen: u64,
|
||||||
|
pub expires_at: u64,
|
||||||
|
/// Unix seconds of the last `reauthenticate` of this session; 0 if never.
|
||||||
|
pub last_reauth: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Session {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Session")
|
||||||
|
.field("id", &self.id)
|
||||||
|
.field("user_id", &self.user_id)
|
||||||
|
.field("expires_at", &self.expires_at)
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much an API token may do. `Read` < `Admin`.
|
||||||
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum Scope {
|
||||||
|
#[default]
|
||||||
|
Read,
|
||||||
|
Admin,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct ApiToken {
|
||||||
|
pub id: String,
|
||||||
|
pub user_id: String,
|
||||||
|
pub name: String,
|
||||||
|
/// SHA-256 hex of the token; the token itself is never stored.
|
||||||
|
pub token_hash: String,
|
||||||
|
pub scope: Scope,
|
||||||
|
/// Unix seconds.
|
||||||
|
pub created_at: u64,
|
||||||
|
/// Unix seconds; every token expires.
|
||||||
|
pub expires_at: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for ApiToken {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("ApiToken")
|
||||||
|
.field("id", &self.id)
|
||||||
|
.field("name", &self.name)
|
||||||
|
.field("token_hash", &"<redacted>")
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default, Serialize, Deserialize)]
|
||||||
|
#[serde(default)]
|
||||||
|
pub struct Bootstrap {
|
||||||
|
pub token_hash: String,
|
||||||
|
/// Unix seconds.
|
||||||
|
pub created_at: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for Bootstrap {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Bootstrap")
|
||||||
|
.field("token_hash", &"<redacted>")
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `version` is required: `{}` or an unrelated JSON object must not load as an
|
||||||
|
/// empty state that the next update would overwrite.
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct AuthState {
|
||||||
|
pub version: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub users: Vec<User>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub sessions: Vec<Session>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub tokens: Vec<ApiToken>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub bootstrap: Option<Bootstrap>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for AuthState {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
version: STATE_VERSION,
|
||||||
|
users: Vec::new(),
|
||||||
|
sessions: Vec::new(),
|
||||||
|
tokens: Vec::new(),
|
||||||
|
bootstrap: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// File-backed state. Every operation takes the directory lock and rereads
|
||||||
|
/// `state.json`, so several processes or instances stay coherent.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct AuthStore {
|
||||||
|
dir: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AuthStore {
|
||||||
|
/// Opens (creating the directory if needed) and validates existing state.
|
||||||
|
/// Corrupted state is an error and is never overwritten.
|
||||||
|
pub fn open(dir: &Path) -> Result<AuthStore> {
|
||||||
|
let store = AuthStore {
|
||||||
|
dir: dir.to_path_buf(),
|
||||||
|
};
|
||||||
|
store.read(|_| ())?;
|
||||||
|
Ok(store)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn read<T>(&self, f: impl FnOnce(&AuthState) -> T) -> Result<T> {
|
||||||
|
let _lock = DirLock::acquire(&self.dir, false)?;
|
||||||
|
let state = self.load()?;
|
||||||
|
Ok(f(&state))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `f` on a copy under an exclusive lock; the copy is persisted
|
||||||
|
/// atomically only if `f` returns `Ok`.
|
||||||
|
pub fn update<T>(&self, f: impl FnOnce(&mut AuthState) -> Result<T>) -> Result<T> {
|
||||||
|
let _lock = DirLock::acquire(&self.dir, true)?;
|
||||||
|
let mut state = self.load()?;
|
||||||
|
let out = f(&mut state)?;
|
||||||
|
state.version = STATE_VERSION;
|
||||||
|
self.persist(&state)?;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(&self) -> Result<AuthState> {
|
||||||
|
let raw = match fs::read(self.dir.join(STATE_FILE)) {
|
||||||
|
Ok(raw) => raw,
|
||||||
|
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(AuthState::default()),
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
};
|
||||||
|
let state: AuthState = serde_json::from_slice(&raw).map_err(|e| {
|
||||||
|
// Serde's message can quote the file, which holds hashes and
|
||||||
|
// sealed secrets: the position is enough to find the damage.
|
||||||
|
AcauaError::Auth(AuthFailure::StateCorrupt(format!(
|
||||||
|
"invalid JSON at line {}, column {}",
|
||||||
|
e.line(),
|
||||||
|
e.column()
|
||||||
|
)))
|
||||||
|
})?;
|
||||||
|
if state.version == 0 || state.version > STATE_VERSION {
|
||||||
|
return Err(AuthFailure::StateVersionUnsupported(state.version).into());
|
||||||
|
}
|
||||||
|
Ok(state)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn persist(&self, state: &AuthState) -> Result<()> {
|
||||||
|
let tmp = self.dir.join(format!("{STATE_FILE}.tmp"));
|
||||||
|
let data = serde_json::to_vec_pretty(state)?;
|
||||||
|
let mut opts = OpenOptions::new();
|
||||||
|
opts.write(true).create(true).truncate(true);
|
||||||
|
set_mode(&mut opts, 0o600);
|
||||||
|
let mut file = opts.open(&tmp)?;
|
||||||
|
let written = file.write_all(&data).and_then(|_| file.sync_all());
|
||||||
|
drop(file);
|
||||||
|
if let Err(e) = written.and_then(|_| fs::rename(&tmp, self.dir.join(STATE_FILE))) {
|
||||||
|
let _ = fs::remove_file(&tmp);
|
||||||
|
return Err(e.into());
|
||||||
|
}
|
||||||
|
// Persist the rename itself.
|
||||||
|
if let Ok(d) = File::open(&self.dir) {
|
||||||
|
let _ = d.sync_all();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
|
||||||
|
fn user(name: &str) -> User {
|
||||||
|
User {
|
||||||
|
id: name.into(),
|
||||||
|
username: name.into(),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn state_file_is_0600_and_atomic() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = AuthStore::open(dir.path()).unwrap();
|
||||||
|
store
|
||||||
|
.update(|s| {
|
||||||
|
s.users.push(user("ana"));
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let mode = fs::metadata(dir.path().join(STATE_FILE))
|
||||||
|
.unwrap()
|
||||||
|
.permissions()
|
||||||
|
.mode();
|
||||||
|
assert_eq!(mode & 0o777, 0o600);
|
||||||
|
assert!(!dir.path().join("state.json.tmp").exists());
|
||||||
|
assert_eq!(store.read(|s| s.users.len()).unwrap(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn corrupted_state_fails_closed() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join(STATE_FILE);
|
||||||
|
fs::write(&path, "{not json").unwrap();
|
||||||
|
let err = AuthStore::open(dir.path()).unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
err,
|
||||||
|
AcauaError::Auth(AuthFailure::StateCorrupt(_))
|
||||||
|
));
|
||||||
|
let store = AuthStore {
|
||||||
|
dir: dir.path().to_path_buf(),
|
||||||
|
};
|
||||||
|
assert!(store.update(|_| Ok(())).is_err());
|
||||||
|
assert_eq!(fs::read_to_string(&path).unwrap(), "{not json");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn state_without_version_fails_closed() {
|
||||||
|
for body in ["{}", r#"{"foo":1}"#, r#"{"users":[]}"#, "[]", "null"] {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let path = dir.path().join(STATE_FILE);
|
||||||
|
fs::write(&path, body).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
AuthStore::open(dir.path()).unwrap_err(),
|
||||||
|
AcauaError::Auth(AuthFailure::StateCorrupt(_))
|
||||||
|
));
|
||||||
|
let store = AuthStore {
|
||||||
|
dir: dir.path().to_path_buf(),
|
||||||
|
};
|
||||||
|
assert!(store.update(|_| Ok(())).is_err());
|
||||||
|
assert_eq!(fs::read_to_string(&path).unwrap(), body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn future_version_rejected() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
fs::write(dir.path().join(STATE_FILE), r#"{"version":99}"#).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
AuthStore::open(dir.path()).unwrap_err(),
|
||||||
|
AcauaError::Auth(AuthFailure::StateVersionUnsupported(99))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn update_failure_keeps_state() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let store = AuthStore::open(dir.path()).unwrap();
|
||||||
|
store
|
||||||
|
.update(|s| {
|
||||||
|
s.users.push(user("ana"));
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let before = fs::read(dir.path().join(STATE_FILE)).unwrap();
|
||||||
|
let r: Result<()> = store.update(|s| {
|
||||||
|
s.users.push(user("bob"));
|
||||||
|
Err(AcauaError::InvalidInput("nope".into()))
|
||||||
|
});
|
||||||
|
assert!(r.is_err());
|
||||||
|
assert_eq!(fs::read(dir.path().join(STATE_FILE)).unwrap(), before);
|
||||||
|
assert_eq!(store.read(|s| s.users.len()).unwrap(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn external_change_is_seen() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let a = AuthStore::open(dir.path()).unwrap();
|
||||||
|
let b = AuthStore::open(dir.path()).unwrap();
|
||||||
|
a.update(|s| {
|
||||||
|
s.users.push(user("ana"));
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(b.read(|s| s.users[0].username.clone()).unwrap(), "ana");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn older_files_with_missing_fields_load() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
fs::write(
|
||||||
|
dir.path().join(STATE_FILE),
|
||||||
|
r#"{"version":1,"users":[{"id":"u1"}]}"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let store = AuthStore::open(dir.path()).unwrap();
|
||||||
|
assert_eq!(store.read(|s| s.users[0].id.clone()).unwrap(), "u1");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,753 @@
|
|||||||
|
//! Attempt limits: the delay schedule, the in-memory IP limiter and the
|
||||||
|
//! in-memory login throttle.
|
||||||
|
//!
|
||||||
|
//! Login failures count per username + address prefix, so one address cannot
|
||||||
|
//! lock the owner out from another. Each username also has a budget for
|
||||||
|
//! failures from addresses it has not logged in from: guessing spread over many
|
||||||
|
//! addresses ends there, before Argon2. Addresses with a recent completed login
|
||||||
|
//! skip the budget, which is what keeps the owner in during an attack. Usernames
|
||||||
|
//! with no account go through the same code, so the schedule reveals nobody.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
use std::net::{IpAddr, Ipv6Addr};
|
||||||
|
use std::sync::{Mutex, MutexGuard};
|
||||||
|
|
||||||
|
pub const IP_MAX_FAILURES: usize = 20;
|
||||||
|
pub const IP_WINDOW_SECS: u64 = 900;
|
||||||
|
pub const ACCOUNT_DELAY_CAP_SECS: u64 = 900;
|
||||||
|
/// The failure count at which the delay starts.
|
||||||
|
const ACCOUNT_FREE_FAILURES: u32 = 5;
|
||||||
|
const ACCOUNT_DELAY_BASE_SECS: u64 = 30;
|
||||||
|
/// One failure is forgotten per this many seconds without another.
|
||||||
|
pub const DECAY_SECS: u64 = 900;
|
||||||
|
/// Failures from unknown addresses that one username can take in any 24 hours.
|
||||||
|
pub const BUDGET_MAX_FAILURES: usize = 100;
|
||||||
|
pub const BUDGET_WINDOW_SECS: u64 = 86_400;
|
||||||
|
/// A budget is written to disk at most this often, bar crossing the cap.
|
||||||
|
pub const BUDGET_WRITE_SECS: u64 = 60;
|
||||||
|
/// Only a sweep for reservations whose request died unseen: an attempt whose
|
||||||
|
/// reservation is gone is refused, see `renew`.
|
||||||
|
const RESERVATION_SECS: u64 = 3600;
|
||||||
|
const IP_TABLE_CAPACITY: usize = 100_000;
|
||||||
|
const PAIR_TABLE_CAPACITY: usize = 100_000;
|
||||||
|
const ACCOUNT_TABLE_CAPACITY: usize = 10_000;
|
||||||
|
|
||||||
|
/// Delay after `failures` failures: none before the 5th, then 30 s doubling
|
||||||
|
/// up to 900 s.
|
||||||
|
pub fn account_delay(failures: u32) -> u64 {
|
||||||
|
if failures < ACCOUNT_FREE_FAILURES {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let doublings = failures - ACCOUNT_FREE_FAILURES;
|
||||||
|
ACCOUNT_DELAY_BASE_SECS
|
||||||
|
.checked_shl(doublings)
|
||||||
|
.filter(|d| doublings < 32 && *d < ACCOUNT_DELAY_CAP_SECS)
|
||||||
|
.unwrap_or(ACCOUNT_DELAY_CAP_SECS)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Instant until which an account with `failures` failures stays locked.
|
||||||
|
pub(super) fn lock_until(failures: u32, now: u64) -> u64 {
|
||||||
|
match account_delay(failures) {
|
||||||
|
0 => 0,
|
||||||
|
delay => now.saturating_add(delay),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `(failures, last)` after forgiving one failure per `DECAY_SECS` elapsed.
|
||||||
|
pub(super) fn decayed(failures: u32, last: u64, now: u64) -> (u32, u64) {
|
||||||
|
let steps = now.saturating_sub(last) / DECAY_SECS;
|
||||||
|
if steps >= u64::from(failures) {
|
||||||
|
return (0, now);
|
||||||
|
}
|
||||||
|
// `steps` is below `failures`, so it fits in u32.
|
||||||
|
(failures - steps as u32, last + steps * DECAY_SECS)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn guard<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||||
|
// The tables stay valid whatever a panicking holder did.
|
||||||
|
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One holder of an IPv6 /64 can use all of it, so the /64 is what counts; an
|
||||||
|
/// IPv4-mapped address is the IPv4 address.
|
||||||
|
fn ip_key(ip: IpAddr) -> IpAddr {
|
||||||
|
match ip {
|
||||||
|
IpAddr::V4(_) => ip,
|
||||||
|
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
|
||||||
|
Some(v4) => IpAddr::V4(v4),
|
||||||
|
None => {
|
||||||
|
let s = v6.segments();
|
||||||
|
IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], s[3], 0, 0, 0, 0))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the login throttle and the budget treat as one address: an IPv4 address,
|
||||||
|
/// or an IPv6 /48, the size routinely handed to one customer. An IPv4-mapped
|
||||||
|
/// address is the IPv4 address.
|
||||||
|
pub fn address_key(ip: IpAddr) -> IpAddr {
|
||||||
|
match ip_key(ip) {
|
||||||
|
IpAddr::V6(v6) => {
|
||||||
|
let s = v6.segments();
|
||||||
|
IpAddr::V6(Ipv6Addr::new(s[0], s[1], s[2], 0, 0, 0, 0, 0))
|
||||||
|
}
|
||||||
|
v4 => v4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sliding window of failures per IP. Kept in memory: a restart clears it.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct IpLimiter {
|
||||||
|
capacity: usize,
|
||||||
|
table: Mutex<HashMap<IpAddr, VecDeque<u64>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for IpLimiter {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::with_capacity(IP_TABLE_CAPACITY)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IpLimiter {
|
||||||
|
pub fn with_capacity(capacity: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
capacity,
|
||||||
|
table: Mutex::new(HashMap::new()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Takes a slot before the attempt runs, so parallel requests cannot all
|
||||||
|
/// pass the check. The slot stands as a failure unless `release`d.
|
||||||
|
/// `Err` carries the seconds until a slot frees.
|
||||||
|
pub fn acquire(&self, ip: IpAddr, now: u64) -> Result<(), u64> {
|
||||||
|
let key = ip_key(ip);
|
||||||
|
let mut table = guard(&self.table);
|
||||||
|
if !table.contains_key(&key) && table.len() >= self.capacity {
|
||||||
|
table.retain(|_, hits| hits.back().is_some_and(|t| t + IP_WINDOW_SECS > now));
|
||||||
|
if table.len() >= self.capacity {
|
||||||
|
let stalest = table
|
||||||
|
.iter()
|
||||||
|
.min_by_key(|(_, hits)| hits.back().copied().unwrap_or(0))
|
||||||
|
.map(|(k, _)| *k);
|
||||||
|
if let Some(k) = stalest {
|
||||||
|
table.remove(&k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let hits = table.entry(key).or_default();
|
||||||
|
while hits.front().is_some_and(|t| t + IP_WINDOW_SECS <= now) {
|
||||||
|
hits.pop_front();
|
||||||
|
}
|
||||||
|
if hits.len() >= IP_MAX_FAILURES {
|
||||||
|
let oldest = hits.front().copied().unwrap_or(now);
|
||||||
|
return Err((oldest + IP_WINDOW_SECS).saturating_sub(now));
|
||||||
|
}
|
||||||
|
hits.push_back(now);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the slot of an attempt that was not a failure.
|
||||||
|
pub fn release(&self, ip: IpAddr) {
|
||||||
|
let key = ip_key(ip);
|
||||||
|
let mut table = guard(&self.table);
|
||||||
|
if let Some(hits) = table.get_mut(&key) {
|
||||||
|
hits.pop_back();
|
||||||
|
if hits.is_empty() {
|
||||||
|
table.remove(&key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn tracked(&self) -> usize {
|
||||||
|
guard(&self.table).len()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, Default)]
|
||||||
|
struct PairEntry {
|
||||||
|
failures: u32,
|
||||||
|
last: u64,
|
||||||
|
locked_until: u64,
|
||||||
|
/// The account's `budget_generation` these counts belong to.
|
||||||
|
generation: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A budget as the store holds it, for an account the daemon has not met yet.
|
||||||
|
/// A username with no account starts from the default.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct BudgetState {
|
||||||
|
/// Instants of evaluated failures inside the window; never reservations.
|
||||||
|
pub times: Vec<u64>,
|
||||||
|
pub audited_at: u64,
|
||||||
|
pub generation: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Default)]
|
||||||
|
struct BudgetEntry {
|
||||||
|
state: BudgetState,
|
||||||
|
/// `(id, instant)` of attempts between their checks and their evaluation.
|
||||||
|
/// They hold a place under the cap but are not failures yet.
|
||||||
|
reserved: Vec<(u64, u64)>,
|
||||||
|
written_at: u64,
|
||||||
|
written_count: usize,
|
||||||
|
/// Newest failure the disk holds.
|
||||||
|
written_newest: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BudgetEntry {
|
||||||
|
fn prune(&mut self, now: u64) {
|
||||||
|
self.state
|
||||||
|
.times
|
||||||
|
.retain(|t| now.saturating_sub(*t) < BUDGET_WINDOW_SECS);
|
||||||
|
self.reserved
|
||||||
|
.retain(|(_, t)| now.saturating_sub(*t) < RESERVATION_SECS);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn weight(&self, now: u64) -> usize {
|
||||||
|
let live = |t: &&u64| now.saturating_sub(**t) < BUDGET_WINDOW_SECS;
|
||||||
|
self.state.times.iter().filter(live).count() + self.reserved.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seconds until the oldest failure leaves the window.
|
||||||
|
fn wait(&self, now: u64) -> u64 {
|
||||||
|
self.state
|
||||||
|
.times
|
||||||
|
.iter()
|
||||||
|
.min()
|
||||||
|
.map_or(1, |t| (t + BUDGET_WINDOW_SECS).saturating_sub(now))
|
||||||
|
.max(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What an evaluated failure asks of the caller, outside the throttle's lock.
|
||||||
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
|
pub struct FailureNote {
|
||||||
|
/// The state to persist, when a write is due.
|
||||||
|
pub write: Option<BudgetState>,
|
||||||
|
/// The cap was crossed and this window has no audit event yet.
|
||||||
|
pub audit: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct LoginTables {
|
||||||
|
pairs: HashMap<(String, IpAddr), PairEntry>,
|
||||||
|
budgets: HashMap<String, BudgetEntry>,
|
||||||
|
next_reservation: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Failure counts for login attempts, known username or not. In memory and
|
||||||
|
/// bounded; only budgets of real accounts reach the disk, by way of the caller,
|
||||||
|
/// and a restart clears the rest.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct LoginThrottle {
|
||||||
|
pair_capacity: usize,
|
||||||
|
budget_capacity: usize,
|
||||||
|
tables: Mutex<LoginTables>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for LoginThrottle {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self::with_capacity(PAIR_TABLE_CAPACITY, ACCOUNT_TABLE_CAPACITY)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LoginThrottle {
|
||||||
|
pub fn with_capacity(pair_capacity: usize, budget_capacity: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
pair_capacity,
|
||||||
|
budget_capacity,
|
||||||
|
tables: Mutex::new(LoginTables::default()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reserves the attempt before Argon2 runs, in one step under one lock, so
|
||||||
|
/// parallel guesses cannot pass the cap. `right_password` or `abandon` undoes
|
||||||
|
/// it; `failed` makes it a failure. `Ok` holds the budget reservation, if one
|
||||||
|
/// was taken; `Err` carries the seconds to wait, and a refusal changes no count.
|
||||||
|
pub fn acquire(
|
||||||
|
&self,
|
||||||
|
account: &str,
|
||||||
|
ip: IpAddr,
|
||||||
|
known: bool,
|
||||||
|
stored: BudgetState,
|
||||||
|
now: u64,
|
||||||
|
) -> Result<Option<u64>, u64> {
|
||||||
|
let pair_key = (account.to_string(), address_key(ip));
|
||||||
|
let generation = stored.generation;
|
||||||
|
let mut guard = guard(&self.tables);
|
||||||
|
let t = &mut *guard;
|
||||||
|
// A reset, possibly from another process, starts this account over. Each
|
||||||
|
// table checks for itself: either entry may have been evicted.
|
||||||
|
if t.budgets
|
||||||
|
.get(account)
|
||||||
|
.is_some_and(|e| e.state.generation != generation)
|
||||||
|
{
|
||||||
|
t.budgets.remove(account);
|
||||||
|
}
|
||||||
|
let known_pair = t
|
||||||
|
.pairs
|
||||||
|
.get(&pair_key)
|
||||||
|
.copied()
|
||||||
|
.filter(|e| e.generation == generation);
|
||||||
|
if let Some(left) = known_pair
|
||||||
|
.map(|e| e.locked_until.saturating_sub(now))
|
||||||
|
.filter(|left| *left > 0)
|
||||||
|
{
|
||||||
|
return Err(left);
|
||||||
|
}
|
||||||
|
let mut budget = t.budgets.get(account).cloned().unwrap_or_else(|| {
|
||||||
|
let written_count = stored.times.len();
|
||||||
|
let written_newest = stored.times.iter().max().copied().unwrap_or(0);
|
||||||
|
BudgetEntry {
|
||||||
|
state: stored,
|
||||||
|
written_count,
|
||||||
|
written_newest,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
budget.prune(now);
|
||||||
|
if !known && budget.weight(now) >= BUDGET_MAX_FAILURES {
|
||||||
|
return Err(budget.wait(now));
|
||||||
|
}
|
||||||
|
|
||||||
|
if !t.pairs.contains_key(&pair_key) && t.pairs.len() >= self.pair_capacity {
|
||||||
|
evict_pair(&mut t.pairs, self.pair_capacity, now);
|
||||||
|
}
|
||||||
|
let pair = t.pairs.entry(pair_key).or_default();
|
||||||
|
let current = known_pair.unwrap_or_default();
|
||||||
|
let (pair_failures, pair_last) = decayed(current.failures, current.last, now);
|
||||||
|
pair.generation = generation;
|
||||||
|
pair.failures = pair_failures.saturating_add(1);
|
||||||
|
pair.last = if pair_failures == 0 { now } else { pair_last };
|
||||||
|
pair.locked_until = lock_until(pair.failures, now);
|
||||||
|
|
||||||
|
let reservation = (!known).then(|| {
|
||||||
|
t.next_reservation = t.next_reservation.wrapping_add(1);
|
||||||
|
budget.reserved.push((t.next_reservation, now));
|
||||||
|
t.next_reservation
|
||||||
|
});
|
||||||
|
if !t.budgets.contains_key(account) && t.budgets.len() >= self.budget_capacity {
|
||||||
|
evict_budget(&mut t.budgets, self.budget_capacity, now);
|
||||||
|
}
|
||||||
|
t.budgets.insert(account.to_string(), budget);
|
||||||
|
Ok(reservation)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Called with a permit in hand, just before Argon2. `false`: the reservation
|
||||||
|
/// is gone, its place may belong to someone else, and the attempt must not be
|
||||||
|
/// evaluated. `true` restarts its clock, so it cannot expire during the hash.
|
||||||
|
pub fn renew(&self, account: &str, reservation: u64, now: u64) -> bool {
|
||||||
|
let mut t = guard(&self.tables);
|
||||||
|
let Some(e) = t.budgets.get_mut(account) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
e.prune(now);
|
||||||
|
match e.reserved.iter_mut().find(|(id, _)| *id == reservation) {
|
||||||
|
Some(held) => {
|
||||||
|
held.1 = now;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
None => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reservation was evaluated and failed. Says what the caller must write
|
||||||
|
/// and audit, once the throttle's lock is gone.
|
||||||
|
pub fn failed(&self, account: &str, reservation: u64, now: u64) -> FailureNote {
|
||||||
|
let mut t = guard(&self.tables);
|
||||||
|
let Some(e) = t.budgets.get_mut(account) else {
|
||||||
|
return FailureNote::default();
|
||||||
|
};
|
||||||
|
let held = take_reservation(e, reservation);
|
||||||
|
e.prune(now);
|
||||||
|
// Without its reservation (evicted during the hash) it counts only if
|
||||||
|
// that keeps the cap.
|
||||||
|
if held || e.weight(now) < BUDGET_MAX_FAILURES {
|
||||||
|
e.state.times.push(now);
|
||||||
|
}
|
||||||
|
let count = e.state.times.len();
|
||||||
|
let newest = e.state.times.iter().max().copied().unwrap_or(0);
|
||||||
|
let over = count >= BUDGET_MAX_FAILURES;
|
||||||
|
let audit = over
|
||||||
|
&& (e.state.audited_at == 0
|
||||||
|
|| now.saturating_sub(e.state.audited_at) >= BUDGET_WINDOW_SECS);
|
||||||
|
if audit {
|
||||||
|
e.state.audited_at = now;
|
||||||
|
}
|
||||||
|
let due = e.written_at == 0 || now.saturating_sub(e.written_at) >= BUDGET_WRITE_SECS;
|
||||||
|
// At the cap no further failure may come to carry this one to disk, and
|
||||||
|
// the older instants on disk may have left the window by a restart, so
|
||||||
|
// the disk must hold the newest one.
|
||||||
|
let at_cap = over && (e.written_count < BUDGET_MAX_FAILURES || e.written_newest < newest);
|
||||||
|
let write = (due || at_cap || audit).then(|| {
|
||||||
|
e.written_at = now;
|
||||||
|
e.written_count = count;
|
||||||
|
e.written_newest = newest;
|
||||||
|
e.state.clone()
|
||||||
|
});
|
||||||
|
FailureNote { write, audit }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The password was right: this address is clear, and the reservation goes
|
||||||
|
/// back. Other failures stay, or each login by the owner would hand a
|
||||||
|
/// distributed attacker a fresh budget.
|
||||||
|
pub fn right_password(&self, account: &str, ip: IpAddr, reservation: Option<u64>) {
|
||||||
|
let mut t = guard(&self.tables);
|
||||||
|
if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) {
|
||||||
|
pair.failures = 0;
|
||||||
|
pair.locked_until = 0;
|
||||||
|
}
|
||||||
|
if let Some(id) = reservation {
|
||||||
|
if let Some(e) = t.budgets.get_mut(account) {
|
||||||
|
take_reservation(e, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The attempt was never evaluated: it gives back what it reserved.
|
||||||
|
pub fn abandon(&self, account: &str, ip: IpAddr, reservation: Option<u64>) {
|
||||||
|
let mut t = guard(&self.tables);
|
||||||
|
if let Some(pair) = t.pairs.get_mut(&(account.to_string(), address_key(ip))) {
|
||||||
|
pair.failures = pair.failures.saturating_sub(1);
|
||||||
|
if account_delay(pair.failures) == 0 {
|
||||||
|
pair.locked_until = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(id) = reservation {
|
||||||
|
if let Some(e) = t.budgets.get_mut(account) {
|
||||||
|
take_reservation(e, id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
fn tracked(&self) -> (usize, usize) {
|
||||||
|
let t = guard(&self.tables);
|
||||||
|
(t.pairs.len(), t.budgets.len())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take_reservation(e: &mut BudgetEntry, id: u64) -> bool {
|
||||||
|
let before = e.reserved.len();
|
||||||
|
e.reserved.retain(|(held, _)| *held != id);
|
||||||
|
e.reserved.len() != before
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drops what no longer matters; if that frees no room, the entry with the
|
||||||
|
/// fewest failures. Never the oldest: a flood of new entries must not be able
|
||||||
|
/// to erase a count someone has run up.
|
||||||
|
fn evict_pair(pairs: &mut HashMap<(String, IpAddr), PairEntry>, capacity: usize, now: u64) {
|
||||||
|
pairs.retain(|_, e| e.locked_until > now || decayed(e.failures, e.last, now).0 > 0);
|
||||||
|
if pairs.len() < capacity {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let least = pairs
|
||||||
|
.iter()
|
||||||
|
.min_by_key(|(_, e)| (e.failures, e.last))
|
||||||
|
.map(|(k, _)| k.clone());
|
||||||
|
if let Some(k) = least {
|
||||||
|
pairs.remove(&k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn evict_budget(budgets: &mut HashMap<String, BudgetEntry>, capacity: usize, now: u64) {
|
||||||
|
budgets.retain(|_, e| e.weight(now) > 0);
|
||||||
|
if budgets.len() < capacity {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let least = budgets
|
||||||
|
.iter()
|
||||||
|
.min_by_key(|(_, e)| (e.weight(now), e.state.times.iter().max().copied()))
|
||||||
|
.map(|(k, _)| k.clone());
|
||||||
|
if let Some(k) = least {
|
||||||
|
budgets.remove(&k);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use std::net::Ipv4Addr;
|
||||||
|
#[test]
|
||||||
|
fn delay_starts_at_fifth_failure_grows_and_caps() {
|
||||||
|
let seq: Vec<u64> = (0..=12).map(account_delay).collect();
|
||||||
|
assert_eq!(seq, [0, 0, 0, 0, 0, 30, 60, 120, 240, 480, 900, 900, 900]);
|
||||||
|
assert_eq!(account_delay(u32::MAX), 900);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn ip_window_slides_and_release_returns_the_slot() {
|
||||||
|
let l = IpLimiter::default();
|
||||||
|
let ip: IpAddr = "198.51.100.7".parse().unwrap();
|
||||||
|
for i in 0..20 {
|
||||||
|
assert!(l.acquire(ip, 1000 + i).is_ok(), "attempt {i}");
|
||||||
|
}
|
||||||
|
assert_eq!(l.acquire(ip, 1100), Err(800));
|
||||||
|
assert!(l.acquire("198.51.100.8".parse().unwrap(), 1100).is_ok());
|
||||||
|
// The oldest failure (t=1000) leaves the window at t=1900.
|
||||||
|
assert!(l.acquire(ip, 1899).is_err());
|
||||||
|
assert!(l.acquire(ip, 1901).is_ok());
|
||||||
|
l.release(ip);
|
||||||
|
assert!(l.acquire(ip, 1901).is_ok());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn ipv6_is_grouped_by_64_and_mapped_v4_is_v4() {
|
||||||
|
let l = IpLimiter::default();
|
||||||
|
for i in 0..20u32 {
|
||||||
|
let ip: IpAddr = format!("2001:db8:1:2::{:x}", i + 1).parse().unwrap();
|
||||||
|
assert!(l.acquire(ip, 1000).is_ok());
|
||||||
|
}
|
||||||
|
assert!(l
|
||||||
|
.acquire("2001:db8:1:2:ffff::1".parse().unwrap(), 1000)
|
||||||
|
.is_err());
|
||||||
|
assert!(l.acquire("2001:db8:1:3::1".parse().unwrap(), 1000).is_ok());
|
||||||
|
let l = IpLimiter::default();
|
||||||
|
for _ in 0..20 {
|
||||||
|
l.acquire("::ffff:203.0.113.9".parse().unwrap(), 1000)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
assert!(l.acquire("203.0.113.9".parse().unwrap(), 1000).is_err());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn ip_table_stays_bounded() {
|
||||||
|
let l = IpLimiter::with_capacity(4);
|
||||||
|
for i in 0..50u8 {
|
||||||
|
let _ = l.acquire(IpAddr::from([10, 0, 0, i]), 1000 + u64::from(i));
|
||||||
|
}
|
||||||
|
assert!(l.tracked() <= 4);
|
||||||
|
}
|
||||||
|
fn addr(n: u8) -> IpAddr {
|
||||||
|
IpAddr::from([198, 51, 100, n])
|
||||||
|
}
|
||||||
|
fn reserve(t: &LoginThrottle, account: &str, ip: IpAddr, now: u64) -> Result<u64, u64> {
|
||||||
|
t.acquire(account, ip, false, BudgetState::default(), now)
|
||||||
|
.map(|id| id.expect("an unknown address is charged"))
|
||||||
|
}
|
||||||
|
/// An attempt from an address the account does not know.
|
||||||
|
fn pair(t: &LoginThrottle, account: &str, ip: IpAddr, now: u64) -> Result<(), u64> {
|
||||||
|
t.acquire(account, ip, false, BudgetState::default(), now)
|
||||||
|
.map(|_| ())
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_pair_follows_the_schedule_and_other_addresses_stay_free() {
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
for _ in 0..5 {
|
||||||
|
assert!(pair(&t, "k", addr(1), 1000).is_ok());
|
||||||
|
}
|
||||||
|
assert_eq!(pair(&t, "k", addr(1), 1000), Err(30));
|
||||||
|
assert_eq!(
|
||||||
|
pair(&t, "k", addr(1), 1010),
|
||||||
|
Err(20),
|
||||||
|
"refusal adds nothing"
|
||||||
|
);
|
||||||
|
assert!(pair(&t, "k", addr(2), 1000).is_ok());
|
||||||
|
assert!(pair(&t, "other", addr(1), 1000).is_ok());
|
||||||
|
assert!(pair(&t, "k", addr(1), 1030).is_ok());
|
||||||
|
assert_eq!(pair(&t, "k", addr(1), 1030), Err(60));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn counts_decay_with_time() {
|
||||||
|
assert_eq!(decayed(3, 1000, 1000 + DECAY_SECS - 1), (3, 1000));
|
||||||
|
assert_eq!(decayed(3, 1000, 1000 + DECAY_SECS), (2, 1000 + DECAY_SECS));
|
||||||
|
assert_eq!(decayed(3, 1000, 1000 + 3 * DECAY_SECS).0, 0);
|
||||||
|
assert_eq!(decayed(0, 5, u64::MAX), (0, u64::MAX));
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
for _ in 0..5 {
|
||||||
|
pair(&t, "k", addr(1), 1000).unwrap();
|
||||||
|
}
|
||||||
|
// Two windows later three failures remain: the next one is the fourth,
|
||||||
|
// which carries no delay.
|
||||||
|
let later = 1000 + 2 * DECAY_SECS;
|
||||||
|
assert!(pair(&t, "k", addr(1), later).is_ok());
|
||||||
|
assert!(pair(&t, "k", addr(1), later).is_ok(), "fifth is evaluated");
|
||||||
|
assert_eq!(pair(&t, "k", addr(1), later), Err(30));
|
||||||
|
}
|
||||||
|
/// Fails `n` times, each from its own address.
|
||||||
|
fn spend(t: &LoginThrottle, account: &str, n: u32, first: u32, now: u64) -> u32 {
|
||||||
|
let mut through = 0;
|
||||||
|
for i in 0..n {
|
||||||
|
let ip = IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + first + i));
|
||||||
|
if let Ok(id) = reserve(t, account, ip, now) {
|
||||||
|
through += 1;
|
||||||
|
t.failed(account, id, now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
through
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn the_budget_is_a_cap_over_a_rolling_day() {
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
assert_eq!(spend(&t, "k", 150, 0, 1000), 100);
|
||||||
|
assert_eq!(pair(&t, "k", addr(1), 1800), Err(BUDGET_WINDOW_SECS - 800));
|
||||||
|
// Nothing opens before the oldest failure is a day old, then all at once:
|
||||||
|
// these 100 all happened at the same instant.
|
||||||
|
assert_eq!(spend(&t, "k", 5, 200, 1000 + BUDGET_WINDOW_SECS - 1), 0);
|
||||||
|
assert_eq!(spend(&t, "k", 150, 300, 1000 + BUDGET_WINDOW_SECS), 100);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_known_address_skips_the_budget_but_not_the_pair() {
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
spend(&t, "k", 100, 0, 1000);
|
||||||
|
let known = |now| {
|
||||||
|
t.acquire("k", addr(1), true, BudgetState::default(), now)
|
||||||
|
.map(|id| id.is_some())
|
||||||
|
};
|
||||||
|
for _ in 0..5 {
|
||||||
|
assert_eq!(known(1000), Ok(false));
|
||||||
|
}
|
||||||
|
assert_eq!(known(1000), Err(30));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_right_password_returns_only_a_reservation() {
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
spend(&t, "k", 99, 0, 1000);
|
||||||
|
let id = reserve(&t, "k", addr(2), 1000).unwrap();
|
||||||
|
assert!(pair(&t, "k", addr(1), 1000).is_err(), "reserved counts");
|
||||||
|
t.right_password("k", addr(2), None);
|
||||||
|
assert!(pair(&t, "k", addr(1), 1000).is_err(), "not charged");
|
||||||
|
t.right_password("k", addr(2), Some(id));
|
||||||
|
let id = reserve(&t, "k", addr(1), 1000).unwrap();
|
||||||
|
t.failed("k", id, 1000);
|
||||||
|
t.right_password("k", addr(1), Some(id));
|
||||||
|
assert!(pair(&t, "k", addr(3), 1000).is_err(), "failures stay");
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn taking_every_opening_slot_never_passes_the_rolling_cap() {
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
let start = 10_000u64;
|
||||||
|
let mut taken: Vec<u64> = Vec::new();
|
||||||
|
let mut first = 0;
|
||||||
|
for minute in 0..(3 * 1440u64) {
|
||||||
|
let now = start + minute * 60;
|
||||||
|
// Fresh addresses: only the budget can refuse.
|
||||||
|
for _ in 0..3 {
|
||||||
|
first += 1;
|
||||||
|
if spend(&t, "k", 1, first, now) == 1 {
|
||||||
|
taken.push(now);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(taken.len() >= 200, "the window reopens: {}", taken.len());
|
||||||
|
for (i, a) in taken.iter().enumerate() {
|
||||||
|
let inside = taken[i..]
|
||||||
|
.iter()
|
||||||
|
.take_while(|b| **b < a + BUDGET_WINDOW_SECS)
|
||||||
|
.count();
|
||||||
|
assert!(inside <= 100, "{inside} failures in the day from {a}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_reset_frees_a_pair_even_after_its_budget_was_evicted() {
|
||||||
|
let t = LoginThrottle::with_capacity(1000, 1);
|
||||||
|
for _ in 0..5 {
|
||||||
|
pair(&t, "k", addr(1), 1000).unwrap();
|
||||||
|
}
|
||||||
|
pair(&t, "other", addr(2), 1000).unwrap();
|
||||||
|
pair(&t, "other2", addr(2), 1000).unwrap();
|
||||||
|
let reset = BudgetState {
|
||||||
|
generation: 1,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
t.acquire("k", addr(1), false, reset.clone(), 1000)
|
||||||
|
.map(|id| id.is_some()),
|
||||||
|
Ok(true)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_new_generation_starts_the_account_over() {
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
spend(&t, "k", 100, 0, 1000);
|
||||||
|
for _ in 0..5 {
|
||||||
|
let _ = t.acquire("k", addr(1), true, BudgetState::default(), 1000);
|
||||||
|
}
|
||||||
|
let reset = BudgetState {
|
||||||
|
generation: 1,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
t.acquire("k", addr(1), false, reset.clone(), 1000)
|
||||||
|
.map(|id| id.is_some()),
|
||||||
|
Ok(true)
|
||||||
|
);
|
||||||
|
// Pairs too, even for an account seen only from a known address.
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
for _ in 0..5 {
|
||||||
|
t.acquire("k", addr(1), true, BudgetState::default(), 1000)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
t.acquire("k", addr(1), true, reset.clone(), 1000)
|
||||||
|
.map(|id| id.is_some()),
|
||||||
|
Ok(false)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_stored_budget_is_where_an_unmet_account_starts() {
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
let stored = BudgetState {
|
||||||
|
times: vec![1000; BUDGET_MAX_FAILURES],
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
assert!(t.acquire("k", addr(1), false, stored, 1000).is_err());
|
||||||
|
assert_eq!(t.tracked().1, 0, "a refusal keeps nothing");
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn eviction_takes_the_faded_then_the_least_counted() {
|
||||||
|
let t = LoginThrottle::with_capacity(1000, 3);
|
||||||
|
spend(&t, "faded", 1, 0, 1000);
|
||||||
|
spend(&t, "busy", 50, 10, 1000);
|
||||||
|
spend(&t, "small", 2, 100, 1000);
|
||||||
|
// Newer than all of them, and each new name pushes out the last.
|
||||||
|
let now = 1001;
|
||||||
|
for i in 0..50 {
|
||||||
|
spend(&t, &format!("junk{i}"), 1, 200 + i, now);
|
||||||
|
}
|
||||||
|
assert_eq!(spend(&t, "busy", 60, 300, now), 50);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_flood_does_not_free_a_locked_pair() {
|
||||||
|
let t = LoginThrottle::with_capacity(4, 1000);
|
||||||
|
for _ in 0..5 {
|
||||||
|
pair(&t, "k", addr(1), 1000).unwrap();
|
||||||
|
}
|
||||||
|
for i in 0..50u8 {
|
||||||
|
let _ = pair(&t, &format!("j{i}"), addr(100 + i), 1001);
|
||||||
|
}
|
||||||
|
assert!(pair(&t, "k", addr(1), 1001).is_err());
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_failure_asks_for_a_write_per_minute_and_at_the_crossing() {
|
||||||
|
let t = LoginThrottle::default();
|
||||||
|
let note = |now| {
|
||||||
|
let id = reserve(&t, "k", addr(9), now).unwrap();
|
||||||
|
t.failed("k", id, now)
|
||||||
|
};
|
||||||
|
assert!(note(1000).write.is_some());
|
||||||
|
assert!(note(1000).write.is_none());
|
||||||
|
assert!(note(1000 + BUDGET_WRITE_SECS).write.is_some());
|
||||||
|
spend(&t, "x", 99, 0, 1000);
|
||||||
|
let id = reserve(&t, "x", addr(8), 1000).unwrap();
|
||||||
|
let crossing = t.failed("x", id, 1000);
|
||||||
|
assert_eq!(crossing.write.map(|s| s.times.len()), Some(100));
|
||||||
|
assert!(crossing.audit);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn a_48_is_one_address_and_a_mapped_v4_is_the_v4() {
|
||||||
|
let key = |s: &str| address_key(s.parse().unwrap());
|
||||||
|
assert_eq!(key("2001:db8:1:2::1"), key("2001:db8:1:ffff:1::9"));
|
||||||
|
assert_ne!(key("2001:db8:1::1"), key("2001:db8:2::1"));
|
||||||
|
assert_eq!(key("::ffff:203.0.113.9"), key("203.0.113.9"));
|
||||||
|
assert_ne!(key("203.0.113.9"), key("203.0.113.8"));
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn tables_stay_bounded() {
|
||||||
|
let t = LoginThrottle::with_capacity(3, 3);
|
||||||
|
for i in 0..20u8 {
|
||||||
|
let _ = pair(&t, &format!("k{i}"), addr(i), u64::from(i));
|
||||||
|
}
|
||||||
|
let (pairs, accounts) = t.tracked();
|
||||||
|
assert!(pairs <= 3 && accounts <= 3);
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -19,6 +19,55 @@ pub enum AcauaError {
|
|||||||
|
|
||||||
#[error("database error: {0}")]
|
#[error("database error: {0}")]
|
||||||
Database(#[from] duckdb::Error),
|
Database(#[from] duckdb::Error),
|
||||||
|
|
||||||
|
#[error("authentication error: {0}")]
|
||||||
|
Auth(#[from] AuthFailure),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every refusal the authentication layer can raise. Variants never carry
|
||||||
|
/// secret material, only a description of what went wrong.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||||
|
pub enum AuthFailure {
|
||||||
|
#[error("secret key is missing while auth state already exists")]
|
||||||
|
KeyMissing,
|
||||||
|
#[error("secret key is invalid: {0}")]
|
||||||
|
KeyInvalid(&'static str),
|
||||||
|
#[error("sealed value is malformed or failed authentication")]
|
||||||
|
SealInvalid,
|
||||||
|
#[error("MFA is not enabled for this account")]
|
||||||
|
MfaNotEnabled,
|
||||||
|
#[error("auth state is corrupted: {0}")]
|
||||||
|
StateCorrupt(String),
|
||||||
|
#[error("auth state version {0} is not supported")]
|
||||||
|
StateVersionUnsupported(u32),
|
||||||
|
#[error("audit log is corrupted: {0}")]
|
||||||
|
AuditCorrupt(String),
|
||||||
|
/// Same value for unknown user, wrong password, bad code and bad or
|
||||||
|
/// expired pending token, so a refusal reveals nothing more.
|
||||||
|
#[error("invalid credentials")]
|
||||||
|
InvalidCredentials,
|
||||||
|
#[error("too many attempts, retry in {retry_after_secs} s")]
|
||||||
|
Throttled { retry_after_secs: u64 },
|
||||||
|
#[error("initial setup is not complete")]
|
||||||
|
SetupRequired,
|
||||||
|
#[error("setup code is invalid or expired")]
|
||||||
|
BootstrapInvalid,
|
||||||
|
#[error("the last administrator cannot be removed or demoted")]
|
||||||
|
LastAdmin,
|
||||||
|
#[error("MFA is mandatory for administrators")]
|
||||||
|
MfaMandatory,
|
||||||
|
#[error("no MFA enrollment in progress")]
|
||||||
|
EnrollmentNotStarted,
|
||||||
|
#[error("username is already in use")]
|
||||||
|
UsernameTaken,
|
||||||
|
#[error("user not found")]
|
||||||
|
UserNotFound,
|
||||||
|
#[error("recent authentication is required")]
|
||||||
|
ReauthRequired,
|
||||||
|
#[error("not permitted for this role or scope")]
|
||||||
|
Forbidden,
|
||||||
|
#[error("not found")]
|
||||||
|
NotFound,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type Result<T> = std::result::Result<T, AcauaError>;
|
pub type Result<T> = std::result::Result<T, AcauaError>;
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
pub mod auth;
|
||||||
pub mod dns_store;
|
pub mod dns_store;
|
||||||
pub mod doctor;
|
pub mod doctor;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
@@ -6,8 +7,9 @@ pub mod pillar1;
|
|||||||
pub mod pillar2;
|
pub mod pillar2;
|
||||||
pub mod pillar3;
|
pub mod pillar3;
|
||||||
pub mod pillar4;
|
pub mod pillar4;
|
||||||
|
pub mod report;
|
||||||
pub mod storage;
|
pub mod storage;
|
||||||
pub mod update;
|
pub mod update;
|
||||||
pub mod zeek;
|
pub mod zeek;
|
||||||
|
|
||||||
pub use error::{AcauaError, Result};
|
pub use error::{AcauaError, AuthFailure, Result};
|
||||||
@@ -0,0 +1,957 @@
|
|||||||
|
//! Executive report: renders an [`AnalysisReport`] as a self-contained HTML
|
||||||
|
//! document paginated by Paged.js (A4, cover, table of contents, margin boxes).
|
||||||
|
//!
|
||||||
|
//! Every string that comes from Zeek logs (hosts, domains, summaries, evidence)
|
||||||
|
//! is attacker-controlled and goes through [`html_escape`] before it reaches
|
||||||
|
//! the markup. The logo is embedded as a base64 data URI so the file renders
|
||||||
|
//! offline and keeps its branding when saved.
|
||||||
|
|
||||||
|
use crate::fusion::Alert;
|
||||||
|
use crate::pillar4::HostScore;
|
||||||
|
use crate::zeek::AnalysisReport;
|
||||||
|
use serde_json::Value;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fmt::Write;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
|
||||||
|
const LOGO: &[u8] = include_bytes!("../../../logo.png");
|
||||||
|
const LOGO_MARK: &[u8] = include_bytes!("../assets/logo-mark.png");
|
||||||
|
|
||||||
|
/// Path the web server exposes the vendored Paged.js polyfill under.
|
||||||
|
pub const PAGED_JS_PATH: &str = "/vendor/paged.polyfill.min.js";
|
||||||
|
|
||||||
|
/// Traffic Light Protocol labels accepted by the report.
|
||||||
|
pub const TLP_LEVELS: [&str; 5] = ["CLEAR", "GREEN", "AMBER", "AMBER+STRICT", "RED"];
|
||||||
|
|
||||||
|
/// Options that change how the report is rendered.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ReportOptions {
|
||||||
|
/// TLP label without the `TLP:` prefix. Unknown values fall back to AMBER.
|
||||||
|
pub tlp: String,
|
||||||
|
/// Issue timestamp shown on the cover; `None` uses the current UTC time.
|
||||||
|
pub issued_at: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for ReportOptions {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
tlp: "AMBER".to_string(),
|
||||||
|
issued_at: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Normalizes a user supplied TLP label; anything unknown becomes AMBER.
|
||||||
|
pub fn normalize_tlp(raw: &str) -> &'static str {
|
||||||
|
let upper = raw.trim().to_ascii_uppercase();
|
||||||
|
let upper = upper.trim_start_matches("TLP:");
|
||||||
|
TLP_LEVELS
|
||||||
|
.iter()
|
||||||
|
.find(|level| **level == upper)
|
||||||
|
.copied()
|
||||||
|
.unwrap_or("AMBER")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Escapes text for HTML element content and quoted attribute values.
|
||||||
|
pub fn html_escape(raw: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(raw.len());
|
||||||
|
for c in raw.chars() {
|
||||||
|
match c {
|
||||||
|
'&' => out.push_str("&"),
|
||||||
|
'<' => out.push_str("<"),
|
||||||
|
'>' => out.push_str(">"),
|
||||||
|
'"' => out.push_str("""),
|
||||||
|
'\'' => out.push_str("'"),
|
||||||
|
_ => out.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn base64(bytes: &[u8]) -> String {
|
||||||
|
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
|
||||||
|
for chunk in bytes.chunks(3) {
|
||||||
|
let b = [
|
||||||
|
chunk[0],
|
||||||
|
*chunk.get(1).unwrap_or(&0),
|
||||||
|
*chunk.get(2).unwrap_or(&0),
|
||||||
|
];
|
||||||
|
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
|
||||||
|
out.push(TABLE[(n >> 18) as usize & 63] as char);
|
||||||
|
out.push(TABLE[(n >> 12) as usize & 63] as char);
|
||||||
|
out.push(if chunk.len() > 1 {
|
||||||
|
TABLE[(n >> 6) as usize & 63] as char
|
||||||
|
} else {
|
||||||
|
'='
|
||||||
|
});
|
||||||
|
out.push(if chunk.len() > 2 {
|
||||||
|
TABLE[n as usize & 63] as char
|
||||||
|
} else {
|
||||||
|
'='
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `data:image/png;base64,...` URI of the full logo.
|
||||||
|
pub fn logo_data_uri() -> String {
|
||||||
|
format!("data:image/png;base64,{}", base64(LOGO))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Small logo wrapped in an SVG data URI, usable as a CSS background in the
|
||||||
|
/// Paged.js margin boxes.
|
||||||
|
fn logo_mark_css_uri() -> String {
|
||||||
|
let svg = format!(
|
||||||
|
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"128\" height=\"128\" viewBox=\"0 0 128 128\"><image width=\"128\" height=\"128\" xlink:href=\"data:image/png;base64,{}\"/></svg>",
|
||||||
|
base64(LOGO_MARK)
|
||||||
|
);
|
||||||
|
format!("data:image/svg+xml;base64,{}", base64(svg.as_bytes()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn num(value: f64, decimals: usize) -> String {
|
||||||
|
if !value.is_finite() {
|
||||||
|
return "—".to_string();
|
||||||
|
}
|
||||||
|
format!("{value:.decimals$}").replace('.', ",")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn int(value: u64) -> String {
|
||||||
|
let digits = value.to_string();
|
||||||
|
let mut out = String::new();
|
||||||
|
for (i, c) in digits.chars().enumerate() {
|
||||||
|
if i > 0 && (digits.len() - i).is_multiple_of(3) {
|
||||||
|
out.push('.');
|
||||||
|
}
|
||||||
|
out.push(c);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ev_f64(evidence: &Value, key: &str) -> Option<f64> {
|
||||||
|
evidence.get(key).and_then(Value::as_f64)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ev_str<'a>(evidence: &'a Value, key: &str) -> Option<&'a str> {
|
||||||
|
evidence.get(key).and_then(Value::as_str)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pillar_name(pillar: u8) -> &'static str {
|
||||||
|
match pillar {
|
||||||
|
1 => "Beaconing",
|
||||||
|
2 => "Sessão persistente",
|
||||||
|
3 => "Túnel DNS / anomalia de protocolo",
|
||||||
|
4 => "Fusão de evidências",
|
||||||
|
_ => "Desconhecido",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn severity(score: f64) -> (&'static str, &'static str) {
|
||||||
|
if score >= 0.85 {
|
||||||
|
("crit", "Crítico")
|
||||||
|
} else if score >= 0.65 {
|
||||||
|
("high", "Alto")
|
||||||
|
} else if score >= 0.40 {
|
||||||
|
("med", "Médio")
|
||||||
|
} else {
|
||||||
|
("low", "Baixo")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn score_chip(score: f64) -> String {
|
||||||
|
let (class, label) = severity(score);
|
||||||
|
format!(
|
||||||
|
"<span class=\"sev sev-{class}\">{} · {label}</span>",
|
||||||
|
num(score, 3)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Origin and destination of a conn based alert. The summary is built by
|
||||||
|
/// `zeek::analyze_dir` as `"...: ORIG[:any] -> DEST:PORT (...)"`.
|
||||||
|
fn endpoints(alert: &Alert, owner: Option<&str>) -> (String, String) {
|
||||||
|
if let (Some(orig), Some(domain)) = (
|
||||||
|
ev_str(&alert.evidence, "orig_h"),
|
||||||
|
ev_str(&alert.evidence, "base_domain"),
|
||||||
|
) {
|
||||||
|
return (orig.to_string(), domain.to_string());
|
||||||
|
}
|
||||||
|
let summary = alert.summary.as_str();
|
||||||
|
let after_colon = summary.split_once(": ").map(|(_, rest)| rest).unwrap_or("");
|
||||||
|
let (left, right) = after_colon.split_once(" -> ").unwrap_or(("", ""));
|
||||||
|
let orig = left.trim_end_matches(":any").to_string();
|
||||||
|
let dest = right
|
||||||
|
.split_once(" (")
|
||||||
|
.map(|(d, _)| d)
|
||||||
|
.unwrap_or(right)
|
||||||
|
.to_string();
|
||||||
|
let orig = if orig.is_empty() {
|
||||||
|
owner.unwrap_or("—").to_string()
|
||||||
|
} else {
|
||||||
|
orig
|
||||||
|
};
|
||||||
|
let dest = if dest.is_empty() {
|
||||||
|
"—".to_string()
|
||||||
|
} else {
|
||||||
|
dest
|
||||||
|
};
|
||||||
|
(orig, dest)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flatten_evidence(value: &Value, prefix: &str, out: &mut Vec<(String, String)>) {
|
||||||
|
match value {
|
||||||
|
Value::Object(map) => {
|
||||||
|
for (k, v) in map {
|
||||||
|
let key = if prefix.is_empty() {
|
||||||
|
k.clone()
|
||||||
|
} else {
|
||||||
|
format!("{prefix}.{k}")
|
||||||
|
};
|
||||||
|
flatten_evidence(v, &key, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Array(items) => {
|
||||||
|
let joined = items
|
||||||
|
.iter()
|
||||||
|
.take(8)
|
||||||
|
.map(|v| match v {
|
||||||
|
Value::String(s) => s.clone(),
|
||||||
|
other => other.to_string(),
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", ");
|
||||||
|
let more = if items.len() > 8 { ", …" } else { "" };
|
||||||
|
out.push((prefix.to_string(), format!("[{joined}{more}]")));
|
||||||
|
}
|
||||||
|
Value::Number(n) => {
|
||||||
|
let text = match n.as_f64() {
|
||||||
|
Some(f) if n.is_f64() => num(f, 4),
|
||||||
|
_ => n.to_string(),
|
||||||
|
};
|
||||||
|
out.push((prefix.to_string(), text));
|
||||||
|
}
|
||||||
|
Value::String(s) => out.push((prefix.to_string(), s.clone())),
|
||||||
|
Value::Bool(b) => out.push((prefix.to_string(), if *b { "sim" } else { "não" }.into())),
|
||||||
|
Value::Null => out.push((prefix.to_string(), "—".into())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Ctx<'a> {
|
||||||
|
report: &'a AnalysisReport,
|
||||||
|
owner: HashMap<&'a str, &'a str>,
|
||||||
|
by_id: HashMap<&'a str, &'a Alert>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Ctx<'a> {
|
||||||
|
fn new(report: &'a AnalysisReport) -> Self {
|
||||||
|
let mut owner = HashMap::new();
|
||||||
|
for host in &report.hosts {
|
||||||
|
for term in &host.terms {
|
||||||
|
if let Some(id) = &term.alert_id {
|
||||||
|
owner.insert(id.as_str(), host.orig_h.as_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let by_id = report.alerts.iter().map(|a| (a.id.as_str(), a)).collect();
|
||||||
|
Self {
|
||||||
|
report,
|
||||||
|
owner,
|
||||||
|
by_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn alerts_of(&self, pillar: u8) -> Vec<&'a Alert> {
|
||||||
|
let mut list: Vec<&Alert> = self
|
||||||
|
.report
|
||||||
|
.alerts
|
||||||
|
.iter()
|
||||||
|
.filter(|a| a.pillar == pillar)
|
||||||
|
.collect();
|
||||||
|
list.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.id.cmp(&b.id)));
|
||||||
|
list
|
||||||
|
}
|
||||||
|
|
||||||
|
fn host_alert(&self, host: &HostScore, pillar: u8) -> Option<&'a Alert> {
|
||||||
|
host.terms
|
||||||
|
.iter()
|
||||||
|
.find(|t| t.pillar == pillar)
|
||||||
|
.and_then(|t| t.alert_id.as_deref())
|
||||||
|
.and_then(|id| self.by_id.get(id).copied())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn endpoints(&self, alert: &Alert) -> (String, String) {
|
||||||
|
endpoints(alert, self.owner.get(alert.id.as_str()).copied())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sorted_hosts(report: &AnalysisReport) -> Vec<&HostScore> {
|
||||||
|
let mut hosts: Vec<&HostScore> = report.hosts.iter().collect();
|
||||||
|
hosts.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.orig_h.cmp(&b.orig_h)));
|
||||||
|
hosts
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cover motif: one beacon lane per top host. Lanes with a Pilar 1 alert get
|
||||||
|
/// ticks spaced by the detected period, Pilar 2 shows as a bar sized by
|
||||||
|
/// session hours, Pilar 3 as a dense burst. Opacity follows the fused score.
|
||||||
|
fn cover_motif(ctx: &Ctx) -> String {
|
||||||
|
let hosts = sorted_hosts(ctx.report);
|
||||||
|
let lanes = hosts.len().clamp(1, 9);
|
||||||
|
let mut svg = String::from(
|
||||||
|
"<svg class=\"motif\" viewBox=\"0 0 210 120\" preserveAspectRatio=\"none\" aria-hidden=\"true\">",
|
||||||
|
);
|
||||||
|
let gap = 120.0 / (lanes as f64 + 1.0);
|
||||||
|
for i in 0..lanes {
|
||||||
|
let y = gap * (i as f64 + 1.0);
|
||||||
|
let _ = write!(
|
||||||
|
svg,
|
||||||
|
"<line x1=\"0\" y1=\"{y:.2}\" x2=\"210\" y2=\"{y:.2}\" stroke=\"#45d6b0\" stroke-opacity=\"0.14\" stroke-width=\"0.25\"/>"
|
||||||
|
);
|
||||||
|
let Some(host) = hosts.get(i) else { continue };
|
||||||
|
let opacity = 0.30 + 0.70 * host.score.clamp(0.0, 1.0);
|
||||||
|
let color = if host.score >= 0.70 {
|
||||||
|
"#f0b35b"
|
||||||
|
} else {
|
||||||
|
"#45d6b0"
|
||||||
|
};
|
||||||
|
if let Some(alert) = ctx.host_alert(host, 1) {
|
||||||
|
let period = ev_f64(&alert.evidence, "period_detected_seconds").unwrap_or(3600.0);
|
||||||
|
let spacing = (2.5 + period.max(1.0).log10() * 2.2).clamp(3.0, 16.0);
|
||||||
|
let mut x = 78.0 + (i as f64 * 1.7) % spacing;
|
||||||
|
while x < 206.0 {
|
||||||
|
let _ = write!(
|
||||||
|
svg,
|
||||||
|
"<line x1=\"{x:.2}\" y1=\"{:.2}\" x2=\"{x:.2}\" y2=\"{:.2}\" stroke=\"{color}\" stroke-opacity=\"{opacity:.2}\" stroke-width=\"0.7\" stroke-linecap=\"round\"/>",
|
||||||
|
y - 2.6,
|
||||||
|
y + 2.6
|
||||||
|
);
|
||||||
|
x += spacing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(alert) = ctx.host_alert(host, 2) {
|
||||||
|
let hours = ev_f64(&alert.evidence, "longest_session_seconds").unwrap_or(0.0) / 3600.0;
|
||||||
|
let len = (20.0 + hours * 6.0).clamp(20.0, 150.0);
|
||||||
|
let _ = write!(
|
||||||
|
svg,
|
||||||
|
"<rect x=\"84\" y=\"{:.2}\" width=\"{len:.2}\" height=\"1.6\" rx=\"0.8\" fill=\"{color}\" fill-opacity=\"{:.2}\"/>",
|
||||||
|
y - 0.8,
|
||||||
|
opacity * 0.8
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(alert) = ctx.host_alert(host, 3) {
|
||||||
|
let unique = ev_f64(&alert.evidence, "unique_subdomains").unwrap_or(40.0);
|
||||||
|
let count = (unique / 4.0).clamp(10.0, 60.0) as usize;
|
||||||
|
for k in 0..count {
|
||||||
|
let jitter = ((k * 37 + i * 11) % 17) as f64 / 17.0;
|
||||||
|
let x = 120.0 + k as f64 * 1.4 + jitter;
|
||||||
|
let h = 1.0 + jitter * 2.0;
|
||||||
|
let _ = write!(
|
||||||
|
svg,
|
||||||
|
"<line x1=\"{x:.2}\" y1=\"{:.2}\" x2=\"{x:.2}\" y2=\"{:.2}\" stroke=\"#fb923c\" stroke-opacity=\"{:.2}\" stroke-width=\"0.45\"/>",
|
||||||
|
y - h,
|
||||||
|
y + h,
|
||||||
|
opacity * 0.9
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
svg.push_str("</svg>");
|
||||||
|
svg
|
||||||
|
}
|
||||||
|
|
||||||
|
const CSS: &str = r#"
|
||||||
|
:root{
|
||||||
|
--ink:#0d1f1a;--muted:#55665f;--line:#d7e2dd;--paper:#ffffff;--tint:#f2f8f5;
|
||||||
|
--accent:#087f68;--accent-2:#45d6b0;--gold:#f0b35b;--orange:#f97316;--orange-2:#fb923c;
|
||||||
|
--crit:#b42318;--high:#c2410c;--med:#a16207;--low:#4b6b61;
|
||||||
|
--sans:system-ui,"Inter","Segoe UI",Roboto,sans-serif;
|
||||||
|
--mono:ui-monospace,"JetBrains Mono","IBM Plex Mono",monospace;
|
||||||
|
}
|
||||||
|
*{box-sizing:border-box}
|
||||||
|
html,body{margin:0;background:var(--paper);color:var(--ink);font-family:var(--sans);font-size:10pt;line-height:1.5}
|
||||||
|
@page{size:A4;margin:22mm 16mm 20mm 16mm;
|
||||||
|
@top-left{content:"";background-image:var(--logo-mark);background-size:contain;background-repeat:no-repeat;background-position:left center;width:9mm;height:9mm;margin-top:8mm}
|
||||||
|
@top-center{content:"ACAUÃ · RELATÓRIO EXECUTIVO";font-family:var(--mono);font-size:7pt;letter-spacing:.14em;color:#55665f;margin-top:8mm}
|
||||||
|
@top-right{content:var(--tlp-label);font-family:var(--mono);font-size:7pt;font-weight:700;letter-spacing:.08em;color:#a15c00;margin-top:8mm}
|
||||||
|
@bottom-left{content:"Ciberfauna · Acauã · uso autorizado";font-family:var(--mono);font-size:7pt;color:#55665f}
|
||||||
|
@bottom-right{content:counter(page) " / " counter(pages);font-family:var(--mono);font-size:7pt;color:#55665f}
|
||||||
|
}
|
||||||
|
@page cover{margin:0;@top-left{content:none}@top-center{content:none}@top-right{content:none}@bottom-left{content:none}@bottom-right{content:none}}
|
||||||
|
.cover{page:cover;break-after:page;position:relative;width:210mm;height:297mm;overflow:hidden;color:#e8f5f0;
|
||||||
|
background:radial-gradient(120% 80% at 80% 55%,#0d3a2f 0%,#06201a 45%,#030d0a 100%)}
|
||||||
|
.cover .glow{position:absolute;left:70mm;top:92mm;width:160mm;height:160mm;border-radius:50%;
|
||||||
|
background:radial-gradient(circle,rgba(249,115,22,.42) 0%,rgba(251,146,60,.16) 38%,rgba(249,115,22,0) 68%)}
|
||||||
|
.cover .motif{position:absolute;left:0;top:112mm;width:210mm;height:120mm;opacity:.9}
|
||||||
|
.cover .logo{position:absolute;left:86mm;top:100mm;width:136mm;height:136mm;object-fit:contain;filter:drop-shadow(0 6mm 10mm rgba(0,0,0,.55))}
|
||||||
|
.cover .topbar{position:absolute;left:18mm;right:18mm;top:14mm;display:flex;justify-content:space-between;align-items:center}
|
||||||
|
.wordmark{font-weight:800;letter-spacing:.42em;font-size:11pt;color:#fff}
|
||||||
|
.tlp-wrap{display:flex;gap:3mm;align-items:center;font-family:var(--mono);font-size:7.5pt;letter-spacing:.12em}
|
||||||
|
.tlp{display:inline-block;border:1.2px solid var(--tlp-color);color:var(--tlp-color);border-radius:999px;padding:1mm 3.2mm;font-family:var(--mono);font-weight:700;font-size:7.5pt;letter-spacing:.08em;background:rgba(0,0,0,.25)}
|
||||||
|
.auth{color:#9fc7ba}
|
||||||
|
.cover .head{position:absolute;left:18mm;right:18mm;top:34mm}
|
||||||
|
.eyebrow{font-family:var(--mono);font-size:8pt;letter-spacing:.2em;color:var(--orange-2);text-transform:uppercase}
|
||||||
|
.cover h1{font-size:50px;line-height:1.02;font-weight:800;letter-spacing:-.03em;margin:4mm 0 4mm;color:#fff;max-width:165mm}
|
||||||
|
.cover .sub{font-size:11.5pt;color:#b9d8cd;max-width:150mm;margin:0}
|
||||||
|
.cover .numbers{position:absolute;left:18mm;top:128mm;width:66mm;display:flex;flex-direction:column;gap:6mm}
|
||||||
|
.cover .numbers div{border-left:2px solid var(--accent-2);padding-left:4mm}
|
||||||
|
.cover .numbers b{display:block;font-size:26pt;font-weight:800;line-height:1;color:#fff;letter-spacing:-.02em}
|
||||||
|
.cover .numbers span{font-family:var(--mono);font-size:7pt;letter-spacing:.14em;text-transform:uppercase;color:#9fc7ba}
|
||||||
|
.cover .meta{position:absolute;left:18mm;right:18mm;bottom:14mm;border-top:1px solid rgba(232,245,240,.25);padding-top:4mm;display:grid;grid-template-columns:1fr 1.6fr 1fr 1fr;gap:5mm}
|
||||||
|
.cover .meta span{display:block;font-family:var(--mono);font-size:6.5pt;letter-spacing:.16em;text-transform:uppercase;color:#86b3a5}
|
||||||
|
.cover .meta b{display:block;font-size:9pt;font-weight:600;color:#fff;word-break:break-all}
|
||||||
|
section{break-before:page}
|
||||||
|
section.flow{break-before:auto;margin-top:8mm}
|
||||||
|
h2{font-size:18pt;font-weight:800;letter-spacing:-.02em;margin:0 0 3mm;padding-top:4mm;position:relative;break-after:avoid}
|
||||||
|
h2::before{content:"";position:absolute;top:0;left:0;width:14mm;height:3px;background:var(--accent);border-radius:2px}
|
||||||
|
h3{font-size:11.5pt;margin:6mm 0 2mm;break-after:avoid}
|
||||||
|
p{margin:0 0 3mm}
|
||||||
|
.lead{font-size:11pt;color:#22352f}
|
||||||
|
.muted{color:var(--muted)}
|
||||||
|
.mono{font-family:var(--mono)}
|
||||||
|
.toc ol{list-style:none;padding:0;margin:6mm 0 0}
|
||||||
|
.toc li{border-bottom:1px solid var(--line);padding:2.6mm 0}
|
||||||
|
.toc a{display:flex;color:var(--ink);text-decoration:none;font-size:11pt}
|
||||||
|
.toc a span.n{font-family:var(--mono);color:var(--accent);width:10mm}
|
||||||
|
.toc a span.t{flex:1}
|
||||||
|
.toc a::after{content:target-counter(attr(href),page);font-family:var(--mono);color:var(--muted)}
|
||||||
|
.kpis{display:grid;grid-template-columns:repeat(3,1fr);gap:4mm;margin:5mm 0}
|
||||||
|
.kpi{border-top:3px solid var(--accent);background:var(--tint);padding:3mm 4mm;break-inside:avoid}
|
||||||
|
.kpi.warn{border-top-color:var(--orange)}
|
||||||
|
.kpi b{display:block;font-size:20pt;font-weight:800;letter-spacing:-.02em;line-height:1.1}
|
||||||
|
.kpi span{font-family:var(--mono);font-size:7pt;letter-spacing:.12em;text-transform:uppercase;color:var(--muted)}
|
||||||
|
.callout{border-left:3px solid var(--accent);background:var(--tint);padding:3mm 4mm;margin:4mm 0;break-inside:avoid}
|
||||||
|
.callout.act{border-left-color:var(--orange)}
|
||||||
|
.callout strong{font-family:var(--mono);font-size:7.5pt;letter-spacing:.14em;text-transform:uppercase;display:block;margin-bottom:1mm;color:var(--accent)}
|
||||||
|
.callout.act strong{color:var(--high)}
|
||||||
|
table{width:100%;border-collapse:collapse;margin:3mm 0 5mm;font-size:8.5pt}
|
||||||
|
thead{display:table-header-group}
|
||||||
|
th{text-align:left;font-family:var(--mono);font-size:7pt;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);border-bottom:1.5px solid var(--ink);padding:1.6mm 2mm}
|
||||||
|
td{padding:1.6mm 2mm;border-bottom:1px solid var(--line);vertical-align:top;word-break:break-word}
|
||||||
|
tbody tr:nth-child(even) td{background:var(--tint)}
|
||||||
|
tr{break-inside:avoid}
|
||||||
|
td.num,th.num{text-align:right;font-variant-numeric:tabular-nums}
|
||||||
|
.sev{display:inline-block;font-family:var(--mono);font-size:7pt;font-weight:700;padding:.3mm 1.6mm;border-radius:3px;white-space:nowrap}
|
||||||
|
.sev-crit{background:#fde8e6;color:var(--crit)}.sev-high{background:#fff0e5;color:var(--high)}
|
||||||
|
.sev-med{background:#fdf5df;color:var(--med)}.sev-low{background:#eaf2ef;color:var(--low)}
|
||||||
|
.card{border:1px solid var(--line);border-radius:2mm;padding:3mm 4mm;margin:0 0 4mm;break-inside:avoid}
|
||||||
|
.card header{display:flex;justify-content:space-between;gap:3mm;align-items:baseline;margin-bottom:1.5mm}
|
||||||
|
.card header .id{font-family:var(--mono);font-size:8pt;color:var(--muted)}
|
||||||
|
.card .sum{font-family:var(--mono);font-size:8pt;margin:0 0 2mm;word-break:break-all}
|
||||||
|
.ev{display:grid;grid-template-columns:repeat(2,1fr);gap:.6mm 5mm;font-size:7.5pt;margin:0}
|
||||||
|
.ev div{display:flex;justify-content:space-between;gap:2mm;border-bottom:1px dotted var(--line)}
|
||||||
|
.ev dt{font-family:var(--mono);color:var(--muted)}
|
||||||
|
.ev dd{margin:0;font-family:var(--mono);text-align:right;word-break:break-all}
|
||||||
|
.empty{color:var(--muted);font-style:italic}
|
||||||
|
.gloss dt{font-weight:700;margin-top:3mm}
|
||||||
|
.gloss dd{margin:0 0 0 0;color:#22352f}
|
||||||
|
.pill{font-family:var(--mono);font-size:7pt;color:var(--accent);letter-spacing:.1em;text-transform:uppercase}
|
||||||
|
"#;
|
||||||
|
|
||||||
|
/// Renders the executive report with the default options (TLP:AMBER, now).
|
||||||
|
pub fn render_html(report: &AnalysisReport) -> String {
|
||||||
|
render_html_with(report, &ReportOptions::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the executive report as a standalone HTML document.
|
||||||
|
pub fn render_html_with(report: &AnalysisReport, options: &ReportOptions) -> String {
|
||||||
|
let ctx = Ctx::new(report);
|
||||||
|
let tlp = normalize_tlp(&options.tlp);
|
||||||
|
let tlp_color = match tlp {
|
||||||
|
"CLEAR" => "#e5e7eb",
|
||||||
|
"GREEN" => "#4ade80",
|
||||||
|
"RED" => "#f87171",
|
||||||
|
_ => "#f0b35b",
|
||||||
|
};
|
||||||
|
let issued = options.issued_at.clone().unwrap_or_else(|| {
|
||||||
|
let format = time::macros::format_description!("[day]/[month]/[year] [hour]:[minute] UTC");
|
||||||
|
OffsetDateTime::now_utc()
|
||||||
|
.format(&format)
|
||||||
|
.unwrap_or_else(|_| "—".to_string())
|
||||||
|
});
|
||||||
|
let hosts = sorted_hosts(report);
|
||||||
|
let p1 = ctx.alerts_of(1);
|
||||||
|
let p2 = ctx.alerts_of(2);
|
||||||
|
let p3 = ctx.alerts_of(3);
|
||||||
|
let top_score = hosts.first().map(|h| h.score).unwrap_or(0.0);
|
||||||
|
let critical = hosts.iter().filter(|h| h.score >= 0.85).count();
|
||||||
|
let multi = hosts
|
||||||
|
.iter()
|
||||||
|
.filter(|h| h.terms.iter().filter(|t| t.m > 0.0).count() >= 2)
|
||||||
|
.count();
|
||||||
|
|
||||||
|
let mut h = String::with_capacity(2 * 1024 * 1024);
|
||||||
|
h.push_str("<!doctype html>\n<html lang=\"pt-BR\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Acauã · Relatório executivo</title>\n<style>");
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
":root{{--logo-mark:url(\"{}\");--tlp-label:\"TLP:{tlp}\";--tlp-color:{tlp_color}}}",
|
||||||
|
logo_mark_css_uri()
|
||||||
|
);
|
||||||
|
h.push_str(CSS);
|
||||||
|
h.push_str("</style>\n</head>\n<body>\n");
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ cover
|
||||||
|
let tlp_html = html_escape(tlp);
|
||||||
|
h.push_str("<div class=\"cover\">\n<div class=\"glow\"></div>\n");
|
||||||
|
h.push_str(&cover_motif(&ctx));
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"\n<img class=\"logo\" src=\"{}\" alt=\"Logo do Acauã\">\n",
|
||||||
|
logo_data_uri()
|
||||||
|
);
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<div class=\"topbar\"><span class=\"wordmark\">ACAUÃ</span><span class=\"tlp-wrap\"><span class=\"auth\">USO AUTORIZADO</span><span class=\"tlp\">TLP:{tlp_html}</span></span></div>"
|
||||||
|
);
|
||||||
|
h.push_str("<div class=\"head\"><div class=\"eyebrow\">Ciberfauna · Detecção de ameaças em tráfego de rede</div><h1>Relatório executivo de caça a ameaças</h1><p class=\"sub\">Análise determinística de logs Zeek: beaconing, sessões persistentes, túneis DNS e fusão de evidências por host.</p></div>\n");
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<div class=\"numbers\"><div><b>{}</b><span>alertas</span></div><div><b>{}</b><span>hosts priorizados</span></div><div><b>{}</b><span>maior score de host</span></div><div><b>{}</b><span>registros lidos</span></div></div>",
|
||||||
|
report.alerts.len(),
|
||||||
|
report.hosts.len(),
|
||||||
|
num(top_score, 2),
|
||||||
|
int(report.records)
|
||||||
|
);
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<div class=\"meta\"><div><span>Emissão</span><b>{}</b></div><div><span>Escopo</span><b>{}</b></div><div><span>Achados</span><b>{} alertas · {} hosts</b></div><div><span>Classificação</span><b>TLP:{tlp_html}</b></div></div>\n</div>",
|
||||||
|
html_escape(&issued),
|
||||||
|
// the cover only names the folder; the full path is in "Escopo da análise"
|
||||||
|
html_escape(
|
||||||
|
report
|
||||||
|
.directory
|
||||||
|
.trim_end_matches(['/', '\\'])
|
||||||
|
.rsplit(['/', '\\'])
|
||||||
|
.next()
|
||||||
|
.filter(|s| !s.is_empty())
|
||||||
|
.unwrap_or(&report.directory)
|
||||||
|
),
|
||||||
|
report.alerts.len(),
|
||||||
|
report.hosts.len()
|
||||||
|
);
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ TOC
|
||||||
|
let sections = [
|
||||||
|
("resumo", "Sumário executivo"),
|
||||||
|
("hosts", "Hosts priorizados"),
|
||||||
|
("pilar1", "Pilar 1 · Beaconing"),
|
||||||
|
("pilar2", "Pilar 2 · Sessões persistentes"),
|
||||||
|
("pilar3", "Pilar 3 · Túneis DNS e anomalias de protocolo"),
|
||||||
|
("pilar4", "Pilar 4 · Fusão de evidências"),
|
||||||
|
("alertas", "Alertas e evidências"),
|
||||||
|
("metodologia", "Metodologia e glossário"),
|
||||||
|
("escopo", "Escopo da análise"),
|
||||||
|
];
|
||||||
|
h.push_str("<section class=\"toc\"><h2>Sumário</h2><ol>");
|
||||||
|
for (i, (id, title)) in sections.iter().enumerate() {
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<li><a href=\"#{id}\"><span class=\"n\">{:02}</span><span class=\"t\">{title}</span></a></li>",
|
||||||
|
i + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
h.push_str("</ol></section>\n");
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ summary
|
||||||
|
h.push_str("<section id=\"resumo\"><h2>Sumário executivo</h2>");
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<p class=\"lead\">O Acauã leu {} arquivo(s) de log Zeek ({} de DNS), com {} registros, e produziu {} alerta(s) em {} host(s) de origem. Os scores são determinísticos e reproduzíveis: cada número vem acompanhado da evidência em JSON que o gerou.</p>",
|
||||||
|
report.logs_seen,
|
||||||
|
report.dns_logs_seen,
|
||||||
|
int(report.records),
|
||||||
|
report.alerts.len(),
|
||||||
|
report.hosts.len()
|
||||||
|
);
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<div class=\"kpis\"><div class=\"kpi\"><b>{}</b><span>Beaconing (P1)</span></div><div class=\"kpi\"><b>{}</b><span>Sessões persistentes (P2)</span></div><div class=\"kpi\"><b>{}</b><span>Túneis DNS (P3)</span></div><div class=\"kpi warn\"><b>{}</b><span>Hosts com score ≥ 0,85</span></div><div class=\"kpi\"><b>{}</b><span>Hosts com 2+ pilares</span></div><div class=\"kpi\"><b>{}</b><span>Maior score fundido</span></div></div>",
|
||||||
|
p1.len(),
|
||||||
|
p2.len(),
|
||||||
|
p3.len(),
|
||||||
|
critical,
|
||||||
|
multi,
|
||||||
|
num(top_score, 3)
|
||||||
|
);
|
||||||
|
if let Some(top) = hosts.first() {
|
||||||
|
let pillars: Vec<String> = top
|
||||||
|
.terms
|
||||||
|
.iter()
|
||||||
|
.filter(|t| t.m > 0.0)
|
||||||
|
.map(|t| format!("P{}", t.pillar))
|
||||||
|
.collect();
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<div class=\"callout\"><strong>Leitura</strong>O host de maior prioridade é <span class=\"mono\">{}</span>, com score fundido {} a partir de {}. Hosts que aparecem em mais de um pilar acumulam evidências independentes e merecem atenção primeiro.</div>",
|
||||||
|
html_escape(&top.orig_h),
|
||||||
|
num(top.score, 3),
|
||||||
|
if pillars.is_empty() {
|
||||||
|
"nenhum pilar".to_string()
|
||||||
|
} else {
|
||||||
|
pillars.join(", ")
|
||||||
|
}
|
||||||
|
);
|
||||||
|
h.push_str("<div class=\"callout act\"><strong>Ação</strong>Valide os hosts do topo do ranking com o responsável pela máquina, confira os destinos e domínios listados contra inteligência de ameaças e, se confirmado, isole o host e bloqueie o destino no perímetro.</div>");
|
||||||
|
} else {
|
||||||
|
h.push_str("<div class=\"callout\"><strong>Leitura</strong>Nenhum alerta atingiu os limiares dos pilares neste recorte. Isso não prova ausência de ameaça: confira se o período e os logs analisados cobrem o tráfego de interesse.</div>");
|
||||||
|
}
|
||||||
|
h.push_str("</section>\n");
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ hosts
|
||||||
|
h.push_str("<section id=\"hosts\" class=\"flow\"><h2>Hosts priorizados</h2><p>Ranking por score fundido (Pilar 4). As colunas m1, m2 e m3 são as massas de evidência de cada pilar que entram na combinação.</p>");
|
||||||
|
if hosts.is_empty() {
|
||||||
|
h.push_str("<p class=\"empty\">Nenhum host com alerta.</p>");
|
||||||
|
} else {
|
||||||
|
h.push_str("<table><thead><tr><th>#</th><th>Host de origem</th><th class=\"num\">m1</th><th class=\"num\">m2</th><th class=\"num\">m3</th><th>Score fundido</th></tr></thead><tbody>");
|
||||||
|
for (i, host) in hosts.iter().enumerate() {
|
||||||
|
let m = |p: u8| {
|
||||||
|
host.terms
|
||||||
|
.iter()
|
||||||
|
.find(|t| t.pillar == p)
|
||||||
|
.map(|t| num(t.m, 3))
|
||||||
|
.unwrap_or_else(|| "—".into())
|
||||||
|
};
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<tr><td class=\"num\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td>{}</td></tr>",
|
||||||
|
i + 1,
|
||||||
|
html_escape(&host.orig_h),
|
||||||
|
m(1),
|
||||||
|
m(2),
|
||||||
|
m(3),
|
||||||
|
score_chip(host.score)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
h.push_str("</tbody></table>");
|
||||||
|
}
|
||||||
|
h.push_str("</section>\n");
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ pillar 1
|
||||||
|
h.push_str("<section id=\"pilar1\" class=\"flow\"><h2>Pilar 1 · Beaconing</h2><p>Implantes de comando e controle costumam chamar o servidor em intervalos regulares, mesmo espaçados por horas. O pilar procura periodicidade nos horários de início das conexões de cada tupla (origem, destino, porta) com um periodograma de Rayleigh/Schuster e exige significância e regularidade. Alerta a partir de score 0,40.</p>");
|
||||||
|
if p1.is_empty() {
|
||||||
|
h.push_str("<p class=\"empty\">Nenhum alerta de beaconing neste recorte.</p>");
|
||||||
|
} else {
|
||||||
|
h.push_str("<table><thead><tr><th>Origem</th><th>Destino</th><th class=\"num\">Período</th><th class=\"num\">Obs.</th><th class=\"num\">p-valor</th><th>Score</th></tr></thead><tbody>");
|
||||||
|
for a in &p1 {
|
||||||
|
let (o, d) = ctx.endpoints(a);
|
||||||
|
let period = ev_f64(&a.evidence, "period_detected_seconds").unwrap_or(f64::NAN);
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<tr><td class=\"mono\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{} s</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td>{}</td></tr>",
|
||||||
|
html_escape(&o),
|
||||||
|
html_escape(&d),
|
||||||
|
num(period, 0),
|
||||||
|
ev_f64(&a.evidence, "observations").map(|v| int(v as u64)).unwrap_or_else(|| "—".into()),
|
||||||
|
ev_f64(&a.evidence, "p_value").map(|v| format!("{v:.2e}")).unwrap_or_else(|| "—".into()),
|
||||||
|
score_chip(a.score)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
h.push_str("</tbody></table>");
|
||||||
|
}
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<p class=\"muted\">Tuplas excluídas antes do cálculo: {} fora de TCP/UDP, {} multicast ou broadcast, {} em portas de infraestrutura (DNS, NTP, DHCP, NetBIOS, SSDP, mDNS, LLMNR).</p></section>",
|
||||||
|
report.p1_excluded.non_tcp_udp,
|
||||||
|
report.p1_excluded.multicast_broadcast,
|
||||||
|
report.p1_excluded.infra_port
|
||||||
|
);
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ pillar 2
|
||||||
|
h.push_str("<section id=\"pilar2\" class=\"flow\"><h2>Pilar 2 · Sessões persistentes</h2><p>Conexões TCP que ficam abertas por horas são típicas de shells reversos e túneis. O Zeek divide sessões longas por timeout de inatividade; o pilar reencadeia as partes (intervalo de até 3600 s sem novo SYN) e pontua a duração em escala logarítmica, registrando PCR e tentativas falhas. Alerta a partir de score 0,2181.</p>");
|
||||||
|
if p2.is_empty() {
|
||||||
|
h.push_str("<p class=\"empty\">Nenhuma sessão persistente acima do limiar.</p>");
|
||||||
|
} else {
|
||||||
|
h.push_str("<table><thead><tr><th>Origem</th><th>Destino</th><th class=\"num\">Duração</th><th class=\"num\">Partes</th><th class=\"num\">PCR</th><th class=\"num\">Bytes/h</th><th>Score</th></tr></thead><tbody>");
|
||||||
|
for a in &p2 {
|
||||||
|
let (o, d) = ctx.endpoints(a);
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<tr><td class=\"mono\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{} h</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td>{}</td></tr>",
|
||||||
|
html_escape(&o),
|
||||||
|
html_escape(&d),
|
||||||
|
num(ev_f64(&a.evidence, "longest_session_seconds").unwrap_or(f64::NAN) / 3600.0, 1),
|
||||||
|
ev_f64(&a.evidence, "parts").map(|v| int(v as u64)).unwrap_or_else(|| "—".into()),
|
||||||
|
num(ev_f64(&a.evidence, "pcr").unwrap_or(f64::NAN), 2),
|
||||||
|
ev_f64(&a.evidence, "bytes_per_hour").map(|v| int(v.max(0.0) as u64)).unwrap_or_else(|| "—".into()),
|
||||||
|
score_chip(a.score)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
h.push_str("</tbody></table>");
|
||||||
|
}
|
||||||
|
h.push_str("</section>\n");
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ pillar 3
|
||||||
|
h.push_str("<section id=\"pilar3\" class=\"flow\"><h2>Pilar 3 · Túneis DNS e anomalias de protocolo</h2><p>Túneis DNS escondem dados nos subdomínios das consultas. O pilar mede, por host e domínio base, a capacidade de informação por hora UTC: entropia de Shannon multiplicada pelos caracteres de subdomínios únicos. A divergência JSD aparece só como contexto (peso 0) e nunca altera o score. Alerta a partir de score 0,40.</p>");
|
||||||
|
if p3.is_empty() {
|
||||||
|
h.push_str("<p class=\"empty\">Nenhuma anomalia DNS acima do limiar.</p>");
|
||||||
|
} else {
|
||||||
|
h.push_str("<table><thead><tr><th>Origem</th><th>Domínio base</th><th class=\"num\">Subd. únicos</th><th class=\"num\">Bits</th><th class=\"num\">Entropia</th><th class=\"num\">NXDOMAIN</th><th>Score</th></tr></thead><tbody>");
|
||||||
|
for a in &p3 {
|
||||||
|
let (o, d) = ctx.endpoints(a);
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<tr><td class=\"mono\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}</td><td class=\"num\">{}%</td><td>{}</td></tr>",
|
||||||
|
html_escape(&o),
|
||||||
|
html_escape(&d),
|
||||||
|
ev_f64(&a.evidence, "unique_subdomains").map(|v| int(v as u64)).unwrap_or_else(|| "—".into()),
|
||||||
|
ev_f64(&a.evidence, "information_bits").map(|v| int(v.max(0.0) as u64)).unwrap_or_else(|| "—".into()),
|
||||||
|
num(ev_f64(&a.evidence, "entropy_bits_per_char").unwrap_or(f64::NAN), 2),
|
||||||
|
num(ev_f64(&a.evidence, "nxdomain_ratio").unwrap_or(f64::NAN) * 100.0, 1),
|
||||||
|
score_chip(a.score)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
h.push_str("</tbody></table>");
|
||||||
|
}
|
||||||
|
h.push_str("</section>\n");
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ pillar 4
|
||||||
|
h.push_str("<section id=\"pilar4\" class=\"flow\"><h2>Pilar 4 · Fusão de evidências</h2><p>Cada host recebe um score único pela combinação noisy-OR ponderada das evidências dos três pilares: S = 1 − ∏(1 − wᵢ·mᵢ), com w₁ = w₂ = w₃ = 0,75. Evidências independentes reforçam umas às outras, mas nenhum pilar sozinho chega a 1.</p>");
|
||||||
|
if hosts.is_empty() {
|
||||||
|
h.push_str("<p class=\"empty\">Sem hosts para fundir.</p>");
|
||||||
|
} else {
|
||||||
|
if let Some(top) = hosts.first() {
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<p class=\"muted\">Método {} · fórmula {}.</p>",
|
||||||
|
html_escape(top.method),
|
||||||
|
html_escape(top.formula_version)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
h.push_str("<table><thead><tr><th>Host</th><th>Termos (pilar: w·m)</th><th class=\"num\">∏(1 − w·m)</th><th>Score</th></tr></thead><tbody>");
|
||||||
|
for host in &hosts {
|
||||||
|
let terms = host
|
||||||
|
.terms
|
||||||
|
.iter()
|
||||||
|
.map(|t| format!("P{}: {}", t.pillar, num(t.weighted, 3)))
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(" · ");
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<tr><td class=\"mono\">{}</td><td class=\"mono\">{}</td><td class=\"num\">{}</td><td>{}</td></tr>",
|
||||||
|
html_escape(&host.orig_h),
|
||||||
|
html_escape(&terms),
|
||||||
|
num(host.product, 4),
|
||||||
|
score_chip(host.score)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
h.push_str("</tbody></table>");
|
||||||
|
}
|
||||||
|
h.push_str("</section>\n");
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ alerts
|
||||||
|
h.push_str("<section id=\"alertas\"><h2>Alertas e evidências</h2><p>Cada alerta traz o resumo gerado pelo motor e a evidência JSON achatada em pares chave e valor, na ordem em que o motor a registrou.</p>");
|
||||||
|
if report.alerts.is_empty() {
|
||||||
|
h.push_str("<p class=\"empty\">Nenhum alerta.</p>");
|
||||||
|
}
|
||||||
|
let mut ordered: Vec<&Alert> = report.alerts.iter().collect();
|
||||||
|
ordered.sort_by(|a, b| b.score.total_cmp(&a.score).then(a.id.cmp(&b.id)));
|
||||||
|
for a in ordered {
|
||||||
|
let mut pairs = Vec::new();
|
||||||
|
flatten_evidence(&a.evidence, "", &mut pairs);
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<article class=\"card\"><header><span><span class=\"pill\">Pilar {} · {}</span></span><span>{} <span class=\"id\">{}</span></span></header><p class=\"sum\">{}</p><dl class=\"ev\">",
|
||||||
|
a.pillar,
|
||||||
|
pillar_name(a.pillar),
|
||||||
|
score_chip(a.score),
|
||||||
|
html_escape(&a.id),
|
||||||
|
html_escape(&a.summary)
|
||||||
|
);
|
||||||
|
for (k, v) in &pairs {
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<div><dt>{}</dt><dd>{}</dd></div>",
|
||||||
|
html_escape(k),
|
||||||
|
html_escape(v)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
h.push_str("</dl></article>");
|
||||||
|
}
|
||||||
|
h.push_str("</section>\n");
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ methodology
|
||||||
|
h.push_str(concat!(
|
||||||
|
"<section id=\"metodologia\"><h2>Metodologia e glossário</h2>",
|
||||||
|
"<p>O Acauã é determinístico: mesma entrada, mesmos scores. Não há modelo opaco; cada pilar é uma fórmula versionada, validada com fixtures sintéticas e capturas públicas, e todo alerta carrega a evidência que o justifica.</p>",
|
||||||
|
"<dl class=\"gloss\">",
|
||||||
|
"<dt>Pilar 1 · Beaconing (v1.2)</dt><dd>Periodicidade sobre os horários de início das conexões com periodograma de Rayleigh/Schuster limitado ao intervalo observado, portão de significância por regularidade (MADM e assimetria de Bowley) e exclusão de portas de infraestrutura. Exige ao menos 20 observações.</dd>",
|
||||||
|
"<dt>Pilar 2 · Sessões persistentes (v1.0)</dt><dd>Conexões TCP longas reencadeadas através dos timeouts de inatividade do Zeek, score logarítmico de persistência, PCR e contagem de tentativas falhas.</dd>",
|
||||||
|
"<dt>Pilar 3 · Anomalias de protocolo (v1.0)</dt><dd>Capacidade de informação em subdomínios DNS únicos por hora UTC (entropia × caracteres), com taxa de NXDOMAIN e distribuição de tipos de consulta como contexto.</dd>",
|
||||||
|
"<dt>Pilar 4 · Fusão de evidências (v1.0)</dt><dd>Noisy-OR ponderado por host, com pesos iguais de 0,75 e evidência determinística em JSON para auditoria do ranking.</dd>",
|
||||||
|
"<dt>Beaconing</dt><dd>Chamadas periódicas de um implante ao servidor de comando e controle.</dd>",
|
||||||
|
"<dt>PCR</dt><dd>Producer/consumer ratio: (bytes enviados − recebidos) / total. Perto de +1 indica envio de dados; perto de −1, download.</dd>",
|
||||||
|
"<dt>NXDOMAIN</dt><dd>Resposta DNS de domínio inexistente; taxas altas acompanham geração algorítmica de nomes.</dd>",
|
||||||
|
"<dt>JSD</dt><dd>Divergência de Jensen-Shannon entre a distribuição de caracteres do grupo e a referência; informativa, peso 0.</dd>",
|
||||||
|
"<dt>Noisy-OR</dt><dd>Combinação probabilística em que cada evidência independente reduz a chance de o host ser benigno.</dd>",
|
||||||
|
"<dt>TLP</dt><dd>Traffic Light Protocol: indica com quem o relatório pode ser compartilhado. TLP:AMBER limita o uso à organização e a quem precisa saber.</dd>",
|
||||||
|
"<dt>Faixas de score</dt><dd>Crítico ≥ 0,85 · Alto ≥ 0,65 · Médio ≥ 0,40 · Baixo abaixo disso.</dd>",
|
||||||
|
"</dl></section>\n"
|
||||||
|
));
|
||||||
|
|
||||||
|
// ------------------------------------------------------------ scope
|
||||||
|
h.push_str("<section id=\"escopo\" class=\"flow\"><h2>Escopo da análise</h2><table><tbody>");
|
||||||
|
let rows = [
|
||||||
|
("Diretório analisado", html_escape(&report.directory)),
|
||||||
|
("Arquivos de log lidos", report.logs_seen.to_string()),
|
||||||
|
("Arquivos dns.log", report.dns_logs_seen.to_string()),
|
||||||
|
("Registros ingeridos", int(report.records)),
|
||||||
|
("Alertas", report.alerts.len().to_string()),
|
||||||
|
("Hosts com score", report.hosts.len().to_string()),
|
||||||
|
(
|
||||||
|
"Versão do esquema de evidência",
|
||||||
|
report.evidence_schema_version.to_string(),
|
||||||
|
),
|
||||||
|
("Estado do motor", html_escape(report.status)),
|
||||||
|
("Emissão", html_escape(&issued)),
|
||||||
|
("Classificação", format!("TLP:{tlp_html}")),
|
||||||
|
];
|
||||||
|
for (k, v) in rows {
|
||||||
|
let _ = write!(h, "<tr><th>{k}</th><td class=\"mono\">{v}</td></tr>");
|
||||||
|
}
|
||||||
|
h.push_str("</tbody></table><div class=\"callout\"><strong>Limites</strong>O resultado reflete apenas os logs entregues ao Acauã e a janela de sete dias usada pelos pilares 1 e 2. Movimentação lateral e sessões UDP ainda não são avaliadas. Use este relatório como priorização para investigação humana, não como veredito.</div></section>\n");
|
||||||
|
|
||||||
|
let _ = write!(
|
||||||
|
h,
|
||||||
|
"<script src=\"{PAGED_JS_PATH}\"></script>\n</body>\n</html>"
|
||||||
|
);
|
||||||
|
h
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::pillar4::{FusionTerm, FusionWeights};
|
||||||
|
use crate::zeek::P1ExcludedCounts;
|
||||||
|
|
||||||
|
fn sample() -> AnalysisReport {
|
||||||
|
let evil = "<script>alert(1)</script>";
|
||||||
|
AnalysisReport {
|
||||||
|
directory: "/logs/\"x\"<b>".into(),
|
||||||
|
logs_seen: 2,
|
||||||
|
dns_logs_seen: 1,
|
||||||
|
records: 12345,
|
||||||
|
alerts: vec![
|
||||||
|
Alert {
|
||||||
|
id: "aaaa".into(),
|
||||||
|
pillar: 1,
|
||||||
|
score: 0.91,
|
||||||
|
summary: format!("Beaconing detected: {evil}:any -> 198.51.100.1:443 (period ~3600s, score 0.910)"),
|
||||||
|
evidence: serde_json::json!({"period_detected_seconds": 3600.0, "observations": 42, "p_value": 1e-9}),
|
||||||
|
created_at: "now".into(),
|
||||||
|
},
|
||||||
|
Alert {
|
||||||
|
id: "bbbb".into(),
|
||||||
|
pillar: 3,
|
||||||
|
score: 0.7,
|
||||||
|
summary: "DNS".into(),
|
||||||
|
evidence: serde_json::json!({"orig_h": "10.0.0.9", "base_domain": "<img src=x onerror=alert(2)>.evil", "unique_subdomains": 200}),
|
||||||
|
created_at: "now".into(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
hosts: vec![HostScore {
|
||||||
|
orig_h: evil.into(),
|
||||||
|
score: 0.68,
|
||||||
|
terms: vec![FusionTerm {
|
||||||
|
pillar: 1,
|
||||||
|
alert_id: Some("aaaa".into()),
|
||||||
|
m: 0.91,
|
||||||
|
w: 0.75,
|
||||||
|
weighted: 0.6825,
|
||||||
|
complement: 0.3175,
|
||||||
|
}],
|
||||||
|
product: 0.3175,
|
||||||
|
method: "noisy_or",
|
||||||
|
weights: FusionWeights {
|
||||||
|
p1: 0.75,
|
||||||
|
p2: 0.75,
|
||||||
|
p3: 0.75,
|
||||||
|
},
|
||||||
|
order: [1, 2, 3],
|
||||||
|
formula_version: "1.0",
|
||||||
|
}],
|
||||||
|
evidence_schema_version: 1,
|
||||||
|
status: "ok",
|
||||||
|
p1_excluded: P1ExcludedCounts::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn contains_title_tlp_logo_and_paged_js() {
|
||||||
|
let html = render_html(&sample());
|
||||||
|
assert!(html.contains("<title>Acauã · Relatório executivo</title>"));
|
||||||
|
assert!(html.contains("TLP:AMBER"));
|
||||||
|
assert!(html.contains("src=\"data:image/png;base64,iVBOR"));
|
||||||
|
assert!(html.contains("data:image/svg+xml;base64,"));
|
||||||
|
assert!(html.contains(PAGED_JS_PATH));
|
||||||
|
for id in [
|
||||||
|
"resumo",
|
||||||
|
"hosts",
|
||||||
|
"pilar1",
|
||||||
|
"pilar2",
|
||||||
|
"pilar3",
|
||||||
|
"pilar4",
|
||||||
|
"alertas",
|
||||||
|
"metodologia",
|
||||||
|
"escopo",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
html.contains(&format!("id=\"{id}\"")),
|
||||||
|
"missing section {id}"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
html.contains(&format!("href=\"#{id}\"")),
|
||||||
|
"missing toc entry {id}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn escapes_attacker_controlled_strings() {
|
||||||
|
let html = render_html(&sample());
|
||||||
|
assert!(!html.contains("<script>alert(1)"));
|
||||||
|
assert!(!html.contains("<img src=x"));
|
||||||
|
assert!(!html.contains("\"x\"<b>"));
|
||||||
|
assert!(html.contains("<script>alert(1)</script>"));
|
||||||
|
assert!(html.contains("<img src=x onerror=alert(2)>.evil"));
|
||||||
|
assert!(html.contains("/logs/"x"<b>"));
|
||||||
|
// Only the Paged.js loader is a real script element.
|
||||||
|
assert_eq!(html.matches("<script").count(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tlp_is_normalized() {
|
||||||
|
assert_eq!(normalize_tlp("tlp:red"), "RED");
|
||||||
|
assert_eq!(normalize_tlp("amber+strict"), "AMBER+STRICT");
|
||||||
|
assert_eq!(normalize_tlp("\";}body{"), "AMBER");
|
||||||
|
let html = render_html_with(
|
||||||
|
&sample(),
|
||||||
|
&ReportOptions {
|
||||||
|
tlp: "green".into(),
|
||||||
|
issued_at: Some("01/01/2026 00:00 UTC".into()),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert!(html.contains("TLP:GREEN"));
|
||||||
|
assert!(html.contains("01/01/2026 00:00 UTC"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn empty_report_renders() {
|
||||||
|
let mut report = sample();
|
||||||
|
report.alerts.clear();
|
||||||
|
report.hosts.clear();
|
||||||
|
let html = render_html(&report);
|
||||||
|
assert!(html.contains("Nenhum alerta atingiu os limiares"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn base64_matches_known_vectors() {
|
||||||
|
assert_eq!(base64(b""), "");
|
||||||
|
assert_eq!(base64(b"f"), "Zg==");
|
||||||
|
assert_eq!(base64(b"fo"), "Zm8=");
|
||||||
|
assert_eq!(base64(b"foo"), "Zm9v");
|
||||||
|
assert_eq!(base64(b"foobar"), "Zm9vYmFy");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn numbers_use_portuguese_format() {
|
||||||
|
assert_eq!(int(1234567), "1.234.567");
|
||||||
|
assert_eq!(num(0.5, 2), "0,50");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,6 +27,15 @@ services:
|
|||||||
acaua:
|
acaua:
|
||||||
image: ${ACAUA_IMAGE:-git.lucasrguerra.dev.br/ciberfauna/acaua}:${ACAUA_VERSION:-latest}
|
image: ${ACAUA_IMAGE:-git.lucasrguerra.dev.br/ciberfauna/acaua}:${ACAUA_VERSION:-latest}
|
||||||
build: .
|
build: .
|
||||||
|
environment:
|
||||||
|
ACAUA_TRANSPORT: ${ACAUA_TRANSPORT:-local}
|
||||||
|
# Informs the daemon where the port is published; `local` refuses a
|
||||||
|
# non-loopback address.
|
||||||
|
ACAUA_PUBLISHED: ${ACAUA_PUBLISH:-127.0.0.1:8787}
|
||||||
|
ACAUA_SECRET_KEY_FILE: ${ACAUA_SECRET_KEY_FILE:-}
|
||||||
|
ACAUA_TLS_CERT: ${ACAUA_TLS_CERT:-}
|
||||||
|
ACAUA_TLS_KEY: ${ACAUA_TLS_KEY:-}
|
||||||
|
ACAUA_TRUSTED_PROXIES: ${ACAUA_TRUSTED_PROXIES:-}
|
||||||
ports:
|
ports:
|
||||||
- "${ACAUA_PUBLISH:-127.0.0.1:8787}:8787"
|
- "${ACAUA_PUBLISH:-127.0.0.1:8787}:8787"
|
||||||
volumes:
|
volumes:
|
||||||
|
|||||||
+14
-5
@@ -186,16 +186,25 @@ The HTTP API is served by `acaua serve`:
|
|||||||
|
|
||||||
| Method | Path | Meaning |
|
| Method | Path | Meaning |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| GET | `/api/health` | Liveness and version |
|
| GET | `/api/health` | Liveness (no version) |
|
||||||
| GET | `/api/status` | Uptime, data directory, dataset summary |
|
| GET | `/api/status` | Version, mode and dataset summary |
|
||||||
| GET | `/api/alerts` | Paginated alerts with evidence |
|
| GET | `/api/alerts` | Alerts of the latest analysis, held in memory, with evidence |
|
||||||
|
| GET | `/api/auth/state` | Whether setup is needed; the caller's name, role, MFA state and CSRF token |
|
||||||
|
| POST | `/api/auth/bootstrap`, `/api/auth/login`, `/api/auth/mfa`, `/api/auth/password-change-required` | First administrator and login steps (public) |
|
||||||
|
| POST | `/api/auth/logout`, `/api/auth/reauth`, `/api/auth/password`, `/api/auth/mfa/disable` | Session actions |
|
||||||
|
| POST | `/api/auth/enroll/start`, `/api/auth/enroll/confirm` | MFA enrollment |
|
||||||
|
| GET, DELETE | `/api/auth/sessions` | List and revoke sessions |
|
||||||
|
| GET, POST, DELETE | `/api/auth/tokens` | List, create and revoke API tokens |
|
||||||
|
| GET, POST, PATCH, DELETE | `/api/admin/users` | User management (administrators; changes need recent reauthentication) |
|
||||||
|
| GET | `/api/admin/audit` | Audit log (administrators) |
|
||||||
| POST | `/api/analyze` | Ingest and analyze a dataset directory |
|
| POST | `/api/analyze` | Ingest and analyze a dataset directory |
|
||||||
| GET | `/api/update` | Check for newer releases |
|
| GET | `/api/update` | Check for newer releases |
|
||||||
| GET | `/logo.png` | Embedded brand asset |
|
| GET | `/logo.png` | Embedded brand asset |
|
||||||
| GET | `/*` | Embedded UI fallback (`rust-embed`) |
|
| GET | `/*` | Embedded UI fallback (`rust-embed`) |
|
||||||
|
|
||||||
`serve` binds to `127.0.0.1:8787` by default. Exposing it on an external network
|
`serve` binds to `127.0.0.1:8787` by default. Only `GET /api/health`, `GET /api/auth/state`, `POST /api/auth/{bootstrap,login,mfa,password-change-required}` and the login assets (`/login.html`, `/login.js`, `/app.css`, `/logo.png`, `/i18n.js`, `/i18n-en.js`) work without a session or token; `/api/analyze` is admin-only.
|
||||||
requires an authenticating reverse proxy.
|
Beyond loopback use the `tls` or `proxy` transport
|
||||||
|
([docker.md](docker.md#authentication-and-transport)).
|
||||||
|
|
||||||
## Storage
|
## Storage
|
||||||
|
|
||||||
|
|||||||
+30
-3
@@ -13,6 +13,7 @@ Commands:
|
|||||||
analyze Analyze a Zeek log directory
|
analyze Analyze a Zeek log directory
|
||||||
doctor Check the local environment
|
doctor Check the local environment
|
||||||
update Check for available releases
|
update Check for available releases
|
||||||
|
auth Local account recovery (`auth reset`)
|
||||||
```
|
```
|
||||||
|
|
||||||
## `acaua serve`
|
## `acaua serve`
|
||||||
@@ -28,9 +29,12 @@ acaua serve --bind 127.0.0.1:8787 --data-dir .acaua
|
|||||||
| `--bind` | `127.0.0.1:8787` | Listen address |
|
| `--bind` | `127.0.0.1:8787` | Listen address |
|
||||||
| `--data-dir` | `.acaua` | Store and runtime files |
|
| `--data-dir` | `.acaua` | Store and runtime files |
|
||||||
|
|
||||||
The default bind is loopback-only. Exposing the daemon on a network requires a
|
The default bind is loopback-only. Login is mandatory in every mode (MFA is mandatory for
|
||||||
reverse proxy with authentication. The API is documented in
|
administrators and optional for analysts), but plain HTTP is not encrypted: the daemon refuses to start without
|
||||||
[architecture.md](architecture.md#api).
|
`ACAUA_TRANSPORT` set to `local`, `tls` or `proxy`; `local` refuses a non-loopback
|
||||||
|
`--bind` unless `ACAUA_RUNTIME=container` (see
|
||||||
|
[docker.md](docker.md#authentication-and-transport)). In `tls` mode `--bind`
|
||||||
|
must be an `IP:port`. The API is documented in [architecture.md](architecture.md#api).
|
||||||
|
|
||||||
## `acaua analyze`
|
## `acaua analyze`
|
||||||
|
|
||||||
@@ -68,6 +72,29 @@ Runs environment checks:
|
|||||||
- `duckdb`: confirms dynamic linkage against `libduckdb.so` in runtime.
|
- `duckdb`: confirms dynamic linkage against `libduckdb.so` in runtime.
|
||||||
- `research`: verifies that the research workspace remains isolated.
|
- `research`: verifies that the research workspace remains isolated.
|
||||||
|
|
||||||
|
## `acaua auth reset`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
acaua auth reset --username admin --data-dir .acaua
|
||||||
|
docker compose exec acaua acaua auth reset --username admin --data-dir /data/acaua
|
||||||
|
```
|
||||||
|
|
||||||
|
Local recovery for any account, administrator or analyst, that lost the password
|
||||||
|
or the authenticator. It removes the user's MFA, recovery codes, sessions and all
|
||||||
|
API tokens (read tokens included), clears the per-user count of MFA and session
|
||||||
|
password failures, writes an audit entry and prints a **temporary password once**.
|
||||||
|
The next login with it requires choosing a new password before any ordinary session;
|
||||||
|
an administrator enrolls MFA again first. It also clears the account's known
|
||||||
|
addresses and its login failure budget and per-address counts, which is the way in
|
||||||
|
for an owner locked out on an unknown address; a running daemon applies this at the
|
||||||
|
next login. An attacker still running can spend the budget again. The per-address
|
||||||
|
overall limit stays in the daemon's memory: wait for it, use another address, or
|
||||||
|
restart the daemon.
|
||||||
|
The command edits the data directory only: it never starts the daemon and does
|
||||||
|
not need `ACAUA_TRANSPORT`. A running daemon sees the change on its next request.
|
||||||
|
If the secret key is an external file, `ACAUA_SECRET_KEY_FILE` must be set for
|
||||||
|
the command too. An unknown user is refused.
|
||||||
|
|
||||||
## `acaua update`
|
## `acaua update`
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+54
-1
@@ -57,6 +57,56 @@ Or run a one-off inspection container:
|
|||||||
docker run --rm -v acaua_acaua-data:/data:ro debian:trixie-slim ls -la /data
|
docker run --rm -v acaua_acaua-data:/data:ro debian:trixie-slim ls -la /data
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Authentication and transport
|
||||||
|
|
||||||
|
Login is mandatory in every mode; MFA is mandatory for administrators and optional
|
||||||
|
for analysts. Without a credential only these work: `GET /api/health`, `GET /api/auth/state`, `POST /api/auth/{bootstrap,login,mfa,password-change-required}` and the login assets (`/login.html`, `/login.js`, `/app.css`, `/logo.png`, `/i18n.js`, `/i18n-en.js`).
|
||||||
|
|
||||||
|
**First setup.** On the first start the daemon prints a one-time setup code
|
||||||
|
(valid for 1 hour) to its log: `docker compose logs acaua`. Open the dashboard,
|
||||||
|
enter the code, create the first administrator, then enroll an authenticator app
|
||||||
|
(TOTP) and store the recovery codes shown once. An expired code needs a daemon
|
||||||
|
restart (`docker compose restart acaua`), which prints a new one.
|
||||||
|
|
||||||
|
**Transport modes.** `ACAUA_TRANSPORT` is required; the image defaults to `local`.
|
||||||
|
|
||||||
|
| Mode | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `local` | Plain HTTP, loopback only. `ACAUA_PUBLISH` must be `127.0.0.1` or `[::1]`; the daemon refuses to start if `ACAUA_PUBLISHED` is anything else. Outside a container it also refuses a non-loopback `--bind`; the image sets `ACAUA_RUNTIME=container`, where `ACAUA_PUBLISHED` is the control. |
|
||||||
|
| `tls` | The daemon terminates HTTPS. Set `ACAUA_TLS_CERT` and `ACAUA_TLS_KEY` and mount the certificate and key in the container with a compose override; `--bind` must be an `IP:port`. |
|
||||||
|
| `proxy` | An HTTPS reverse proxy sits in front. Set `ACAUA_TRUSTED_PROXIES` to its address as CIDRs. The daemon port must be reachable only by the proxy. A wrong value makes every client appear as one address, which removes the failure budget's protection and can share lockouts between users. A too-wide value lets clients forge `X-Forwarded-For` and spend budgets or pose as a known address. |
|
||||||
|
|
||||||
|
**Limits worth knowing.** A bare `docker run -p 0.0.0.0:8787:8787` without
|
||||||
|
`ACAUA_PUBLISHED` is not detected by `local` mode; login still protects the
|
||||||
|
dashboard, but the traffic is plain HTTP. Use compose.
|
||||||
|
|
||||||
|
**Secret key.** The key that seals MFA secrets is created in the data volume by
|
||||||
|
default. Anyone who copies the volume copies the key with it, so prefer a Docker
|
||||||
|
secret and point `ACAUA_SECRET_KEY_FILE` to it (for example
|
||||||
|
`/run/secrets/acaua_key`, 32 random bytes encoded as base64).
|
||||||
|
|
||||||
|
**Tokens.** Users create API tokens with `read` or `admin` scope. Changing a
|
||||||
|
password or disabling MFA revokes that user's admin tokens and keeps read tokens.
|
||||||
|
`/api/analyze` is admin-only.
|
||||||
|
|
||||||
|
**Failed logins.** Wrong passwords delay that username from that address (an IPv6
|
||||||
|
/48 counts as one address). Each username also has a budget of 100 failures in
|
||||||
|
any 24 hours (a true rolling window) from unknown addresses: once spent, those addresses are refused,
|
||||||
|
even with the right password. An address with a completed login in the last 30 days
|
||||||
|
skips the budget (a credential change from a session keeps only its own address), so an attacker can delay a real user's login from a *new* address
|
||||||
|
for up to the budget window, and longer if they keep going, but not from a known
|
||||||
|
address, and not an open session. If you are locked out on a new address, log in
|
||||||
|
from a known one or run the reset below. Crossing the budget writes
|
||||||
|
`login.budget_exhausted` to the audit log (Admin screen), once per real account per 24
|
||||||
|
hours. The audit log has no rotation yet. MFA remains recommended for analysts. A
|
||||||
|
restart clears the per-address counts, not the budgets.
|
||||||
|
|
||||||
|
**Recovery.** `docker compose exec acaua acaua auth reset --username <name> --data-dir /data/acaua`
|
||||||
|
(see [cli.md](cli.md#acaua-auth-reset)) works for any account: it prints a temporary
|
||||||
|
password and forces a password change; administrators also enroll MFA again.
|
||||||
|
Anyone with Docker access on the host can run it, so Docker access is
|
||||||
|
administrator access to Acauã.
|
||||||
|
|
||||||
## Updating
|
## Updating
|
||||||
|
|
||||||
Because Acauã runs as a multi-user collective SOC daemon, updates are performed
|
Because Acauã runs as a multi-user collective SOC daemon, updates are performed
|
||||||
@@ -74,6 +124,9 @@ ensuring Parquet writes and DuckDB transactions are committed properly.
|
|||||||
- The `zeek` service requires packet capture privileges (`NET_RAW`, `NET_ADMIN`).
|
- The `zeek` service requires packet capture privileges (`NET_RAW`, `NET_ADMIN`).
|
||||||
Run it only on interfaces and networks you are explicitly authorized to monitor.
|
Run it only on interfaces and networks you are explicitly authorized to monitor.
|
||||||
- The default dashboard binding is loopback-only (`ACAUA_PUBLISH=127.0.0.1:8787`).
|
- The default dashboard binding is loopback-only (`ACAUA_PUBLISH=127.0.0.1:8787`).
|
||||||
Do not expose the service on external interfaces without an authenticating reverse proxy.
|
Login is always required (MFA is mandatory for administrators, optional for
|
||||||
|
analysts), but only `tls` and `proxy` encrypt the
|
||||||
|
traffic: publish beyond loopback only with one of them
|
||||||
|
([details](#authentication-and-transport)).
|
||||||
- The image contains no telemetry. Outbound traffic is restricted to operator-initiated
|
- The image contains no telemetry. Outbound traffic is restricted to operator-initiated
|
||||||
update checks against the Gitea Releases API.
|
update checks against the Gitea Releases API.
|
||||||
@@ -38,3 +38,18 @@ The interface communicates with `/api/health` and displays:
|
|||||||
|
|
||||||
Posting a directory path to `/api/analyze` triggers the Zeek ingestion and
|
Posting a directory path to `/api/analyze` triggers the Zeek ingestion and
|
||||||
analytical detection pipeline.
|
analytical detection pipeline.
|
||||||
|
|
||||||
|
## Executive report
|
||||||
|
|
||||||
|
After an analysis, the **Relatório** button (Report, in English) opens
|
||||||
|
`GET /relatorio` in a new tab: an A4 executive report of the latest analysis,
|
||||||
|
paginated in the browser by the vendored Paged.js (`apps/gui/ui/vendor/`), so it
|
||||||
|
works offline and prints to PDF with the browser's print dialog. It has a cover
|
||||||
|
with the embedded logo and a motif drawn from the top hosts, a table of
|
||||||
|
contents, executive summary with KPIs, the host ranking, one section per pillar
|
||||||
|
(beaconing, persistent sessions, DNS tunnels, evidence fusion), every alert with
|
||||||
|
its JSON evidence flattened, methodology and glossary, and the analysis scope.
|
||||||
|
The report is classified `TLP:AMBER` by default; `/relatorio?tlp=GREEN` (or
|
||||||
|
`CLEAR`, `AMBER+STRICT`, `RED`) changes the label, and unknown values fall back
|
||||||
|
to AMBER. Every string read from the logs (hosts, domains, summaries) is
|
||||||
|
HTML-escaped. Without a previous analysis the route answers 404.
|
||||||
@@ -187,16 +187,25 @@ A API HTTP é servida por `acaua serve`:
|
|||||||
|
|
||||||
| Método | Caminho | Significado |
|
| Método | Caminho | Significado |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| GET | `/api/health` | Liveness e versão |
|
| GET | `/api/health` | Liveness (sem versão) |
|
||||||
| GET | `/api/status` | Uptime, diretório de dados, sumário do dataset |
|
| GET | `/api/status` | Versão, modo e sumário do dataset |
|
||||||
| GET | `/api/alerts` | Alertas paginados com evidência |
|
| GET | `/api/alerts` | Alertas da análise mais recente, mantidos em memória, com evidência |
|
||||||
|
| GET | `/api/auth/state` | Se falta a configuração inicial; nome, papel, estado do MFA e token CSRF de quem chama |
|
||||||
|
| POST | `/api/auth/bootstrap`, `/api/auth/login`, `/api/auth/mfa`, `/api/auth/password-change-required` | Primeiro administrador e etapas do login (públicas) |
|
||||||
|
| POST | `/api/auth/logout`, `/api/auth/reauth`, `/api/auth/password`, `/api/auth/mfa/disable` | Ações da sessão |
|
||||||
|
| POST | `/api/auth/enroll/start`, `/api/auth/enroll/confirm` | Cadastro de MFA |
|
||||||
|
| GET, DELETE | `/api/auth/sessions` | Listar e revogar sessões |
|
||||||
|
| GET, POST, DELETE | `/api/auth/tokens` | Listar, criar e revogar tokens de API |
|
||||||
|
| GET, POST, PATCH, DELETE | `/api/admin/users` | Gestão de usuários (administradores; alterações exigem reautenticação recente) |
|
||||||
|
| GET | `/api/admin/audit` | Log de auditoria (administradores) |
|
||||||
| POST | `/api/analyze` | Ingestão e análise de diretório de dataset |
|
| POST | `/api/analyze` | Ingestão e análise de diretório de dataset |
|
||||||
| GET | `/api/update` | Checagem de novas releases |
|
| GET | `/api/update` | Checagem de novas releases |
|
||||||
| GET | `/logo.png` | Asset de marca embutido |
|
| GET | `/logo.png` | Asset de marca embutido |
|
||||||
| GET | `/*` | Fallback de UI embutida (`rust-embed`) |
|
| GET | `/*` | Fallback de UI embutida (`rust-embed`) |
|
||||||
|
|
||||||
`serve` escuta em `127.0.0.1:8787` por padrão. Expô-lo em uma rede externa exige
|
`serve` escuta em `127.0.0.1:8787` por padrão. Só `GET /api/health`, `GET /api/auth/state`, `POST /api/auth/{bootstrap,login,mfa,password-change-required}` e os arquivos da tela de login (`/login.html`, `/login.js`, `/app.css`, `/logo.png`, `/i18n.js`, `/i18n-en.js`) funcionam sem sessão ou token; `/api/analyze` é exclusivo de
|
||||||
um proxy reverso com autenticação.
|
administrador. Além do loopback use o transporte `tls` ou `proxy`
|
||||||
|
([docker.md](docker.md#autenticação-e-transporte)).
|
||||||
|
|
||||||
## Armazenamento
|
## Armazenamento
|
||||||
|
|
||||||
|
|||||||
+30
-3
@@ -13,6 +13,7 @@ Comandos:
|
|||||||
analyze Analisa um diretório de logs do Zeek
|
analyze Analisa um diretório de logs do Zeek
|
||||||
doctor Verifica o ambiente local
|
doctor Verifica o ambiente local
|
||||||
update Checa por releases disponíveis
|
update Checa por releases disponíveis
|
||||||
|
auth Recuperação local de contas (`auth reset`)
|
||||||
```
|
```
|
||||||
|
|
||||||
## `acaua serve`
|
## `acaua serve`
|
||||||
@@ -28,9 +29,12 @@ acaua serve --bind 127.0.0.1:8787 --data-dir .acaua
|
|||||||
| `--bind` | `127.0.0.1:8787` | Endereço de escuta |
|
| `--bind` | `127.0.0.1:8787` | Endereço de escuta |
|
||||||
| `--data-dir` | `.acaua` | Diretório de dados e arquivos de execução |
|
| `--data-dir` | `.acaua` | Diretório de dados e arquivos de execução |
|
||||||
|
|
||||||
O bind padrão restringe-se a loopback. Expô-lo em uma rede exige um proxy
|
O bind padrão restringe-se a loopback. O login é obrigatório em todos os modos (o MFA é
|
||||||
reverso com autenticação. A API está documentada em
|
obrigatório para administradores e opcional para analistas), mas HTTP puro não é criptografado: o daemon recusa iniciar sem
|
||||||
[arquitetura.md](arquitetura.md#api).
|
`ACAUA_TRANSPORT` definido como `local`, `tls` ou `proxy`; `local` recusa um `--bind`
|
||||||
|
que não seja loopback, salvo com `ACAUA_RUNTIME=container` (veja
|
||||||
|
[docker.md](docker.md#autenticação-e-transporte)). No modo `tls`, `--bind` deve
|
||||||
|
ser `IP:porta`. A API está documentada em [arquitetura.md](arquitetura.md#api).
|
||||||
|
|
||||||
## `acaua analyze`
|
## `acaua analyze`
|
||||||
|
|
||||||
@@ -68,6 +72,29 @@ Executa checagens de ambiente:
|
|||||||
- `duckdb`: confirma linkagem dinâmica contra a `libduckdb.so` em tempo de execução.
|
- `duckdb`: confirma linkagem dinâmica contra a `libduckdb.so` em tempo de execução.
|
||||||
- `research`: valida o isolamento do workspace de pesquisa.
|
- `research`: valida o isolamento do workspace de pesquisa.
|
||||||
|
|
||||||
|
## `acaua auth reset`
|
||||||
|
|
||||||
|
```bash
|
||||||
|
acaua auth reset --username admin --data-dir .acaua
|
||||||
|
docker compose exec acaua acaua auth reset --username admin --data-dir /data/acaua
|
||||||
|
```
|
||||||
|
|
||||||
|
Recuperação local para qualquer conta, administrador ou analista, que perdeu a
|
||||||
|
senha ou o autenticador. Remove o MFA, os códigos de recuperação, as sessões e todos
|
||||||
|
os tokens de API do usuário (inclusive os de leitura), zera a contagem por usuário
|
||||||
|
de falhas de MFA e de senha em sessão, grava uma entrada na auditoria e exibe uma
|
||||||
|
**senha temporária uma única vez**. O próximo login com ela exige escolher uma nova
|
||||||
|
senha antes de qualquer sessão comum; um administrador cadastra o MFA de novo antes.
|
||||||
|
Também apaga os endereços conhecidos da conta e sua cota de falhas de login e
|
||||||
|
contagens por endereço, que é o caminho para um dono bloqueado em um endereço
|
||||||
|
desconhecido; um daemon em execução aplica isso no próximo login. Um atacante ainda
|
||||||
|
ativo pode gastar a cota de novo. O limite geral por endereço fica na memória do
|
||||||
|
daemon: aguarde, use outro endereço ou reinicie o daemon. O comando altera apenas o diretório de dados:
|
||||||
|
nunca inicia o daemon e não precisa de `ACAUA_TRANSPORT`. Um daemon em execução
|
||||||
|
enxerga a mudança na próxima requisição. Se a chave secreta for um arquivo
|
||||||
|
externo, `ACAUA_SECRET_KEY_FILE` também precisa estar definido para o comando.
|
||||||
|
Usuário inexistente é recusado.
|
||||||
|
|
||||||
## `acaua update`
|
## `acaua update`
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+55
-1
@@ -57,6 +57,57 @@ Ou executar um container efêmero de inspeção:
|
|||||||
docker run --rm -v acaua_acaua-data:/data:ro debian:trixie-slim ls -la /data
|
docker run --rm -v acaua_acaua-data:/data:ro debian:trixie-slim ls -la /data
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Autenticação e transporte
|
||||||
|
|
||||||
|
O login é obrigatório em todos os modos; o MFA é obrigatório para administradores
|
||||||
|
e opcional para analistas. Sem credencial só funcionam: `GET /api/health`, `GET /api/auth/state`, `POST /api/auth/{bootstrap,login,mfa,password-change-required}` e os arquivos da tela de login (`/login.html`, `/login.js`, `/app.css`, `/logo.png`, `/i18n.js`, `/i18n-en.js`).
|
||||||
|
|
||||||
|
**Primeira configuração.** Na primeira inicialização o daemon imprime no log um
|
||||||
|
código de configuração de uso único (válido por 1 hora): `docker compose logs acaua`.
|
||||||
|
Abra o dashboard, informe o código, crie o primeiro administrador, cadastre um
|
||||||
|
aplicativo autenticador (TOTP) e guarde os códigos de recuperação, mostrados uma vez.
|
||||||
|
Um código expirado exige reiniciar o daemon (`docker compose restart acaua`), que
|
||||||
|
imprime outro.
|
||||||
|
|
||||||
|
**Modos de transporte.** `ACAUA_TRANSPORT` é obrigatório; a imagem usa `local` por padrão.
|
||||||
|
|
||||||
|
| Modo | Significado |
|
||||||
|
|---|---|
|
||||||
|
| `local` | HTTP puro, só em loopback. `ACAUA_PUBLISH` deve ser `127.0.0.1` ou `[::1]`; o daemon recusa iniciar se `ACAUA_PUBLISHED` for outro. Fora de container também recusa um `--bind` que não seja loopback; a imagem define `ACAUA_RUNTIME=container`, onde o controle é `ACAUA_PUBLISHED`. |
|
||||||
|
| `tls` | O daemon termina o HTTPS. Defina `ACAUA_TLS_CERT` e `ACAUA_TLS_KEY` e monte o certificado e a chave no container por um override do compose; `--bind` deve ser `IP:porta`. |
|
||||||
|
| `proxy` | Um proxy reverso HTTPS fica na frente. Defina `ACAUA_TRUSTED_PROXIES` com o endereço dele em CIDR. A porta do daemon deve ser acessível somente pelo proxy. Um valor errado faz todos os clientes parecerem um só endereço, o que elimina a proteção da cota de falhas e pode compartilhar bloqueios entre usuários. Um valor amplo demais permite que clientes forjem `X-Forwarded-For` e gastem cotas ou se passem por um endereço conhecido. |
|
||||||
|
|
||||||
|
**Limites que vale conhecer.** Um `docker run -p 0.0.0.0:8787:8787` direto, sem
|
||||||
|
`ACAUA_PUBLISHED`, não é detectado pelo modo `local`; o login continua protegendo
|
||||||
|
o dashboard, mas o tráfego é HTTP puro. Use o compose.
|
||||||
|
|
||||||
|
**Chave secreta.** A chave que protege os segredos do MFA é criada por padrão no
|
||||||
|
volume de dados. Quem copia o volume copia a chave junto, então prefira um Docker
|
||||||
|
secret e aponte `ACAUA_SECRET_KEY_FILE` para ele (por exemplo
|
||||||
|
`/run/secrets/acaua_key`, 32 bytes aleatórios em base64).
|
||||||
|
|
||||||
|
**Tokens.** Os usuários criam tokens de API com escopo `read` ou `admin`. Trocar a
|
||||||
|
senha ou desativar o MFA revoga os tokens admin desse usuário e mantém os de leitura.
|
||||||
|
`/api/analyze` é exclusivo de administrador.
|
||||||
|
|
||||||
|
**Logins com falha.** Senhas erradas atrasam aquele usuário naquele endereço (um /48
|
||||||
|
IPv6 conta como um endereço). Cada usuário também tem uma cota de 100 falhas em
|
||||||
|
quaisquer 24 horas (janela móvel real) vindas de endereços desconhecidos: esgotada, esses endereços são
|
||||||
|
recusados, mesmo com a senha certa. Um endereço com login completo nos últimos 30
|
||||||
|
dias não usa a cota (uma troca de credencial feita de uma sessão mantém só o próprio endereço), então um atacante consegue atrasar o login de um usuário real a
|
||||||
|
partir de um endereço *novo* por até a janela da cota, e por mais tempo se continuar,
|
||||||
|
mas não de um endereço conhecido nem uma sessão aberta. Se ficar bloqueado em um
|
||||||
|
endereço novo, entre por um conhecido ou execute a recuperação abaixo. Esgotar a cota
|
||||||
|
grava `login.budget_exhausted` no log de auditoria (tela de administração), uma vez
|
||||||
|
por conta real a cada 24 horas. O log de auditoria ainda não tem rotação. O MFA continua
|
||||||
|
recomendado para analistas. Um reinício apaga as contagens por endereço, não as cotas.
|
||||||
|
|
||||||
|
**Recuperação.** `docker compose exec acaua acaua auth reset --username <nome> --data-dir /data/acaua`
|
||||||
|
(veja [cli.md](cli.md#acaua-auth-reset)) vale para qualquer conta: imprime uma senha
|
||||||
|
temporária e força a troca de senha; administradores também cadastram o MFA de novo.
|
||||||
|
Quem tem acesso ao Docker do host pode executá-lo, portanto acesso ao Docker
|
||||||
|
equivale a ser administrador do Acauã.
|
||||||
|
|
||||||
## Atualização
|
## Atualização
|
||||||
|
|
||||||
Por rodar como um daemon de SOC de uso coletivo, atualizações são realizadas
|
Por rodar como um daemon de SOC de uso coletivo, atualizações são realizadas
|
||||||
@@ -75,6 +126,9 @@ sem corrupção.
|
|||||||
- O serviço `zeek` requer privilégios de captura de pacotes (`NET_RAW`, `NET_ADMIN`).
|
- O serviço `zeek` requer privilégios de captura de pacotes (`NET_RAW`, `NET_ADMIN`).
|
||||||
Execute-o apenas em interfaces e redes que você tem autorização explícita para monitorar.
|
Execute-o apenas em interfaces e redes que você tem autorização explícita para monitorar.
|
||||||
- A publicação padrão do dashboard é restrita a loopback (`ACAUA_PUBLISH=127.0.0.1:8787`).
|
- A publicação padrão do dashboard é restrita a loopback (`ACAUA_PUBLISH=127.0.0.1:8787`).
|
||||||
Não exponha o serviço em interfaces externas sem um proxy reverso com autenticação.
|
O login é sempre exigido (MFA obrigatório para administradores, opcional para
|
||||||
|
analistas), mas só `tls` e `proxy` criptografam o
|
||||||
|
tráfego: publique além do loopback apenas com um deles
|
||||||
|
([detalhes](#autenticação-e-transporte)).
|
||||||
- A imagem não possui telemetria. Tráfego de saída restringe-se a checagens de
|
- A imagem não possui telemetria. Tráfego de saída restringe-se a checagens de
|
||||||
versão iniciadas pelo operador contra a API de Releases do Gitea.
|
versão iniciadas pelo operador contra a API de Releases do Gitea.
|
||||||
@@ -38,3 +38,18 @@ A interface comunica-se com `/api/health` e exibe:
|
|||||||
|
|
||||||
Enviar um caminho de diretório para `/api/analyze` dispara a ingestão do Zeek e o
|
Enviar um caminho de diretório para `/api/analyze` dispara a ingestão do Zeek e o
|
||||||
pipeline analítico de detecção.
|
pipeline analítico de detecção.
|
||||||
|
|
||||||
|
## Relatório executivo
|
||||||
|
|
||||||
|
Depois de uma análise, o botão **Relatório** abre `GET /relatorio` em uma nova
|
||||||
|
aba: um relatório executivo A4 da última análise, paginado no navegador pelo
|
||||||
|
Paged.js empacotado no projeto (`apps/gui/ui/vendor/`), então funciona offline e
|
||||||
|
vira PDF pela janela de impressão do navegador. Ele traz capa com o logo
|
||||||
|
embutido e um motivo desenhado a partir dos hosts do topo, sumário, sumário
|
||||||
|
executivo com indicadores, ranking de hosts, uma seção por pilar (beaconing,
|
||||||
|
sessões persistentes, túneis DNS, fusão de evidências), todos os alertas com a
|
||||||
|
evidência JSON achatada, metodologia e glossário, e o escopo da análise. A
|
||||||
|
classificação padrão é `TLP:AMBER`; `/relatorio?tlp=GREEN` (ou `CLEAR`,
|
||||||
|
`AMBER+STRICT`, `RED`) troca o rótulo, e valores desconhecidos voltam para
|
||||||
|
AMBER. Todo texto lido dos logs (hosts, domínios, resumos) é escapado em HTML.
|
||||||
|
Sem uma análise anterior, a rota responde 404.
|
||||||
@@ -32,6 +32,6 @@ Não inclua detalhes de exploração em uma issue pública. Siga a política em
|
|||||||
| Sintoma | O que verificar |
|
| Sintoma | O que verificar |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Container não sobe | Confirme linkagem de `libduckdb.so` via `docker logs` e verifique permissões nos volumes nomeados |
|
| Container não sobe | Confirme linkagem de `libduckdb.so` via `docker logs` e verifique permissões nos volumes nomeados |
|
||||||
| `serve` inacessível a partir de outro host | O serviço escuta em loopback (`127.0.0.1:8787`) por padrão; verifique o proxy reverso |
|
| `serve` inacessível a partir de outro host | O serviço escuta em loopback (`127.0.0.1:8787`) por padrão; `ACAUA_TRANSPORT` é obrigatório e o modo `local` exige `ACAUA_PUBLISH` em loopback; para acessar de outro host defina `ACAUA_PUBLISH` e use `ACAUA_TRANSPORT=tls` ou `proxy` ([detalhes](docker.md#autenticação-e-transporte)) |
|
||||||
| `update` falha | Verifique conectividade de rede com a API de Releases do Gitea ou permissões de pull do registry |
|
| `update` falha | Verifique conectividade de rede com a API de Releases do Gitea ou permissões de pull do registry |
|
||||||
| UI web exibe português | `Auto` segue o idioma do navegador; escolha inglês nas configurações |
|
| UI web exibe português | `Auto` segue o idioma do navegador; escolha inglês nas configurações |
|
||||||
+1
-1
@@ -32,6 +32,6 @@ Do not include exploit details in a public issue. Follow
|
|||||||
| Symptom | What to check |
|
| Symptom | What to check |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Container fails to start | Confirm `libduckdb.so` linkage via `docker logs` and verify permissions on named volumes |
|
| Container fails to start | Confirm `libduckdb.so` linkage via `docker logs` and verify permissions on named volumes |
|
||||||
| `serve` is unreachable from another host | Service binds to loopback (`127.0.0.1:8787`) by default; verify reverse proxy configuration |
|
| `serve` is unreachable from another host | Service binds to loopback (`127.0.0.1:8787`) by default; `ACAUA_TRANSPORT` is required, and `local` mode needs `ACAUA_PUBLISH` on loopback; to reach it from another host set `ACAUA_PUBLISH` and use `ACAUA_TRANSPORT=tls` or `proxy` ([details](docker.md#authentication-and-transport)) |
|
||||||
| `update` fails | Check network connectivity to Gitea Releases API or verify registry pull permissions |
|
| `update` fails | Check network connectivity to Gitea Releases API or verify registry pull permissions |
|
||||||
| Web UI shows Portuguese | `Auto` follows the browser language; select English in settings |
|
| Web UI shows Portuguese | `Auto` follows the browser language; select English in settings |
|
||||||
@@ -257,7 +257,7 @@ function rustLabels(source, file) {
|
|||||||
const uiFiles = readdirSync(join(root, 'apps/gui/ui'))
|
const uiFiles = readdirSync(join(root, 'apps/gui/ui'))
|
||||||
.filter((f) => f.endsWith('.js') && f !== 'i18n-en.js' && f !== 'vendor')
|
.filter((f) => f.endsWith('.js') && f !== 'i18n-en.js' && f !== 'vendor')
|
||||||
.map((f) => join(root, 'apps/gui/ui', f));
|
.map((f) => join(root, 'apps/gui/ui', f));
|
||||||
uiFiles.push(join(root, 'apps/gui/ui/index.html'));
|
uiFiles.push(join(root, 'apps/gui/ui/index.html'), join(root, 'apps/gui/ui/login.html'));
|
||||||
|
|
||||||
const rustFiles = [
|
const rustFiles = [
|
||||||
'crates/acaua-core/src/error.rs',
|
'crates/acaua-core/src/error.rs',
|
||||||
|
|||||||
+30
-3
@@ -17,12 +17,39 @@ for _ in $(seq 1 30); do
|
|||||||
docker exec "$name" curl -fsS http://127.0.0.1:8787/api/health >/dev/null 2>&1 && break
|
docker exec "$name" curl -fsS http://127.0.0.1:8787/api/health >/dev/null 2>&1 && break
|
||||||
sleep 1
|
sleep 1
|
||||||
done
|
done
|
||||||
docker exec "$name" curl -fsS http://127.0.0.1:8787/api/health | grep -q '"status":"ok"' || fail "/api/health did not answer"
|
# Capture output instead of piping into `grep -q`: grep exits at the first match,
|
||||||
docker exec "$name" curl -fsS http://127.0.0.1:8787/ | grep -qi '<!doctype html' || fail "dashboard is not served"
|
# the writer gets SIGPIPE and `pipefail` turns that into a flaky failure.
|
||||||
docker exec "$name" acaua doctor --json | grep -A1 '"name": "duckdb"' | grep -q '"ok": true' || fail "libduckdb is not usable"
|
out=$(docker exec "$name" curl -fsS http://127.0.0.1:8787/api/health) || fail "/api/health did not answer"
|
||||||
|
grep -q '"status":"ok"' <<<"$out" || fail "/api/health is not ok"
|
||||||
|
# The health endpoint is public and must not reveal the version.
|
||||||
|
if grep -q '"version"' <<<"$out"; then fail "/api/health exposes the version"; fi
|
||||||
|
# Without a login the dashboard and the API must refuse (401) or redirect.
|
||||||
|
for path in / /api/alerts; do
|
||||||
|
code=$(docker exec "$name" curl -sS -o /dev/null -w '%{http_code}' "http://127.0.0.1:8787$path") || fail "$path did not answer"
|
||||||
|
case "$code" in
|
||||||
|
401 | 301 | 302 | 303 | 307 | 308) ;;
|
||||||
|
*) fail "$path answered $code without a login (expected 401 or a redirect)" ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
out=$(docker exec "$name" curl -fsS http://127.0.0.1:8787/login.html) || fail "login page did not answer"
|
||||||
|
grep -qi '<!doctype html' <<<"$out" || fail "login page is not served"
|
||||||
|
logs=$(docker logs "$name" 2>&1)
|
||||||
|
grep -q 'código de configuração' <<<"$logs" || fail "container log has no setup code"
|
||||||
|
out=$(docker exec "$name" acaua doctor --json) || { echo "$out" >&2; fail "acaua doctor --json failed"; }
|
||||||
|
duckdb=$(grep -A1 '"name": "duckdb"' <<<"$out") || true
|
||||||
|
grep -q '"ok": true' <<<"$duckdb" || { echo "$out" >&2; fail "libduckdb is not usable"; }
|
||||||
[ "$(docker inspect -f '{{if .Config.Healthcheck}}yes{{end}}' "$name")" = yes ] || fail "image has no HEALTHCHECK"
|
[ "$(docker inspect -f '{{if .Config.Healthcheck}}yes{{end}}' "$name")" = yes ] || fail "image has no HEALTHCHECK"
|
||||||
[ "$(docker exec "$name" id -u)" != 0 ] || fail "daemon runs as root"
|
[ "$(docker exec "$name" id -u)" != 0 ] || fail "daemon runs as root"
|
||||||
docker stop -t 10 "$name" >/dev/null
|
docker stop -t 10 "$name" >/dev/null
|
||||||
code=$(docker inspect -f '{{.State.ExitCode}}' "$name")
|
code=$(docker inspect -f '{{.State.ExitCode}}' "$name")
|
||||||
[ "$code" = 0 ] || fail "exit code $code after SIGTERM (expected 0: SIGTERM must stop serve)"
|
[ "$code" = 0 ] || fail "exit code $code after SIGTERM (expected 0: SIGTERM must stop serve)"
|
||||||
|
# Mode `local` must refuse a port published beyond loopback.
|
||||||
|
bad="$name-bad"
|
||||||
|
trap 'docker rm -f "$name" "$bad" >/dev/null 2>&1 || true' EXIT
|
||||||
|
docker run -d --name "$bad" -e ACAUA_PUBLISHED=0.0.0.0:8787 "$image" >/dev/null
|
||||||
|
docker wait "$bad" >/dev/null
|
||||||
|
code=$(docker inspect -f '{{.State.ExitCode}}' "$bad")
|
||||||
|
[ "$code" != 0 ] || fail "local mode accepted ACAUA_PUBLISHED=0.0.0.0:8787"
|
||||||
|
logs=$(docker logs "$bad" 2>&1)
|
||||||
|
grep -q 'ACAUA_PUBLISHED' <<<"$logs" || { echo "$logs" >&2; fail "local mode refused for the wrong reason"; }
|
||||||
echo "smoke: $image ok"
|
echo "smoke: $image ok"
|
||||||
Reference in new issue
Block a user