12 Commits
Author SHA1 Message Date
Lucas RayanandClaude Opus 5.5 9a533e2170 chore(release): 1.1.0
CI / Format and clippy (push) Successful in 18s
CI / Check desktop app (Linux) (push) Successful in 1m9s
CI / Tests (Linux) (push) Successful in 25s
CI / Dependency audit (push) Successful in 12s
Release / Create release (push) Successful in 9s
Release / CLI (linux-aarch64) (push) Successful in 1m22s
Release / CLI (linux-x86_64) (push) Successful in 52s
Release / Desktop app (linux-x86_64) (push) Successful in 4m21s
Release / Desktop app (windows) (push) Successful in 3m14s
Release / Desktop app (linux-aarch64) (push) Successful in 8m33s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 21:26:40 -03:00
Lucas RayanandClaude Opus 5.5 1597b2fb63 feat(report): new cover and layout for the audit report
CI / Format and clippy (push) Successful in 19s
CI / Tests (Linux) (push) Canceled after 8s
CI / Dependency audit (push) Canceled after 2s
CI / Check desktop app (Linux) (push) Canceled after 0s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 21:23:57 -03:00
Lucas RayanandClaude Sonnet 5.5 a7505f4ff3 docs: refresh docs and screenshots, drop em dashes, add scripts/screenshots.sh
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 20:44:47 -03:00
Lucas RayanandClaude Sonnet 5.5 1bbb5f934c fix(update): non-blocking desktop update with progress bar (1.0.7)
Release / Desktop app (windows) (push) Successful in 3m27s
Release / Create release (push) Successful in 13s
CI / Tests (Linux) (push) Successful in 29s
CI / Format and clippy (push) Successful in 28s
CI / Dependency audit (push) Successful in 14s
Release / CLI (linux-aarch64) (push) Successful in 53s
Release / CLI (linux-x86_64) (push) Successful in 1m22s
CI / Check desktop app (Linux) (push) Successful in 1m19s
Release / Desktop app (linux-aarch64) (push) Successful in 4m27s
Release / Desktop app (linux-x86_64) (push) Successful in 4m58s
Update commands ran on the UI thread and froze the window; they now run
in the background, with a real download percentage bar.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 19:34:00 -03:00
lucasrguerra fd7435cc68 Merge pull request 'Unguessable sabia ui token (1.0.6)' (#1) from fix/token-ui into main
CI / Format and clippy (push) Successful in 24s
CI / Tests (Linux) (push) Successful in 41s
Release / Create release (push) Successful in 9s
CI / Dependency audit (push) Successful in 19s
CI / Check desktop app (Linux) (push) Successful in 1m44s
Release / CLI (linux-aarch64) (push) Successful in 1m52s
Release / CLI (linux-x86_64) (push) Successful in 1m42s
Release / Desktop app (linux-aarch64) (push) Successful in 10m43s
Release / Desktop app (linux-x86_64) (push) Successful in 12m33s
Release / Desktop app (windows) (push) Successful in 3m51s
2026-11-03 14:50:30 +00:00
Lucas RayanandClaude Opus 5.5 bcc4178e89 fix(ui): generate the sabia ui token from the OS CSPRNG
CI / Format and clippy (pull_request) Successful in 30s
CI / Tests (Linux) (pull_request) Successful in 29s
CI / Dependency audit (pull_request) Successful in 17s
CI / Check desktop app (Linux) (pull_request) Successful in 1m13s
The token was the startup time in nanoseconds, guessable by another local
user or process within a small window, which would hand over the API
(captures, deauth, Evil Twin). It is now 32 random bytes from getrandom,
checked in constant time. Release 1.0.6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:16:27 -03:00
Lucas GuerraandClaude Sonnet 5 0ff945ef65 feat(report): add TLP classification badge to the audit report
CI / Format and clippy (push) Successful in 1m34s
CI / Dependency audit (push) Successful in 12s
CI / Tests (Linux) (push) Successful in 2m5s
CI / Check desktop app (Linux) (push) Successful in 4m2s
The cover already had the Sabiá logo, but only an "Uso autorizado" badge —
no sharing classification. Adds a TLP:AMBER badge (FIRST.org brand color)
next to it, on both the cover and the running per-page header, matching
the convention the rest of the Ciberfauna ecosystem's reports now follow.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-02 11:32:04 -03:00
Lucas RayanandClaude Sonnet 5 7e01e599fd chore(release): bump version to 1.0.5, move repository to the ciberfauna org
Release / Create release (push) Successful in 7s
CI / Format and clippy (push) Successful in 1m25s
CI / Tests (Linux) (push) Successful in 1m57s
CI / Check desktop app (Linux) (push) Successful in 3m43s
Release / Desktop app (linux-aarch64) (push) Successful in 4m22s
Release / CLI (linux-x86_64) (push) Successful in 51s
Release / Desktop app (linux-x86_64) (push) Successful in 4m20s
CI / Dependency audit (push) Successful in 11s
Release / CLI (linux-aarch64) (push) Successful in 45s
Release / Desktop app (windows) (push) Successful in 3m12s
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VAyr8d7HuAdUGB6aA5xmDD
2026-10-31 10:19:32 -03:00
Lucas RayanandClaude Sonnet 5 6191c7bbc6 feat(update): one-click desktop self-update (AppImage, .deb, Windows)
Same change as Guará: update_apply used to flatly refuse to run for
the GUI binary and point the user to a manual download instead. Since
the desktop app already elevates to root before showing its window,
the process applying the update already has everything it needs — no
second authentication round is required.

- New sabia_core::update::apply_desktop[_with_progress], alongside the
  existing CLI-only apply() (left untouched): detects the install kind
  at runtime (AppImage via the APPIMAGE env var, same FUSE-mount issue
  elevated_exe() already works around and this reuses; Deb otherwise
  on Linux; WindowsInstaller on Windows), matches the right release
  asset by the GUI bundle naming (_amd64/_aarch64.AppImage,
  _amd64/_arm64.deb, _x64-setup.exe), verifies SHA-256 when a sidecar
  is published, and installs:
  - AppImage: downloads to a temp file in the same directory, renames
    over the running file, execs it in place (same PID, already root).
  - .deb: runs dpkg -i directly (already root), execs current_exe()
    again now that dpkg replaced it on disk.
  - Windows: runs the installer silently and detached, exits
    immediately to release the file lock. Does not claim to relaunch
    the app afterwards — no documented NSIS or Tauri flag does that;
    needs a real Windows machine to confirm actual post-install
    behavior.
- Engine::update_apply_desktop wires it into the Tauri update_apply
  command (now takes AppHandle, emits update-progress events).
- Fixed a real gap: the existing update button handler changed its own
  label when an update was available but never actually called apply
  — wired it for real, with per-phase progress feedback in the
  interface's existing language (download/verify/install/restart).
- scripts/build-gui.sh: generates a checksum file next to every file
  in dist-gui/, matching the CLI release archive convention.
- 3 new unit tests: install-kind detection, GUI asset suffix matching
  against real release naming, existing CLI-refusal test unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VAyr8d7HuAdUGB6aA5xmDD
2026-10-31 10:18:31 -03:00
Lucas RayanandClaude Sonnet 5 7d69f2e4b2 ci: pin CI jobs to the arm64 runners, not the shared ubuntu-latest alias
CI / Format and clippy (push) Successful in 17s
CI / Tests (Linux) (push) Successful in 27s
CI / Dependency audit (push) Successful in 10s
CI / Check desktop app (Linux) (push) Successful in 1m47s
Release / Create release (push) Successful in 6s
Release / CLI (linux-aarch64) (push) Successful in 49s
Release / Desktop app (linux-aarch64) (push) Successful in 4m22s
Release / CLI (linux-x86_64) (push) Successful in 50s
Release / Desktop app (linux-x86_64) (push) Successful in 4m4s
Release / Desktop app (windows) (push) Successful in 3m8s
Same issue and fix as Guará: ci.yml's four jobs used
runs-on: ubuntu-latest, which now resolves only to hostinger-runner
after the Gitea runner relabeling, piling every CI push onto the same
single machine release.yml routes x86_64 builds to and overloading it.
Pins all four jobs to linux-arm64.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VAyr8d7HuAdUGB6aA5xmDD
2026-10-30 22:23:45 -03:00
Lucas RayanandClaude Sonnet 5 ba0c99d5b6 chore(release): bump version to 1.0.4
CI / Dependency audit (push) Canceled after 0s
CI / Check desktop app (Linux) (push) Canceled after 0s
Release / Create release (push) Successful in 6s
CI / Format and clippy (push) Canceled after 0s
CI / Tests (Linux) (push) Canceled after 0s
Release / CLI (linux-aarch64) (push) Successful in 53s
Release / Desktop app (linux-aarch64) (push) Successful in 4m45s
Release / CLI (linux-x86_64) (push) Successful in 1m28s
Release / Desktop app (linux-x86_64) (push) Successful in 10m26s
Release / Desktop app (windows) (push) Successful in 8m12s
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VAyr8d7HuAdUGB6aA5xmDD
2026-10-30 22:06:19 -03:00
Lucas RayanandClaude Sonnet 5 476e27e253 ci(release): build linux-x86_64 natively on the new amd64 runner
A native x86_64 Gitea Actions runner (hostinger-runner, label
linux-amd64) is now available alongside the two aarch64 runners
(oracle-runner/-b, label linux-arm64). Routes the linux-x86_64 leg of
the cli and gui release matrices to it instead of cross-compiling it
from an aarch64 host, same change as the Guará repository.

- matrix.include gets an explicit runner field per platform
  (linux-arm64 for aarch64, linux-amd64 for x86_64 and windows);
  runs-on: ${{ matrix.runner }} picks it per job. windows is pinned to
  linux-amd64 explicitly rather than relying on the ubuntu-latest
  alias, since that alias has already been reassigned once between
  the aarch64 and the x86_64 runner on this Gitea instance.
- The "Platform cross-linker" step (gcc-x86-64-linux-gnu) only runs
  when NOT on the native amd64 runner, since a native build needs no
  cross-linker.
- scripts/build-gui.sh and scripts/package-cli.sh are intentionally
  left untouched: both already branch on `uname -m` and take the
  simple native path when run on x86_64, so no script change was
  needed. The existing cross-compile path (qemu wrappers, the ELF
  launcher that survives tauri-bundler's dd patch) stays in place as a
  dormant fallback in case the single amd64 runner is ever
  unavailable — deliberately kept, not deleted.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VAyr8d7HuAdUGB6aA5xmDD
2026-10-30 22:06:13 -03:00
49 changed files with 1252 additions and 221 deletions

No files matched your search

+4 -4
View File
@@ -26,7 +26,7 @@ env:
jobs:
lint:
name: Format and clippy
runs-on: ubuntu-latest
runs-on: linux-arm64
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/sabia-lint
steps:
@@ -45,7 +45,7 @@ jobs:
# Linux-only runner (ARM64).
test:
name: Tests (Linux)
runs-on: ubuntu-latest
runs-on: linux-arm64
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/sabia-test
steps:
@@ -55,7 +55,7 @@ jobs:
audit:
name: Dependency audit
runs-on: ubuntu-latest
runs-on: linux-arm64
steps:
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@stable
@@ -69,7 +69,7 @@ jobs:
gui:
name: Check desktop app (Linux)
runs-on: ubuntu-latest
runs-on: linux-arm64
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/sabia-gui
steps:
+9 -6
View File
@@ -48,22 +48,22 @@ jobs:
cli:
name: CLI (${{ matrix.platform }})
needs: release
runs-on: ubuntu-latest
runs-on: ${{ matrix.runner }}
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/sabia-release-cli-${{ matrix.platform }}
strategy:
fail-fast: false
matrix:
include:
- { platform: linux-aarch64, target: aarch64-unknown-linux-gnu, apt: "" }
- { platform: linux-x86_64, target: x86_64-unknown-linux-gnu, apt: "gcc-x86-64-linux-gnu" }
- { platform: linux-aarch64, target: aarch64-unknown-linux-gnu, apt: "", runner: linux-arm64 }
- { platform: linux-x86_64, target: x86_64-unknown-linux-gnu, apt: "gcc-x86-64-linux-gnu", runner: linux-amd64 }
steps:
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- name: Platform cross-linker
if: ${{ matrix.apt != '' }}
if: ${{ matrix.apt != '' && matrix.runner != 'linux-amd64' }}
run: scripts/apt-install.sh /opt/hostedtoolcache/apt-cache/cli-x86_64 ${{ matrix.apt }}
- name: Build and package
run: scripts/package-cli.sh "${{ gitea.ref_name }}" "${{ matrix.platform }}" "${{ matrix.target }}" | tee packages.txt
@@ -76,7 +76,7 @@ jobs:
gui:
name: Desktop app (${{ matrix.platform }})
needs: release
runs-on: ubuntu-latest
runs-on: ${{ matrix.runner }}
env:
CARGO_TARGET_DIR: /opt/hostedtoolcache/cargo-target/sabia-release-gui-${{ matrix.platform }}
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.SABIA_TAURI_SIGNING_PRIVATE_KEY || secrets.TAURI_SIGNING_PRIVATE_KEY }}
@@ -84,7 +84,10 @@ jobs:
strategy:
fail-fast: false
matrix:
platform: [linux-aarch64, linux-x86_64, windows]
include:
- { platform: linux-aarch64, runner: linux-arm64 }
- { platform: linux-x86_64, runner: linux-amd64 }
- { platform: windows, runner: linux-amd64 }
steps:
- uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@stable
+36 -9
View File
@@ -4,6 +4,33 @@
Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow SemVer.
## [1.1.0] - 2026-11-04
### Changed
- **Redesigned audit report.** Full-bleed cover with the Sabiá logo as the hero, a data-driven Wi-Fi arc motif (one dot per network, distance by signal, colour by security), headline numbers and a meta grid with the TLP:AMBER classification; inner pages carry the logo in the running header. Fixed Paged.js running twice, which printed the report on Letter instead of A4.
- Documentation brought up to date and rewritten without em dashes; interface text no longer uses em dashes either. The interface screenshots were retaken, and `scripts/screenshots.sh` now regenerates them from the real interface with synthetic data.
## [1.0.7] - 2026-11-03
### Added
- **Update progress bar.** The in-app update shows a bar with the real download percentage, then the verify, install and restart steps.
### Fixed
- **Updating no longer freezes the app.** The update check and install ran on the UI thread; they now run in the background.
## [1.0.6] - 2026-11-03
### Security
- **`sabia ui` token is now unguessable.** It was the server's startup time in nanoseconds, so another user or process on the same machine could find it by trying values around that moment and then drive the API (captures, deauthentication, Evil Twin). It is now 32 random bytes from the operating system, and requests are checked in constant time. The desktop app does not use this token and is unaffected.
## [1.0.5] - 2026-10-31
### Added
- **One-click desktop update.** The update button actually downloads, verifies (SHA-256) and installs the new version now, instead of only changing its own label. Works for all three desktop packages: AppImage (atomic self-replace), `.deb` (`dpkg -i`, no new password prompt, the app is already running as root by the time you click it), and the Windows installer (silent install). On Linux, the app restarts itself automatically; on Windows, the installer runs silently but the app does not reopen on its own yet, start it again once the install finishes.
### Changed
- **The repository moved to the Ciberfauna organization** (`ciberfauna/sabia`, was `lucasrguerra/sabia`). **Important notice for existing installations:** versions up to 1.0.4 have the old location baked into their update check; they will not find this release automatically. Download 1.0.5 once manually from the new Releases page, and future update checks will work through the new location.
## [1.0.3] - 2026-10-30
### Fixed
@@ -19,7 +46,7 @@ Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versio
- The desktop app build on CI looked for its bundle under `target/`, but the
runner's Cargo target directory is elsewhere and persists between runs; the
Linux and Windows jobs failed before publishing anything. `v1.0.1`'s desktop
app was never published for this reason — use `v1.0.2`.
app was never published for this reason, use `v1.0.2`.
## [1.0.1] - 2026-10-30
@@ -55,7 +82,7 @@ First stable release: real-hardware validation across the whole attack surface,
- **WPS attack:** PIN/Pixie Dust via a bundled `reaver` (extracted at
runtime), or `bully` when installed on the system.
- **Evil Twin:** clones an already-seen AP (open SSID) on a second interface
with a captive portal, for WPA/WPA2-PSK — the submitted password is only
with a captive portal, for WPA/WPA2-PSK, the submitted password is only
accepted after being verified against the real captured handshake, never
"accepts anything". An **Enterprise (802.1X/EAP)** variant captures
credentials automatically via `hostapd-wpe`, no portal or human action
@@ -66,10 +93,10 @@ First stable release: real-hardware validation across the whole attack surface,
network, missing PMF, WPS exposed, possible evil twin by duplicate SSID).
- **Redesigned audit report:** full-page cover with embedded logo, table of
contents, running header/footer via `@page` margin boxes (current
section, page numbers), KPI and findings cards with severity colors —
section, page numbers), KPI and findings cards with severity colors,
still paginated by Paged.js in the browser, printable to PDF.
- `ScanSnapshot.warning`: tells you when a capture has been running for a
while without receiving a single frame — a card that accepts turning
while without receiving a single frame, a card that accepts turning
monitor mode on without actually delivering capture (common with
built-in laptop Wi-Fi) now says so, instead of silently "listening".
@@ -77,13 +104,13 @@ First stable release: real-hardware validation across the whole attack surface,
- **Handshake capture never completed on real networks:** `eapol.rs` read
`key_info`/`replay_counter`/`key_data_len` as little-endian; those
802.1X fields are big-endian. Deauth worked, EAPOL frames were seen, but
`HandshakeTracker` silently discarded every one — 0 handshakes no matter
`HandshakeTracker` silently discarded every one, 0 handshakes no matter
how much traffic was generated. The project's own synthetic test frames
made the same mistake symmetrically, so round-trip tests never caught
it; verified live against a real AP after the fix.
- **Monitor mode fighting NetworkManager:** `set_monitor()` now releases
the interface from NetworkManager before switching modes and returns it
afterward — without this, NM reasserted its own connection within
afterward, without this, NM reasserted its own connection within
seconds and capture died with "is in managed mode".
- **Evil Twin left the system half-configured if the process died mid-run**
(Ctrl+C, `kill -9`, power loss): both interfaces stuck `managed=no`
@@ -91,7 +118,7 @@ First stable release: real-hardware validation across the whole attack surface,
self-healing pass on every engine start now undoes this automatically;
`sabia ui` also handles SIGINT gracefully.
- **Repeated deauth/disassoc frames were dropped as duplicates** after the
first send — the same Sequence Control was reused on every injection;
first send, the same Sequence Control was reused on every injection;
now increments per frame.
- **Network list reordered under the cursor** during capture, as signal-based
sorting reacted to every 1-2 dBm fluctuation; order is now stable
@@ -106,7 +133,7 @@ First stable release: real-hardware validation across the whole attack surface,
### Changed
- `crack_reader`/`crack_mask` parallelize across available cores and reuse
the HMAC base per iteration instead of reconstructing it — roughly 640x
the HMAC base per iteration instead of reconstructing it, roughly 640x
faster in release builds versus the original debug/single-thread path.
## [0.1.0] - 2026-10-23
@@ -126,7 +153,7 @@ First release: CLI, desktop app and shared core.
`deauth` (with `--yes`), `doctor`, `audit` (verify/show), `update` and `ui`
(local interface server).
- Desktop app (Tauri) with the same interface served by `sabia ui`, elevating to
administrator automatically on startup — monitor mode and raw capture require
administrator automatically on startup, monitor mode and raw capture require
root/admin.
- Interface: interface sidebar, capture panel with an animated signal line,
networks table with signal bars and color-coded security badges, an
+36 -9
View File
@@ -4,6 +4,33 @@
Formato baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/); versões seguem SemVer.
## [1.1.0] - 2026-11-04
### Alterado
- **Relatório de auditoria redesenhado.** Capa em sangria total com o logo do Sabiá como protagonista, um motivo de arcos Wi-Fi gerado a partir dos dados (um ponto por rede, distância pelo sinal, cor pela segurança), números de destaque e uma grade de metadados com a classificação TLP:AMBER; as páginas internas trazem o logo no cabeçalho. Corrigido o Paged.js rodando duas vezes, o que imprimia o relatório em Carta em vez de A4.
- Documentação atualizada e reescrita sem travessões; os textos da interface também não usam mais travessões. As capturas de tela da interface foram refeitas, e o `scripts/screenshots.sh` agora as regera a partir da interface real com dados sintéticos.
## [1.0.7] - 2026-11-03
### Adicionado
- **Barra de progresso da atualização.** A atualização dentro do app mostra uma barra com a porcentagem real do download, seguida das etapas de verificação, instalação e reinício.
### Corrigido
- **Atualizar não trava mais o app.** A verificação e a instalação rodavam na thread da interface; agora rodam em segundo plano.
## [1.0.6] - 2026-11-03
### Segurança
- **O token do `sabia ui` agora não pode ser adivinhado.** Ele era o horário de partida do servidor em nanossegundos, então outro usuário ou processo na mesma máquina podia achá-lo testando valores próximos daquele momento e passar a comandar a API (capturas, desautenticação, Evil Twin). Agora são 32 bytes aleatórios do sistema operacional, e as requisições são conferidas em tempo constante. O app desktop não usa esse token e não é afetado.
## [1.0.5] - 2026-10-31
### Adicionado
- **Atualização do app desktop em um clique.** O botão de atualizar agora baixa, confere (SHA-256) e instala a versão nova de verdade, em vez de só mudar o próprio texto. Funciona nos três pacotes do desktop: AppImage (substituição atômica), `.deb` (`dpkg -i`, sem pedir senha de novo, o app já roda como root quando você clica), e o instalador do Windows (instalação silenciosa). No Linux o app reabre sozinho; no Windows o instalador roda silencioso mas o app ainda não reabre por conta própria, abra de novo depois que a instalação terminar.
### Alterado
- **O repositório se mudou pra organização Ciberfauna** (`ciberfauna/sabia`, era `lucasrguerra/sabia`). **Aviso importante pra instalações existentes:** versões até a 1.0.4 têm o endereço antigo fixo na checagem de atualização e não vão encontrar esta versão sozinhas. Baixe a 1.0.5 manualmente uma vez na nova página de Releases, e as próximas verificações voltam a funcionar pelo novo endereço.
## [1.0.3] - 2026-10-30
### Corrigido
@@ -19,7 +46,7 @@ Formato baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/);
- O build do app desktop no CI procurava o pacote em `target/`, mas o
diretório do Cargo no runner é outro e persiste entre execuções; os jobs de
Linux e Windows falhavam antes de publicar qualquer coisa. Por isso o app
desktop da `v1.0.1` nunca foi publicado — use a `v1.0.2`.
desktop da `v1.0.1` nunca foi publicado, use a `v1.0.2`.
## [1.0.1] - 2026-10-30
@@ -56,7 +83,7 @@ Primeira versão estável: validação em hardware real por toda a superfície d
- **Ataque WPS:** PIN/Pixie Dust via `reaver` embutido (extraído em tempo de
execução), ou `bully` quando instalado no sistema.
- **Evil Twin:** clona um AP já visto na sessão (SSID aberto) numa segunda
interface com portal cativo, para WPA/WPA2-PSK — a senha só é aceita
interface com portal cativo, para WPA/WPA2-PSK, a senha só é aceita
depois de conferida de verdade contra o handshake real já capturado,
nunca "aceita qualquer coisa". Uma variante **Enterprise (802.1X/EAP)**
captura credenciais automaticamente via `hostapd-wpe`, sem portal nem
@@ -69,10 +96,10 @@ Primeira versão estável: validação em hardware real por toda a superfície d
- **Relatório de auditoria redesenhado:** capa em página cheia com o logo
embutido, sumário com âncoras, cabeçalho/rodapé corridos via margin
boxes do `@page` (seção atual, numeração de página), cards de KPI e
achados com cor por severidade — a paginação continua feita pelo
achados com cor por severidade, a paginação continua feita pelo
Paged.js no navegador, imprimível em PDF.
- `ScanSnapshot.warning`: avisa quando uma captura está rodando há um
tempo sem receber nenhum quadro — uma placa que aceita ativar modo
tempo sem receber nenhum quadro, uma placa que aceita ativar modo
monitor sem realmente entregar captura (comum em Wi-Fi interno de
notebook) agora diz isso, em vez de ficar "escutando o ar" caladinha.
@@ -80,14 +107,14 @@ Primeira versão estável: validação em hardware real por toda a superfície d
- **Captura de handshake nunca completava em rede real:** `eapol.rs` lia
`key_info`/`replay_counter`/`key_data_len` como little-endian; esses
campos do 802.1X são big-endian. O deauth funcionava, os quadros EAPOL
eram vistos, mas o `HandshakeTracker` descartava todos silenciosamente —
eram vistos, mas o `HandshakeTracker` descartava todos silenciosamente,
0 handshakes não importa quanto tráfego fosse gerado. Os próprios
quadros sintéticos de teste do projeto cometiam o mesmo engano
simetricamente, então os testes de ida e volta nunca pegaram isso;
verificado ao vivo contra um AP real depois da correção.
- **Modo monitor brigando com o NetworkManager:** `set_monitor()` agora
solta a interface do NetworkManager antes de trocar de modo e devolve
depois — sem isso o NM reafirmava a própria conexão em segundos e a
depois, sem isso o NM reafirmava a própria conexão em segundos e a
captura caía com "está em modo managed".
- **Evil Twin deixava o sistema pela metade se o processo morresse no
meio** (Ctrl+C, `kill -9`, queda de energia): as duas interfaces ficavam
@@ -96,7 +123,7 @@ Primeira versão estável: validação em hardware real por toda a superfície d
desfazem isso sozinhos agora; o `sabia ui` também trata SIGINT
graciosamente.
- **Quadros repetidos de deauth/disassoc eram descartados como duplicata**
depois do primeiro envio — o mesmo Sequence Control era reusado em toda
depois do primeiro envio, o mesmo Sequence Control era reusado em toda
injeção; agora incrementa por quadro.
- **Lista de redes reordenava debaixo do cursor** durante a captura, porque
a ordenação por sinal reagia a cada oscilação de 1-2 dBm; a ordem agora
@@ -111,7 +138,7 @@ Primeira versão estável: validação em hardware real por toda a superfície d
### Alterado
- `crack_reader`/`crack_mask` paralelizam entre os núcleos disponíveis e
reaproveitam a base do HMAC por iteração em vez de reconstruí-la — cerca
reaproveitam a base do HMAC por iteração em vez de reconstruí-la, cerca
de 640x mais rápido em build release comparado ao caminho original
debug/single-thread.
@@ -132,7 +159,7 @@ Primeira versão: CLI, app desktop e núcleo compartilhado.
`deauth` (com `--yes`), `doctor`, `audit` (verify/show), `update` e `ui`
(servidor local da interface).
- App desktop (Tauri) com a mesma interface servida pelo `sabia ui`, pedindo
elevação de administrador automaticamente ao abrir — modo monitor e captura
elevação de administrador automaticamente ao abrir, modo monitor e captura
crua exigem root/admin.
- Interface gráfica: sidebar de interfaces, painel de captura com linha de sinal
animada, tabela de redes com barras de sinal e selos de segurança por cor,
+4 -2
View File
@@ -5,7 +5,7 @@
Thanks for helping! Golden rules:
1. **Authorized auditing only.** Every new feature is for testing your own networks or networks you're authorized to test. Sensitive operations (deauthentication) require explicit confirmation and are recorded in the audit trail. PRs that hide activity from the trail or remove the confirmations are rejected.
2. **Test the parsers with real data.** New readers (radiotap, 802.11, EAPOL, pcap) need tests against known frames — see `crates/sabia-core/tests/` and the helpers in `crates/sabia-core/src/testutil.rs`. No parser without a test.
2. **Test the parsers with real data.** New readers (radiotap, 802.11, EAPOL, pcap) need tests against known frames, see `crates/sabia-core/tests/` and the helpers in `crates/sabia-core/src/testutil.rs`. No parser without a test.
3. **Be honest about what works.** If a feature is Linux-only, or only covers WPA2-PSK, say so in `--help`, in the README and in the test.
4. **100% English codebase and comments.** All source code, comments, scripts, CI workflows, and commit messages must be written in English, while the GUI/CLI remains bilingual (PT-BR and EN via `i18n-en.js`).
@@ -40,7 +40,9 @@ Module map in [docs/architecture.md](docs/architecture.md). What's missing and w
## Interface and translation
The source text of the interface is **Portuguese**; English comes from `apps/gui/ui/i18n-en.js`, applied at runtime by `i18n.js`. When adding or changing visible text, run `node scripts/check-ui-i18n.mjs` and include the translation — CI rejects Portuguese without an English pair. Don't translate user data (SSID, BSSID, values) or technical terms (WPA, EAPOL, pcap…).
The source text of the interface is **Portuguese**; English comes from `apps/gui/ui/i18n-en.js`, applied at runtime by `i18n.js`. When adding or changing visible text, run `node scripts/check-ui-i18n.mjs` and include the translation, CI rejects Portuguese without an English pair. Don't translate user data (SSID, BSSID, values) or technical terms (WPA, EAPOL, pcap…).
The screenshots in `docs/img` are regenerated by `scripts/screenshots.sh` from the real interface with synthetic data (needs Chrome and `puppeteer-core`; see the script header). Run it after any visible UI change.
## Documentation
+4 -2
View File
@@ -5,7 +5,7 @@
Obrigado por ajudar! Regras de ouro:
1. **Só auditoria autorizada.** Todo recurso novo é para testar redes próprias ou com autorização. Operações sensíveis (desautenticação) exigem confirmação explícita e ficam na trilha de auditoria. PRs que escondem atividade da trilha ou removem as confirmações são recusados.
2. **Teste os parsers com dados reais.** Novos leitores (radiotap, 802.11, EAPOL, pcap) precisam de teste com quadros conhecidos — veja `crates/sabia-core/tests/` e os ajudantes em `crates/sabia-core/src/testutil.rs`. Nada de parser sem teste.
2. **Teste os parsers com dados reais.** Novos leitores (radiotap, 802.11, EAPOL, pcap) precisam de teste com quadros conhecidos, veja `crates/sabia-core/tests/` e os ajudantes em `crates/sabia-core/src/testutil.rs`. Nada de parser sem teste.
3. **Seja honesto sobre o que funciona.** Se um recurso só roda no Linux, ou só cobre WPA2-PSK, diga isso no `--help`, no README e no teste.
4. **Código, comentários e commits 100% em inglês.** Todo código-fonte, comentários, scripts, workflows de CI e mensagens de commit devem ser escritos em inglês, enquanto a interface gráfica/CLI permanece bilíngue (PT-BR e EN via `i18n-en.js`).
@@ -40,7 +40,9 @@ Mapa dos módulos em [docs/pt-BR/arquitetura.md](docs/pt-BR/arquitetura.md). O q
## Interface e tradução
O texto-fonte da interface é em **português**; o inglês vem de `apps/gui/ui/i18n-en.js`, aplicado em tempo de execução por `i18n.js`. Ao adicionar ou mudar texto visível, rode `node scripts/check-ui-i18n.mjs` e inclua a tradução — o CI recusa português sem par em inglês. Não traduza dados do usuário (SSID, BSSID, valores) nem termos técnicos (WPA, EAPOL, pcap…).
O texto-fonte da interface é em **português**; o inglês vem de `apps/gui/ui/i18n-en.js`, aplicado em tempo de execução por `i18n.js`. Ao adicionar ou mudar texto visível, rode `node scripts/check-ui-i18n.mjs` e inclua a tradução, o CI recusa português sem par em inglês. Não traduza dados do usuário (SSID, BSSID, valores) nem termos técnicos (WPA, EAPOL, pcap…).
As capturas de tela em `docs/img` são regeradas por `scripts/screenshots.sh` a partir da interface real com dados sintéticos (precisa de Chrome e `puppeteer-core`; veja o cabeçalho do script). Rode depois de qualquer mudança visível na interface.
## Documentação
Generated
+3 -2
View File
@@ -440,10 +440,11 @@ dependencies = [
[[package]]
name = "sabia-cli"
version = "1.0.3"
version = "1.1.0"
dependencies = [
"clap",
"ctrlc",
"getrandom",
"sabia-core",
"serde",
"serde_json",
@@ -451,7 +452,7 @@ dependencies = [
[[package]]
name = "sabia-core"
version = "1.0.3"
version = "1.1.0"
dependencies = [
"aes",
"flate2",
+2 -2
View File
@@ -3,10 +3,10 @@ resolver = "2"
members = ["crates/sabia-core", "crates/sabia-cli"]
[workspace.package]
version = "1.0.3"
version = "1.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
repository = "https://git.lucasrguerra.dev.br/lucasrguerra/sabia"
repository = "https://git.lucasrguerra.dev.br/ciberfauna/sabia"
authors = ["Sabiá contributors"]
rust-version = "1.80"
+11 -11
View File
@@ -10,22 +10,22 @@
---
Sabiá brings together, in a single sweep, what tools like `airodump-ng`, `hcxdumptool`, `aircrack-ng` and `wifite` do separately — in one Rust binary, with no `libpcap` dependency:
Sabiá brings together, in a single sweep, what tools like `airodump-ng`, `hcxdumptool`, `aircrack-ng` and `wifite` do separately, in one Rust binary, with no `libpcap` dependency:
- **Network discovery:** hops across the **2.4, 5 and 6 GHz** channels and lists access points and associated clients, with SSID, BSSID, channel, signal, security type, WPS details and vendor.
- **Monitor mode without scripts:** turns the card's monitor mode on and off straight through netlink/`iw`, recovering automatically if NetworkManager tries to reclaim the interface, and shows which channels the radio supports.
- **Handshake capture:** recognizes the **4-way handshake (EAPOL)** and the **PMKID** on the air and keeps only what offline cracking needs; decrypts CCMP traffic for a client once its password is known.
- **Cracking, three ways:** dictionary (9.7M passwords bundled by default, rockyou + Probable-Wordlists), hashcat-style **mutation rules**, and **mask brute force** (`?d?l?u?s?a`) — recomputes the PMK with **PBKDF2-HMAC-SHA1** and checks the **MIC** (4-way) or the **PMKID** — for WPA/WPA2-PSK. Export to **`.hc22000`** to hand the handshake to hashcat/John instead.
- **Cracking, three ways:** dictionary (9.7M passwords bundled by default, rockyou + Probable-Wordlists), hashcat-style **mutation rules**, and **mask brute force** (`?d?l?u?s?a`) (recomputes the PMK with **PBKDF2-HMAC-SHA1** and checks the **MIC** (4-way) or the **PMKID**) for WPA/WPA2-PSK. Export to **`.hc22000`** to hand the handshake to hashcat/John instead.
- **pcap round-trip:** writes captured frames to `.pcap` and **analyzes a `.pcap` offline** (networks, clients and handshakes), interoperable with the other tools.
- **Deauthentication and WPS:** directional/continuous _deauth_, PMF probing, clientless PMKID hunting, and a WPS PIN/Pixie Dust attack (bundled reaver, or bully when installed) — all gated behind an explicit authorization confirmation (`--yes` / checkbox).
- **Evil Twin:** clones an already-seen AP with a captive portal for WPA/WPA2-PSK — the submitted password is only accepted after it's verified against the real captured handshake, never "accepts anything" — plus an Enterprise (802.1X/EAP) variant that captures credentials automatically, no portal needed.
- **Deauthentication and WPS:** directional/continuous _deauth_, PMF probing, clientless PMKID hunting, and a WPS PIN/Pixie Dust attack (bundled reaver, or bully when installed), all gated behind an explicit authorization confirmation (`--yes` / checkbox).
- **Evil Twin:** clones an already-seen AP with a captive portal for WPA/WPA2-PSK (the submitted password is only accepted after it's verified against the real captured handshake, never "accepts anything") plus an Enterprise (802.1X/EAP) variant that captures credentials automatically, no portal needed.
- **Audit report:** a paginated, printable report (cover, table of contents, findings, channel scoring, audit trail) generated locally.
- **Audit trail:** every monitor-mode activation and capture session is recorded in a local **hash-chained** trail.
- **Diagnostics:** `doctor` checks privileges, tools and interfaces before you start.
## Authorized use
Sabiá is an **auditing** tool — for testing the security of networks you **own** or have **explicit authorization** to assess.
Sabiá is an **auditing** tool, for testing the security of networks you **own** or have **explicit authorization** to assess.
- Capturing handshakes, sending deauthentication or cracking passwords on third-party networks **without permission is illegal** in most countries. The responsibility is the operator's.
- Deauthentication (`deauth`) requires the `--yes` flag, an assertion that you are authorized to test that network.
@@ -39,18 +39,18 @@ Download the package for your system from **[Releases](../../releases)**:
| | CLI | Desktop app |
|---|---|---|
| Windows | — | `.exe` installer |
| Windows | none | `.exe` installer |
| Linux | `sabia-*-linux-{x86_64,aarch64}.tar.gz` | `.AppImage` / `.deb` |
The CLI is Linux-only; the desktop app ships for Linux and Windows. Each CLI
package has a `.sha256` next to it. Build from source: `cargo build --release
-p sabia-cli` (Rust 1.80+, Linux).
**Updates:** the desktop app checks Gitea on startup; when a new version exists, a button offers **Update now**. The CLI updates the same way (`sabia update`); it downloads the right binary for your platform, verifies the **SHA-256** and swaps the running executable — no manual download. The check is a single request to the releases API and sends nothing of yours.
**Updates:** the desktop app checks Gitea on startup; when a new version exists, a button offers **Update now**. The CLI updates the same way (`sabia update`); it downloads the right binary for your platform, verifies the **SHA-256** and swaps the running executable, no manual download. The check is a single request to the releases API and sends nothing of yours.
> The binaries are **not signed yet**: Windows SmartScreen will warn. Check the SHA-256.
**Capture and monitor mode require Linux and root** — the only platform the CLI ships for (`CAP_NET_ADMIN`/`CAP_NET_RAW`): raw capture uses `AF_PACKET` and interface control uses netlink. **Offline `.pcap` analysis and cracking** also run on Windows and macOS. The desktop app elevates to administrator on its own at startup.
**Capture and monitor mode require Linux and root**, the only platform the CLI ships for (`CAP_NET_ADMIN`/`CAP_NET_RAW`): raw capture uses `AF_PACKET` and interface control uses netlink. **Offline `.pcap` analysis and cracking** also run on Windows and macOS. The desktop app elevates to administrator on its own at startup.
## Getting started
@@ -80,9 +80,9 @@ Desktop app (Tauri) with an interface sidebar, a capture panel with an animated
## Known limits
- **Capture is Linux-only**, with a card that supports **monitor mode** (and injection, for `deauth`); the CLI is not built for other platforms. On Windows Sabiá's desktop app only does `.pcap` analysis and offline cracking.
- **WPA3/SAE** does not fall to handshake dictionaries — cracking covers **WPA/WPA2-PSK** (4-way and PMKID).
- **WPA3/SAE** does not fall to handshake dictionaries, cracking covers **WPA/WPA2-PSK** (4-way and PMKID).
- **5 and 6 GHz** depend on the card and the regulatory domain; some channels stay passive (no probing).
- **Evil Twin's self-signed certificate:** the Enterprise variant's TLS certificate isn't trusted by clients that validate the chain (common on updated corporate/MDM devices) — that's the correct defense working, not a bug.
- **Evil Twin's self-signed certificate:** the Enterprise variant's TLS certificate isn't trusted by clients that validate the chain (common on updated corporate/MDM devices), that's the correct defense working, not a bug.
- **Windows:** the code compiles and is tested in CI, but live capture does not run there; the desktop app does offline analysis only. There is no macOS build: Tauri needs the macOS SDK and code signing, both tied to Apple hardware and an Apple Developer account, which this project's CI (a single Linux runner) does not have.
## Where it's going
@@ -93,7 +93,7 @@ Summary of the [ROADMAP](ROADMAP.md):
|---|---|
| **Done** | Monitor mode via netlink (with NetworkManager recovery), 2.4/5/6 GHz scanning, 4-way and PMKID capture, CCMP decryption, dictionary/rules/mask cracking (WPA/WPA2-PSK), `.hc22000` export, `.pcap` read/write, authorized `deauth`/PMF/PMKID, WPS attack, Evil Twin (PSK + Enterprise), channel scoring and findings, paginated audit report, hash-chained audit trail, `doctor`, CLI + desktop app, one-click update |
| **Next** | GPU acceleration for cracking, capture on Windows (Npcap) |
| **Not planned** | A macOS build — see [Known limits](#known-limits) |
| **Not planned** | A macOS build, see [Known limits](#known-limits) |
| **Later** | WPA3/SAE downgrade, validation on varied hardware, signed release binaries |
## Development
+11 -11
View File
@@ -10,22 +10,22 @@
---
O Sabiá junta, numa única varredura, o que ferramentas como `airodump-ng`, `hcxdumptool`, `aircrack-ng` e `wifite` fazem separadamente — em um só binário Rust, sem depender de `libpcap`:
O Sabiá junta, numa única varredura, o que ferramentas como `airodump-ng`, `hcxdumptool`, `aircrack-ng` e `wifite` fazem separadamente, em um só binário Rust, sem depender de `libpcap`:
- **Descoberta de redes:** percorre os canais de **2.4, 5 e 6 GHz** e lista os pontos de acesso e os clientes associados, com SSID, BSSID, canal, sinal, tipo de segurança, detalhes de WPS e fabricante.
- **Modo monitor sem scripts:** liga e desliga o modo monitor da placa direto pelo netlink/`iw`, com recuperação automática se o NetworkManager tentar retomar a interface, e mostra os canais que o rádio suporta.
- **Captura de handshake:** reconhece o **4-way handshake (EAPOL)** e o **PMKID** no ar e guarda só o que é preciso para a quebra offline; decifra tráfego CCMP de um cliente assim que a senha dele é conhecida.
- **Quebra, de três jeitos:** dicionário (9,7 milhões de senhas por padrão, rockyou + Probable-Wordlists), **regras de mutação** estilo hashcat e **força bruta por máscara** (`?d?l?u?s?a`) — recalcula a PMK com **PBKDF2-HMAC-SHA1** e confere o **MIC** (4-way) ou o **PMKID** — para WPA/WPA2-PSK. Exporta em **`.hc22000`** para levar o handshake direto ao hashcat/John.
- **Quebra, de três jeitos:** dicionário (9,7 milhões de senhas por padrão, rockyou + Probable-Wordlists), **regras de mutação** estilo hashcat e **força bruta por máscara** (`?d?l?u?s?a`) (recalcula a PMK com **PBKDF2-HMAC-SHA1** e confere o **MIC** (4-way) ou o **PMKID**) para WPA/WPA2-PSK. Exporta em **`.hc22000`** para levar o handshake direto ao hashcat/John.
- **pcap de ida e volta:** grava os quadros capturados em `.pcap` e **analisa um `.pcap` offline** (redes, clientes e handshakes), compatível com as outras ferramentas.
- **Desautenticação e WPS:** _deauth_ direcional/contínuo, teste de PMF, caça de PMKID sem cliente, e ataque WPS PIN/Pixie Dust (reaver embutido, ou bully quando instalado) — tudo atrás de confirmação explícita de autorização (`--yes`/checkbox).
- **Evil Twin:** clona um AP já visto com portal cativo para WPA/WPA2-PSK — a senha só é aceita depois de conferida contra o handshake real já capturado, nunca "aceita qualquer coisa" — mais uma variante Enterprise (802.1X/EAP) que captura credenciais automaticamente, sem portal.
- **Desautenticação e WPS:** _deauth_ direcional/contínuo, teste de PMF, caça de PMKID sem cliente, e ataque WPS PIN/Pixie Dust (reaver embutido, ou bully quando instalado), tudo atrás de confirmação explícita de autorização (`--yes`/checkbox).
- **Evil Twin:** clona um AP já visto com portal cativo para WPA/WPA2-PSK (a senha só é aceita depois de conferida contra o handshake real já capturado, nunca "aceita qualquer coisa") mais uma variante Enterprise (802.1X/EAP) que captura credenciais automaticamente, sem portal.
- **Relatório de auditoria:** relatório paginado e imprimível (capa, sumário, achados, pontuação de canais, trilha de auditoria) gerado localmente.
- **Trilha de auditoria:** toda ativação de modo monitor e sessão de captura fica registrada numa trilha local **encadeada por hash**.
- **Diagnóstico:** o `doctor` confere privilégios, ferramentas e interfaces antes de você começar.
## Uso autorizado
O Sabiá é uma ferramenta de **auditoria** — para testar a segurança de redes **suas** ou de redes que você tem **autorização explícita** para avaliar.
O Sabiá é uma ferramenta de **auditoria**, para testar a segurança de redes **suas** ou de redes que você tem **autorização explícita** para avaliar.
- Capturar handshakes, enviar desautenticação ou quebrar senhas de redes de terceiros **sem permissão é ilegal** na maioria dos países. A responsabilidade é de quem usa.
- A desautenticação (`deauth`) exige a flag `--yes`, uma afirmação de que você tem autorização para testar aquela rede.
@@ -39,18 +39,18 @@ Baixe o pacote do seu sistema em **[Releases](../../releases)**:
| | CLI | App gráfico |
|---|---|---|
| Windows | — | instalador `.exe` |
| Windows | nenhum | instalador `.exe` |
| Linux | `sabia-*-linux-{x86_64,aarch64}.tar.gz` | `.AppImage` / `.deb` |
O CLI é só para Linux; o app desktop sai para Linux e Windows. Cada pacote do
CLI tem um `.sha256` ao lado. Compilar do código: `cargo build --release -p
sabia-cli` (Rust 1.80+, Linux).
**Atualizações:** o app desktop consulta o Gitea ao abrir; havendo versão nova, um botão oferece **Atualizar agora**. O CLI atualiza do mesmo jeito (`sabia update`); ele baixa o binário certo para a plataforma, confere o **SHA-256** e troca o executável em uso — você não precisa baixar nada na mão. A consulta é uma única requisição à API de releases e nada seu é enviado.
**Atualizações:** o app desktop consulta o Gitea ao abrir; havendo versão nova, um botão oferece **Atualizar agora**. O CLI atualiza do mesmo jeito (`sabia update`); ele baixa o binário certo para a plataforma, confere o **SHA-256** e troca o executável em uso, você não precisa baixar nada na mão. A consulta é uma única requisição à API de releases e nada seu é enviado.
> Os binários ainda **não são assinados**: o SmartScreen do Windows vai avisar. Confira o SHA-256.
**Captura e modo monitor exigem Linux e privilégio de root** — a única plataforma para a qual o CLI é compilado (`CAP_NET_ADMIN`/`CAP_NET_RAW`): a captura crua usa `AF_PACKET` e o controle de interface usa netlink. A **análise de `.pcap` e a quebra offline** rodam também em Windows e macOS. O app desktop pede elevação de administrador sozinho ao abrir.
**Captura e modo monitor exigem Linux e privilégio de root**, a única plataforma para a qual o CLI é compilado (`CAP_NET_ADMIN`/`CAP_NET_RAW`): a captura crua usa `AF_PACKET` e o controle de interface usa netlink. A **análise de `.pcap` e a quebra offline** rodam também em Windows e macOS. O app desktop pede elevação de administrador sozinho ao abrir.
## Começando
@@ -80,9 +80,9 @@ App desktop (Tauri) com sidebar de interfaces, painel de captura com linha de si
## Limites conhecidos
- **Captura só no Linux**, com placa que suporte **modo monitor** (e injeção, para `deauth`); o CLI não é compilado para outras plataformas. Em Windows o app desktop do Sabiá faz só análise de `.pcap` e quebra offline.
- **WPA3/SAE** não cai por dicionário de handshake — a quebra cobre **WPA/WPA2-PSK** (4-way e PMKID).
- **WPA3/SAE** não cai por dicionário de handshake, a quebra cobre **WPA/WPA2-PSK** (4-way e PMKID).
- **5 e 6 GHz** dependem da placa e do _regulatory domain_; alguns canais ficam passivos (sem _probe_).
- **Certificado autoassinado do Evil Twin Enterprise:** clientes que validam a cadeia de certificado da rede (comum em perfil corporativo/MDM atualizado) não confiam nele — é a defesa correta funcionando, não um bug.
- **Certificado autoassinado do Evil Twin Enterprise:** clientes que validam a cadeia de certificado da rede (comum em perfil corporativo/MDM atualizado) não confiam nele, é a defesa correta funcionando, não um bug.
- **Windows:** o código compila e é testado em CI, mas a captura ao vivo não roda lá; o app desktop faz só análise offline. Não há build para macOS: o Tauri precisa do SDK do macOS e de assinatura, os dois presos a hardware Apple e a uma conta Apple Developer, que o CI deste projeto (um único runner Linux) não tem.
## Para onde vai
@@ -93,7 +93,7 @@ Resumo do [ROADMAP](ROADMAP.pt-BR.md):
|---|---|
| **Feito** | Modo monitor por netlink (com recuperação do NetworkManager), varredura 2.4/5/6 GHz, captura de 4-way e PMKID, decriptação CCMP, quebra por dicionário/regras/máscara (WPA/WPA2-PSK), exportação `.hc22000`, escrita e leitura de `.pcap`, `deauth`/PMF/PMKID autorizados, ataque WPS, Evil Twin (PSK + Enterprise), pontuação de canais e achados, relatório de auditoria paginado, trilha de auditoria por hash, `doctor`, CLI + app desktop, atualização em um clique |
| **Próximo** | Aceleração por GPU na quebra, captura em Windows (Npcap) |
| **Fora de plano** | Um build para macOS — veja [Limites conhecidos](#limites-conhecidos) |
| **Fora de plano** | Um build para macOS, veja [Limites conhecidos](#limites-conhecidos) |
| **Depois** | WPA3/SAE _downgrade_, validação em hardware variado, binários de release assinados |
## Desenvolvimento
+2 -2
View File
@@ -2,6 +2,6 @@
**English** · [Português](SECURITY.pt-BR.md)
Sabiá processes untrusted data from the air and from `.pcap` files (802.11 frames and handshakes, possibly forged) and controls network interfaces with root privilege. Vulnerabilities — memory corruption in the radiotap/802.11/EAPOL parsers, path escape when writing `.pcap` or exporting, privilege misuse — should be reported privately through the private vulnerability reporting feature of the repository on Gitea. Do not open a public issue before a fix.
Sabiá processes untrusted data from the air and from `.pcap` files (802.11 frames and handshakes, possibly forged) and controls network interfaces with root privilege. Vulnerabilities, memory corruption in the radiotap/802.11/EAPOL parsers, path escape when writing `.pcap` or exporting, privilege misuse, should be reported privately through the private vulnerability reporting feature of the repository on Gitea. Do not open a public issue before a fix.
Sabiá is a tool for **authorized auditing**. Reports about using it to attack third-party networks are out of the project's security scope — see the **Authorized use** section of the [README](README.md).
Sabiá is a tool for **authorized auditing**. Reports about using it to attack third-party networks are out of the project's security scope, see the **Authorized use** section of the [README](README.md).
+2 -2
View File
@@ -2,6 +2,6 @@
[English](SECURITY.md) · **Português**
O Sabiá processa dados não confiáveis vindos do ar e de arquivos `.pcap` (quadros 802.11 e handshakes, possivelmente forjados) e controla interfaces de rede com privilégio de root. Vulnerabilidades — corrupção de memória nos parsers de radiotap/802.11/EAPOL, escape de caminho na escrita de `.pcap` ou na exportação, uso indevido de privilégio — devem ser reportadas em privado pelo recurso de relato privado de vulnerabilidade do repositório no Gitea. Não abra issue pública antes da correção.
O Sabiá processa dados não confiáveis vindos do ar e de arquivos `.pcap` (quadros 802.11 e handshakes, possivelmente forjados) e controla interfaces de rede com privilégio de root. Vulnerabilidades, corrupção de memória nos parsers de radiotap/802.11/EAPOL, escape de caminho na escrita de `.pcap` ou na exportação, uso indevido de privilégio, devem ser reportadas em privado pelo recurso de relato privado de vulnerabilidade do repositório no Gitea. Não abra issue pública antes da correção.
O Sabiá é uma ferramenta de **auditoria autorizada**. Relatos sobre uso para atacar redes de terceiros não são escopo de segurança do projeto — veja a seção **Uso autorizado** do [README](README.pt-BR.md).
O Sabiá é uma ferramenta de **auditoria autorizada**. Relatos sobre uso para atacar redes de terceiros não são escopo de segurança do projeto, veja a seção **Uso autorizado** do [README](README.pt-BR.md).
+2 -2
View File
@@ -2538,7 +2538,7 @@ checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "sabia-core"
version = "1.0.3"
version = "1.1.0"
dependencies = [
"aes",
"flate2",
@@ -2555,7 +2555,7 @@ dependencies = [
[[package]]
name = "sabia-gui"
version = "1.0.3"
version = "1.1.0"
dependencies = [
"libc",
"sabia-core",
+2 -2
View File
@@ -3,11 +3,11 @@
[package]
name = "sabia-gui"
description = "Sabiá: graphical Wi-Fi security auditing interface"
version = "1.0.3"
version = "1.1.0"
edition = "2021"
license = "MIT OR Apache-2.0"
authors = ["Sabiá contributors"]
repository = "https://git.lucasrguerra.dev.br/lucasrguerra/sabia"
repository = "https://git.lucasrguerra.dev.br/ciberfauna/sabia"
rust-version = "1.80"
[workspace]
+35 -5
View File
@@ -496,14 +496,44 @@ fn start_scan_opts(
}
#[tauri::command]
fn update_check(state: tauri::State<'_, State>) -> Result<serde_json::Value, String> {
let status = state.0.update_check().map_err(|e| e.to_string())?;
serde_json::to_value(status).map_err(|e| e.to_string())
async fn update_check(state: tauri::State<'_, State>) -> Result<serde_json::Value, String> {
let eng = state.0.clone();
tauri::async_runtime::spawn_blocking(move || {
let status = eng.update_check().map_err(|e| e.to_string())?;
serde_json::to_value(status).map_err(|e| e.to_string())
})
.await
.map_err(|e| e.to_string())?
}
#[tauri::command]
fn update_apply(state: tauri::State<'_, State>) -> Result<String, String> {
state.0.update_apply().map_err(|e| e.to_string())
async fn update_apply(
app: tauri::AppHandle,
state: tauri::State<'_, State>,
) -> Result<String, String> {
use tauri::Emitter;
#[cfg(any(target_os = "linux", target_os = "macos"))]
let exe = elevated_exe().unwrap_or_else(|_| std::env::current_exe().unwrap_or_default());
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
let exe = std::env::current_exe().unwrap_or_default();
// Blocking download/install must not run on the UI thread, or the window freezes.
let eng = state.0.clone();
tauri::async_runtime::spawn_blocking(move || {
eng.update_apply_desktop(&exe, move |phase| {
let (name, pct) = match phase.split_once(':') {
Some((n, p)) => (n, p.parse::<u8>().ok()),
None => (phase, None),
};
let _ = app.emit(
"update-progress",
serde_json::json!({ "phase": name, "percent": pct }),
);
})
.map_err(|e| e.to_string())
})
.await
.map_err(|e| e.to_string())?
}
/// `true` when the process already has sufficient privileges for all
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "Sabiá",
"version": "1.0.3",
"version": "1.1.0",
"identifier": "dev.sabia.app",
"build": {
"frontendDist": "../ui"
+6 -1
View File
@@ -116,7 +116,7 @@ code, .mono { font-family: var(--mono); font-variant-numeric: tabular-nums; }
.iface-pick .pill { align-self: flex-start; }
.side-foot { margin-top: auto; padding: 14px 4px 4px; font-size: 11.5px; color: var(--text-3); display: grid; gap: 8px; }
.foot-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.foot-row { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px; }
.side-foot button { background: transparent; border: 0; color: var(--text-3); cursor: pointer; }
.side-foot .foot-row > button:not(.icon-btn) { text-decoration: underline; text-underline-offset: 2px; }
.side-foot button:hover { color: var(--text-2); }
@@ -457,3 +457,8 @@ dialog menu { display: flex; gap: 10px; justify-content: flex-end; padding: 0; m
.report-dlg { width: 100vw; height: 100vh; max-height: 100vh; border-radius: 0; }
.report-view { padding: 8px; }
}
.upd-bar { flex-basis: 100%; height: 6px; border-radius: 99px; margin-top: 8px; overflow: hidden; background: color-mix(in srgb, currentColor 12%, transparent); }
.upd-bar > i { display: block; height: 100%; border-radius: 99px; background: var(--accent, currentColor); transition: width .3s ease; }
.upd-bar.indet > i { animation: upd-slide 1.2s infinite ease-in-out; }
@keyframes upd-slide { 0% { transform: translateX(-100%); } 100% { transform: translateX(300%); } }
+82 -20
View File
@@ -267,6 +267,8 @@ async function tauriApi(path, opts = {}) {
return await invoke('export_all_hc22000', { iface: q.get('iface'), out: q.get('out') });
case 'GET /api/update/check':
return await invoke('update_check');
case 'POST /api/update/apply':
return await invoke('update_apply');
default:
return { error: 'rota desconhecida' };
}
@@ -371,12 +373,72 @@ els.btnScan.addEventListener('click', async () => {
}
});
let updateStatus = null;
let updateInProgress = false;
// Progress bar under the update button (indeterminate until a percentage arrives).
function setUpdBar(pct) {
const row = els.btnUpdate.parentElement;
let bar = row.querySelector('.upd-bar');
if (!bar) {
bar = document.createElement('div');
bar.className = 'upd-bar';
bar.innerHTML = '<i></i>';
row.appendChild(bar);
}
bar.classList.toggle('indet', pct == null);
bar.firstChild.style.width = pct == null ? '35%' : `${pct}%`;
}
els.btnUpdate.addEventListener('click', async () => {
if (updateInProgress) return;
if (updateStatus?.update_available) {
updateInProgress = true;
els.btnUpdate.disabled = true;
els.btnUpdate.textContent = 'baixando…';
setUpdBar(null);
let unlisten = null;
if (tauri?.event?.listen) {
try {
unlisten = await tauri.event.listen('update-progress', (event) => {
const phase = event.payload?.phase;
const pct = event.payload?.percent;
setUpdBar(pct);
if (phase === 'downloading') els.btnUpdate.textContent = pct != null ? `baixando… ${pct}%` : 'baixando…';
else if (phase === 'verifying') els.btnUpdate.textContent = 'verificando…';
else if (phase === 'installing') els.btnUpdate.textContent = 'instalando…';
else if (phase === 'restarting') els.btnUpdate.textContent = 'reiniciando…';
});
} catch (_) {}
}
try {
await api('/api/update/apply', { method: 'POST' });
els.btnUpdate.textContent = 'já atualizado';
} catch (err) {
updateInProgress = false;
els.btnUpdate.parentElement.querySelector('.upd-bar')?.remove();
els.btnUpdate.disabled = false;
els.btnUpdate.textContent = `atualizar para ${updateStatus.latest_version}`;
alert('Falha na atualização: ' + (err?.message || err));
} finally {
if (unlisten) unlisten();
}
return;
}
els.btnUpdate.textContent = 'checando…';
const status = await api('/api/update/check');
els.btnUpdate.textContent = status.update_available
? `atualizar para ${status.latest_version}`
: 'já atualizado';
try {
const status = await api('/api/update/check');
updateStatus = status;
els.btnUpdate.textContent = status?.update_available
? `atualizar para ${status.latest_version}`
: 'já atualizado';
} catch (err) {
els.btnUpdate.textContent = 'checar atualização';
alert('Não foi possível verificar atualizações: ' + (err?.message || err));
}
});
const SEC_RANK = {
@@ -637,7 +699,7 @@ const CHAN_TONE_WORD = { ok: 'Boa', warn: 'Atenção', bad: 'Saturado' };
function bandHealth(band, rec) {
if (!rec) return { tone: 'bad', label: 'Sem canal livre nessa banda' };
if (rec.score >= 1.5) return { tone: 'bad', label: 'Até o melhor canal está saturado' };
if (rec.dfs) return { tone: 'warn', label: 'Recomendado é DFS — pode cair com radar por perto' };
if (rec.dfs) return { tone: 'warn', label: 'Recomendado é DFS: pode cair com radar por perto' };
if (rec.score >= 0.5) return { tone: 'warn', label: 'Espectro congestionado' };
return { tone: 'ok', label: 'Boa condição' };
}
@@ -679,9 +741,9 @@ function renderChannels() {
const alert = health.tone !== 'ok'
? `<div class="notice ${health.tone === 'bad' ? 'bad' : 'warn'}">${warnSvg}<div><b>${escapeHtml(health.label)}</b>
<div class="hint" style="margin-top:4px">${band.band === '2.4 GHz'
? 'Nessa banda, prefira sempre 1, 6 ou 11 — canais no meio sobrepõem vizinhos.'
? 'Nessa banda, prefira sempre 1, 6 ou 11: canais no meio sobrepõem vizinhos.'
: rec?.dfs
? 'Canais DFS liberam mais espaço, mas o rádio é obrigado a sair do ar se detectar radar — tenha um canal não-DFS de reserva.'
? 'Canais DFS liberam mais espaço, mas o rádio é obrigado a sair do ar se detectar radar; tenha um canal não-DFS de reserva.'
: 'Considere mudar o AP para o canal recomendado ou mover pra outra banda.'}</div></div></div>`
: '';
@@ -701,7 +763,7 @@ function renderChannels() {
.map((b) => `<button type="button" data-band="${escapeAttr(b.band)}" aria-pressed="${b.band === band.band}">${escapeHtml(b.band)}</button>`)
.join('')}</div>`;
const legend = `<div class="sp-legend"><span><i style="background:#2f8f70"></i>WPA2</span><span><i style="background:#356f9e"></i>WPA3</span><span><i style="background:#b8443a"></i>aberta/WEP</span><span><i style="background:#c98a2e"></i>WPA</span></div>`;
const wpa3 = analysis?.wpa3?.length ? `<p class="hint">${analysis.wpa3.length} rede(s) WPA3 analisada(s) — detalhes na aba do alvo e no relatório.</p>` : '';
const wpa3 = analysis?.wpa3?.length ? `<p class="hint">${analysis.wpa3.length} rede(s) WPA3 analisada(s): detalhes na aba do alvo e no relatório.</p>` : '';
setResultsHtml(`${alertsHtml()}${alert}<div class="ap-card channel-card">
<div class="channel-head">${switches}${legend}</div>
@@ -1078,7 +1140,7 @@ function bigSparkline(history) {
}
/** Detailed client view: consolidates everything captured about a station —
* identity hints, associated AP, signal history, and event timeline — in one modal. */
* identity hints, associated AP, signal history, and event timeline, in one modal. */
function renderClientDetail(clients) {
const client = clients.find((c) => c.mac === attack.timelineMac);
if (!client) return '';
@@ -1269,7 +1331,7 @@ function eviltwinHtml() {
: job.error
? `Falha: ${job.error}`
: `${jobStatusLabel(job.status)} · ${job.attempts ?? 0} tentativa(s) no portal${job.last_attempt ? ` · última: ${attemptWord[job.last_attempt] || job.last_attempt}` : ''}`
: 'Clona o AP (aberto) numa segunda interface e sobe um portal pedindo a senha de novo. A senha só é aceita se bater de verdade com o handshake já capturado — não é um "aceita qualquer coisa".';
: 'Clona o AP (aberto) numa segunda interface e sobe um portal pedindo a senha de novo. A senha só é aceita se bater de verdade com o handshake já capturado; não é um "aceita qualquer coisa".';
return `<section class="attack-card attack-wide eviltwin-card">
<h3>Evil Twin + portal cativo</h3>
<p class="hint">Exige um handshake quebrável já capturado deste AP (aba Handshake). Precisa de <span class="mono">hostapd</span> instalado e de uma <strong>segunda</strong> interface Wi-Fi em modo AP, diferente da que está capturando.</p>
@@ -1294,10 +1356,10 @@ function enterpriseTwinHtml(ap) {
? job.error
? `Falha: ${job.error}`
: `${jobStatusLabel(job.status)} · ${job.captured ?? 0} credencial(is) capturada(s)${job.last_identity ? ` · última: ${job.last_identity}` : ''}`
: 'Clona o AP numa segunda interface e deixa o hostapd-wpe aceitar a autenticação EAP de qualquer cliente. A credencial sai sozinha, como parte do próprio 802.1X — sem portal, sem ação humana.';
: 'Clona o AP numa segunda interface e deixa o hostapd-wpe aceitar a autenticação EAP de qualquer cliente. A credencial sai sozinha, como parte do próprio 802.1X, sem portal, sem ação humana.';
return `<section class="attack-card attack-wide eviltwin-card">
<h3>Evil Twin Enterprise (802.1X)</h3>
<p class="hint">Rede Enterprise detectada (AKM 802.1X) — aqui a credencial é enviada automaticamente pelo cliente durante o handshake EAP, não precisa de portal. Exige <span class="mono">hostapd-wpe</span> instalado (não vem com o Sabiá: é um patch no build do hostapd — <a href="https://github.com/aircrack-ng/hostapd-wpe" target="_blank" rel="noopener">github.com/aircrack-ng/hostapd-wpe</a>) e uma <strong>segunda</strong> interface Wi-Fi em modo AP.</p>
<p class="hint">Rede Enterprise detectada (AKM 802.1X): aqui a credencial é enviada automaticamente pelo cliente durante o handshake EAP, não precisa de portal. Exige <span class="mono">hostapd-wpe</span> instalado (não vem com o Sabiá: é um patch no build do hostapd, <a href="https://github.com/aircrack-ng/hostapd-wpe" target="_blank" rel="noopener">github.com/aircrack-ng/hostapd-wpe</a>) e uma <strong>segunda</strong> interface Wi-Fi em modo AP.</p>
<div class="field-row">
<label class="field"><span class="field-label">Interface do clone (2ª placa)</span><input id="entTwinIface" class="input mono" value="${escapeAttr(attack.entTwinApIface || '')}" placeholder="ex.: wlan1" spellcheck="false"></label>
</div>
@@ -1307,7 +1369,7 @@ function enterpriseTwinHtml(ap) {
</div>
<p class="hint${job?.error ? ' bad' : ''}" id="entTwinResult">${escapeHtml(result)}</p>
${job && job.captured ? `<p class="hint">Log de credenciais (p/ <span class="mono">john --format=netntlm</span> ou reformatar pro hashcat -m 5500): <span class="mono">${escapeHtml(job.log_path)}</span></p>` : ''}
<p class="hint">Limitação honesta: o certificado TLS do clone é autoassinado. Dispositivo que valida a cadeia de certificado da rede (comum em perfil corporativo/MDM atualizado) vai recusar ou avisar o usuário — essa é a defesa que deveria existir. Funciona contra configuração sem essa validação.</p>
<p class="hint">Limitação honesta: o certificado TLS do clone é autoassinado. Dispositivo que valida a cadeia de certificado da rede (comum em perfil corporativo/MDM atualizado) vai recusar ou avisar o usuário; essa é a defesa que deveria existir. Funciona contra configuração sem essa validação.</p>
</section>`;
}
@@ -1425,11 +1487,11 @@ function renderAttacks(ap, clients, hs) {
</div>
<p class="hint" id="exportResult"></p>
<label class="field"><span class="field-label">Dicionário (vazio = embutido, 9,7 milhões de senhas)</span><input id="wordlist" class="input mono" value="${escapeAttr(attack.wordlist)}" placeholder="dicionário próprio, opcional" spellcheck="false"></label>
<label class="auth-check"><input type="checkbox" id="crackRules"${attack.crackRules ? ' checked' : ''}> Aplicar regras de mutação (maiúscula, sufixos, leet — multiplica o tempo)</label>
<label class="auth-check"><input type="checkbox" id="crackRules"${attack.crackRules ? ' checked' : ''}> Aplicar regras de mutação (maiúscula, sufixos, leet; multiplica o tempo)</label>
<button type="button" class="btn primary" data-act="crack" data-needs-auth ${crackable.length ? '' : 'data-locked="1"'}>Quebrar senha</button>
<div id="crackProgress">${crackHtml()}</div>
<p class="hint" style="margin-top:14px">Força bruta por máscara — sem dicionário, testa toda combinação do padrão. <span class="mono">?d</span> dígito, <span class="mono">?l</span> minúscula, <span class="mono">?u</span> maiúscula, <span class="mono">?s</span> símbolo, <span class="mono">?a</span> qualquer um; o resto é literal.</p>
<p class="hint" style="margin-top:14px">Força bruta por máscara: sem dicionário, testa toda combinação do padrão. <span class="mono">?d</span> dígito, <span class="mono">?l</span> minúscula, <span class="mono">?u</span> maiúscula, <span class="mono">?s</span> símbolo, <span class="mono">?a</span> qualquer um; o resto é literal.</p>
<label class="field"><span class="field-label">Máscara</span><input id="crackMask" class="input mono" value="${escapeAttr(attack.crackMask || '')}" placeholder="ex.: ?d?d?d?d?d?d?d?d" spellcheck="false"></label>
<button type="button" class="btn primary" data-act="crack-mask" data-needs-auth ${crackable.length ? '' : 'data-locked="1"'}>Força bruta por máscara</button>
</section>
@@ -1523,7 +1585,7 @@ async function loadSnapshot() {
// While startDeauthJob is restarting capture and waiting for the AP
// to reappear in the scan, the fresh session returns empty for a few poll
// cycles — without this guard, renderTarget() treats "AP not seen yet"
// cycles, without this guard, renderTarget() treats "AP not seen yet"
// as "AP gone" and closes the modal underneath the user mid-action.
//
let resumingForBssid = null;
@@ -2327,7 +2389,7 @@ els.reportDownload.addEventListener('click', async () => {
a.download = `sabia-${current.replace(/[^0-9a-z]/gi, '')}.html`;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 2000);
els.reportStatus.textContent = 'HTML baixado — abre offline e imprime em A4.';
els.reportStatus.textContent = 'HTML baixado: abre offline e imprime em A4.';
} else {
window.open(reportUrl(current, true), '_blank', 'noopener');
}
@@ -2378,7 +2440,7 @@ async function poll() {
els.wave.classList.remove('scanning');
lastSnapshot = snap;
renderResults(snap.access_points);
alert('A captura parou sozinha: ' + (snap.error || 'motivo desconhecido — confira se o adaptador ainda está conectado.'));
alert('A captura parou sozinha: ' + (snap.error || 'motivo desconhecido: confira se o adaptador ainda está conectado.'));
} else if (snap?.access_points) {
lastSnapshot = snap;
renderResults(snap.access_points);
@@ -2411,11 +2473,11 @@ async function checkElevation() {
if (elevated) return;
notice.hidden = false;
msg.textContent = 'Pedindo privilégio de administrador — necessário pra modo monitor e captura…';
msg.textContent = 'Pedindo privilégio de administrador: necessário pra modo monitor e captura…';
retry.hidden = true;
retry.addEventListener('click', async () => {
msg.textContent = 'Pedindo privilégio de administrador — necessário pra modo monitor e captura…';
msg.textContent = 'Pedindo privilégio de administrador: necessário pra modo monitor e captura…';
retry.hidden = true;
await tauri.core.invoke('relaunch_elevated').catch((e) => {
msg.textContent = String(e);
+32 -25
View File
@@ -12,6 +12,12 @@ export const EN = {
'checando…': 'checking…',
'atualizar para {n}': 'update to {n}',
'já atualizado': 'already up to date',
'baixando…': 'downloading…',
'verificando…': 'verifying…',
'instalando…': 'installing…',
'reiniciando…': 'restarting…',
'Falha na atualização:': 'Update failed:',
'Não foi possível verificar atualizações:': 'Could not check for updates:',
// topbar
'Painel de captura': 'Capture dashboard',
@@ -20,8 +26,8 @@ export const EN = {
'modo gerenciado': 'managed mode',
// elevation / notices
'Pedindo privilégio de administrador — necessário pra modo monitor e captura…':
'Requesting administrator privilege — needed for monitor mode and capture…',
'Pedindo privilégio de administrador: necessário pra modo monitor e captura…':
'Requesting administrator privilege: needed for monitor mode and capture…',
'tentar de novo': 'try again',
'Não foi possível obter privilégio de administrador.': 'Could not get administrator privilege.',
'Use somente em redes próprias ou com autorização explícita do responsável. Toda ativação de modo monitor e sessão de captura fica registrada na trilha de auditoria local.':
@@ -178,8 +184,8 @@ export const EN = {
'A placa não está capturando nada': 'The adapter is not capturing anything',
'Nenhum quadro recebido depois de alguns segundos saltando canais — esta placa pode aceitar ativar o modo monitor sem conseguir capturar de verdade (comum em Wi-Fi interna de notebook). Tente um adaptador USB dedicado a modo monitor/injeção.':
'No frame received after several seconds of channel hopping — this adapter may accept turning monitor mode on without actually being able to capture (common with a laptop\'s built-in Wi-Fi). Try a USB adapter dedicated to monitor mode/injection.',
'motivo desconhecido — confira se o adaptador ainda está conectado.':
'unknown reason — check whether the adapter is still connected.',
'motivo desconhecido: confira se o adaptador ainda está conectado.':
'unknown reason: check whether the adapter is still connected.',
'Clientes e handshake': 'Clients and handshake',
'Nenhum cliente visto.': 'No client seen.',
'Associe ou gere tráfego na rede para que o Sabiá identifique estações.': 'Associate or generate traffic on the network so Sabiá can identify stations.',
@@ -221,8 +227,8 @@ export const EN = {
'Selecione um handshake.': 'Select a handshake.',
'Informe o dicionário.': 'Enter the wordlist.',
'Informe o caminho do .pcap.': 'Enter the .pcap path.',
'Força bruta por máscara — sem dicionário, testa toda combinação do padrão.':
'Mask brute force — no wordlist, tests every combination of the pattern.',
'Força bruta por máscara: sem dicionário, testa toda combinação do padrão.':
'Mask brute force: no wordlist, tests every combination of the pattern.',
'dígito,': 'digit,',
'minúscula,': 'lowercase,',
'maiúscula,': 'uppercase,',
@@ -276,8 +282,8 @@ export const EN = {
'Status: {n}': 'Status: {n}',
'tamanho inválido': 'invalid length',
'· última: {n}': '· last: {n}',
'Clona o AP (aberto) numa segunda interface e sobe um portal pedindo a senha de novo. A senha só é aceita se bater de verdade com o handshake já capturado — não é um "aceita qualquer coisa".':
'Clones the AP (open) on a second interface and shows a portal asking for the password again. The password is only accepted if it truly matches the already-captured handshake — it is not an "accept anything" page.',
'Clona o AP (aberto) numa segunda interface e sobe um portal pedindo a senha de novo. A senha só é aceita se bater de verdade com o handshake já capturado; não é um "aceita qualquer coisa".':
'Clones the AP (open) on a second interface and shows a portal asking for the password again. The password is only accepted if it truly matches the already-captured handshake; it is not an "accept anything" page.',
'Exige um handshake quebrável já capturado deste AP (aba Handshake). Precisa de':
'Requires a crackable handshake already captured for this AP (Handshake tab). Needs',
'instalado e de uma': 'installed and a',
@@ -296,17 +302,17 @@ export const EN = {
'hostapd não está instalado (sudo apt install hostapd) — necessário pro Evil Twin':
'hostapd is not installed (sudo apt install hostapd) — needed for Evil Twin',
'{n} · {n} credencial(is) capturada(s){n}': '{n} · {n} credential(s) captured{n}',
'Clona o AP numa segunda interface e deixa o hostapd-wpe aceitar a autenticação EAP de qualquer cliente. A credencial sai sozinha, como parte do próprio 802.1X — sem portal, sem ação humana.':
'Clones the AP on a second interface and lets hostapd-wpe accept the EAP authentication from any client. The credential comes out on its own, as part of 802.1X itself — no portal, no human action.',
'Rede Enterprise detectada (AKM 802.1X) — aqui a credencial é enviada automaticamente pelo cliente durante o handshake EAP, não precisa de portal. Exige':
'Enterprise network detected (AKM 802.1X) — here the credential is sent automatically by the client during the EAP handshake, no portal needed. Requires',
'instalado (não vem com o Sabiá: é um patch no build do hostapd —':
'installed (not bundled with Sabiá: it is a patch on the hostapd build —',
'Clona o AP numa segunda interface e deixa o hostapd-wpe aceitar a autenticação EAP de qualquer cliente. A credencial sai sozinha, como parte do próprio 802.1X, sem portal, sem ação humana.':
'Clones the AP on a second interface and lets hostapd-wpe accept the EAP authentication from any client. The credential comes out on its own, as part of 802.1X itself, no portal, no human action.',
'Rede Enterprise detectada (AKM 802.1X): aqui a credencial é enviada automaticamente pelo cliente durante o handshake EAP, não precisa de portal. Exige':
'Enterprise network detected (AKM 802.1X): here the credential is sent automatically by the client during the EAP handshake, no portal needed. Requires',
'instalado (não vem com o Sabiá: é um patch no build do hostapd,':
'installed (not bundled with Sabiá: it is a patch on the hostapd build,',
') e uma': ') and a',
'interface Wi-Fi em modo AP.': 'Wi-Fi interface in AP mode.',
'Iniciar Evil Twin Enterprise': 'Start Enterprise Evil Twin',
'Limitação honesta: o certificado TLS do clone é autoassinado. Dispositivo que valida a cadeia de certificado da rede (comum em perfil corporativo/MDM atualizado) vai recusar ou avisar o usuário — essa é a defesa que deveria existir. Funciona contra configuração sem essa validação.':
'Honest limitation: the clone\'s TLS certificate is self-signed. A device that validates the network\'s certificate chain (common on an updated corporate/MDM profile) will refuse or warn the user — that is the defense that is supposed to exist. It works against configurations without that validation.',
'Limitação honesta: o certificado TLS do clone é autoassinado. Dispositivo que valida a cadeia de certificado da rede (comum em perfil corporativo/MDM atualizado) vai recusar ou avisar o usuário; essa é a defesa que deveria existir. Funciona contra configuração sem essa validação.':
'Honest limitation: the clone\'s TLS certificate is self-signed. A device that validates the network\'s certificate chain (common on an updated corporate/MDM profile) will refuse or warn the user; that is the defense that is supposed to exist. It works against configurations without that validation.',
'essa rede não é WPA2/WPA3-Enterprise (802.1X) — pra rede com senha única (PSK), use o Evil Twin com portal cativo':
'this network is not WPA2/WPA3-Enterprise (802.1X) — for a single-password (PSK) network, use the Evil Twin with captive portal',
'hostapd-wpe não está instalado — não vem com o Sabiá (é um patch sobre o build do hostapd, não um binário pequeno); instale pelo repositório do Kali ou compile https://github.com/aircrack-ng/hostapd-wpe':
@@ -349,8 +355,8 @@ export const EN = {
'{n} AP(s) · recomendado': '{n} AP(s) · recommended',
'· recomendado': '· recommended',
'aberta/WEP': 'open/WEP',
'{n} rede(s) WPA3 analisada(s) — detalhes na aba do alvo e no relatório.':
'{n} WPA3 network(s) analyzed — details in the target tab and report.',
'{n} rede(s) WPA3 analisada(s): detalhes na aba do alvo e no relatório.':
'{n} WPA3 network(s) analyzed: details in the target tab and report.',
'Restrito a 1, 6 e 11 para evitar sobreposição.':
'Limited to 1, 6 and 11 to avoid overlap.',
'Menor pontuação de interferência entre os canais observados.':
@@ -365,17 +371,17 @@ export const EN = {
'Boa condição': 'Good condition',
'Sem canal livre nessa banda': 'No free channel on this band',
'Até o melhor canal está saturado': 'Even the best channel is saturated',
'Recomendado é DFS — pode cair com radar por perto': 'The recommended channel is DFS — it can drop off if radar is detected nearby',
'Recomendado é DFS: pode cair com radar por perto': 'The recommended channel is DFS: it can drop off if radar is detected nearby',
'Espectro congestionado': 'Congested spectrum',
'Canal recomendado': 'Recommended channel',
'Canais ocupados': 'Busy channels',
'APs na banda': 'APs on this band',
'Pior canal': 'Worst channel',
'Canais DFS': 'DFS channels',
'Nessa banda, prefira sempre 1, 6 ou 11 — canais no meio sobrepõem vizinhos.':
'On this band, always prefer 1, 6 or 11 — channels in between overlap neighbors.',
'Canais DFS liberam mais espaço, mas o rádio é obrigado a sair do ar se detectar radar — tenha um canal não-DFS de reserva.':
'DFS channels free up more room, but the radio must go off the air if it detects radar — keep a non-DFS channel as backup.',
'Nessa banda, prefira sempre 1, 6 ou 11: canais no meio sobrepõem vizinhos.':
'On this band, always prefer 1, 6 or 11: channels in between overlap neighbors.',
'Canais DFS liberam mais espaço, mas o rádio é obrigado a sair do ar se detectar radar; tenha um canal não-DFS de reserva.':
'DFS channels free up more room, but the radio must go off the air if it detects radar; keep a non-DFS channel as backup.',
'Considere mudar o AP para o canal recomendado ou mover pra outra banda.':
'Consider moving the AP to the recommended channel or to another band.',
'Canais detalhados ({n})': 'Detailed channels ({n})',
@@ -547,8 +553,8 @@ export const EN = {
'The bundled reaver could not be extracted in this run.',
'Dicionário (vazio = embutido, 9,7 milhões de senhas)': 'Wordlist (empty = bundled, 9.7 million passwords)',
'dicionário próprio, opcional': 'custom wordlist, optional',
'Aplicar regras de mutação (maiúscula, sufixos, leet — multiplica o tempo)':
'Apply mutation rules (uppercase, suffixes, leetspeak — multiplies run time)',
'Aplicar regras de mutação (maiúscula, sufixos, leet; multiplica o tempo)':
'Apply mutation rules (uppercase, suffixes, leetspeak; multiplies run time)',
'Dispositivo': 'Device',
'MAC aleatório': 'Random MAC',
'Cliente {n}': 'Client {n}',
@@ -564,4 +570,5 @@ export const EN = {
'a captura em {n} não está ativa': 'capture on {n} is not active',
'{n} não está disponível; o reaver integrado não pôde ser extraído':
'{n} is not available; the bundled reaver could not be extracted',
'baixando… {n}%': 'downloading… {n}%',
};
+1 -1
View File
@@ -73,7 +73,7 @@
<div class="notice" id="elevateNotice" hidden>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
<span id="elevateMsg">Pedindo privilégio de administrador — necessário pra modo monitor e captura…</span>
<span id="elevateMsg">Pedindo privilégio de administrador: necessário pra modo monitor e captura…</span>
<button id="btnElevateRetry" class="btn" style="margin-left:auto" hidden>tentar de novo</button>
</div>
+1
View File
@@ -13,6 +13,7 @@ name = "sabia"
path = "src/main.rs"
[dependencies]
getrandom = "0.4"
sabia-core = { path = "../sabia-core" }
clap = { version = "4", features = ["derive"] }
serde = { version = "1", features = ["derive"] }
+42 -9
View File
@@ -10,7 +10,6 @@ use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
const INDEX_HTML: &str = include_str!("../../../../apps/gui/ui/index.html");
const APP_CSS: &str = include_str!("../../../../apps/gui/ui/app.css");
@@ -54,12 +53,27 @@ pub fn serve(port: u16, audit_path: std::path::PathBuf, open: bool) -> sabia_cor
Ok(())
}
/// 32 bytes from the operating system's CSPRNG, hex-encoded. The token used to
/// be the startup time in nanoseconds, which anyone on the machine could guess
/// within a small window and use to drive the API (captures, deauth, Evil Twin).
fn gen_token() -> String {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_nanos();
format!("{nanos:x}")
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).expect("operating system random number generator");
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
/// Constant-time check, so response timing does not reveal how much of a
/// guess was right.
fn token_ok(candidate: Option<&str>, expected: &str) -> bool {
let Some(candidate) = candidate else {
return false;
};
let (candidate, expected) = (candidate.as_bytes(), expected.as_bytes());
let mut diff = candidate.len() ^ expected.len();
for (index, byte) in expected.iter().enumerate() {
diff |= usize::from(byte ^ candidate.get(index).copied().unwrap_or(0));
}
diff == 0
}
#[cfg(target_os = "linux")]
@@ -230,7 +244,7 @@ fn handle(
let req = parse_request(&mut stream)?;
if req.path == "/" {
if req.token.as_deref() != Some(expected_token) {
if !token_ok(req.token.as_deref(), expected_token) {
return respond(&mut stream, 401, "text/plain", b"token invalido");
}
return respond(
@@ -242,7 +256,7 @@ fn handle(
}
if req.path == "/api/report.html" {
if req.token.as_deref() != Some(expected_token) {
if !token_ok(req.token.as_deref(), expected_token) {
return respond(&mut stream, 401, "text/plain", b"token invalido");
}
let Some(iface) = req.text("iface") else {
@@ -315,7 +329,7 @@ fn handle(
if !req.path.starts_with("/api/") {
return respond(&mut stream, 404, "text/plain", b"not found");
}
if req.token.as_deref() != Some(expected_token) {
if !token_ok(req.token.as_deref(), expected_token) {
return respond(
&mut stream,
401,
@@ -834,6 +848,25 @@ fn api(engine: &Arc<Engine>, req: &Request) -> (u16, String) {
#[cfg(test)]
mod tests {
#[test]
fn tokens_are_random_and_long() {
let (a, b) = (gen_token(), gen_token());
assert_eq!(a.len(), 64);
assert!(a.bytes().all(|c| c.is_ascii_hexdigit()));
assert_ne!(a, b);
}
#[test]
fn token_check_needs_the_exact_value() {
assert!(token_ok(Some("abc123"), "abc123"));
assert!(!token_ok(Some("abc12"), "abc123"));
assert!(!token_ok(Some("abc1234"), "abc123"));
assert!(!token_ok(Some("abc124"), "abc123"));
assert!(!token_ok(None, "abc123"));
assert!(!token_ok(Some(""), "abc123"));
}
use super::*;
#[test]
Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

+11
View File
@@ -2979,6 +2979,17 @@ impl Engine {
update::apply(&exe)
}
pub fn update_apply_desktop<F>(
&self,
current_exe: &std::path::Path,
on_progress: F,
) -> Result<String>
where
F: Fn(&str),
{
update::apply_desktop_with_progress(current_exe, on_progress)
}
fn session_handshake(
&self,
name: &str,
+155 -53
View File
@@ -35,6 +35,9 @@ pub struct ReportOptions {
const PAGED_MARKER: &str = "<!--SABIA_PAGEDJS-->";
const LOGO_PNG: &[u8] = include_bytes!("../../../logo.png");
/// 128 px copy of the logo for the running header, so the full-size PNG is
/// embedded only once (on the cover).
const LOGO_MARK_PNG: &[u8] = include_bytes!("../assets/logo-mark.png");
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// Encodes the Sabiá logo as a `data:image/png;base64,...` URI so standalone
@@ -340,6 +343,68 @@ fn audit_html(model: &ReportModel) -> String {
)
}
/// Security bucket used to colour a network on the cover motif.
fn security_tone(security: Option<&str>) -> &'static str {
match security.unwrap_or("") {
"Open" | "" => "#ef4444",
"WEP" => "#f97316",
s if s.contains("WPA3") => "#5eead4",
s if s.contains("EAP") => "#93c5fd",
"WPA" => "#f59e0b",
_ => "#fde68a",
}
}
/// Cover motif: concentric Wi-Fi arcs radiating from the logo, one dot per
/// observed network. Distance from the logo follows the signal (stronger is
/// nearer), colour follows the advertised security. Coordinates are in mm on
/// the full A4 cover.
fn cover_motif(model: &ReportModel) -> String {
const CX: f32 = 137.0;
const CY: f32 = 151.0;
let mut out = String::new();
for (i, r) in [72.0f32, 92.0, 112.0, 132.0, 152.0, 172.0]
.iter()
.enumerate()
{
let op = 0.30 - i as f32 * 0.04;
out.push_str(&format!(
"<circle cx=\"{CX}\" cy=\"{CY}\" r=\"{r}\" fill=\"none\" stroke=\"#f59e0b\" stroke-opacity=\"{op:.2}\" stroke-width=\".35\" stroke-dasharray=\"{}\"/>",
if i % 2 == 0 { "none" } else { "1.2 2.4" }
));
}
let aps: Vec<&AccessPoint> = model.access_points.iter().take(64).collect();
let n = aps.len().max(1) as f32;
for (i, ap) in aps.iter().enumerate() {
let sig = ap.signal_dbm.unwrap_or(-80) as f32;
let dist = 72.0 + (-sig - 35.0).clamp(0.0, 45.0) * 1.2;
// Spread over the lower-left arc, away from the title block.
let a = (150.0 + 55.0 * (i as f32 + 0.5) / n).to_radians();
let x = CX + dist * a.cos();
let y = CY + dist * a.sin();
let tone = security_tone(ap.security.as_deref());
let near_logo = x > 50.0;
let label = ap
.ssid
.as_deref()
.filter(|s| !s.is_empty())
.unwrap_or("(oculta)");
out.push_str(&format!(
"<circle cx=\"{x:.1}\" cy=\"{y:.1}\" r=\"3.2\" fill=\"{tone}\" fill-opacity=\".16\"/><circle cx=\"{x:.1}\" cy=\"{y:.1}\" r=\"1.25\" fill=\"{tone}\"/><text x=\"{:.1}\" y=\"{:.1}\" class=\"m-l\"{}>{} · {}</text>",
// The strongest networks sit close to the bird: their label goes to the
// left of the dot so it never runs under the logo.
if near_logo { x - 3.0 } else { x + 3.0 },
y + 0.9,
if near_logo { " text-anchor=\"end\"" } else { "" },
esc(label),
ap.signal_dbm.map(|s| format!("{s} dBm")).unwrap_or_else(|| "—".into()),
));
}
format!(
"<svg class=\"cover-motif\" viewBox=\"0 0 210 297\" preserveAspectRatio=\"none\" aria-hidden=\"true\">{out}</svg>"
)
}
const CSS: &str = r#"
:root {
--ink: #17211a;
@@ -347,7 +412,7 @@ const CSS: &str = r#"
--faint: #838f87;
--line: #d8dfdb;
--soft: #f3f6f3;
--accent: #92400e;
--accent: #b45309;
--accent-soft: #fbe9d9;
--deep: #241705;
--deep2: #140d02;
@@ -359,9 +424,9 @@ const CSS: &str = r#"
--warn-soft: #fbe9d9;
--info: #0e7490;
--info-soft: #d9f0f3;
--display: "Source Serif 4", Georgia, serif;
--body: "Inter", "Segoe UI", system-ui, sans-serif;
--mono: "JetBrains Mono", "SFMono-Regular", Consolas, monospace;
--display: "Inter", "Segoe UI", system-ui, Roboto, sans-serif;
--body: 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; padding: 0; }
@@ -374,8 +439,8 @@ body {
font-variant-numeric: tabular-nums;
}
.report { background: #fff; }
h1, h2, h3 { font-family: var(--display); line-height: 1.15; margin: 0; }
h2 { font-size: 18pt; letter-spacing: -0.01em; margin: 0 0 1mm; color: var(--deep); break-after: avoid; string-set: section content(); }
h1, h2, h3 { font-family: var(--display); font-weight: 800; line-height: 1.15; margin: 0; }
h2 { font-size: 18pt; letter-spacing: -0.01em; margin: 0 0 5mm; color: var(--deep); break-after: avoid; string-set: section content(); }
h2::before { content: ""; display: block; width: 9mm; height: 1mm; background: var(--accent); margin-bottom: 3mm; border-radius: 1mm; }
h3 { font-size: 12.5pt; margin: 0 0 6pt; break-after: avoid; color: var(--deep); }
p { margin: 0 0 8pt; }
@@ -392,25 +457,38 @@ section.chapter:first-of-type { break-before: avoid; }
/* ---------- cover ---------- */
.cover {
page: cover;
height: 297mm; width: 210mm; margin: 0;
display: flex; flex-direction: column; justify-content: space-between;
padding: 22mm 18mm; break-after: page; position: relative; overflow: hidden;
background: radial-gradient(120% 120% at 100% 0%, #3a2409 0%, var(--deep) 45%, var(--deep2) 100%);
color: #fff;
height: 296mm; width: 210mm; margin: 0; padding: 0;
break-after: page; position: relative; overflow: hidden; color: #fff;
background:
radial-gradient(70% 55% at 65% 51%, rgba(249,115,22,.30) 0%, rgba(249,115,22,.08) 45%, rgba(0,0,0,0) 70%),
linear-gradient(160deg, #2a1806 0%, #1a0f04 48%, #0d0702 100%);
}
.cover .top { display: flex; justify-content: space-between; align-items: flex-start; }
.cover .brand { display: flex; align-items: center; gap: 3mm; }
.cover .brand img { width: 11mm; height: 11mm; border-radius: 3mm; display: block; }
.cover .brand span { font-family: var(--display); font-size: 14pt; font-weight: 700; letter-spacing: -0.01em; }
.cover .badge { font: 700 8pt var(--mono); letter-spacing: .14em; text-transform: uppercase; color: #ffd38a; border: 1px solid #a66a2e; background: rgba(255,211,138,.08); padding: 2.5mm 4mm; border-radius: 1mm; white-space: nowrap; }
.cover .mid { margin-top: auto; }
.cover .eyebrow { color: #ffb963; margin-bottom: 4mm; }
.cover h1 { font-size: 40pt; letter-spacing: -0.02em; max-width: 150mm; color: #fff; margin-bottom: 6mm; }
.cover .lead { max-width: 125mm; font-size: 12.5pt; color: #e7d9c4; line-height: 1.6; }
.cover .meta { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6mm; margin-top: 16mm; padding-top: 6mm; border-top: 1px solid rgba(255,255,255,.18); }
.cover .meta dt { font: 500 7.5pt var(--mono); text-transform: uppercase; letter-spacing: .12em; color: #c9b599; margin-bottom: 1.5mm; }
.cover .meta dd { margin: 0; font-size: 10.5pt; color: #fff; }
.cover .foot { font-size: 8.3pt; color: #c9b599; margin-top: 10mm; max-width: 150mm; }
.cover, .cover * { break-inside: avoid; }
.cover-motif { position: absolute; inset: 0; width: 210mm; height: 297mm; }
.cover-motif .m-l { font: 500 2.1px var(--mono); fill: #e9cfa6; fill-opacity: .7; letter-spacing: .05px; }
.cover .hero { position: absolute; left: 72mm; top: 86mm; width: 130mm; height: 130mm; display: block;
filter: drop-shadow(0 0 9mm rgba(249,115,22,.35)); }
.cover .top { position: absolute; left: 18mm; right: 18mm; top: 16mm; display: flex; justify-content: space-between; align-items: center; }
.cover .wordmark { font: 800 11pt var(--body); letter-spacing: .42em; text-transform: uppercase; color: #fff; }
.cover .badges { display: flex; align-items: center; gap: 2.5mm; }
.cover .badge { font: 700 7.5pt var(--mono); letter-spacing: .16em; text-transform: uppercase; color: #e9cfa6; border: 1px solid rgba(233,207,166,.45); padding: 1.8mm 3.2mm; border-radius: 1mm; white-space: nowrap; }
/* FIRST.org TLP 2.0 brand color (amber), matching the sharing-classification badge the Ciberfauna report convention requires. */
.cover .badge-tlp { color: #FFC000; border-color: #FFC000; background: rgba(255,192,0,.07); }
.cover .head { position: absolute; left: 18mm; top: 40mm; width: 128mm; }
.cover .eyebrow { font: 600 8pt var(--mono); letter-spacing: .22em; color: #fb923c; margin: 0 0 5mm; }
.cover h1 { font: 800 38pt/1.02 var(--body); letter-spacing: -0.025em; color: #fff; margin: 0 0 5mm; }
.cover .lead { font-size: 11pt; color: #e7d3b6; line-height: 1.55; max-width: 108mm; margin: 0; }
.cover .strip { position: absolute; left: 18mm; top: 224mm; display: flex; gap: 9mm; }
.cover .strip div { border-top: .8mm solid #f59e0b; padding-top: 2mm; min-width: 22mm; }
.cover .strip div.hot { border-top-color: #ef4444; }
.cover .strip strong { display: block; font: 800 22pt/1 var(--body); color: #fff; letter-spacing: -0.02em; }
.cover .strip span { font: 500 6.8pt var(--mono); letter-spacing: .14em; text-transform: uppercase; color: #c9ad86; }
.cover .meta { position: absolute; left: 18mm; right: 18mm; top: 244mm; display: grid; grid-template-columns: 1.3fr 1fr 1fr 1fr; gap: 6mm; margin: 0; padding-top: 4.5mm; border-top: 1px solid rgba(251,146,60,.35); }
.cover .meta dt { font: 500 7pt var(--mono); text-transform: uppercase; letter-spacing: .16em; color: #c9ad86; margin-bottom: 1.2mm; }
.cover .meta dd { margin: 0; font-size: 9.5pt; color: #fff; white-space: nowrap; }
/* Paged.js measures overflow against the default page's bottom margin even on the
margin-less cover: anything below ~275mm spills onto a second sheet. */
.cover .foot { position: absolute; left: 18mm; right: 18mm; top: 263mm; font-size: 6.8pt; color: #9c8466; margin: 0; }
/* ---------- table of contents ---------- */
.toc { break-after: page; }
@@ -453,7 +531,7 @@ tbody tr { break-inside: avoid; }
tbody tr:nth-child(even) td { background: #f7f9f7; }
.band { margin: 0 0 7mm; break-inside: avoid; }
.band header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 3mm; }
.chan-row { display: grid; grid-template-columns: 11mm 1fr 12mm 30mm; gap: 2mm; align-items: center; font-size: 8.6pt; padding: 1mm 0; }
.chan-row { display: grid; grid-template-columns: 19mm 1fr 12mm 30mm; gap: 2mm; align-items: center; font-size: 8.6pt; padding: 1mm 0; }
.chan-n { font-weight: 600; }
.chan-bar { height: 3.2mm; background: #eef2ef; border-radius: 999px; overflow: hidden; }
.chan-bar i { display: block; height: 100%; background: #b8c8bf; border-radius: 999px; }
@@ -482,14 +560,16 @@ tbody tr:nth-child(even) td { background: #f7f9f7; }
size: A4;
margin: 24mm 16mm 20mm 16mm;
background: #fff;
@top-left { content: "SABIÁ · AUDITORIA WI-FI"; font: 600 7.5pt var(--mono); letter-spacing: .1em; color: var(--faint); vertical-align: bottom; padding-bottom: 4mm; }
@top-center { content: string(section); font: 500 7.5pt var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--faint); vertical-align: bottom; padding-bottom: 4mm; text-align: center; }
@top-right { content: "\25CF USO AUTORIZADO"; font: 700 7.5pt var(--mono); letter-spacing: .1em; color: var(--accent); vertical-align: bottom; padding-bottom: 4mm; text-align: right; white-space: nowrap; }
@top-left { content: __HEADER_LOGO__; vertical-align: bottom; padding-bottom: 3mm; width: 30%; }
@top-center { content: "SABIÁ · " string(section); width: 40%; white-space: nowrap; font: 500 7.5pt var(--mono); letter-spacing: .08em; text-transform: uppercase; color: var(--faint); vertical-align: bottom; padding-bottom: 4mm; text-align: center; }
@top-right { content: "TLP:AMBER \25CF USO AUTORIZADO"; font: 700 7.5pt var(--mono); letter-spacing: .1em; color: var(--accent); vertical-align: bottom; padding-bottom: 4mm; text-align: right; white-space: nowrap; }
@bottom-left { content: string(footline); font: 400 7.5pt var(--mono); color: var(--faint); vertical-align: top; padding-top: 4mm; }
@bottom-right { content: counter(page) " / " counter(pages); font: 700 8pt var(--mono); color: var(--ink); vertical-align: top; padding-top: 4mm; text-align: right; }
}
@page cover {
size: A4;
margin: 0;
background: #0d0702;
@top-left { content: none; } @top-center { content: none; } @top-right { content: none; }
@bottom-left { content: none; } @bottom-right { content: none; }
}
@@ -525,6 +605,16 @@ pub fn render(model: &ReportModel, options: ReportOptions) -> String {
model.title.clone()
};
let logo_data_uri = format!("data:image/png;base64,{}", base64(LOGO_PNG));
// Margin boxes draw `content: url()` at intrinsic size; an SVG wrapper with
// explicit dimensions lets the running header pick its own height.
let mark_data_uri = format!("data:image/png;base64,{}", base64(LOGO_MARK_PNG));
let header_svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"30\" height=\"30\" viewBox=\"0 0 30 30\"><image width=\"30\" height=\"30\" xlink:href=\"{mark_data_uri}\"/></svg>"
);
let header_logo = format!(
"url(\"data:image/svg+xml;base64,{}\")",
base64(header_svg.as_bytes())
);
let footline = format!("Uso autorizado · gerado em {date}");
let overall = if critical > 0 {
"bad"
@@ -541,30 +631,37 @@ pub fn render(model: &ReportModel, options: ReportOptions) -> String {
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>{css}</style>
<script>window.PagedConfig = {{ auto: false }};</script>
{paged}
</head>
<body>
<div class="doc-meta" data-footline="{footline}"></div>
<main class="report">
<section class="cover">
<div class="doc-meta" data-footline="{footline}"></div>
{motif}
<img class="hero" src="{logo}" alt="Sabiá">
<div class="top">
<div class="brand"><img src="{logo}" alt=""><span>Sabiá</span></div>
<span class="badge">Uso autorizado</span>
<span class="wordmark">Sabiá</span>
<div class="badges"><span class="badge badge-tlp">TLP:AMBER</span><span class="badge">Uso autorizado</span></div>
</div>
<div class="mid">
<p class="eyebrow">Relatório de auditoria · redes sem fio</p>
<div class="head">
<p class="eyebrow">CIBERFAUNA · AUDITORIA DE REDES WI-FI</p>
<h1>{title}</h1>
<p class="lead">Achados de configuração, canais, clientes, handshakes e trilha de auditoria da captura, com verificação criptográfica — nenhuma senha é inventada.</p>
<p class="lead">Achados de configuração, canais, clientes, handshakes e trilha de auditoria da captura, com verificação criptográfica. Nenhuma senha é inventada.</p>
</div>
<div>
<dl class="meta">
<div><dt>Interface</dt><dd class="mono">{iface}</dd></div>
<div><dt>Gerado em</dt><dd>{date}</dd></div>
<div><dt>Versão do Sabiá</dt><dd>{version}</dd></div>
<div><dt>Captura</dt><dd>{capture_state}</dd></div>
</dl>
<p class="foot">Documento gerado localmente. Use somente em redes próprias ou com autorização explícita do responsável. Cada ação ativa fica registrada na trilha de auditoria encadeada por hash (seção final).</p>
<div class="strip">
<div><strong>{n_aps}</strong><span>redes</span></div>
<div><strong>{n_clients}</strong><span>clientes</span></div>
<div><strong>{n_hs}</strong><span>handshakes</span></div>
<div class="{crit_cls}"><strong>{critical}</strong><span>achados críticos</span></div>
</div>
<dl class="meta">
<div><dt>Emissão</dt><dd>{date}</dd></div>
<div><dt>Interface · captura</dt><dd><span class="mono">{iface}</span> · {capture_state}</dd></div>
<div><dt>Achados</dt><dd>{critical} críticos · {warnings} atenção</dd></div>
<div><dt>Classificação</dt><dd>TLP:AMBER</dd></div>
</dl>
<p class="foot">Sabiá {version}. Documento gerado localmente. Use somente em redes próprias ou com autorização explícita do responsável. Cada ação ativa fica registrada na trilha de auditoria encadeada por hash (seção final).</p>
</section>
<section class="toc">
@@ -582,7 +679,7 @@ pub fn render(model: &ReportModel, options: ReportOptions) -> String {
</ol>
</section>
<section class="chapter" id="sec-exec">
<section class="chapter chapter-open" id="sec-exec">
<h2>Sumário executivo</h2>
<div class="stats">
{stat_aps}{stat_clients}{stat_hs}{stat_crackable}
@@ -593,46 +690,46 @@ pub fn render(model: &ReportModel, options: ReportOptions) -> String {
<p class="muted">Captura em {iface}, com {frames} quadros processados, {eapol} EAPOL e {deauth} quadros de desautenticação/desassociação. Os dados refletem apenas o que foi visto no ar durante a sessão; não há varredura ativa além das ações listadas na auditoria.</p>
</section>
<section class="chapter" id="sec-findings">
<section class="chapter chapter-open" id="sec-findings">
<h2>Achados</h2>
{findings}
</section>
<section class="chapter" id="sec-channels">
<section class="chapter chapter-open" id="sec-channels">
<h2>Canais e interferência</h2>
<p class="desc">Pontuação menor é melhor. O cálculo pondera sobreposição espectral e intensidade de cada AP; em 2,4 GHz a recomendação fica restrita a 1, 6 e 11.</p>
{channels}
</section>
<section class="chapter" id="sec-aps">
<section class="chapter chapter-open" id="sec-aps">
<h2>Redes observadas</h2>
{aps}
</section>
<section class="chapter" id="sec-clients">
<section class="chapter chapter-open" id="sec-clients">
<h2>Clientes</h2>
<p class="desc">Exibindo até 120 estações ordenadas por volume de quadros.</p>
{clients}
</section>
<section class="chapter" id="sec-hs">
<section class="chapter chapter-open" id="sec-hs">
<h2>Handshakes e PMKID</h2>
{handshakes}
<p class="muted">Handshakes com senha encontrada aparecem com o valor em texto; os demais podem ser exportados em .pcap ou .hc22000 na interface.</p>
</section>
<section class="chapter" id="sec-wpa3">
<section class="chapter chapter-open" id="sec-wpa3">
<h2>WPA3 e PMF</h2>
{wpa3}
</section>
<section class="chapter" id="sec-audit">
<section class="chapter chapter-open" id="sec-audit">
<h2>Trilha de auditoria</h2>
<p class="desc">Últimas 60 entradas, com hash encadeado. A verificação completa fica disponível na interface.</p>
{audit}
</section>
<section class="chapter" id="sec-method">
<section class="chapter chapter-open" id="sec-method">
<h2>Metodologia e limites</h2>
<p>O Sabiá opera em modo monitor, agrega beacons, respostas de probe, associação e EAPOL, e só injeta quadros quando uma ação é confirmada na interface. A análise de canais é uma estimativa de sobreposição, não uma medição de espectro por SDR. A detecção de evil twin é heurística: nomes iguais com seguranças diferentes e rajadas de gerenciamento merecem verificação manual.</p>
<p>O teste de PMF observa reassociação após desautenticação; um resultado inconclusivo não prova que o PMF está ativo. O ataque WPS depende de reaver/bully instalados e de o AP aceitar PIN. Nenhuma senha é inventada: handshakes só aparecem como quebrados quando a verificação criptográfica local confirma a candidata.</p>
@@ -659,7 +756,12 @@ pub fn render(model: &ReportModel, options: ReportOptions) -> String {
</body>
</html>"##,
title = esc(&title),
css = CSS,
css = CSS.replace("__HEADER_LOGO__", &header_logo),
motif = cover_motif(model),
n_aps = stats.aps,
n_clients = stats.clients,
n_hs = stats.handshakes,
crit_cls = if critical > 0 { "hot" } else { "" },
paged = paged,
logo = logo_data_uri,
footline = esc(&footline),
@@ -716,7 +818,7 @@ fn summary_html(model: &ReportModel) -> String {
.count();
let mut parts = Vec::new();
parts.push(format!(
"Foram observadas {} redes e {} estações.",
"Foram observadas {} redes e {} estações",
model.stats.aps, model.stats.clients
));
if open > 0 {
+390 -7
View File
@@ -9,16 +9,16 @@ use crate::error::{Result, SabiaError};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::fs;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::process::Command;
/// Gitea `releases/latest` API endpoint (`tag_name`, `assets[].name`, `assets[].browser_download_url`).
///
const LATEST_RELEASE_URL: &str =
"https://git.lucasrguerra.dev.br/api/v1/repos/lucasrguerra/sabia/releases/latest";
"https://git.lucasrguerra.dev.br/api/v1/repos/ciberfauna/sabia/releases/latest";
/// Human-facing Gitea Releases page for desktop GUI users.
const RELEASES_PAGE_URL: &str = "https://git.lucasrguerra.dev.br/lucasrguerra/sabia/releases";
const RELEASES_PAGE_URL: &str = "https://git.lucasrguerra.dev.br/ciberfauna/sabia/releases";
#[derive(Debug, Deserialize)]
struct Release {
@@ -30,6 +30,8 @@ struct Release {
struct Asset {
name: String,
browser_download_url: String,
#[serde(default)]
size: u64,
}
#[derive(Debug, Clone, serde::Serialize)]
@@ -56,16 +58,32 @@ fn curl_text(url: &str) -> Result<String> {
Ok(String::from_utf8_lossy(&out.stdout).into_owned())
}
fn curl_download(url: &str, dest: &PathBuf) -> Result<()> {
let status = Command::new("curl")
/// Downloads `url` to `dest`, polling the file size to report a percentage (0-100)
/// through `on_pct` while curl runs; `total` is the release asset size (0 = unknown).
fn curl_download(url: &str, dest: &Path, total: u64, on_pct: &dyn Fn(u8)) -> Result<()> {
let mut child = Command::new("curl")
.args(["-fsSL", "-H", "User-Agent: sabia-updater", "-o"])
.arg(dest)
.arg(url)
.status()
.spawn()
.map_err(|e| SabiaError::CommandFailed {
cmd: format!("curl {url}"),
detail: e.to_string(),
})?;
let status = loop {
let waited = child.try_wait().map_err(|e| SabiaError::CommandFailed {
cmd: format!("curl {url}"),
detail: e.to_string(),
})?;
if let Some(st) = waited {
break st;
}
let got = fs::metadata(dest).map(|m| m.len()).unwrap_or(0);
if let Some(pct) = got.saturating_mul(100).checked_div(total) {
on_pct(pct.min(100) as u8);
}
std::thread::sleep(std::time::Duration::from_millis(150));
};
if !status.success() {
return Err(SabiaError::CommandFailed {
cmd: format!("curl {url}"),
@@ -162,7 +180,7 @@ pub fn apply(current_exe: &PathBuf) -> Result<String> {
let tmp_dir = std::env::temp_dir().join("sabia-update");
fs::create_dir_all(&tmp_dir)?;
let archive_path = tmp_dir.join(&asset.name);
curl_download(&asset.browser_download_url, &archive_path)?;
curl_download(&asset.browser_download_url, &archive_path, 0, &|_| {})?;
if let Some(checksum_asset) = checksum_asset {
let expected = curl_text(&checksum_asset.browser_download_url)?;
@@ -246,6 +264,305 @@ fn find_binary(dir: &PathBuf) -> Result<PathBuf> {
})
}
/// Desktop GUI installation type detected at runtime.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DesktopInstall {
/// Linux AppImage: real filesystem path of the .AppImage file (from APPIMAGE env var).
AppImage(PathBuf),
/// Linux Debian package installed via dpkg: `current_exe` is reliable here.
Deb,
/// Windows NSIS installer: downloaded setup executable run with `/S`
/// (silent). Does not relaunch the app on its own — see the comment on
/// the `WindowsInstaller` apply path.
WindowsInstaller,
}
/// Detects the desktop installation type given an optional `APPIMAGE` environment
/// variable value and the current executable path.
pub fn detect_desktop_install_from(
appimage_env: Option<&std::ffi::OsStr>,
current_exe: &Path,
) -> Result<DesktopInstall> {
#[cfg(windows)]
{
let _ = (appimage_env, current_exe);
Ok(DesktopInstall::WindowsInstaller)
}
#[cfg(target_os = "linux")]
{
if let Some(val) = appimage_env {
let path = PathBuf::from(val);
if path.is_file() {
return Ok(DesktopInstall::AppImage(path));
}
}
if current_exe.is_file()
&& current_exe
.extension()
.and_then(|e| e.to_str())
.map(|e| e.eq_ignore_ascii_case("appimage"))
.unwrap_or(false)
{
return Ok(DesktopInstall::AppImage(current_exe.to_path_buf()));
}
Ok(DesktopInstall::Deb)
}
#[cfg(not(any(windows, target_os = "linux")))]
{
let _ = (appimage_env, current_exe);
Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: format!(
"automatic self-update is not supported on this platform; please download manually from {RELEASES_PAGE_URL}"
),
})
}
}
/// Detects the desktop installation type using the live environment.
pub fn detect_desktop_install() -> Result<DesktopInstall> {
let exe = std::env::current_exe()?;
detect_desktop_install_from(std::env::var_os("APPIMAGE").as_deref(), &exe)
}
/// Returns the expected release asset suffix for a desktop installation and CPU architecture.
pub fn gui_asset_suffix_for(install: &DesktopInstall, arch: &str) -> Result<&'static str> {
match install {
DesktopInstall::AppImage(_) => match arch {
"x86_64" => Ok("_amd64.AppImage"),
"aarch64" => Ok("_aarch64.AppImage"),
other => Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: format!("unsupported architecture for AppImage: {other}"),
}),
},
DesktopInstall::Deb => match arch {
"x86_64" => Ok("_amd64.deb"),
"aarch64" => Ok("_arm64.deb"),
other => Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: format!("unsupported architecture for deb package: {other}"),
}),
},
DesktopInstall::WindowsInstaller => match arch {
"x86_64" => Ok("_x64-setup.exe"),
other => Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: format!("unsupported architecture for Windows installer: {other}"),
}),
},
}
}
/// Returns the expected release asset suffix for the current architecture.
pub fn gui_asset_suffix(install: &DesktopInstall) -> Result<&'static str> {
gui_asset_suffix_for(install, std::env::consts::ARCH)
}
/// Downloads, verifies, and installs the latest desktop GUI release in place.
pub fn apply_desktop(current_exe: &Path) -> Result<String> {
apply_desktop_with_progress(current_exe, |_| {})
}
/// Downloads, verifies, and installs the latest desktop GUI release in place,
/// notifying the progress callback of phase transitions (`"downloading"`,
/// `"verifying"`, `"installing"`, `"restarting"`).
pub fn apply_desktop_with_progress<F>(current_exe: &Path, on_progress: F) -> Result<String>
where
F: Fn(&str),
{
let install =
detect_desktop_install_from(std::env::var_os("APPIMAGE").as_deref(), current_exe)?;
let body = curl_text(LATEST_RELEASE_URL)?;
let release: Release = serde_json::from_str(&body)?;
let suffix = gui_asset_suffix(&install)?;
let asset = release
.assets
.iter()
.find(|a| a.name.ends_with(suffix))
.ok_or_else(|| SabiaError::CommandFailed {
cmd: "update".into(),
detail: format!(
"no asset ending with `{suffix}` in release {}",
release.tag_name
),
})?;
let checksum_asset = release
.assets
.iter()
.find(|a| a.name == format!("{}.sha256", asset.name));
let tmp_dir = std::env::temp_dir().join("sabia-desktop-update");
fs::create_dir_all(&tmp_dir)?;
let download_path = tmp_dir.join(&asset.name);
on_progress("downloading");
curl_download(
&asset.browser_download_url,
&download_path,
asset.size,
&|pct| on_progress(&format!("downloading:{pct}")),
)?;
if let Some(checksum_asset) = checksum_asset {
on_progress("verifying");
let expected = curl_text(&checksum_asset.browser_download_url)?;
let expected_hash = expected
.split_whitespace()
.next()
.unwrap_or("")
.to_lowercase();
let data = fs::read(&download_path)?;
let mut hasher = Sha256::new();
hasher.update(&data);
let actual_hash: String = hasher
.finalize()
.iter()
.map(|b| format!("{b:02x}"))
.collect();
if actual_hash != expected_hash {
return Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: "checksum SHA-256 não confere — atualização descartada".into(),
});
}
}
on_progress("installing");
match install {
DesktopInstall::AppImage(target_appimage) => {
#[cfg(target_os = "linux")]
{
let parent_dir = target_appimage.parent().unwrap_or_else(|| Path::new("."));
let temp_name = format!(
".{}.tmp-{}",
target_appimage
.file_name()
.and_then(|n| n.to_str())
.unwrap_or("appimage"),
std::process::id()
);
let temp_file = parent_dir.join(temp_name);
fs::copy(&download_path, &temp_file)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(&temp_file)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(&temp_file, perms)?;
}
fs::rename(&temp_file, &target_appimage)?;
let _ = fs::remove_file(&download_path);
on_progress("restarting");
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
let err = Command::new(&target_appimage)
.args(std::env::args().skip(1))
.exec();
return Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: format!("failed to relaunch AppImage: {err}"),
});
}
}
#[cfg(not(target_os = "linux"))]
{
let _ = (&target_appimage, &download_path);
return Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: "AppImage updates are only supported on Linux".into(),
});
}
}
DesktopInstall::Deb => {
#[cfg(target_os = "linux")]
{
let status = Command::new("dpkg")
.args(["-i"])
.arg(&download_path)
.status()
.map_err(|e| SabiaError::CommandFailed {
cmd: "dpkg -i".into(),
detail: e.to_string(),
})?;
if !status.success() {
return Err(SabiaError::CommandFailed {
cmd: "dpkg -i".into(),
detail: format!("dpkg -i failed with exit code {:?}", status.code()),
});
}
let _ = fs::remove_file(&download_path);
on_progress("restarting");
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
let err = Command::new(current_exe)
.args(std::env::args().skip(1))
.exec();
return Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: format!("failed to relaunch updated app: {err}"),
});
}
}
#[cfg(not(target_os = "linux"))]
{
let _ = (&download_path, current_exe);
return Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: "deb updates are only supported on Linux".into(),
});
}
}
DesktopInstall::WindowsInstaller => {
#[cfg(windows)]
{
// `/S` is the one NSIS silent-install switch with a documented,
// stable meaning. There is no standard NSIS or Tauri flag that
// makes a silent install relaunch the app afterwards — that was
// claimed in an earlier draft of this code and could not be
// verified against NSIS's or Tauri's documentation; passing an
// invented flag to a stock NSIS installer is silently ignored,
// not harmful, but also not a relaunch mechanism. Spawning
// detached and exiting immediately (instead of waiting on the
// child) also avoids a self-deadlock: if the installer's script
// waits for this process to close before it can overwrite the
// running .exe, blocking here on the installer's exit status
// would hang forever. The practical effect: the update installs
// silently, but the app does not reopen itself — the user needs
// to start it again. This needs real-world confirmation on
// Windows before relying on it; if testing shows the bundled
// NSIS template does support an explicit relaunch flag or step,
// wire it in here instead of this comment.
on_progress("restarting");
Command::new(&download_path)
.arg("/S")
.spawn()
.map_err(|e| SabiaError::CommandFailed {
cmd: "installer".into(),
detail: format!("failed to launch installer: {e}"),
})?;
std::process::exit(0);
}
#[cfg(not(windows))]
{
let _ = &download_path;
return Err(SabiaError::CommandFailed {
cmd: "update".into(),
detail: "Windows installer updates are only supported on Windows".into(),
});
}
}
}
#[allow(unreachable_code)]
Ok(release.tag_name)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -258,4 +575,70 @@ mod tests {
let err = apply(&PathBuf::from("C:/Program Files/Sabia/sabia-gui.exe")).unwrap_err();
assert!(err.to_string().contains(RELEASES_PAGE_URL), "{err}");
}
#[test]
fn detect_desktop_install_variants() {
#[cfg(target_os = "linux")]
{
let temp_appimage =
std::env::temp_dir().join(format!("test-sabia-{}.AppImage", std::process::id()));
let _ = fs::write(&temp_appimage, b"dummy appimage");
let res = detect_desktop_install_from(
Some(temp_appimage.as_os_str()),
Path::new("/usr/bin/sabia-gui"),
)
.unwrap();
assert_eq!(res, DesktopInstall::AppImage(temp_appimage.clone()));
let res_fallback = detect_desktop_install_from(None, &temp_appimage).unwrap();
assert_eq!(
res_fallback,
DesktopInstall::AppImage(temp_appimage.clone())
);
let _ = fs::remove_file(&temp_appimage);
let res_deb =
detect_desktop_install_from(None, Path::new("/usr/bin/sabia-gui")).unwrap();
assert_eq!(res_deb, DesktopInstall::Deb);
}
#[cfg(windows)]
{
let res = detect_desktop_install_from(
None,
Path::new("C:/Program Files/Sabia/sabia-gui.exe"),
)
.unwrap();
assert_eq!(res, DesktopInstall::WindowsInstaller);
}
}
#[test]
fn gui_asset_suffix_matches_known_release_naming() {
let appimage = DesktopInstall::AppImage(PathBuf::from("/tmp/Sabia.AppImage"));
assert_eq!(
gui_asset_suffix_for(&appimage, "x86_64").unwrap(),
"_amd64.AppImage"
);
assert_eq!(
gui_asset_suffix_for(&appimage, "aarch64").unwrap(),
"_aarch64.AppImage"
);
let deb = DesktopInstall::Deb;
assert_eq!(gui_asset_suffix_for(&deb, "x86_64").unwrap(), "_amd64.deb");
assert_eq!(gui_asset_suffix_for(&deb, "aarch64").unwrap(), "_arm64.deb");
let win = DesktopInstall::WindowsInstaller;
assert_eq!(
gui_asset_suffix_for(&win, "x86_64").unwrap(),
"_x64-setup.exe"
);
assert!(gui_asset_suffix_for(&appimage, "mips").is_err());
assert!(gui_asset_suffix_for(&deb, "riscv64").is_err());
assert!(gui_asset_suffix_for(&win, "arm").is_err());
}
}
+135
View File
@@ -0,0 +1,135 @@
//! Renders the audit report from a realistic synthetic capture (7 networks,
//! 9 clients, 1 handshake). Set `SABIA_REPORT_OUT=<file.html>` to save the
//! HTML for visual inspection (e.g. `verificar-paginacao.mjs`).
mod common;
use sabia_core::analysis::analyze;
use sabia_core::audit::AuditEntry;
use sabia_core::report::{render, ReportModel, ReportOptions};
use sabia_core::scan::ScanTable;
const NETS: &[(&str, u8, &str, i8)] = &[
("Ciberfauna-Lab", 6, "WPA2", -38),
("Cafe-Livre", 1, "Open", -52),
("Vizinho-Antigo", 11, "WEP", -71),
("Ciberfauna-6E", 36, "WPA3", -47),
("Corp-Radius", 44, "WPA2-EAP", -63),
("", 6, "WPA2", -79),
("IoT-Casa", 1, "WPA2", -58),
];
fn synthetic_model() -> ReportModel {
let mut table = ScanTable::new();
for (i, (ssid, ch, _, sig)) in NETS.iter().enumerate() {
let mut mac = common::ap();
mac[5] = mac[5].wrapping_add(i as u8 + 1);
let freq = if *ch > 14 {
5000 + 5 * *ch as u16
} else {
2407 + 5 * *ch as u16
};
let b = common::beacon_frame(mac, ssid, *ch, &[2]);
table.ingest(&common::radiotap_wrap(&b, freq, *sig));
}
let probes = [
"Ciberfauna-Lab",
"Cafe-Livre",
"Aeroporto-WiFi",
"IoT-Casa",
"Hotel-Guest",
"Corp-Radius",
"Ciberfauna-Lab",
"Casa-Mae",
"Cafe-Livre",
];
for (i, p) in probes.iter().enumerate() {
let mut mac = common::sta();
mac[5] = mac[5].wrapping_add(i as u8 + 1);
let pr = common::probe_request(mac, p);
table.ingest(&common::radiotap_wrap(&pr, 2437, -45 - 4 * i as i8));
}
let (f1, f2) = common::handshake_radiotap_frames("Ciberfauna-Lab", "senha-correta", 2, false);
table.ingest_at(&f1, 10);
table.ingest_at(&f2, 11);
let mut aps = table.access_points();
aps.retain(|a| a.bssid != sabia_core::dot11::mac_to_string(&common::ap()));
for ap in aps.iter_mut() {
if let Some((_, _, sec, sig)) = NETS
.iter()
.find(|n| ap.ssid.as_deref().unwrap_or("") == n.0)
{
ap.security = Some(sec.to_string());
ap.signal_dbm = Some(*sig);
ap.cipher = Some(
match *sec {
"Open" => "—",
"WEP" => "WEP-104",
_ => "CCMP",
}
.into(),
);
ap.pmf = *sec == "WPA3";
ap.pmf_required = *sec == "WPA3";
ap.wps = ap.ssid.as_deref() == Some("IoT-Casa");
}
}
let mut clients = table.clients();
for (i, c) in clients.iter_mut().enumerate() {
c.packets = 900 - 80 * i as u64;
c.vendor = Some(["Apple", "Samsung", "Intel", "Espressif", "Xiaomi"][i % 5].into());
}
let mut handshakes = table.handshakes();
handshakes.truncate(1);
let now = 1_793_700_000;
let analysis = analyze(&aps, 14, now);
let mut stats = table.stats();
stats.aps = aps.len();
stats.frames = 48_213;
stats.deauth_frames = 14;
let audit = (0..6)
.map(|i| AuditEntry {
timestamp: format!("2026-11-03T14:{:02}:10Z", 10 + i * 3),
action: [
"scan.start",
"channel.hop",
"deauth",
"handshake.capture",
"crack.verify",
"report.export",
][i]
.into(),
target: "Ciberfauna-Lab".into(),
detail: "ação confirmada na interface pelo operador".into(),
prev_hash: "0".repeat(64),
hash: format!("{:064x}", 0x9a3f_11c2_u64 * (i as u64 + 7)),
})
.collect();
ReportModel {
title: "Auditoria Wi-Fi do laboratório".into(),
version: "1.0.7".into(),
iface: "wlan0mon".into(),
running: false,
generated_unix: now,
stats,
access_points: aps,
clients,
handshakes,
analysis,
audit,
}
}
#[test]
fn renders_synthetic_capture_report() {
let model = synthetic_model();
assert_eq!(model.access_points.len(), 7);
let html = render(&model, ReportOptions::default());
assert!(html.contains("Ciberfauna-Lab"));
assert!(html.contains("TLP:AMBER"));
assert!(html.contains("class=\"cover-motif\""));
if let Ok(out) = std::env::var("SABIA_REPORT_OUT") {
std::fs::write(out, html).unwrap();
}
}
+1 -1
View File
@@ -33,7 +33,7 @@ The CLI and the desktop app are thin clients: both call the core's `Engine`. The
## Platform
Capture and monitor mode are **Linux** (`AF_PACKET` + netlink). Parsing (`radiotap`, `dot11`, `eapol`, `handshake`), cracking (`crack`) and `.pcap` are cross-platform, being offline — which is why the tests run on Linux in CI.
Capture and monitor mode are **Linux** (`AF_PACKET` + netlink). Parsing (`radiotap`, `dot11`, `eapol`, `handshake`), cracking (`crack`) and `.pcap` are cross-platform, being offline, which is why the tests run on Linux in CI.
## UI transport
+11 -11
View File
@@ -4,7 +4,7 @@
The `sabia` binary has the global option `--audit <file>` (audit trail; default `.sabia-audit.log`) and the commands below. Capture and monitor mode require Linux and root; analysis and cracking run on any platform.
## `iface` — interfaces and monitor mode
## `iface`: interfaces and monitor mode
```bash
sabia iface list # Wi-Fi interfaces and their modes
@@ -12,7 +12,7 @@ sabia iface channels <iface> # channels the radio supports [--json]
sudo sabia iface monitor <iface> on # enable monitor mode (on|off)
```
## `scan` — capture the air
## `scan`: capture the air
```bash
sudo sabia scan <iface> [options]
@@ -30,29 +30,29 @@ sudo sabia scan <iface> [options]
Shows networks (APs), clients and handshakes seen (4-way and PMKID).
## `analyze` — read a `.pcap` offline
## `analyze`: read a `.pcap` offline
```bash
sabia analyze <file.pcap> [--json]
```
## `crack` — dictionary cracking
## `crack`: dictionary cracking
```bash
sabia crack <file.pcap> --wordlist <list.txt> [--bssid <mac>] [--station <mac>] [--rules] [--json]
```
Recomputes the PMK with PBKDF2-HMAC-SHA1 and checks the MIC (4-way) or the PMKID, for WPA/WPA2-PSK. `--bssid`/`--station` filter which handshake to use. `--rules` applies hashcat-style mutations (uppercase, numeric/symbol suffixes, simple leet) to each dictionary word — multiplies the time for real. The desktop app and `sabia ui` additionally offer the bundled 9.7M-password dictionary by default, mask brute force (`?d?l?u?s?a`), and `.hc22000` export.
Recomputes the PMK with PBKDF2-HMAC-SHA1 and checks the MIC (4-way) or the PMKID, for WPA/WPA2-PSK. `--bssid`/`--station` filter which handshake to use. `--rules` applies hashcat-style mutations (uppercase, numeric/symbol suffixes, simple leet) to each dictionary word, multiplies the time for real. The desktop app and `sabia ui` additionally offer the bundled 9.7M-password dictionary by default, mask brute force (`?d?l?u?s?a`), and `.hc22000` export.
## `deauth` — authorized deauthentication test
## `deauth`: authorized deauthentication test
```bash
sudo sabia deauth <iface> --bssid <mac> [--station <mac>] [--count 5] [--reason 7] --yes
```
Without `--station`, the target is broadcast. The **`--yes`** flag confirms you are authorized to test this network — without it, the command refuses. It is recorded in the audit trail.
Without `--station`, the target is broadcast. The **`--yes`** flag confirms you are authorized to test this network, without it, the command refuses. It is recorded in the audit trail.
## `doctor` — diagnostics
## `doctor`: diagnostics
```bash
sabia doctor [--json]
@@ -60,21 +60,21 @@ sabia doctor [--json]
Checks privileges, tools (`iw`, `ip`) and monitor-capable interfaces.
## `audit` — audit trail
## `audit`: audit trail
```bash
sabia audit verify [file] # check the hash-chain integrity
sabia audit show [--limit 20] # latest entries
```
## `update` — updating
## `update`: updating
```bash
sabia update # check for a new version
sabia update --apply # download, verify the SHA-256 and swap the executable
```
## `ui` — desktop/web interface
## `ui`: desktop/web interface
```bash
sabia ui [--port 4337] [--no-open]
Binary file not shown.

Before

Width:  |  Height:  |  Size: 176 KiB

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 179 KiB

After

Width:  |  Height:  |  Size: 180 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 190 KiB

After

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 193 KiB

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 110 KiB

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 113 KiB

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 115 KiB

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

+3 -1
View File
@@ -13,7 +13,7 @@ The desktop app (Tauri) and the browser version (`sabia ui`) are the same front-
- **Authorized-use notice**, always in view: use only on your own networks or with authorization; every monitor activation and capture goes into the local audit trail.
- **Networks seen:** live table with SSID, signal bars, channel and a color-coded security badge (open, WEP, WPA/WPA2, WPA3). Row order is stable (arrival order, signal rounded to 4 dBm buckets) so it doesn't shuffle under the cursor as signal fluctuates.
- **Channels view:** interference/overlap scoring per band with a recommended channel.
- **Network detail → Attacks tab:** directional/continuous deauthentication, PMF probing, clientless PMKID hunting, handshake capture (auto-resumes the capture session if it was stopped), cracking (bundled 9.7M-password dictionary, mutation rules, mask brute force), `.hc22000` export, WPS PIN/Pixie Dust, Evil Twin with captive portal (WPA/WPA2-PSK), and — only shown for 802.1X networks — the Enterprise Evil Twin variant that captures credentials automatically. Every action requires the authorized-use checkbox and is logged to the audit trail.
- **Network detail → Attacks tab:** directional/continuous deauthentication, PMF probing, clientless PMKID hunting, handshake capture (auto-resumes the capture session if it was stopped), cracking (bundled 9.7M-password dictionary, mutation rules, mask brute force), `.hc22000` export, WPS PIN/Pixie Dust, Evil Twin with captive portal (WPA/WPA2-PSK), and, only shown for 802.1X networks, the Enterprise Evil Twin variant that captures credentials automatically. Every action requires the authorized-use checkbox and is logged to the audit trail.
- **Report:** a paginated, printable audit report (cover, table of contents, findings, channel scoring, networks/clients/handshakes, audit trail) previewed in a dialog and printable to PDF from the browser.
<p align="center"><img src="img/attack-light-en.png" width="900" alt="Network detail dialog showing the Attacks tab (deauthentication, handshake capture, cracking, PMF, WPS and Evil Twin)"></p>
@@ -34,3 +34,5 @@ Monitor mode and capture require root/admin. On startup, the app elevates automa
They show the real interface running with synthetic audit data: 7 access points across 2.4 and 5 GHz (covering open, WEP, WPA/WPA2, WPA3 and 802.1X Enterprise), simulated client stations, and captured handshakes. No real third-party network data appears.
Regenerate them all with `scripts/screenshots.sh` (no Wi-Fi hardware needed): it serves the real UI with `sabia ui` and answers `/api/*` from `scripts/screenshots/mock-api.mjs`.
+1 -1
View File
@@ -33,7 +33,7 @@ A CLI e o app desktop são clientes finos: ambos chamam o `Engine` do núcleo. A
## Plataforma
Captura e modo monitor são **Linux** (`AF_PACKET` + netlink). Parsing (`radiotap`, `dot11`, `eapol`, `handshake`), quebra (`crack`) e `.pcap` são multiplataforma, por serem offline — por isso os testes rodam em Linux no CI.
Captura e modo monitor são **Linux** (`AF_PACKET` + netlink). Parsing (`radiotap`, `dot11`, `eapol`, `handshake`), quebra (`crack`) e `.pcap` são multiplataforma, por serem offline, por isso os testes rodam em Linux no CI.
## Transporte da UI
+11 -11
View File
@@ -4,7 +4,7 @@
O binário `sabia` tem a opção global `--audit <arquivo>` (trilha de auditoria; padrão `.sabia-audit.log`) e os comandos abaixo. Captura e modo monitor exigem Linux e root; análise e quebra rodam em qualquer plataforma.
## `iface` — interfaces e modo monitor
## `iface`: interfaces e modo monitor
```bash
sabia iface list # interfaces Wi-Fi e seus modos
@@ -12,7 +12,7 @@ sabia iface channels <iface> # canais que o rádio suporta [--json]
sudo sabia iface monitor <iface> on # liga o modo monitor (on|off)
```
## `scan` — captura o ar
## `scan`: captura o ar
```bash
sudo sabia scan <iface> [opções]
@@ -30,29 +30,29 @@ sudo sabia scan <iface> [opções]
Mostra redes (APs), clientes e handshakes vistos (4-way e PMKID).
## `analyze` — lê um `.pcap` offline
## `analyze`: lê um `.pcap` offline
```bash
sabia analyze <arquivo.pcap> [--json]
```
## `crack` — quebra por dicionário
## `crack`: quebra por dicionário
```bash
sabia crack <arquivo.pcap> --wordlist <lista.txt> [--bssid <mac>] [--station <mac>] [--rules] [--json]
```
Recalcula a PMK com PBKDF2-HMAC-SHA1 e confere o MIC (4-way) ou o PMKID, para WPA/WPA2-PSK. `--bssid`/`--station` filtram qual handshake usar. `--rules` aplica mutações estilo hashcat (maiúscula, sufixos numéricos/símbolos, leet simples) a cada palavra do dicionário — multiplica o tempo de verdade. O app desktop e o `sabia ui` oferecem também o dicionário embutido de 9,7 milhões de senhas por padrão, força bruta por máscara (`?d?l?u?s?a`) e exportação em `.hc22000`.
Recalcula a PMK com PBKDF2-HMAC-SHA1 e confere o MIC (4-way) ou o PMKID, para WPA/WPA2-PSK. `--bssid`/`--station` filtram qual handshake usar. `--rules` aplica mutações estilo hashcat (maiúscula, sufixos numéricos/símbolos, leet simples) a cada palavra do dicionário, multiplica o tempo de verdade. O app desktop e o `sabia ui` oferecem também o dicionário embutido de 9,7 milhões de senhas por padrão, força bruta por máscara (`?d?l?u?s?a`) e exportação em `.hc22000`.
## `deauth` — teste autorizado de desautenticação
## `deauth`: teste autorizado de desautenticação
```bash
sudo sabia deauth <iface> --bssid <mac> [--station <mac>] [--count 5] [--reason 7] --yes
```
Sem `--station`, o destino é broadcast. A flag **`--yes`** confirma que você tem autorização para testar esta rede — sem ela, o comando recusa. Fica na trilha de auditoria.
Sem `--station`, o destino é broadcast. A flag **`--yes`** confirma que você tem autorização para testar esta rede, sem ela, o comando recusa. Fica na trilha de auditoria.
## `doctor` — diagnóstico
## `doctor`: diagnóstico
```bash
sabia doctor [--json]
@@ -60,21 +60,21 @@ sabia doctor [--json]
Confere privilégios, ferramentas (`iw`, `ip`) e interfaces com suporte a modo monitor.
## `audit` — trilha de auditoria
## `audit`: trilha de auditoria
```bash
sabia audit verify [arquivo] # confere a integridade da cadeia por hash
sabia audit show [--limit 20] # últimas entradas
```
## `update` — atualização
## `update`: atualização
```bash
sabia update # verifica se há versão nova
sabia update --apply # baixa, confere o SHA-256 e troca o executável
```
## `ui` — interface gráfica
## `ui`: interface gráfica
```bash
sabia ui [--port 4337] [--no-open]
+4 -2
View File
@@ -11,9 +11,9 @@ O app desktop (Tauri) e a versão no navegador (`sabia ui`) são o mesmo front-e
- **Sidebar de interfaces:** lista as interfaces Wi-Fi; selecione uma para trabalhar. No rodapé ficam a versão e o botão de **atualização** em um clique.
- **Painel de captura:** cabeçalho com o modo atual (managed/monitor), uma **linha de sinal animada**, e os botões **ativar modo monitor** e **iniciar captura**.
- **Aviso de uso autorizado**, sempre à vista: use só em redes próprias ou com autorização; toda ativação de monitor e captura entra na trilha de auditoria local.
- **Redes vistas:** tabela em tempo real com SSID, barras de sinal, canal e um selo de segurança por cor (aberta, WEP, WPA/WPA2, WPA3). A ordem das linhas é estável (ordem de chegada, sinal arredondado em buckets de 4 dBm) — não fica trocando de posição debaixo do cursor conforme o sinal oscila.
- **Redes vistas:** tabela em tempo real com SSID, barras de sinal, canal e um selo de segurança por cor (aberta, WEP, WPA/WPA2, WPA3). A ordem das linhas é estável (ordem de chegada, sinal arredondado em buckets de 4 dBm), não fica trocando de posição debaixo do cursor conforme o sinal oscila.
- **Visão de canais:** pontuação de interferência/sobreposição por banda, com canal recomendado.
- **Detalhe da rede → aba Ataques:** desautenticação direcional/contínua, teste de PMF, caça de PMKID sem cliente, captura de handshake (religa a captura sozinha se ela tiver sido parada), quebra de senha (dicionário embutido de 9,7 milhões de senhas, regras de mutação, força bruta por máscara), exportação `.hc22000`, WPS PIN/Pixie Dust, Evil Twin com portal cativo (WPA/WPA2-PSK) e — só exibido para redes 802.1X — a variante Enterprise do Evil Twin, que captura credenciais automaticamente. Toda ação exige o checkbox de autorização e fica registrada na trilha de auditoria.
- **Detalhe da rede → aba Ataques:** desautenticação direcional/contínua, teste de PMF, caça de PMKID sem cliente, captura de handshake (religa a captura sozinha se ela tiver sido parada), quebra de senha (dicionário embutido de 9,7 milhões de senhas, regras de mutação, força bruta por máscara), exportação `.hc22000`, WPS PIN/Pixie Dust, Evil Twin com portal cativo (WPA/WPA2-PSK) e, só exibido para redes 802.1X, a variante Enterprise do Evil Twin, que captura credenciais automaticamente. Toda ação exige o checkbox de autorização e fica registrada na trilha de auditoria.
- **Relatório:** relatório de auditoria paginado e imprimível (capa, sumário, achados, pontuação de canais, redes/clientes/handshakes, trilha de auditoria), pré-visualizado num diálogo e imprimível em PDF pelo navegador.
<p align="center"><img src="../img/attack-light-pt.png" width="900" alt="Diálogo de detalhes da rede exibindo a aba de Ataques (desautenticação, captura de handshake, quebra de senha, PMF, WPS e Evil Twin)"></p>
@@ -34,3 +34,5 @@ Temas **Auto, Claro e Escuro** e interface em **português e inglês**. O idioma
Elas mostram a interface real rodando com dados sintéticos de auditoria: 7 pontos de acesso cobrindo 2,4 e 5 GHz (aberta, WEP, WPA/WPA2, WPA3 e 802.1X Enterprise), estações de clientes simuladas e handshakes capturados. Nenhum dado de rede real de terceiros é exibido.
Regere todas com `scripts/screenshots.sh` (sem precisar de hardware Wi-Fi): ele serve a interface real com `sabia ui` e responde `/api/*` a partir de `scripts/screenshots/mock-api.mjs`.
+1 -1
View File
@@ -2,7 +2,7 @@
[English](../support.md) · **Português**
Matriz do que existe hoje (versão 1.0.3). Para o que vem a seguir, veja o [ROADMAP](../../ROADMAP.pt-BR.md).
Matriz do que existe hoje (versão 1.0.7). Para o que vem a seguir, veja o [ROADMAP](../../ROADMAP.pt-BR.md).
## Plataformas
+1 -1
View File
@@ -2,7 +2,7 @@
[English](support.md) · [Português](pt-BR/suporte.md)
Matrix of what exists today (version 1.0.3). For what comes next, see the [ROADMAP](../ROADMAP.md).
Matrix of what exists today (version 1.0.7). For what comes next, see the [ROADMAP](../ROADMAP.md).
## Platforms
+13 -4
View File
@@ -76,8 +76,6 @@ case "$platform" in
rm -rf "$bundle/appimage" "$bundle/deb"
tauri build --bundles appimage,deb
cp "$bundle"/appimage/*.AppImage "$bundle"/deb/*.deb ../../../dist-gui/
# Include .sig alongside the bundle when updater signing is enabled.
cp "$bundle"/appimage/*.AppImage.sig ../../../dist-gui/ 2>/dev/null || true
;;
linux-x86_64)
if [ "$(uname -m)" = x86_64 ]; then
@@ -165,7 +163,6 @@ EOF
tauri build --target x86_64-unknown-linux-gnu --bundles appimage,deb
fi
cp "$bundle"/appimage/*.AppImage "$bundle"/deb/*.deb ../../../dist-gui/
cp "$bundle"/appimage/*.AppImage.sig ../../../dist-gui/ 2>/dev/null || true
;;
windows)
rustup target add x86_64-pc-windows-msvc >/dev/null
@@ -173,9 +170,21 @@ EOF
rm -rf "$bundle"
tauri build --runner cargo-xwin --target x86_64-pc-windows-msvc --bundles nsis
cp "$bundle"/*-setup.exe ../../../dist-gui/
cp "$bundle"/*-setup.exe.sig ../../../dist-gui/ 2>/dev/null || true
;;
*) echo "unknown platform: $platform" >&2; exit 2 ;;
esac
(
cd ../../../dist-gui
for asset in *; do
[ -f "$asset" ] || continue
case "$asset" in
*.sha256) ;;
*)
sha256sum "$asset" > "$asset.sha256"
;;
esac
done
)
ls -1 ../../../dist-gui
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env bash
# Regenerates every image in docs/img from the real interface, with synthetic audit data
# (no Wi-Fi hardware needed): `sabia ui` serves the page and the browser answers /api/* from
# scripts/screenshots/mock-api.mjs.
#
# scripts/screenshots.sh [out-dir] # default: docs/img (or $OUT)
#
# Env: CHROME (default ~/.claude/tools/chrome-claude), PUPPETEER_CORE (default the puppeteer-core
# in ~/.claude/tools/node_modules), SABIA (binary to use; default: build target/release/sabia).
set -euo pipefail
cd "$(dirname "$0")/.."
OUT=${1:-${OUT:-docs/img}}
CHROME=${CHROME:-$HOME/.claude/tools/chrome-claude}
PUPPETEER_CORE=${PUPPETEER_CORE:-$HOME/.claude/tools/node_modules/puppeteer-core/lib/esm/puppeteer/puppeteer-core.js}
[ -x "$CHROME" ] || { echo "screenshots: Chrome not found at $CHROME (set CHROME)" >&2; exit 1; }
[ -f "$PUPPETEER_CORE" ] || { echo "screenshots: puppeteer-core not found at $PUPPETEER_CORE (set PUPPETEER_CORE)" >&2; exit 1; }
# The UI is embedded in the binary at compile time, so rebuild (incremental) unless SABIA is given.
if [ -z "${SABIA:-}" ]; then cargo build --release -p sabia-cli; SABIA=target/release/sabia; fi
mkdir -p "$OUT"
OUT=$(cd "$OUT" && pwd)
work=$(mktemp -d)
pid=
cleanup() { [ -n "$pid" ] && kill "$pid" 2>/dev/null || true; rm -rf "$work"; }
trap cleanup EXIT
port=$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1])')
# The audit log goes to the temp dir, never into the repo.
"$SABIA" ui --port "$port" --no-open --audit "$work/audit.log" >"$work/ui.log" 2>&1 &
pid=$!
token=
for _ in $(seq 1 50); do
token=$(grep -o 'token=[A-Za-z0-9]*' "$work/ui.log" | head -1 | cut -d= -f2 || true)
[ -n "$token" ] && break
sleep 0.2
done
[ -n "$token" ] || { echo "screenshots: could not read the UI token" >&2; cat "$work/ui.log" >&2; exit 1; }
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
BASE_URL="http://127.0.0.1:$port" TOKEN="$token" OUT="$OUT" VERSION="$version" CHROME="$CHROME" PUPPETEER_CORE="$PUPPETEER_CORE" \
node scripts/screenshots/capture.mjs
+66
View File
@@ -0,0 +1,66 @@
// Photographs the real Sabiá interface (served by `sabia ui`) with `/api/*` answered by
// mock-api.mjs. Called by scripts/screenshots.sh; env: BASE_URL, TOKEN, OUT, VERSION,
// CHROME, PUPPETEER_CORE.
import { mockFor, LAB_BSSID } from './mock-api.mjs';
const { BASE_URL, TOKEN, OUT, VERSION, CHROME, PUPPETEER_CORE } = process.env;
const puppeteer = (await import(PUPPETEER_CORE)).default;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const browser = await puppeteer.launch({ executablePath: CHROME, args: ['--no-sandbox'], defaultViewport: { width: 1600, height: 940, deviceScaleFactor: 1 } });
async function newPage(theme, lang) {
const page = await browser.newPage();
await page.evaluateOnNewDocument((t, l) => {
try {
localStorage.setItem('sabia-theme', t);
localStorage.setItem('sabia-lang', l);
localStorage.setItem('sabia-view', 'nets');
} catch { /* storage unavailable */ }
}, theme, lang);
await page.setRequestInterception(true);
page.on('request', (req) => {
const u = new URL(req.url());
if (!u.pathname.startsWith('/api/')) return req.continue();
const body = JSON.stringify(mockFor(req.method(), u.pathname, VERSION));
req.respond({ status: 200, contentType: 'application/json', body });
});
await page.goto(`${BASE_URL}/?token=${TOKEN}`, { waitUntil: 'networkidle0' });
await page.emulateMediaFeatures([{ name: 'prefers-color-scheme', value: theme }]);
return page;
}
async function startCapture(page) {
await page.click('#btnScan');
await page.waitForSelector('.net-row', { timeout: 15000 });
await sleep(1500);
}
for (const lang of ['pt', 'en']) {
for (const theme of ['dark', 'light']) {
const page = await newPage(theme, lang);
await startCapture(page);
await page.screenshot({ path: `${OUT}/networks-${theme}-${lang}.png` });
await page.click(`.ssid-btn[data-bssid="${LAB_BSSID}"]`);
await page.waitForSelector('#targetDlg[open]');
await page.click('#targetDlg .tabs [data-tab="attacks"]');
await sleep(600);
await page.click('#authChk');
await sleep(600);
await page.screenshot({ path: `${OUT}/attack-${theme}-${lang}.png` });
await page.close();
}
// Small dialog shot, light theme, as in the docs.
const page = await newPage('light', lang);
await startCapture(page);
await page.click('#settingsBtn');
await page.waitForSelector('#settingsDlg[open]');
await sleep(500);
const r = await page.$eval('#settingsDlg', (el) => { const b = el.getBoundingClientRect(); return { x: b.x, y: b.y, width: b.width, height: b.height }; });
const pad = 24;
await page.screenshot({ path: `${OUT}/settings-language-${lang}.png`, clip: { x: Math.round(r.x - pad), y: Math.round(r.y - pad), width: Math.floor(r.width + 2 * pad), height: Math.floor(r.height + 2 * pad) } });
await page.close();
}
await browser.close();
console.log('ok');
+79
View File
@@ -0,0 +1,79 @@
// Synthetic audit data served in place of `/api/*`, so the real interface can be photographed
// without Wi-Fi hardware. Shapes mirror the serde structs in crates/sabia-core (scan.rs,
// handshake.rs, iface.rs, wps.rs). Everything here is invented: no real network appears.
const now = Math.floor(Date.now() / 1000);
const ap = (o) => ({
bssid: '', ssid: null, hidden: false, channel: null, band: null, freq_mhz: null,
security: null, cipher: null, akm: [], pmf: false, pmf_required: false,
wps: false, wps_locked: null, wps_version: null, wps_manufacturer: null, wps_model: null,
wps_model_number: null, wps_device_name: null, wps_serial: null, vendor: null, country: 'BR',
phy: ['n'], width_mhz: 20, beacon_interval: 100, privacy: true,
signal_dbm: null, max_signal_dbm: null, beacons: 1200, data_frames: 340, clients: [],
first_seen_unix: now - 600, last_seen_unix: now, ...o,
});
const LAB = 'c0:25:e9:1a:2b:3c';
const C = (n) => `02:5a:${n}`;
const access_points = [
ap({ bssid: LAB, ssid: 'Ciberfauna-Lab', channel: 6, band: '2.4 GHz', freq_mhz: 2437, security: 'WPA2', cipher: 'CCMP', akm: ['PSK'], vendor: 'TP-Link', signal_dbm: -42, max_signal_dbm: -42, phy: ['n', 'ax'], clients: ['38:f9:d3:4a:5b:6c', '9c:b6:d0:11:22:33', 'a4:83:e7:44:55:66'] }),
ap({ bssid: '8c:3b:ad:20:00:01', ssid: 'Starlink-HighSpeed', channel: 36, band: '5 GHz', freq_mhz: 5180, security: 'WPA3', cipher: 'CCMP', akm: ['SAE'], pmf: true, pmf_required: true, vendor: 'Starlink', signal_dbm: -50, max_signal_dbm: -50, width_mhz: 80, phy: ['n', 'ac', 'ax'], clients: ['f0:18:98:77:88:99', 'dc:a6:32:aa:bb:cc'] }),
ap({ bssid: 'b0:4e:26:30:00:02', ssid: 'Campus-Guest', channel: 1, band: '2.4 GHz', freq_mhz: 2412, security: 'Open', cipher: null, akm: [], privacy: false, vendor: 'Ubiquiti', signal_dbm: -56, max_signal_dbm: -56, clients: ['3c:22:fb:12:34:56'] }),
ap({ bssid: 'e4:5f:01:40:00:03', ssid: 'Corp-Enterprise', channel: 149, band: '5 GHz', freq_mhz: 5745, security: 'WPA2-EAP', cipher: 'CCMP', akm: ['802.1X'], pmf: true, vendor: 'Cisco', signal_dbm: -60, max_signal_dbm: -60, width_mhz: 80, phy: ['n', 'ac'], clients: ['00:1b:63:84:45:e6', '28:cf:e9:21:43:65'] }),
ap({ bssid: 'fc:ec:da:50:00:04', ssid: 'SmartHome-IoT', channel: 11, band: '2.4 GHz', freq_mhz: 2462, security: 'WPA', cipher: 'TKIP', akm: ['PSK'], wps: true, wps_locked: false, wps_version: '2.0', wps_manufacturer: 'Genérico', wps_model: 'IoT-Hub', vendor: 'Espressif', signal_dbm: -67, max_signal_dbm: -67, phy: ['g', 'n'], clients: ['24:6f:28:99:00:11'] }),
ap({ bssid: '00:1f:33:60:00:05', ssid: 'Netgear-Legacy', channel: 3, band: '2.4 GHz', freq_mhz: 2422, security: 'WEP', cipher: 'WEP', akm: [], wps: true, wps_locked: false, wps_version: '1.0', vendor: 'Netgear', signal_dbm: -72, max_signal_dbm: -72, phy: ['b', 'g'], clients: [] }),
ap({ bssid: 'f8:1a:67:89:ab:cd', ssid: null, hidden: true, channel: 44, band: '5 GHz', freq_mhz: 5220, security: 'WPA2', cipher: 'CCMP', akm: ['PSK'], vendor: 'TP-Link', signal_dbm: -78, max_signal_dbm: -78, width_mhz: 40, phy: ['n', 'ac'], clients: [] }),
];
const client = (mac, bssid, name, vendor, dbm, extra = {}) => ({
mac, display_name: name, vendor, manufacturer: null, model: null, device_name: null,
hostname: name, ip: null, os: null, device: null, random_mac: false, bssid,
signal_dbm: dbm, max_signal_dbm: dbm, packets: 420, probes: [], associated: true,
first_seen_unix: now - 500, last_seen_unix: now,
signal_history: Array.from({ length: 24 }, (_, i) => ({ t: now - (24 - i) * 5, dbm: dbm + ((i * 7) % 5) - 2 })),
events: [{ t: now - 480, kind: 'associação', detail: null }], ...extra,
});
const clients = [
client('38:f9:d3:4a:5b:6c', LAB, 'notebook-lab', 'Apple', -48),
client('9c:b6:d0:11:22:33', LAB, 'estacao-02', 'Intel', -55),
client('a4:83:e7:44:55:66', LAB, 'celular-visita', 'Samsung', -61),
client('f0:18:98:77:88:99', '8c:3b:ad:20:00:01', 'tablet-sala', 'Apple', -58),
client('dc:a6:32:aa:bb:cc', '8c:3b:ad:20:00:01', 'raspberry-lab', 'Raspberry Pi', -63),
client('3c:22:fb:12:34:56', 'b0:4e:26:30:00:02', null, 'Apple', -66),
client('00:1b:63:84:45:e6', 'e4:5f:01:40:00:03', 'ws-financeiro', 'Dell', -64),
client('28:cf:e9:21:43:65', 'e4:5f:01:40:00:03', 'ws-rh', 'Dell', -70),
client('24:6f:28:99:00:11', 'fc:ec:da:50:00:04', 'sensor-estufa', 'Espressif', -69),
];
const handshakes = [{
bssid: LAB, station: '38:f9:d3:4a:5b:6c', ssid: 'Ciberfauna-Lab', kind: '4-way', messages: '1,2,3,4',
complete: true, crackable: true, pmkid: null, key_version: 2, password: null, raw_frames: 4,
first_seen_unix: now - 300, last_seen_unix: now - 300,
}];
const snapshot = {
iface: 'wlan0', running: true, channel: 6,
stats: { frames: 48213, eapol_frames: 4, deauth_frames: 0, aps: access_points.length, clients: clients.length, handshakes: 1 },
access_points, clients, handshakes,
analysis: { bands: [], findings: [], wpa3: [], deauth_60s: 0 },
error: null, warning: null,
};
export function mockFor(method, path, version) {
switch (`${method} ${path}`) {
case 'GET /api/version': return { version };
case 'GET /api/ifaces': return [{ name: 'wlan0', mac: '00:c0:ca:9b:12:34', phy: 'phy0', mode: 'Monitor', up: true }];
case 'POST /api/scan/start': return { ok: true };
case 'GET /api/scan/snapshot': return snapshot;
case 'GET /api/scan/clients': return clients;
case 'GET /api/handshakes': return handshakes;
case 'GET /api/wps/tools': return [{ name: 'reaver', path: 'embutido', bundled: true }, { name: 'bully', path: '/usr/bin/bully', bundled: false }];
case 'GET /api/update/check': return { current_version: version, latest_version: version, update_available: false };
default:
return path.endsWith('s') || path.endsWith('/jobs') ? [] : { ok: true };
}
}
export const LAB_BSSID = LAB;