Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,6 @@ Conventions for authoring this skill. This governs how skill content is **writte
never against the authoring machine.
- **If you cannot verify something, mark it `untested` or leave it out.** Never present unconfirmed
behavior as confirmed.
- **Avoid duplicates** by checking in the existing skill documentation if the information is already present. If it is, ensure it's properly linked/routed, but don't duplicate instruction, code blocks or configurations.


14 changes: 13 additions & 1 deletion crowdsec/references/appsec/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,21 +113,33 @@ The smoke test above proves the WAF works. For production you point a real bounc
|---|---|
| `crowdsec-nginx-bouncer` (lua module) | `APPSEC_URL=http://127.0.0.1:7422` in `/etc/crowdsec/bouncers/crowdsec-nginx-bouncer.conf` (shell-style `KEY=VALUE`, empty by default = WAF off). The self-registered `API_KEY` already serves AppSec — reuse it. |
| Traefik (`maxlerebourg/crowdsec-bouncer-traefik-plugin`) | Flat plugin options: `crowdsecAppsecEnabled: true` (default false), `crowdsecAppsecHost: crowdsec:7422` (host:port, no scheme), and the bouncer key in `crowdsecLapiKey`. Full recipe in [../configure/bouncers/web-servers.md](../configure/bouncers/web-servers.md) § Traefik. |
| `crowdsec-caddy-bouncer` (Caddy module) | Equivalent `appsec_url` directive on the bouncer block. |
| `github.com/hslatman/caddy-crowdsec-bouncer` (Caddy module) | Two handlers required in the Caddy route — **`appsec` AND `crowdsec`** (see critical note below). The `appsec_url` field goes in the top-level `crowdsec` app config block. |
| Any other AppSec-aware bouncer | Look for an `appsec_url` / `appsec.url` field; auth is always the bouncer's existing API key. |

After wiring: send a request through the real web server (not directly to 7422) and confirm the verdict propagates. The bouncer's own log should show one line per consultation; AppSec's `cscli metrics show appsec` increments.

> **Critical — Caddy (`hslatman/caddy-crowdsec-bouncer`) requires TWO handlers:**
> the `crowdsec` handler only enforces IP-level bans from LAPI — it does **not** forward requests to port 7422. WAF inspection requires the separate `appsec` handler. Both must be in the route, `appsec` first. If only `crowdsec` is present, AppSec metrics will always show 0 processed and no requests are ever blocked by WAF rules. The `appsec_url` field lives in the top-level `crowdsec` app block. Full Caddyfile and JSON recipes: [../configure/bouncers/web-servers.md](../configure/bouncers/web-servers.md) § Caddy.

See also: [../configure/bouncers/web-servers.md](../configure/bouncers/web-servers.md) for installing the bouncer in the first place.

## Per-environment notes

| Env | What changes |
|---|---|
| **systemd / bare-metal** | The recipe above as-is. |
| **OPNsense / FreeBSD** | Config root is `/usr/local/etc/crowdsec/`; drop acquisition in `acquis.d/appsec.yaml`. The `os-crowdsec` plugin manages the engine — reload with `service crowdsec reload`. No Lua module in the OPNsense nginx package: use the Caddy-based bouncer instead (see [../configure/bouncers/web-servers.md](../configure/bouncers/web-servers.md) § Caddy). Note the LAPI port conflict below. |
| **Docker / compose** | AppSec runs inside the crowdsec container and must `listen_addr: 0.0.0.0:7422`. Bouncer containers reach it via the service name + internal port (`appsec_url: http://crowdsec:7422`), not the published port. The acquisition file is mounted from the host or baked into a customised image. `docker compose exec crowdsec cscli appsec-*` for management commands. **Containerized lua bouncers need a DNS `resolver` — see [../install/docker.md](../install/docker.md) § Bouncer key bootstrap.** |
| **Kubernetes / Helm** | The official chart has `appsec.enabled: true` plus values for `appsec.listen_addr`, `appsec.config`, and a separate `appsec` Service. Bouncers target the AppSec Service DNS name. Required collections/rules can be listed in the chart's hub config. |

### OPNsense / FreeBSD: LAPI port conflict

CrowdSec LAPI binds to `127.0.0.1:8080` by default. Any bouncer that listens on `*:8080` (wildcard) will shadow the LAPI only from external IPs — loopback (`127.0.0.1`) always routes to LAPI. This means:

- **Do not test via `127.0.0.1:8080`** — you will hit LAPI, not the bouncer.
- Use the host's internal or external IP for end-to-end testing (e.g. `172.31.x.x:8080` on an AWS instance).
- If both LAPI and the bouncer bind `:8080`, move the **bouncer's backend** to another port (e.g. `:8888`) and keep the bouncer frontend on `:8080` listening on `0.0.0.0` only — LAPI stays on its loopback bind and the conflict is resolved.

## Advanced shapes

- **AppSec on a separate host** from the engine: set `listen_addr` to the private interface and protect with mTLS (cert configuration on both bouncer and AppSec sides; documented at <https://docs.crowdsec.net/docs/next/appsec/advanced_deployments>).
Expand Down
70 changes: 70 additions & 0 deletions crowdsec/references/configure/acquisition.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ problem is here.
|---|---|
| Single legacy file | `/etc/crowdsec/acquis.yaml` (`acquisition_path` in `config.yaml`) |
| Drop-in dir (preferred) | `/etc/crowdsec/acquis.d/*.yaml` (`acquisition_dir` in `config.yaml`) — one file per source set |
| OPNsense / FreeBSD | `/usr/local/etc/crowdsec/acquis.d/` — same drop-in model; `os-crowdsec` plugin drops files here automatically |
| Docker | Bind-mount or env (`COLLECTIONS`, plus a mounted `acquis.d`); see Per-environment notes |
| Kubernetes | The chart's `config.acquisition` values render into the same `acquis.d` files |

Expand Down Expand Up @@ -50,6 +51,38 @@ Glob expansion is evaluated at startup; files created later that match are **not
up until reload. For high-rotation logs prefer the directory plus a glob over naming each
file.

| Field | Notes |
|---|---|
| `filenames` | List of paths; globs are supported. |
| `labels.type` | **Required.** The parser chain selector. |
| `force_inotify` | Set `true` to force inotify-based watching on filesystems that don't advertise it (some NFS mounts, older kernels). |
| `poll_without_inotify` | Set `true` when the file is a **symlink** that rotates by relinking (e.g. OPNsense's `latest.log` pattern). inotify watches the inode, not the path — without polling the engine misses rotation events. |

### OPNsense log paths

OPNsense writes logs in RFC 5424 syslog format. The path pattern is `/var/log/<facility>/latest.log` where `latest.log` is always a symlink to the newest rotation file.

| Log | Path | `labels.type` |
|---|---|---|
| SSH authentication | `/var/log/system/latest.log` | `syslog` |
| nginx access/error | `/var/log/nginx/access.log` | `nginx` |
| pf firewall | `/var/log/filter/latest.log` | `pf` |
| OPNsense GUI / API | `/var/log/audit/latest.log` | (configd audit — **not SSH auth**) |

> **Pitfall — SSH log path on OPNsense:** The `os-crowdsec` plugin ships `acquis.d/opnsense.yaml` which maps `/var/log/audit/latest.log` to the `sshd` collection. This file is the **configd** audit log (web admin actions), not SSH auth. Real SSH authentication events land in `/var/log/system/latest.log` (syslog format). Add a separate `acquis.d/ssh.yaml` pointing at the right path.

Because OPNsense's `latest.log` files are symlinks that rotate, always include both options:

```yaml
# acquis.d/ssh.yaml — SSH auth on OPNsense/FreeBSD
filenames:
- /var/log/system/latest.log
labels:
type: syslog
force_inotify: true
poll_without_inotify: true
```

## journald datasource

```yaml
Expand All @@ -64,6 +97,8 @@ The filter strings are passed straight to `journalctl`. After reload the source
metrics as `journalctl:journalctl-_SYSTEMD_UNIT=ssh.service`. A typo in the unit name is
silent — the source reads **0 lines** rather than erroring.

Not available on FreeBSD/OPNsense (no systemd).

## docker datasource

For a CrowdSec **container** reading other containers' stdout/stderr via the Docker socket:
Expand All @@ -80,6 +115,28 @@ Requires `/var/run/docker.sock` mounted into the CrowdSec container. The source
`docker:<container-name>`. Use this instead of a file source when apps log to stdout (the
12-factor norm in Docker/compose) — there is no log file to bind-mount.

## AppSec datasource

Tells the engine to spin up an inline WAF listener. This is **not a log reader** — it opens a TCP port that bouncers forward HTTP requests to. The CrowdSec agent evaluates them in-process and returns an allow/block verdict.

```yaml
# acquis.d/appsec.yaml
source: appsec
appsec_config: crowdsecurity/appsec-default
labels:
type: appsec
listen_addr: 127.0.0.1:7422
```

| Field | Notes |
|---|---|
| `source: appsec` | **Required.** Identifies the datasource type. Without it the engine ignores the block. |
| `appsec_config` | Hub-installed config name. `crowdsecurity/appsec-default` is included by both canonical WAF collections and carries the health-check test rule. |
| `listen_addr` | `127.0.0.1:7422` for loopback (single-host bouncer); `0.0.0.0:7422` for cross-host bouncers. |
| `labels.type: appsec` | Used by out-of-band scenarios. Keep as `appsec`. |

The WAF collections must be installed before the engine will start with this config — see [../appsec/deploy.md](../appsec/deploy.md).

## When to pick which source

| Logs come from… | `source:` |
Expand Down Expand Up @@ -115,6 +172,14 @@ sudo cscli explain --log 'May 21 09:00:00 host sshd[123]: Failed password for in
sudo cscli explain --file /var/log/nginx/access.log --type nginx # replay a whole file
```

On OPNsense/FreeBSD:

```bash
service crowdsec configtest
service crowdsec reload
cscli metrics show acquisition
```

## Pitfalls

- **Missing/wrong `labels.type`:** lines read but all `unparsed`. The single most common
Expand All @@ -130,11 +195,16 @@ sudo cscli explain --file /var/log/nginx/access.log --type nginx # replay a wh
- **Globs are startup-only:** new files matching a glob need a reload to be acquired.
- **Edited but not applied:** `crowdsec -t` validates the file but does not load it — you
still need `systemctl reload crowdsec` (or recreate the container / `helm upgrade`).
- **Symlinked `latest.log` stops updating after rotation:** inotify watches the old inode — add `poll_without_inotify: true` (and optionally `force_inotify: true`).
- **SSH not detected on OPNsense:** acquisition points at `/var/log/audit/latest.log` (configd, not auth) — point at `/var/log/system/latest.log` with `labels.type: syslog`.
- **AppSec source fails to start:** WAF collections not installed — `cscli collections install crowdsecurity/appsec-virtual-patching crowdsecurity/appsec-generic-rules`.

## Per-environment notes

| Env | What changes |
|---|---|
| **systemd / bare-metal** | Recipes above as-is. Edit `acquis.d/*.yaml`, `crowdsec -t`, `systemctl reload crowdsec`. |
| **OPNsense / FreeBSD** | Config root is `/usr/local/etc/crowdsec/`; drop-in dir is `/usr/local/etc/crowdsec/acquis.d/`. Use `file` source with `poll_without_inotify: true` for symlinked `latest.log` files. No journald. Reload with `service crowdsec reload`. |
| **Docker / compose** | Mount `./acquis.d:/etc/crowdsec/acquis.d` (and `/var/run/docker.sock` for the docker source). `COLLECTIONS=`/`PARSERS=` env install hub items at start. Run cscli with `docker exec <name> cscli metrics show acquisition`. Recreate the container to apply (a reload signal also works). |
| **Kubernetes / Helm** | Define sources under `config.acquisition` in values; `helm upgrade --reset-then-reuse-values`. Inspect with `kubectl exec -n <ns> <agent-pod> -- cscli metrics show acquisition`. The `k8s_audit` source needs the API server's audit webhook pointed at the agent. |

106 changes: 88 additions & 18 deletions crowdsec/references/configure/bouncers/web-servers.md
Original file line number Diff line number Diff line change
Expand Up @@ -330,14 +330,16 @@ docker exec crowdsec cscli metrics show appsec # Processed/Blocked increment
- **`stream` lag:** a fresh ban lands within `updateIntervalSeconds`; immediate ban-then-curl
looks like a failure. (See [../../debug/bouncer-not-blocking.md](../../debug/bouncer-not-blocking.md).)

## Caddy — `caddy-crowdsec-bouncer`
## Caddy — `github.com/hslatman/caddy-crowdsec-bouncer`

WAF-capable Caddy module ([`hslatman/caddy-crowdsec-bouncer`](https://github.com/hslatman/caddy-crowdsec-bouncer)).
Caddy has no plugin loader, so the module must be **compiled in** — build a custom binary/image
with `xcaddy`.

### Build with the module

**Docker / Linux (Dockerfile):**

```dockerfile
FROM caddy:2.10-builder AS builder
RUN xcaddy build \
Expand All @@ -350,6 +352,24 @@ COPY --from=builder /usr/bin/caddy /usr/bin/caddy
(`/http` enforces decisions; `/appsec` adds the WAF handler. Add `/layer4` only for L4
proxying.) Mint a bouncer key with `cscli bouncers add caddy -o raw`.

**FreeBSD/OPNsense** (no Go in base, no Docker):

```bash
# Download Go binary for freebsd-amd64
fetch https://go.dev/dl/go1.22.4.freebsd-amd64.tar.gz # or latest
tar -C /usr/local -xzf go*.tar.gz
export PATH=$PATH:/usr/local/go/bin

sudo pkg install -y git # xcaddy needs git for module resolution

GOPATH=$HOME/go go install github.com/caddyserver/xcaddy/cmd/xcaddy@latest
GOPATH=$HOME/go $HOME/go/bin/xcaddy build \
--with github.com/hslatman/caddy-crowdsec-bouncer \
--output /tmp/caddy-cs

sudo cp /tmp/caddy-cs /usr/local/bin/caddy-cs
```

### Caddyfile

```caddyfile
Expand Down Expand Up @@ -377,26 +397,76 @@ proxying.) Mint a bouncer key with `cscli bouncers add caddy -o raw`.
}
```

### Verify end-to-end (through Caddy)
### Config (JSON API — for OPNsense/FreeBSD or programmatic use)

The bouncer exposes two handlers and one top-level app:

```json
{
"apps": {
"crowdsec": {
"api_url": "http://127.0.0.1:8080",
"api_key": "<bouncer-key>",
"appsec_url": "http://127.0.0.1:7422",
"ticker_interval": "15s",
"enable_streaming": true,
"appsec_fail_open": false
},
"http": {
"servers": {
"demo": {
"listen": [":8080"],
"routes": [
{
"handle": [
{"handler": "appsec"},
{"handler": "crowdsec"},
{
"handler": "reverse_proxy",
"upstreams": [{"dial": "127.0.0.1:8888"}]
}
]
}
]
}
}
}
}
}
```

| Handler | Function |
|---|---|
| `http.handlers.appsec` | Forwards each request to AppSec (port 7422) for WAF inspection — returns 403 on inband rule match |
| `http.handlers.crowdsec` | Checks the LAPI decision list for the client IP — returns 403 on active ban |

> **Both handlers are required.** `crowdsec` alone silently skips WAF inspection — `cscli metrics show appsec` will show 0 processed. Put `appsec` first in the route.

### Verify end-to-end

```bash
curl -sS -o /dev/null -w 'normal: %{http_code}\n' http://127.0.0.1:8082/ # 200
curl -sS -o /dev/null -w 'appsec block: %{http_code}\n' 'http://127.0.0.1:8082/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php' # 403
docker exec crowdsec cscli decisions add --ip 198.51.100.200 --duration 5m --reason test
sleep 12 # ticker_interval=10s
curl -sS -o /dev/null -w 'banned XFF: %{http_code}\n' -H 'X-Forwarded-For: 198.51.100.200' http://127.0.0.1:8082/ # 403
curl -sS -o /dev/null -w 'clean XFF: %{http_code}\n' -H 'X-Forwarded-For: 203.0.113.9' http://127.0.0.1:8082/ # 200
docker exec crowdsec cscli decisions delete --ip 198.51.100.200
# AppSec block (CVE-2017-9841) → 403
curl -sS -o /dev/null -w 'appsec block: %{http_code}\n' \
'http://<host-ip>:8080/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php'

# LAPI ban block
cscli decisions add --ip <test-ip> --duration 2m --reason test
sleep 16 # wait for streaming ticker
curl -sS -o /dev/null -w 'banned: %{http_code}\n' http://<host-ip>:8080/

cscli metrics show appsec # confirm processed/blocked counters
```

> **Do not test via `127.0.0.1:<bouncer-port>`** if LAPI is on `127.0.0.1:8080` and the bouncer frontend shares port `8080`. Loopback traffic routes to LAPI, not the bouncer. Use the host's internal/external IP instead.

### Pitfalls

- **Module not compiled in:** the stock `caddy` image has no `crowdsec` directive — Caddy
errors on the Caddyfile. You must `xcaddy build` (above) or use a prebuilt image that bundles
the module.
- **Real IP:** without `trusted_proxies` + `client_ip_headers`, Caddy treats the proxy/Docker
hop as the client and bans never match. Set both in the global `servers` block.
- **Handler order:** put `appsec` before `crowdsec` in the route so WAF inspection runs ahead of
decision enforcement.
- **WAF off:** omit `appsec_url` and the module enforces decisions only. AppSec must listen on
`0.0.0.0:7422` for a containerized Caddy to reach it.
- **`crowdsec-caddy-bouncer` / `crowdsecurity/caddy-cs-bouncer` do not exist** — these names return 404 on GitHub and pkg.go.dev. The correct module is `github.com/hslatman/caddy-crowdsec-bouncer`.
- **Module not compiled in:** the stock `caddy` image has no `crowdsec` directive — Caddy errors on the Caddyfile. You must `xcaddy build` (above) or use a prebuilt image that bundles the module.
- **xcaddy needs `git`** — the build fails with "git not found" on a minimal FreeBSD install. `sudo pkg install -y git` first.
- **Build to `/tmp`, then copy** — xcaddy may not have write access to `/usr/local/bin` directly; build to `/tmp/caddy-cs`, then `sudo cp`.
- **Real IP:** without `trusted_proxies` + `client_ip_headers`, Caddy treats the proxy/Docker hop as the client and bans never match. Set both in the global `servers` block.
- **Handler order:** put `appsec` before `crowdsec` in the route so WAF inspection runs ahead of decision enforcement.
- **WAF off:** omit `appsec_url` and the module enforces decisions only. AppSec must listen on `0.0.0.0:7422` for a containerized Caddy to reach it.
- **LAPI port conflict** — see [../../appsec/deploy.md](../../appsec/deploy.md) § OPNsense / FreeBSD: LAPI port conflict.

Loading