netsec-scan: HTTP attack-shape rules over the gateway access log (§4d)
F7 (t_e662b03a) gave every Gateway listener a JSON access line and shipped it to Loki; this is the §4d consumer that had none. New `http_rules.py` classifies candidate lines and `loki.py` reads them through the logging/loki Service proxy with two LogQL queries per tick - a `|~` prefilter for attack-shaped lines and a `sum by (client_ip, peer)` 1-minute matrix for 401/403. Loki does the volume reduction: a calm 10-minute window (5 474 requests / 3.5 MB) puts ~150 lines on the wire. Rules (one line per host+client+category, fingerprint excludes the path): http-traversal, -sqli, -nul-byte, -secret-probe, -vcs-probe, -backup-probe, -scanner-ua, http-auth-brute (401/403 only, >=20/min and >=30 in 5m per coalesce(client_ip, peer)), http-flood (cap 12 new fingerprints/tick). FP control is the point: Forgejo is 93.5 % of the stream, so smart-HTTP git endpoints and browse/archive/RSS URLs on the Forgejo hosts are excluded from path rules, and severity escalates only when the shape is in the path component AND the origin answered 2xx (a 200 on `/?file=../../.env` is the landing page). Measured: 17 639 of 35 445 lines/hour are 303 -> /user/login (3xx, never counted); 293 are 404 crawler churn; the noisiest legitimate 401/403 client does 3/min. Verified on the live stream: calm window 07:03:40-07:13:40Z -> 0 findings, empty stdout, exit 0; the 06:48-06:53Z 91.92.47.0/24 burst -> 8 findings; crafted requests fired all nine rule kinds (public via Cloudflare and direct to the overlay for the peer fallback); first tick baselines silently, next emits, next is silent, deleting one fingerprint re-emits exactly one line. 85 unit tests. Docs: docs/gateway-http-rules.md. run.sh now cds to its own directory so a worktree runs its own code.
This commit is contained in:
parent
bde343c75f
commit
63bac6e06f
9 changed files with 1216 additions and 16 deletions
74
README.md
74
README.md
|
|
@ -23,11 +23,14 @@ investigator agent on a hit is a separate, deliberate step — not done here.
|
||||||
|---|---|
|
|---|---|
|
||||||
| `netsec_scan/` | the program (Python 3, **stdlib only** — no `pip install` on the host) |
|
| `netsec_scan/` | the program (Python 3, **stdlib only** — no `pip install` on the host) |
|
||||||
| `netsec_scan/config.py` | every tunable, next to the measurement it came from |
|
| `netsec_scan/config.py` | every tunable, next to the measurement it came from |
|
||||||
| `netsec_scan/rules.py` | the 8 rules |
|
| `netsec_scan/rules.py` | the 8 flow/metric rules (`Finding` lives here) |
|
||||||
|
| `netsec_scan/http_rules.py` | the §4d gateway access-log rules (classification, FP control, caps) |
|
||||||
| `netsec_scan/flows.py` | collector access (remote byte-offset reads) + Cilium flow parsing |
|
| `netsec_scan/flows.py` | collector access (remote byte-offset reads) + Cilium flow parsing |
|
||||||
| `netsec_scan/prom.py` | PromQL through the k8s API proxy |
|
| `netsec_scan/prom.py` | PromQL through the k8s API proxy |
|
||||||
|
| `netsec_scan/loki.py` | LogQL through the k8s API proxy (gateway access log) |
|
||||||
| `netsec_scan/state.py` | cumulative seen-set, offsets, report counters |
|
| `netsec_scan/state.py` | cumulative seen-set, offsets, report counters |
|
||||||
| `netsec_scan/report.py` | daily baseline report |
|
| `netsec_scan/report.py` | daily baseline report |
|
||||||
|
| `docs/gateway-http-rules.md` | rule catalogue, FP reasoning, measurements for the HTTP rules |
|
||||||
| `run.sh` | entrypoint (`exec python3 -m netsec_scan "$@"` from the repo root) |
|
| `run.sh` | entrypoint (`exec python3 -m netsec_scan "$@"` from the repo root) |
|
||||||
| `tests/` | unit tests + 3 small fixtures recorded from the live collector |
|
| `tests/` | unit tests + 3 small fixtures recorded from the live collector |
|
||||||
|
|
||||||
|
|
@ -37,7 +40,8 @@ Run it by hand:
|
||||||
cd ~/Projects/netsec-agent && ./run.sh # silent tick, exit 0
|
cd ~/Projects/netsec-agent && ./run.sh # silent tick, exit 0
|
||||||
./run.sh --verbose # same, diagnostics on stderr
|
./run.sh --verbose # same, diagnostics on stderr
|
||||||
./run.sh --fixture tests/fixtures/beacon-shaped.jsonl --dry-run # what-would-I-say
|
./run.sh --fixture tests/fixtures/beacon-shaped.jsonl --dry-run # what-would-I-say
|
||||||
python3 -m unittest discover -s tests # 40 tests, no network
|
./run.sh --http --flows-dir /tmp/empty --dry-run # gateway rules only, no SSH
|
||||||
|
python3 -m unittest discover -s tests # 89 tests, no network
|
||||||
```
|
```
|
||||||
|
|
||||||
## Output contract
|
## Output contract
|
||||||
|
|
@ -92,11 +96,12 @@ count: the same finding keeps the same id across ticks, restarts and days.
|
||||||
window quoted in the alert (`window_h`, derived from the coverage start in the
|
window quoted in the alert (`window_h`, derived from the coverage start in the
|
||||||
filenames actually consumed) grows tick by tick until the pass completes.
|
filenames actually consumed) grows tick by tick until the pass completes.
|
||||||
|
|
||||||
## The 8 rules
|
## The rules
|
||||||
|
|
||||||
Six PromQL tripwires (read-only, via
|
Six PromQL tripwires, two flow-store rules (§4a/§4b), and the gateway
|
||||||
`kubectl get --raw /api/v1/namespaces/monitoring/services/http:kube-prometheus-stack-prometheus:9090/proxy/api/v1/query`)
|
access-log rules (§4d: nine rule kinds over the `cilium-envoy` JSON stream).
|
||||||
and two flow-store rules (`/var/log/netsec/*.jsonl` on siriussec).
|
See `docs/gateway-http-rules.md` for the HTTP rule catalogue and its
|
||||||
|
false-positive reasoning.
|
||||||
|
|
||||||
| # | Rule | Severity | What it detects | Threshold | Backing series (2026-11-27) |
|
| # | Rule | Severity | What it detects | Threshold | Backing series (2026-11-27) |
|
||||||
|---|---|---|---|---|---|
|
|---|---|---|---|---|---|
|
||||||
|
|
@ -109,6 +114,29 @@ and two flow-store rules (`/var/log/netsec/*.jsonl` on siriussec).
|
||||||
| 7 | `egress-new-dst` | HIGH (non-web port, or any `DROPPED` verdict) / MEDIUM (80/443 forwarded) | first-seen `(workload, dst_ip, dst_port)` outside pod/mesh/LAN space — candidate beacon or exfil | no prior in the cumulative seen-set; the line states the observation window (e.g. `~20m of observed flows`) | 21 workload→world tuples in the first 15 min captured |
|
| 7 | `egress-new-dst` | HIGH (non-web port, or any `DROPPED` verdict) / MEDIUM (80/443 forwarded) | first-seen `(workload, dst_ip, dst_port)` outside pod/mesh/LAN space — candidate beacon or exfil | no prior in the cumulative seen-set; the line states the observation window (e.g. `~20m of observed flows`) | 21 workload→world tuples in the first 15 min captured |
|
||||||
| 8 | `beacon-shape` | HIGH | periodic connections from one workload to one `dst:port` — C2 shape | ≥ **20** distinct client sockets in 2 h, inter-arrival **CV < 0.15**, mean interval ≤ 900 s | requires ≥ 20 conns; the busiest real tuple measured 9 sockets / CV 1.57 |
|
| 8 | `beacon-shape` | HIGH | periodic connections from one workload to one `dst:port` — C2 shape | ≥ **20** distinct client sockets in 2 h, inter-arrival **CV < 0.15**, mean interval ≤ 900 s | requires ≥ 20 conns; the busiest real tuple measured 9 sockets / CV 1.57 |
|
||||||
|
|
||||||
|
Gateway access-log rules (§4d) — input is the `cilium-envoy` JSON line in Loki,
|
||||||
|
not the flow store. Full catalogue and FP reasoning:
|
||||||
|
`docs/gateway-http-rules.md`.
|
||||||
|
|
||||||
|
| # | Rule | Severity | What it detects | Threshold / entity |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 9 | `http-traversal` | HIGH served / MEDIUM attempt | `../`, `..\`, `%2e%2e`, `..%2f`, `%252e` | one finding per `host+client`, not per path |
|
||||||
|
| 10 | `http-sqli` | HIGH served / MEDIUM attempt | `union [all] select`, `' or 1=1`, `sleep(`, `benchmark(`, `information_schema`, `into outfile` | idem |
|
||||||
|
| 11 | `http-nul-byte` | HIGH served / MEDIUM attempt | `%00`, `%2500`, literal NUL | idem |
|
||||||
|
| 12 | `http-secret-probe` | HIGH served / MEDIUM attempt | `.env*`, `.aws/*`, `.ssh/id_*`, `.kube/config`, `*credentials*.json`, cloud metadata path | idem |
|
||||||
|
| 13 | `http-vcs-probe` | HIGH served / MEDIUM attempt | `.git/config`, `.git/HEAD`, `.git-credentials`, `.svn/`, `.hg/` (smart-HTTP endpoints exempt) | idem |
|
||||||
|
| 14 | `http-backup-probe` | MEDIUM served / LOW attempt | `*backup*`/`*dump*`/`*db*` + archive/SQL extension, `.bak/.old/.sql/.swp` | idem |
|
||||||
|
| 15 | `http-scanner-ua` | HIGH / MEDIUM / LOW | sqlmap, nikto, nuclei, wpscan, acunetix (HIGH); gobuster, ffuf, feroxbuster, dirb (MEDIUM); masscan, zgrab, nmap, whatweb (LOW) | UA family + `host+client` |
|
||||||
|
| 16 | `http-auth-brute` | MEDIUM (HIGH at ≥3× total) | one client failing auth repeatedly — **401/403 only**, never 4xx in general | ≥ **20**/min **and** ≥ **30** in 5 min, per `coalesce(client_ip, peer)` |
|
||||||
|
| 17 | `http-flood` | MEDIUM (state) | a scanner rotating source addresses to mint fingerprints | > **12** new client/path findings in one tick → one summary line |
|
||||||
|
|
||||||
|
A finding is one line per **client × host × category**, so a scanner walking 200
|
||||||
|
`.env` variants from one address is one line with a count. Severity escalates only
|
||||||
|
when the shape is in the *path component* and the origin answered 2xx. Per-client
|
||||||
|
keys use `coalesce(client_ip, peer)` — `client_ip` is Cloudflare's
|
||||||
|
`CF-Connecting-IP`, `peer` the real address for internal/WG requests — and never
|
||||||
|
`x_forwarded_for` alone.
|
||||||
|
|
||||||
Rule 7 keeps a `DROPPED` attempt **separate** from forwarded traffic to the same
|
Rule 7 keeps a `DROPPED` attempt **separate** from forwarded traffic to the same
|
||||||
destination (`…/dropped` in the entity, HIGH): a pod trying to reach a new host
|
destination (`…/dropped` in the entity, HIGH): a pod trying to reach a new host
|
||||||
and being refused is a stronger signal than one that succeeded, and collapsing
|
and being refused is a stronger signal than one that succeeded, and collapsing
|
||||||
|
|
@ -134,10 +162,11 @@ Rationale and the measured numbers live in `config.EGRESS_WEB_MIN_TICKS`.
|
||||||
from the flow JSONL instead. No `by (pod)` exists anywhere in this code.
|
from the flow JSONL instead. No `by (pod)` exists anywhere in this code.
|
||||||
* **`hubble_dns_*` / DNS response codes.** The metric family does not exist in
|
* **`hubble_dns_*` / DNS response codes.** The metric family does not exist in
|
||||||
this build (0 series).
|
this build (0 series).
|
||||||
* **HTTP attack-shape text rules** (`../`, `union select`, `.env` probes,
|
* **HTTP attack-shape text rules** — *implemented* (rules 9–17). The blocker was
|
||||||
scanner UAs). `cilium-envoy` emits **no access log** (audit finding F7, card
|
F7 (`t_e662b03a`): `cilium-envoy` emitted no access log, so there was no data
|
||||||
`t_e662b03a`), so there is no data source. When that card lands, this is where
|
source. It now writes one JSON line per request and `http_rules.py` consumes
|
||||||
the parser goes.
|
it from Loki. See `docs/gateway-http-rules.md`. Still not done: blocking (this
|
||||||
|
is a sensor) and header/body inspection (volume + blast radius).
|
||||||
* **`verdict != FORWARDED` as its own rule.** It fires permanently at rest
|
* **`verdict != FORWARDED` as its own rule.** It fires permanently at rest
|
||||||
(constant ICMPv6 L3 drops) — a day-one false positive. TCP/UDP drops are
|
(constant ICMPv6 L3 drops) — a day-one false positive. TCP/UDP drops are
|
||||||
covered by rule 2 instead.
|
covered by rule 2 instead.
|
||||||
|
|
@ -183,6 +212,17 @@ UTC day rollover. No alert is ever raised from it.
|
||||||
|
|
||||||
## Where the inputs come from
|
## Where the inputs come from
|
||||||
|
|
||||||
|
* **Gateway access log**: `cilium-envoy` (kube-system) writes one JSON line per
|
||||||
|
request — `gateway, method, path, protocol, response_code, response_flags,
|
||||||
|
duration_ms, bytes_*, authority, client_ip, x_forwarded_for, peer, user_agent,
|
||||||
|
cf_ray, upstream_host` — and the `logging` Alloy DaemonSet ships it to Loki
|
||||||
|
(192 h retention, ~42 MB/day compressed). The sensor reads it through the
|
||||||
|
`logging/loki` Service proxy with **two LogQL queries per tick**: a `|~`
|
||||||
|
prefilter for attack-shaped lines and a `sum by (client_ip, peer)` 1-minute
|
||||||
|
matrix for 401/403. Loki does the volume reduction; a calm 10-minute window
|
||||||
|
(≈5 500 requests / 3.5 MB) puts ~150 lines on the wire, not 3.5 MB.
|
||||||
|
`client_ip` is Cloudflare's `CF-Connecting-IP`; internal/WG requests have it
|
||||||
|
null and the real address in `peer`.
|
||||||
* **Flows**: the `netsec/hubble-flow-collector` DaemonSet on siriussec writes
|
* **Flows**: the `netsec/hubble-flow-collector` DaemonSet on siriussec writes
|
||||||
filtered JSONL to the host's `/var/log/netsec` (drops, policy verdicts, all L7,
|
filtered JSONL to the host's `/var/log/netsec` (drops, policy verdicts, all L7,
|
||||||
and `trace:to-network` whose peer is outside `10.244.0.0/16` + `10.10.0.0/24`).
|
and `trace:to-network` whose peer is outside `10.244.0.0/16` + `10.10.0.0/24`).
|
||||||
|
|
@ -259,9 +299,19 @@ credentials, no LLM call, no secret reads.
|
||||||
|
|
||||||
## Verified behaviour (2026-11-27)
|
## Verified behaviour (2026-11-27)
|
||||||
|
|
||||||
* 56 unit tests pass against recorded fixtures (`tests/test_archives.py` covers
|
* 89 unit tests pass against recorded fixtures (`tests/test_archives.py` covers
|
||||||
the gz path: read-once, torn archive, budget/pending, cold seed, warm-state
|
the gz path: read-once, torn archive, budget/pending, cold seed, warm-state
|
||||||
archive absorption, single-fire).
|
archive absorption, single-fire; `tests/test_http_rules.py` covers the gateway
|
||||||
|
rules: every category, the Forgejo browse/git FP shapes, `coalesce(client_ip,
|
||||||
|
peer)`, the auth-rate floors and the flood cap).
|
||||||
|
* **Gateway rules (§4d) on the live stream**: calm window `07:03:40–07:13:40Z`
|
||||||
|
(5 474 requests, 154 candidate lines) → **0 findings, stdout empty, exit 0**.
|
||||||
|
The 06:48–06:53Z `91.92.47.0/24` burst → 8 findings (secret-file ×4,
|
||||||
|
traversal, vcs-probe ×2, backup). Crafted requests (public through Cloudflare
|
||||||
|
and direct to `10.10.0.2:8080` to exercise the `peer` path) fired all nine rule
|
||||||
|
kinds — including `http-auth-brute` on a 30× 403 burst (`40 x 401/403 in 5m,
|
||||||
|
peak 33/min`). First tick baselined silently, the next emitted 10 findings,
|
||||||
|
the next was silent; deleting one fingerprint re-emitted exactly that line.
|
||||||
* **Cold start on the live store** (state moved aside, `--no-prom --verbose`):
|
* **Cold start on the live store** (state moved aside, `--no-prom --verbose`):
|
||||||
`5 file(s) (4 archive(s), 1 plain), 150225 flows, 116 tuple(s), 116
|
`5 file(s) (4 archive(s), 1 plain), 150225 flows, 116 tuple(s), 116
|
||||||
fingerprint(s), window 2.06h, 7.34s`, **stdout 0 bytes**, exit 0. The window is
|
fingerprint(s), window 2.06h, 7.34s`, **stdout 0 bytes**, exit 0. The window is
|
||||||
|
|
|
||||||
220
docs/gateway-http-rules.md
Normal file
220
docs/gateway-http-rules.md
Normal file
|
|
@ -0,0 +1,220 @@
|
||||||
|
# Gateway HTTP attack-shape rules (§4d)
|
||||||
|
|
||||||
|
The detector for the only application-layer signal the netsec design asks for:
|
||||||
|
`../` traversal, `union select`, `%00`, `.env`/`.git`/backup probes, scanner
|
||||||
|
user-agents, and high-rate 401/403 per client. Input is the `cilium-envoy`
|
||||||
|
access log, **not** the Hubble flow store — flows carry no `path`, no
|
||||||
|
`user_agent` and no per-request response code.
|
||||||
|
|
||||||
|
```
|
||||||
|
cilium-envoy stdout (JSON, one object per request)
|
||||||
|
→ kubelet /var/log/pods/... (10 MiB × 5, ≈29 min per file)
|
||||||
|
→ Alloy DaemonSet (ns logging)
|
||||||
|
→ Loki {namespace="kube-system", container="cilium-envoy", job="kube/pods", node="siriussec"}
|
||||||
|
→ netsec_scan.http_step() ← this document
|
||||||
|
```
|
||||||
|
|
||||||
|
No second collector, no file re-read, no Envoy config change (no debug logging,
|
||||||
|
no added fields). The pod log stays a rotation artifact; Loki is the archive.
|
||||||
|
|
||||||
|
## Volume discipline
|
||||||
|
|
||||||
|
Measured 2026-11-27: **641 B/line, 9.54 lines/s, 528 MB/day raw**, 93.5 % of it
|
||||||
|
Forgejo. A 10-minute window is ~5 500 requests / ~3.5 MB.
|
||||||
|
|
||||||
|
Each tick runs exactly **two LogQL queries** over that window:
|
||||||
|
|
||||||
|
| Query | Shape | What crosses the wire |
|
||||||
|
|---|---|---|
|
||||||
|
| candidate lines | `{stream} |~ `prefilter`` | only matching lines (calm: ~150–200 of 5 500, ≈100 KB) |
|
||||||
|
| auth rate | `sum by (client_ip, peer) (count_over_time(... | json ... [1m]))` | one number per client per minute |
|
||||||
|
|
||||||
|
The prefilter is a deliberate **superset** (it matches `.gitignore` in a browse
|
||||||
|
URL, `.git/info/refs`, `backup-cronjob.yaml`, …). Loki drops non-matching bytes
|
||||||
|
cheaply; the precise decision is made in `http_rules.classify()` where real
|
||||||
|
semantics are available. Over-matching measured at ~1 100 of 35 445 lines/hour
|
||||||
|
(3 %), all of it filtered out in Python.
|
||||||
|
|
||||||
|
`limit` on the line query is `HTTP_MAX_LINES = 600`; if a flood exceeds it the
|
||||||
|
tick reports `truncated` in the day counter and still classifies what arrived
|
||||||
|
(newest first).
|
||||||
|
|
||||||
|
## The rules
|
||||||
|
|
||||||
|
Every finding is `SEV <fp12> <rule> <detail>`; the fingerprint is
|
||||||
|
`sha256(rule + entity)[:12]`, never a path, count or timestamp.
|
||||||
|
|
||||||
|
| Rule | Category | Severity | Entity | Fires when |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| `http-traversal` | `traversal` | HIGH served / MEDIUM attempt | `traversal\|host\|client` | `../`, `..\`, `%2e%2e`, `..%2f`, `%252e` in path or query |
|
||||||
|
| `http-sqli` | `sqli` | HIGH served / MEDIUM attempt | `sqli\|host\|client` | `union [all] select`, `' or 1=1`, `sleep(`, `benchmark(`, `information_schema`, `waitfor delay`, `load_file(`, `into outfile` |
|
||||||
|
| `http-nul-byte` | `nul-byte` | HIGH served / MEDIUM attempt | `nul-byte\|host\|client` | `%00`, `%2500`, literal NUL |
|
||||||
|
| `http-secret-probe` | `secret-file` | HIGH served / MEDIUM attempt | `secret-file\|host\|client` | `.env*`, `.aws/{credentials,config}`, `.ssh/id_*`, `.docker/config.json`, `.kube/config`, `.npmrc`, `.netrc`, `.pgpass`, `*credentials*.{json,yml,…}`, `/meta-data/iam/security-credentials` |
|
||||||
|
| `http-vcs-probe` | `vcs-probe` | HIGH served / MEDIUM attempt | `vcs-probe\|host\|client` | `.git/config`, `.git/HEAD`, `.git/index`, `.git-credentials`, `.svn/`, `.hg/`, `.bzr/` (**not** the smart-HTTP endpoints) |
|
||||||
|
| `http-backup-probe` | `backup-file` | MEDIUM served / LOW attempt | `backup-file\|host\|client` | `*backup*`/`*dump*`/`*db*`/`*site*` + archive or SQL extension, or any `.bak/.old/.orig/.save/.swp/.sql/.dump` |
|
||||||
|
| `http-scanner-ua` | `scanner-ua:<family>` | HIGH (sqlmap, nikto, nuclei, wpscan, acunetix, …) / MEDIUM (gobuster, ffuf, feroxbuster, dirb) / LOW (masscan, zgrab, nmap, whatweb) | `scanner-ua:<family>\|host\|client` | user-agent fingerprint |
|
||||||
|
| `http-auth-brute` | — | MEDIUM, HIGH at ≥3× the total | `auth-fail\|client` | one client with ≥ **20** × 401/403 in a single minute **and** ≥ **30** over the 5-minute window |
|
||||||
|
| `http-flood` | — | MEDIUM (state, 24 h cooldown) | `overflow\|gateway` | more than **12** *new* client/path fingerprints in one tick |
|
||||||
|
|
||||||
|
**One category per request** (priority: traversal → sqli → nul → secret → vcs →
|
||||||
|
backup → scanner-UA), so `../../.env` is one line, not four.
|
||||||
|
|
||||||
|
**Severity escalates only when the origin actually served the shape**: the match
|
||||||
|
must be in the *path component* and the response 2xx. A 200 on
|
||||||
|
`/?file=../../.env` is the static site's landing page answering, not a
|
||||||
|
successful traversal — measured live, and the reason `served` is path-scoped.
|
||||||
|
|
||||||
|
**Entity excludes the literal path.** A scanner walking 200 `.env` variants from
|
||||||
|
one address is one finding with a count (`29x in 10m`), not 200 fingerprints.
|
||||||
|
That is also what bounds the seen-set under IP rotation; `http-flood` is the
|
||||||
|
last-resort cap, and the cumulative `seen` map is already pruned at
|
||||||
|
`MAX_SEEN = 20000`.
|
||||||
|
|
||||||
|
## False-positive control (the part that decides whether this is usable)
|
||||||
|
|
||||||
|
The stream is 93.5 % Forgejo, and Forgejo legitimately serves every shape a
|
||||||
|
naive substring rule greps for:
|
||||||
|
|
||||||
|
| Legit shape (real lines, 2026-11-27) | Matches | Why it is not an alert |
|
||||||
|
|---|---|---|
|
||||||
|
| `/sirius/homek8s.git/info/refs?service=git-upload-pack` | `.git` | smart-HTTP git endpoint, used by every `git` client and by CI |
|
||||||
|
| `/sirius/homek8s.git/git-upload-pack` (POST) | `.git` | same |
|
||||||
|
| `/sirius/onionwire/raw/commit/<sha>/.gitignore` | `.git` | repository file view (`/raw/`) |
|
||||||
|
| `/mayx/blog/blame/commit/<sha>/.gitlab-ci.yml` | `.git` | repository file view (`/blame/`) |
|
||||||
|
| `/sirius/gcloud-lab/raw/commit/<sha>/.../memory-db-credentials.yaml` | `credential` | repository file view |
|
||||||
|
| `/sirius/gcloud-lab/commit/<sha>/immediate-backup.yaml` | `backup` | repository file view (`/commit/`) |
|
||||||
|
| `/sirius/osint-dashboard/rss/branch/<branch>/.env.example` | `.env` | RSS route for a branch, not a file read (303 → login) |
|
||||||
|
| `/<owner>/<repo>/-/archive/main/repo.tar.gz` | `.tar.gz` | Forgejo archive download |
|
||||||
|
| `303 → /user/login` (17 639 of 35 445 lines in a measured hour) | 3xx | not 4xx at all; the auth rule counts **401/403 only** |
|
||||||
|
| 404 crawler churn (`/linda958336097`, `/roscoedelarosa`, …) | 404 | 293/hour is normal internet noise; "4xx alone" is explicitly not a rule |
|
||||||
|
| `git/2.56.0` retrying a push → 3 × 401/403 per minute, 25/hour | 401 | two orders of magnitude below the 20/min floor |
|
||||||
|
|
||||||
|
Mechanisms:
|
||||||
|
|
||||||
|
* **Browse-URL exclusion is host-scoped.** The `/<owner>/<repo>/{raw,src,blame,
|
||||||
|
commits,commit,tree,media,avatars,archive,compare,diff,patch,pulls,issues,
|
||||||
|
wiki,releases,activity,settings,rss,atom,feeds}/…` and `/-/…` shapes are
|
||||||
|
exempt **only** on `HTTP_FORGEJO_HOSTS` (`forgejo.siriusdevops.com`). On a
|
||||||
|
static site the same path is a probe, and it is alerted on.
|
||||||
|
* **Smart-HTTP git endpoints are exempt everywhere** (`.git/info/refs`,
|
||||||
|
`.git/git-upload-pack`, `.git/git-receive-pack`); a `.git/config` request is
|
||||||
|
not.
|
||||||
|
* **Not 4xx.** The auth rule is scoped to 401/403 (auth *failures*), not "error
|
||||||
|
codes"; Forgejo answers 303 to every crawler login redirect and 404 to
|
||||||
|
crawler churn.
|
||||||
|
* **Per client, per minute.** `coalesce(client_ip, peer)` — `client_ip` is
|
||||||
|
Cloudflare's `CF-Connecting-IP` for tunnelled traffic, `peer` is the real
|
||||||
|
address for internal/WG requests. `x_forwarded_for` is never used as a key:
|
||||||
|
the client can send it and the tunnel appends a hop. A request with neither
|
||||||
|
(`peer = 10.10.0.1`, the Pi's cloudflared) is **unattributable** and can never
|
||||||
|
be the subject of a per-client rule — otherwise a whole internet's brute force
|
||||||
|
collapses into one bucket labelled with the tunnel.
|
||||||
|
|
||||||
|
## Measured proof (2026-11-27, live stream)
|
||||||
|
|
||||||
|
Calm window `07:03:40–07:13:40Z` — 5 474 requests, 154 candidate lines, **0
|
||||||
|
findings**, empty stdout, exit 0.
|
||||||
|
|
||||||
|
Scanner burst `06:48–06:53Z` (four addresses in `91.92.47.0/24`, Chrome UA):
|
||||||
|
|
||||||
|
```
|
||||||
|
MEDIUM 6581ff5be412 http-secret-probe secret-file siriusdevops.com client=91.92.47.94 GET /backup/.env -> 404 (29x in 5m)
|
||||||
|
MEDIUM 207e1756a306 http-secret-probe secret-file siriusdevops.com client=91.92.47.95 GET /.env.bedrock -> 404 (21x in 5m)
|
||||||
|
MEDIUM d5be7f0f5ce0 http-secret-probe secret-file siriusdevops.com client=91.92.47.96 GET /client/src/.env -> 404 (18x in 5m)
|
||||||
|
MEDIUM c3ffebd1bab3 http-secret-probe secret-file siriusdevops.com client=91.92.47.97 GET /client_secrets.json -> 404 (18x in 5m)
|
||||||
|
MEDIUM b92f5c1a095e http-traversal traversal siriusdevops.com client=91.92.47.95 GET /?file=../../../../var/www/html/.env -> 200 (1x in 5m)
|
||||||
|
MEDIUM d3005f01f561 http-vcs-probe vcs-probe siriusdevops.com client=91.92.47.94 GET /.git/config -> 404 (1x in 5m)
|
||||||
|
MEDIUM 9f4585513ff2 http-vcs-probe vcs-probe siriusdevops.com client=91.92.47.95 GET /.git/credentials -> 404 (1x in 5m)
|
||||||
|
LOW b02ba0f708e7 http-backup-probe backup-file siriusdevops.com client=91.92.47.96 GET /credentials.bak -> 404 (1x in 5m)
|
||||||
|
```
|
||||||
|
|
||||||
|
Crafted requests (public via Cloudflare, and direct to the Gateway on
|
||||||
|
`10.10.0.2:8080` to exercise the `peer` fallback):
|
||||||
|
|
||||||
|
```
|
||||||
|
HIGH 1359353db11a http-scanner-ua scanner-ua:nikto siriusdevops.com client=10.10.0.3 GET / -> 200
|
||||||
|
HIGH 431f76220d12 http-scanner-ua scanner-ua:sqlmap siriusdevops.com client=10.10.0.3 GET / -> 200
|
||||||
|
MEDIUM 5d058c9a884f http-auth-brute 137.118.156.124: 40 x 401/403 in 5m (peak 33/min) - sustained auth failure
|
||||||
|
MEDIUM cabab413f491 http-nul-byte nul-byte siriusdevops.com client=10.10.0.3 GET /.env%00probe -> 400
|
||||||
|
MEDIUM eaa5bb802fe6 http-secret-probe secret-file siriusdevops.com client=10.10.0.3 GET /.env.netsec1d-peer -> 404
|
||||||
|
MEDIUM f6686c354bbc http-secret-probe secret-file siriusdevops.com client=137.118.156.124 GET /.env -> 404
|
||||||
|
MEDIUM ff5178bdc5ff http-sqli sqli siriusdevops.com client=137.118.156.124 GET /index.php?q=union+select+1,2 -> 404
|
||||||
|
MEDIUM 58168ee6b092 http-traversal traversal siriusdevops.com client=137.118.156.124 GET /?file=../../../etc/passwd -> 200
|
||||||
|
MEDIUM 1f9388a85f27 http-vcs-probe vcs-probe siriusdevops.com client=10.10.0.3 GET /.git/config -> 404
|
||||||
|
MEDIUM 58d1f046a18a http-vcs-probe vcs-probe siriusdevops.com client=137.118.156.124 GET /.git/config -> 404
|
||||||
|
```
|
||||||
|
|
||||||
|
`10.10.0.3` is the Legion laptop arriving over `wg0` with `client_ip: null` and
|
||||||
|
`peer: 10.10.0.3`; `137.118.156.124` is that laptop's public address as
|
||||||
|
Cloudflare reported it in `CF-Connecting-IP`. Same code path, both attribution
|
||||||
|
sources.
|
||||||
|
|
||||||
|
Behavioural contract on the same state file: first tick baselines silently
|
||||||
|
(`http.baselined_at`, 0 lines out), the next tick after the crafted requests
|
||||||
|
emits 10, the tick after that is silent, deleting one fingerprint re-emits
|
||||||
|
exactly that one line, and the following tick is silent again.
|
||||||
|
|
||||||
|
## State
|
||||||
|
|
||||||
|
Only three scalars/dicts are added, all bounded:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"http": {
|
||||||
|
"baselined_at": "2026-11-27T07:15:58+00:00",
|
||||||
|
"baseline": {"window": "10m", "matched_lines": 154, "findings": 0, "by_rule": {}},
|
||||||
|
"last": {"at": "...", "window": "10m", "matched_lines": 198, "findings": 10}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Dedupe uses the existing cumulative `seen` map (union-only, pruned at
|
||||||
|
`MAX_SEEN`). There is no per-path or per-request set: the windows are re-queried
|
||||||
|
each tick and the fingerprint does the remembering. `st["http"]` is created with
|
||||||
|
`setdefault`, so an old state file loads unchanged.
|
||||||
|
|
||||||
|
The daily report gains one block:
|
||||||
|
|
||||||
|
```json
|
||||||
|
"http": {"ticks": 288, "matched_lines": 4100, "by_rule": {"http-secret-probe": 12, ...},
|
||||||
|
"truncated_ticks": 0}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Operating it
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd ~/Projects/netsec-agent
|
||||||
|
./run.sh # normal 5-minute tick (silent = calm)
|
||||||
|
./run.sh --verbose # include the "http: ..." line on stderr
|
||||||
|
./run.sh --no-http # flow/PromQL rules only
|
||||||
|
./run.sh --http-window 600 --http-end 2026-11-27T06:53:00Z --dry-run --http
|
||||||
|
./run.sh --http --flows-dir /tmp/empty --dry-run # local mode, no SSH, still hits Loki
|
||||||
|
```
|
||||||
|
|
||||||
|
`--http` is implied for the live sensor; it exists so `--fixture`/`--flows-dir`
|
||||||
|
runs (unit tests, local checks) never touch the network unless asked.
|
||||||
|
|
||||||
|
### Re-deriving the thresholds
|
||||||
|
|
||||||
|
```bash
|
||||||
|
kubectl -n logging get svc loki # 3100
|
||||||
|
# one hour of auth failures per client, 1-minute buckets:
|
||||||
|
kubectl get --raw "/api/v1/namespaces/logging/services/loki:3100/proxy/loki/api/v1/query_range?query=$(python3 - <<'PY'
|
||||||
|
import urllib.parse
|
||||||
|
print(urllib.parse.quote('sum by (client_ip, peer) (count_over_time({namespace="kube-system", container="cilium-envoy", job="kube/pods", node="siriussec"} | json response_code, client_ip, peer | response_code != "" | response_code >= 401 and response_code <= 403 [1m]))'))
|
||||||
|
PY
|
||||||
|
)&start=...&end=...&step=60"
|
||||||
|
```
|
||||||
|
|
||||||
|
Calm-hour baseline 2026-11-27: 20 auth failures in the whole hour, all one
|
||||||
|
client (`git/2.56.0` retrying a push), peak **1/min** → the 20/min floor sits
|
||||||
|
20× above the noisiest legitimate client. Do not lower it to "catch more":
|
||||||
|
a rule that fires on CI retries gets the channel muted.
|
||||||
|
|
||||||
|
## Deliberately not done
|
||||||
|
|
||||||
|
* **No Envoy debug/trace logging, no extra fields.** The 17-field allowlist is
|
||||||
|
enough; header/body capture would multiply the volume and the blast radius.
|
||||||
|
* **No "4xx rate" rule.** 303 login redirects and 404 crawler churn are the
|
||||||
|
stream; the auth rule watches 401/403 only.
|
||||||
|
* **No per-path fingerprint.** Unbounded under a path-walking scanner.
|
||||||
|
* **No blocking.** This is a sensor; the bouncer (Cilium/CrowdSec) is a separate
|
||||||
|
decision.
|
||||||
|
|
@ -17,7 +17,7 @@ import time
|
||||||
import traceback
|
import traceback
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
|
|
||||||
from . import config, report, rules, state as state_mod
|
from . import config, report, rules, state as state_mod
|
||||||
from .flows import (
|
from .flows import (
|
||||||
|
|
@ -332,7 +332,8 @@ def apply_dedupe(findings: List[Finding], seen: Dict[str, Any], now: float,
|
||||||
|
|
||||||
|
|
||||||
def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding],
|
def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding],
|
||||||
egress_tick: List[str], malformed: int) -> None:
|
egress_tick: List[str], malformed: int,
|
||||||
|
http_stats: Optional[Dict[str, Any]] = None) -> None:
|
||||||
state_mod.roll_day(st)
|
state_mod.roll_day(st)
|
||||||
day = st["day"]
|
day = st["day"]
|
||||||
day["flows"] = int(day.get("flows", 0)) + flows
|
day["flows"] = int(day.get("flows", 0)) + flows
|
||||||
|
|
@ -349,12 +350,136 @@ def record_counters(st: Dict[str, Any], flows: int, emitted: List[Finding],
|
||||||
if key not in known:
|
if key not in known:
|
||||||
known.append(key)
|
known.append(key)
|
||||||
known.sort()
|
known.sort()
|
||||||
|
if http_stats:
|
||||||
|
http = day.setdefault("http", {"ticks": 0, "matched_lines": 0,
|
||||||
|
"by_rule": {}, "truncated_ticks": 0})
|
||||||
|
http["ticks"] = int(http.get("ticks", 0)) + 1
|
||||||
|
for key in ("lines_processed", "bytes_processed"):
|
||||||
|
if http_stats.get(key) is not None:
|
||||||
|
http[key] = int(http.get(key, 0)) + int(http_stats[key])
|
||||||
|
http["matched_lines"] = int(http.get("matched_lines", 0)) + int(http_stats.get("matched_lines", 0))
|
||||||
|
if http_stats.get("truncated"):
|
||||||
|
http["truncated_ticks"] = int(http.get("truncated_ticks", 0)) + 1
|
||||||
|
for rule, n in (http_stats.get("by_rule") or {}).items():
|
||||||
|
http["by_rule"][rule] = int(http["by_rule"].get(rule, 0)) + int(n)
|
||||||
st["totals"]["ticks"] = int(st["totals"].get("ticks", 0)) + 1
|
st["totals"]["ticks"] = int(st["totals"].get("ticks", 0)) + 1
|
||||||
st["totals"]["flows"] = int(st["totals"].get("flows", 0)) + flows
|
st["totals"]["flows"] = int(st["totals"].get("flows", 0)) + flows
|
||||||
st["totals"]["findings"] = int(st["totals"].get("findings", 0)) + len(emitted)
|
st["totals"]["findings"] = int(st["totals"].get("findings", 0)) + len(emitted)
|
||||||
st["totals"]["malformed"] = int(st["totals"].get("malformed", 0)) + malformed
|
st["totals"]["malformed"] = int(st["totals"].get("malformed", 0)) + malformed
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------- gateway rules ----
|
||||||
|
def http_attack_expr() -> str:
|
||||||
|
"""LogQL for candidate access lines: `|~` filter only, no `| json` pass.
|
||||||
|
|
||||||
|
The returned line *is* the parsed JSON object, so extraction happens once, in
|
||||||
|
Python, where a malformed line costs a `continue` instead of a pipeline
|
||||||
|
error. Backtick string: a regex with `\\.` inside a double-quoted LogQL
|
||||||
|
literal is an escape minefield.
|
||||||
|
"""
|
||||||
|
return "%s |~ `%s`" % (config.LOKI_STREAM, config.HTTP_LINE_FILTER)
|
||||||
|
|
||||||
|
|
||||||
|
def http_rate_expr() -> str:
|
||||||
|
"""Per-client 401/403 counts in 1-minute buckets, aggregated by Loki."""
|
||||||
|
return (
|
||||||
|
'sum by (client_ip, peer) (count_over_time(%s'
|
||||||
|
' | json response_code, client_ip, peer'
|
||||||
|
' | response_code != ""'
|
||||||
|
' | response_code >= 401 and response_code <= 403 [1m]))' % config.LOKI_STREAM
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def http_step(st: Dict[str, Any], start_end: Tuple[float, float], args,
|
||||||
|
verbose: bool) -> Tuple[List[Finding], Dict[str, Any]]:
|
||||||
|
"""One tick of the §4d rules: two Loki queries, then classification.
|
||||||
|
|
||||||
|
Loki does the volume reduction (one line-filter scan + one aggregated
|
||||||
|
metric scan). Nothing is written to disk except a handful of counters, and
|
||||||
|
no seen-set beyond the existing cumulative `seen` map is added: the windows
|
||||||
|
are re-queried each tick and dedupe is the fingerprint map.
|
||||||
|
"""
|
||||||
|
from . import http_rules, loki
|
||||||
|
|
||||||
|
start, end = start_end
|
||||||
|
window = max(60, int(end - start))
|
||||||
|
window_label = "%dm" % max(1, int(round(window / 60.0)))
|
||||||
|
|
||||||
|
streams, summary = loki.query_range(
|
||||||
|
http_attack_expr(), start, end, config.HTTP_MAX_LINES)
|
||||||
|
records: List[Dict[str, Any]] = []
|
||||||
|
dedupe = set()
|
||||||
|
for _labels, values in streams:
|
||||||
|
for _ts, line in values:
|
||||||
|
try:
|
||||||
|
rec = json.loads(line)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if not isinstance(rec, dict) or "path" not in rec:
|
||||||
|
continue
|
||||||
|
# Loki can surface the same line through two streams after a pod
|
||||||
|
# restart; the count must not double for that.
|
||||||
|
key = (rec.get("start_time"), rec.get("method"), rec.get("path"),
|
||||||
|
rec.get("response_code"), rec.get("client_ip"), rec.get("peer"))
|
||||||
|
if key in dedupe:
|
||||||
|
continue
|
||||||
|
dedupe.add(key)
|
||||||
|
records.append(rec)
|
||||||
|
findings, by_rule = http_rules.rule_attack_paths(records, window_label)
|
||||||
|
|
||||||
|
rate_findings: List[Finding] = []
|
||||||
|
rate_series = 0
|
||||||
|
rate_window = min(config.HTTP_RATE_WINDOW, window)
|
||||||
|
if rate_window >= 60:
|
||||||
|
matrix = loki.query_matrix(
|
||||||
|
http_rate_expr(), end - rate_window, end, 60)
|
||||||
|
rate_findings, rate_series = http_rules.rule_auth_rate(
|
||||||
|
matrix, "%dm" % max(1, int(round(rate_window / 60.0))))
|
||||||
|
|
||||||
|
kept, overflow = http_rules.cap_findings(findings, host="gateway")
|
||||||
|
all_findings = kept + rate_findings
|
||||||
|
if overflow is not None:
|
||||||
|
all_findings.append(overflow)
|
||||||
|
|
||||||
|
stats = {
|
||||||
|
"window": window_label,
|
||||||
|
# Loki omits `stats` on this deployment's query_range responses, so these
|
||||||
|
# are recorded only when present; `matched_lines` is always exact and is
|
||||||
|
# the number that matters (it is what crossed the wire to this process).
|
||||||
|
"lines_processed": (int(float(summary["totalLinesProcessed"]))
|
||||||
|
if summary.get("totalLinesProcessed") is not None else None),
|
||||||
|
"bytes_processed": (int(float(summary["totalBytesProcessed"]))
|
||||||
|
if summary.get("totalBytesProcessed") is not None else None),
|
||||||
|
"matched_lines": len(records),
|
||||||
|
"truncated": len(records) >= config.HTTP_MAX_LINES,
|
||||||
|
"rate_series": rate_series,
|
||||||
|
"by_rule": dict(by_rule),
|
||||||
|
"findings": len(all_findings),
|
||||||
|
}
|
||||||
|
log("http: %s window, %d candidate line(s) received, %d attack finding(s), "
|
||||||
|
"%d client(s) with 401/403, %d finding(s) total"
|
||||||
|
% (window_label, stats["matched_lines"], len(findings), rate_series,
|
||||||
|
len(all_findings)), verbose)
|
||||||
|
|
||||||
|
hstate = st.setdefault("http", {})
|
||||||
|
if not hstate.get("baselined_at") and not args.dry_run:
|
||||||
|
# Same contract as the flow seed: the first HTTP tick records what is
|
||||||
|
# already in the window instead of dumping existing scanner traffic.
|
||||||
|
for finding in all_findings:
|
||||||
|
absorb(st, finding.kind, finding.entity, finding.rule, finding.severity)
|
||||||
|
hstate["baselined_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||||
|
hstate["baseline"] = {"window": window_label,
|
||||||
|
"matched_lines": stats["matched_lines"],
|
||||||
|
"findings": len(all_findings),
|
||||||
|
"by_rule": dict(by_rule)}
|
||||||
|
log("http: baseline absorbed %d finding(s) silently" % len(all_findings), verbose)
|
||||||
|
return [], stats
|
||||||
|
hstate["last"] = {"at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
||||||
|
"window": window_label, "matched_lines": stats["matched_lines"],
|
||||||
|
"findings": len(all_findings)}
|
||||||
|
return all_findings, stats
|
||||||
|
|
||||||
|
|
||||||
# ----------------------------------------------------------------- main ----
|
# ----------------------------------------------------------------- main ----
|
||||||
def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
|
def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
|
|
@ -365,6 +490,14 @@ def parse_args(argv: Optional[List[str]] = None) -> argparse.Namespace:
|
||||||
parser.add_argument("--dry-run", action="store_true",
|
parser.add_argument("--dry-run", action="store_true",
|
||||||
help="print findings without writing state/report and without seen-set dedupe")
|
help="print findings without writing state/report and without seen-set dedupe")
|
||||||
parser.add_argument("--no-prom", action="store_true", help="skip the PromQL tripwires")
|
parser.add_argument("--no-prom", action="store_true", help="skip the PromQL tripwires")
|
||||||
|
parser.add_argument("--no-http", action="store_true",
|
||||||
|
help="skip the gateway access-log rules (Loki)")
|
||||||
|
parser.add_argument("--http", action="store_true",
|
||||||
|
help="run the gateway rules even in --fixture/--flows-dir mode")
|
||||||
|
parser.add_argument("--http-window", type=int, metavar="SECONDS",
|
||||||
|
help="gateway log look-back window (default %d)" % config.HTTP_WINDOW)
|
||||||
|
parser.add_argument("--http-end", metavar="EPOCH|ISO8601",
|
||||||
|
help="evaluate the gateway rules as of this instant (forensics; default now)")
|
||||||
parser.add_argument("--state", help="state file path (default ~/.hermes/cron/netsec-scan-state.json)")
|
parser.add_argument("--state", help="state file path (default ~/.hermes/cron/netsec-scan-state.json)")
|
||||||
parser.add_argument("--reports", help="report directory (default ~/Projects/netsec-agent/reports)")
|
parser.add_argument("--reports", help="report directory (default ~/Projects/netsec-agent/reports)")
|
||||||
parser.add_argument("--verbose", action="store_true", help="debug lines on stderr")
|
parser.add_argument("--verbose", action="store_true", help="debug lines on stderr")
|
||||||
|
|
@ -377,6 +510,10 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||||
reports_dir = Path(args.reports or config.REPORT_DIR)
|
reports_dir = Path(args.reports or config.REPORT_DIR)
|
||||||
now = time.time()
|
now = time.time()
|
||||||
|
|
||||||
|
# The gateway rules are an independent input (Loki, not the flow store), so
|
||||||
|
# they are on whenever this runs as a sensor and off for fixture/local runs
|
||||||
|
# unless asked: a unit test must never reach the network.
|
||||||
|
http_enabled = not args.no_http and (args.http or not (args.fixture or args.flows_dir))
|
||||||
if args.fixture:
|
if args.fixture:
|
||||||
store: BaseStore = SingleFileStore(args.fixture)
|
store: BaseStore = SingleFileStore(args.fixture)
|
||||||
prom_enabled = False
|
prom_enabled = False
|
||||||
|
|
@ -471,6 +608,14 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||||
log("rule %s failed: %s" % (rule.__name__, exc), args.verbose)
|
log("rule %s failed: %s" % (rule.__name__, exc), args.verbose)
|
||||||
raise SensorError("prom-error", "%s: %s" % (rule.__name__, exc))
|
raise SensorError("prom-error", "%s: %s" % (rule.__name__, exc))
|
||||||
|
|
||||||
|
http_stats: Optional[Dict[str, Any]] = None
|
||||||
|
if http_enabled:
|
||||||
|
http_end = _parse_instant(args.http_end) if args.http_end else now
|
||||||
|
http_window = args.http_window or config.HTTP_WINDOW
|
||||||
|
http_findings, http_stats = http_step(
|
||||||
|
st, (http_end - http_window, http_end), args, args.verbose)
|
||||||
|
findings.extend(http_findings)
|
||||||
|
|
||||||
if baseline["archive"]:
|
if baseline["archive"]:
|
||||||
# Not a fault, and not news either: these tuples are inside the
|
# Not a fault, and not news either: these tuples are inside the
|
||||||
# window the next alert would quote. Say so once, loudly enough to
|
# window the next alert would quote. Say so once, loudly enough to
|
||||||
|
|
@ -531,7 +676,8 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||||
|
|
||||||
emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run)
|
emitted = apply_dedupe(findings + flow_findings, st["seen"], now, args.dry_run)
|
||||||
|
|
||||||
record_counters(st, stats["flows"], emitted, sorted(tick_egress), stats["malformed"])
|
record_counters(st, stats["flows"], emitted, sorted(tick_egress), stats["malformed"],
|
||||||
|
http_stats)
|
||||||
state_mod.prune(st)
|
state_mod.prune(st)
|
||||||
|
|
||||||
if not args.dry_run:
|
if not args.dry_run:
|
||||||
|
|
@ -554,6 +700,18 @@ def _utcnow() -> datetime:
|
||||||
return datetime.now(timezone.utc)
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_instant(value: str) -> float:
|
||||||
|
"""`--http-end`: epoch seconds or ISO-8601 (Z allowed)."""
|
||||||
|
try:
|
||||||
|
return float(value)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
return datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp()
|
||||||
|
except ValueError:
|
||||||
|
raise SensorError("bad-arg", "--http-end is neither epoch nor ISO-8601: %s" % value[:40])
|
||||||
|
|
||||||
|
|
||||||
def _prommod():
|
def _prommod():
|
||||||
from . import prom
|
from . import prom
|
||||||
return prom
|
return prom
|
||||||
|
|
|
||||||
|
|
@ -151,3 +151,60 @@ NON_EGRESS_NETS = (
|
||||||
|
|
||||||
KUBECTL_CANDIDATES = ("kubectl", "/usr/sbin/kubectl", "/usr/bin/kubectl", "/usr/local/bin/kubectl")
|
KUBECTL_CANDIDATES = ("kubectl", "/usr/sbin/kubectl", "/usr/bin/kubectl", "/usr/local/bin/kubectl")
|
||||||
SSH_CANDIDATES = ("ssh", "/usr/sbin/ssh", "/usr/bin/ssh")
|
SSH_CANDIDATES = ("ssh", "/usr/sbin/ssh", "/usr/bin/ssh")
|
||||||
|
|
||||||
|
# ------------------------------------------------- gateway access log ----
|
||||||
|
# `cilium-envoy` writes one JSON access line per request (t_e662b03a); the
|
||||||
|
# `logging` Alloy DaemonSet ships it to Loki with 192 h retention. The sensor
|
||||||
|
# reads it **only** through LogQL so the filtering runs in Loki, not here.
|
||||||
|
# Measured 2026-11-27: 641 B/line, 9.54 lines/s, 528 MB/day raw, 93.5 % Forgejo.
|
||||||
|
LOKI_PROXY = (
|
||||||
|
"/api/v1/namespaces/logging/services/loki:3100/proxy"
|
||||||
|
)
|
||||||
|
LOKI_TIMEOUT = int(os.environ.get("NETSEC_SCAN_LOKI_TIMEOUT", "25"))
|
||||||
|
# Exact stream selector from the F7 handoff. Narrow on purpose: it is the
|
||||||
|
# difference between reading one pod's stream on one node and the whole cluster.
|
||||||
|
LOKI_STREAM = os.environ.get(
|
||||||
|
"NETSEC_SCAN_LOKI_STREAM",
|
||||||
|
'{namespace="kube-system", container="cilium-envoy", job="kube/pods", node="siriussec"}',
|
||||||
|
)
|
||||||
|
|
||||||
|
# How far back each tick looks. The cron interval is 5 min, so 10 min guarantees
|
||||||
|
# overlap across ticks (a line can never fall between two windows) and the
|
||||||
|
# fingerprint dedupe absorbs the overlap. 10 min ≈ 3.6 MB scanned per query.
|
||||||
|
HTTP_WINDOW = int(os.environ.get("NETSEC_SCAN_HTTP_WINDOW", "600"))
|
||||||
|
HTTP_RATE_WINDOW = int(os.environ.get("NETSEC_SCAN_HTTP_RATE_WINDOW", "300"))
|
||||||
|
HTTP_MAX_LINES = int(os.environ.get("NETSEC_SCAN_HTTP_MAX_LINES", "600"))
|
||||||
|
# A tick may announce at most this many *new* client/path fingerprints; the rest
|
||||||
|
# collapse into one `http-flood` state line. IP-rotating scanners would otherwise
|
||||||
|
# mint one line per source address.
|
||||||
|
HTTP_MAX_NEW_PER_TICK = int(os.environ.get("NETSEC_SCAN_HTTP_MAX_NEW", "12"))
|
||||||
|
|
||||||
|
# Severity control. Cloudflare replaces the socket peer with the tunnel
|
||||||
|
# (10.10.0.1 on the Pi); `client_ip` is the real client there. A request with
|
||||||
|
# neither is unattributable and is never used as a per-client key.
|
||||||
|
HTTP_EDGE_PEERS = frozenset({"10.10.0.1"})
|
||||||
|
# Only these hosts serve Forgejo browse URLs; on any other host the same path
|
||||||
|
# shape (e.g. `/<a>/<b>/raw/.../.env`) is a probe, not a repository view.
|
||||||
|
HTTP_FORGEJO_HOSTS = frozenset({"forgejo.siriusdevops.com"})
|
||||||
|
|
||||||
|
# 401/403 brute force per client. Measured on a calm hour 2026-11-27: 20 auth
|
||||||
|
# failures *total*, all from the CI git client (git/2.56.0 retrying a push),
|
||||||
|
# peak 1/min. Forgejo's legitimate 303 -> /user/login bulk is 3xx and never
|
||||||
|
# counted. So 20 failures in one minute plus 30 over five minutes is a real
|
||||||
|
# attempt, two orders of magnitude above the CI baseline.
|
||||||
|
HTTP_AUTH_PER_MIN = int(os.environ.get("NETSEC_SCAN_HTTP_AUTH_PER_MIN", "20"))
|
||||||
|
HTTP_AUTH_WINDOW_TOTAL = int(os.environ.get("NETSEC_SCAN_HTTP_AUTH_TOTAL", "30"))
|
||||||
|
|
||||||
|
# LogQL prefilter for attack-shaped *lines*. Deliberately a superset: Loki
|
||||||
|
# drops non-matching bytes cheaply, and `http_rules.classify()` makes the precise
|
||||||
|
# decision in Python (semantics the regex cannot express, e.g. Forgejo browse
|
||||||
|
# URLs and smart-HTTP git). Measured over-matching: ~1 090 of 35 445 lines/h.
|
||||||
|
HTTP_LINE_FILTER = os.environ.get(
|
||||||
|
"NETSEC_SCAN_HTTP_LINE_FILTER",
|
||||||
|
"(?i)(\\.\\.|%2e%2e|union|select|%00|%2500|\\.env|\\.git|\\.svn|\\.hg|"
|
||||||
|
"credential|\\.aws|\\.ssh|id_rsa|\\.kube|\\.npmrc|\\.netrc|\\.htpasswd|"
|
||||||
|
"secrets|service-account|\\.bak|\\.old|\\.orig|\\.save|\\.swp|\\.sql|"
|
||||||
|
"\\.dump|\\.zip|\\.tar|\\.tgz|backup|sqlmap|nikto|nuclei|masscan|zgrab|"
|
||||||
|
"nmap|wpscan|gobuster|dirbuster|ffuf|ferox|acunetix|netsparker|nessus|"
|
||||||
|
"openvas|hydra|w3af|zaproxy)",
|
||||||
|
)
|
||||||
|
|
|
||||||
353
netsec_scan/http_rules.py
Normal file
353
netsec_scan/http_rules.py
Normal file
|
|
@ -0,0 +1,353 @@
|
||||||
|
"""HTTP attack-shape rules over the Cilium Gateway access log (§4d).
|
||||||
|
|
||||||
|
Input is the `cilium-envoy` access log: one JSON object per request, shipped by
|
||||||
|
the `logging` Alloy DaemonSet into Loki. It is **not** the Hubble flow store:
|
||||||
|
flows carry no `path`, no `user_agent`, and no per-request response code.
|
||||||
|
|
||||||
|
Volume discipline (measured 2026-11-27: 641 B/line, 9.54 lines/s, 528 MB/day
|
||||||
|
raw): every rule is a LogQL query whose *filtering happens inside Loki*. The
|
||||||
|
agent receives only the matching lines — a 10-minute window is ~5 700 lines /
|
||||||
|
3.6 MB scanned and (calm) zero lines returned. There is no second collector.
|
||||||
|
|
||||||
|
False-positive control is the hard part, because 93.5 % of this stream is
|
||||||
|
Forgejo and Forgejo legitimately serves:
|
||||||
|
|
||||||
|
* `/<owner>/<repo>.git/info/refs?service=git-upload-pack|git-receive-pack`
|
||||||
|
and the two POST endpoints — smart HTTP git, done by every `git` client;
|
||||||
|
* `/<owner>/<repo>/{raw,src,blame,commits,commit,tree,media,avatars}/…` and
|
||||||
|
`/-/archive/…` — users browsing repository files. These paths are full of
|
||||||
|
`.env`, `.gitignore`, `.gitlab-ci.yml`, `backup-cronjob.yaml` and
|
||||||
|
`*-credentials.yaml` **filenames**, which a naive substring rule flags.
|
||||||
|
|
||||||
|
So classification is semantic, not substring: browse URLs on the Forgejo hosts
|
||||||
|
are excluded from path-shape rules, and smart-HTTP git endpoints are excluded
|
||||||
|
from the VCS-probe rule. Severity escalates when the origin actually *served*
|
||||||
|
the request (2xx) instead of 404-ing it.
|
||||||
|
|
||||||
|
`client_ip` is the real client only for Cloudflare-tunnelled traffic
|
||||||
|
(`CF-Connecting-IP`). Internal/WG requests carry `client_ip: null` and the real
|
||||||
|
address in `peer`, so every per-client key uses `coalesce(client_ip, peer)`.
|
||||||
|
`x_forwarded_for` is never trusted on its own (the client can send it, and the
|
||||||
|
tunnel appends its own hop).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
||||||
|
from urllib.parse import unquote
|
||||||
|
|
||||||
|
from . import config
|
||||||
|
from .rules import Finding, SEVERITY_ORDER
|
||||||
|
|
||||||
|
# ------------------------------------------------------------- parsing ----
|
||||||
|
_CTRL = re.compile(r"[\x00-\x1f\x7f]")
|
||||||
|
|
||||||
|
|
||||||
|
def _text(value: Any, limit: int = 120) -> str:
|
||||||
|
"""Single-line, bounded rendering of an untrusted field."""
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
out = _CTRL.sub(" ", str(value)).replace("\n", " ")
|
||||||
|
return out[:limit]
|
||||||
|
|
||||||
|
|
||||||
|
def decode_path(path: str) -> str:
|
||||||
|
"""Percent-decode for classification (twice: `%252f` is `%2f` is `/`)."""
|
||||||
|
out = path or ""
|
||||||
|
for _ in range(2):
|
||||||
|
nxt = unquote(out, errors="replace")
|
||||||
|
if nxt == out:
|
||||||
|
break
|
||||||
|
out = nxt
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def client_of(rec: Dict[str, Any]) -> Optional[str]:
|
||||||
|
"""`coalesce(client_ip, peer)`, minus the unattributable Cloudflare edge.
|
||||||
|
|
||||||
|
`peer == 10.10.0.1` with no `client_ip` means the request came from the Pi's
|
||||||
|
cloudflared but Cloudflare did not pass the client address, so every such
|
||||||
|
request would collapse into one bucket. Treat it as unattributable instead of
|
||||||
|
attributing a whole internet's brute force to the tunnel.
|
||||||
|
"""
|
||||||
|
ip = _text(rec.get("client_ip"), 64).strip()
|
||||||
|
if not ip:
|
||||||
|
ip = _text(rec.get("peer"), 64).strip()
|
||||||
|
if not ip or ip in config.HTTP_EDGE_PEERS:
|
||||||
|
return None
|
||||||
|
return ip
|
||||||
|
|
||||||
|
|
||||||
|
def outcome(rec: Dict[str, Any]) -> int:
|
||||||
|
try:
|
||||||
|
return int(rec.get("response_code"))
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def served(rec: Dict[str, Any]) -> bool:
|
||||||
|
return 200 <= outcome(rec) < 300
|
||||||
|
|
||||||
|
|
||||||
|
# -------------------------------------------------------- classification ----
|
||||||
|
_TRAVERSAL = re.compile(r"(^|[/\\])\.\.([/\\]|$)")
|
||||||
|
_TRAVERSAL_ENC = re.compile(r"(?i)(%2e%2e|\.\.%2f|\.\.%5c|%252e%252e)")
|
||||||
|
_SQLI = re.compile(
|
||||||
|
r"(?i)(union\s+(?:all\s+|distinct\s+)?select"
|
||||||
|
r"|\bor\b\s+['\"]?\w+['\"]?\s*=\s*['\"]?\w+"
|
||||||
|
r"|'\s*(?:or|and)\s*'"
|
||||||
|
r"|\b(?:sleep|pg_sleep|benchmark)\s*\("
|
||||||
|
r"|information_schema|sysobjects|waitfor\s+delay"
|
||||||
|
r"|extractvalue\s*\(|updatexml\s*\(|load_file\s*\(|into\s+outfile"
|
||||||
|
r"|;\s*(?:drop|delete|insert|update)\s)"
|
||||||
|
)
|
||||||
|
_NUL = re.compile(r"(?i)(%00|%2500|\x00)")
|
||||||
|
|
||||||
|
_SECRET = re.compile(
|
||||||
|
r"(?i)(^|/)("
|
||||||
|
r"\.env(rc)?(\.[a-z0-9_-]+)?"
|
||||||
|
r"|\.aws/(credentials|config)"
|
||||||
|
r"|\.ssh/(id_rsa|id_dsa|id_ecdsa|id_ed25519|authorized_keys)"
|
||||||
|
r"|\.docker/config\.json|\.kube/config|\.git-credentials"
|
||||||
|
r"|\.npmrc|\.pypirc|\.netrc|\.pgpass|\.htpasswd|\.my\.cnf"
|
||||||
|
r"|(credentials|secrets|client_secret|service[-_]?account|"
|
||||||
|
r"application_default_credentials|cluster_credentials|smtp_credentials|"
|
||||||
|
r"bedrock[-_]?credentials)[a-z0-9_.-]*\.(json|ya?ml|toml|txt|env|gpg)"
|
||||||
|
r"|meta-data/(iam/)?security-credentials"
|
||||||
|
r")$"
|
||||||
|
)
|
||||||
|
_VCS = re.compile(r"(?i)(^|/)\.git/(config|HEAD|index|packed-refs|logs/HEAD|credentials)$"
|
||||||
|
r"|(^|/)\.(svn|hg|bzr)/")
|
||||||
|
_BACKUP = re.compile(
|
||||||
|
r"(?i)(^|/)(?:[a-z0-9_.-]*[_-])?(?:backup|dump|database|db|www|site|wwwroot|"
|
||||||
|
r"public_html)[a-z0-9_.-]*\.(zip|tar|tgz|tar\.gz|gz|bz2|rar|7z|sql)$"
|
||||||
|
r"|(^|/)[^/]+\.(bak|old|orig|save|swp|swo|sql|dump)$"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Smart-HTTP git endpoints: legitimate traffic from every `git` client.
|
||||||
|
_GIT_ENDPOINTS = re.compile(r"(?i)(\.git/info/refs|\.git/git-upload-pack|"
|
||||||
|
r"\.git/git-receive-pack)$")
|
||||||
|
# Forgejo/Gitea browse + archive URLs. Only applied on the Forgejo hosts: on a
|
||||||
|
# static site the same shape is a probe, not a repository view.
|
||||||
|
_BROWSE = re.compile(
|
||||||
|
r"(?i)^(?:/[^/]+/[^/]+/(?:raw|src|blame|commits?|tree|media|avatars|archive|"
|
||||||
|
r"compare|diff|patch|pulls?|issues?|wiki|releases?|activity|settings|"
|
||||||
|
r"rss|atom|feeds)/"
|
||||||
|
r"|/[^/]+/[^/]+/-/"
|
||||||
|
r"|/[^/]+/[^/]+/src/branch/)"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _browse_url(rec: Dict[str, Any], decoded: str) -> bool:
|
||||||
|
host = _text(rec.get("authority"), 120).lower()
|
||||||
|
if host not in config.HTTP_FORGEJO_HOSTS:
|
||||||
|
return False
|
||||||
|
return bool(_BROWSE.search(decoded))
|
||||||
|
|
||||||
|
|
||||||
|
SEVERITY_BY_CATEGORY = {
|
||||||
|
# A successful traversal/injection is a compromise; an attempt is still
|
||||||
|
# worth a line but not at the same level. `served` bumps these to HIGH.
|
||||||
|
"traversal": ("HIGH", "MEDIUM"),
|
||||||
|
"sqli": ("HIGH", "MEDIUM"),
|
||||||
|
"nul-byte": ("HIGH", "MEDIUM"),
|
||||||
|
"secret-file": ("HIGH", "MEDIUM"),
|
||||||
|
"vcs-probe": ("HIGH", "MEDIUM"),
|
||||||
|
"backup-file": ("MEDIUM", "LOW"),
|
||||||
|
}
|
||||||
|
|
||||||
|
RULE_BY_CATEGORY = {
|
||||||
|
"traversal": "http-traversal",
|
||||||
|
"sqli": "http-sqli",
|
||||||
|
"nul-byte": "http-nul-byte",
|
||||||
|
"secret-file": "http-secret-probe",
|
||||||
|
"vcs-probe": "http-vcs-probe",
|
||||||
|
"backup-file": "http-backup-probe",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Active attack tools vs. generic recon. Both are worth a line; only the former
|
||||||
|
# claims an attempt is in progress.
|
||||||
|
SCANNER_UA = {
|
||||||
|
"sqlmap": "HIGH", "nikto": "HIGH", "nuclei": "HIGH", "wpscan": "HIGH",
|
||||||
|
"acunetix": "HIGH", "netsparker": "HIGH", "nessus": "HIGH", "openvas": "HIGH",
|
||||||
|
"hydra": "HIGH", "w3af": "HIGH", "zaproxy": "HIGH", "commix": "HIGH",
|
||||||
|
"jaeles": "HIGH", "ysoserial": "HIGH", "gobuster": "MEDIUM",
|
||||||
|
"dirbuster": "MEDIUM", "ffuf": "MEDIUM", "feroxbuster": "MEDIUM",
|
||||||
|
"dirb": "MEDIUM", "masscan": "LOW", "zgrab": "LOW", "nmap": "LOW",
|
||||||
|
"whatweb": "LOW", "gospider": "LOW",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def scanner_family(ua: str) -> Optional[str]:
|
||||||
|
low = (ua or "").lower()
|
||||||
|
for family, _sev in SCANNER_UA.items():
|
||||||
|
if family in low:
|
||||||
|
return family
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def classify(rec: Dict[str, Any]) -> Optional[Tuple[str, str, str]]:
|
||||||
|
"""Return `(category, severity, rule)` for one access-log record, or None.
|
||||||
|
|
||||||
|
Exactly one category per request (priority order below), so a request that is
|
||||||
|
both `../../.env` yields one line instead of three.
|
||||||
|
|
||||||
|
Severity escalates to "served" only when the shape is in the **path
|
||||||
|
component** and the origin answered 2xx. A 200 on `/?file=../../.env` is the
|
||||||
|
landing page answering, not the traversal succeeding — on this static site
|
||||||
|
every query string returns 200, so escalating on the response code alone
|
||||||
|
would claim a leak that did not happen.
|
||||||
|
"""
|
||||||
|
raw = _text(rec.get("path"), 512)
|
||||||
|
decoded = decode_path(raw)
|
||||||
|
path_part, _sep, _query = decoded.partition("?")
|
||||||
|
browse = _browse_url(rec, decoded)
|
||||||
|
git_endpoint = bool(_GIT_ENDPOINTS.search(path_part))
|
||||||
|
# `+` is a space in a query string; make `union+select` readable to the regex.
|
||||||
|
probe = decoded.replace("+", " ")
|
||||||
|
|
||||||
|
if not browse:
|
||||||
|
if (_TRAVERSAL.search(decoded) or _TRAVERSAL_ENC.search(raw)
|
||||||
|
or _TRAVERSAL_ENC.search(decoded)):
|
||||||
|
return _shape("traversal", rec, bool(_TRAVERSAL.search(path_part)
|
||||||
|
or _TRAVERSAL_ENC.search(path_part)))
|
||||||
|
if _SQLI.search(probe):
|
||||||
|
return _shape("sqli", rec, bool(_SQLI.search(path_part.replace("+", " "))))
|
||||||
|
if _NUL.search(raw) or _NUL.search(decoded):
|
||||||
|
return _shape("nul-byte", rec, bool(_NUL.search(path_part)))
|
||||||
|
if _SECRET.search(path_part):
|
||||||
|
return _shape("secret-file", rec, True)
|
||||||
|
if _VCS.search(path_part) and not git_endpoint:
|
||||||
|
return _shape("vcs-probe", rec, True)
|
||||||
|
if _BACKUP.search(path_part):
|
||||||
|
return _shape("backup-file", rec, True)
|
||||||
|
family = scanner_family(_text(rec.get("user_agent"), 300))
|
||||||
|
if family:
|
||||||
|
return ("scanner-ua:%s" % family, SCANNER_UA[family], "http-scanner-ua")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _shape(category: str, rec: Dict[str, Any], in_path: bool) -> Tuple[str, str, str]:
|
||||||
|
high, low = SEVERITY_BY_CATEGORY[category]
|
||||||
|
severity = high if (in_path and served(rec)) else low
|
||||||
|
return (category, severity, RULE_BY_CATEGORY[category])
|
||||||
|
|
||||||
|
|
||||||
|
# --------------------------------------------------------------- rules ----
|
||||||
|
def rule_attack_paths(records: Iterable[Dict[str, Any]], window_label: str) -> Tuple[List[Finding], Dict[str, int]]:
|
||||||
|
"""One finding per (category, host, client) over the window.
|
||||||
|
|
||||||
|
The fingerprint deliberately excludes the literal path: a scanner walking
|
||||||
|
200 `.env` variants from one address is one finding (with a count), not 200.
|
||||||
|
That is also what keeps the cumulative seen-set bounded under IP rotation
|
||||||
|
attacks — the entity space is category × host × client.
|
||||||
|
"""
|
||||||
|
out: List[Finding] = []
|
||||||
|
counts: Dict[str, int] = {}
|
||||||
|
seen_keys: Dict[str, Dict[str, Any]] = {}
|
||||||
|
for rec in records:
|
||||||
|
hit = classify(rec)
|
||||||
|
if not hit:
|
||||||
|
continue
|
||||||
|
category, severity, rule = hit
|
||||||
|
client = client_of(rec) or "unknown"
|
||||||
|
host = _text(rec.get("authority"), 120) or "?"
|
||||||
|
counts[rule] = counts.get(rule, 0) + 1
|
||||||
|
entity = "%s|%s|%s" % (category, host, client)
|
||||||
|
entry = seen_keys.get(entity)
|
||||||
|
if entry is None:
|
||||||
|
seen_keys[entity] = {
|
||||||
|
"category": category, "severity": severity, "rule": rule,
|
||||||
|
"client": client, "host": host, "n": 1,
|
||||||
|
"first": rec.get("start_time") or _now_iso(),
|
||||||
|
"sample": (rec.get("method") or "?"), "path": _text(rec.get("path"), 90),
|
||||||
|
"code": outcome(rec),
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
entry["n"] = int(entry["n"]) + 1
|
||||||
|
if SEVERITY_ORDER.get(severity, 9) < SEVERITY_ORDER.get(entry["severity"], 9):
|
||||||
|
entry["severity"] = severity
|
||||||
|
# Keep the response code of the worst record: `-> 200` next to a
|
||||||
|
# HIGH must be the request that was actually served.
|
||||||
|
entry["code"] = outcome(rec)
|
||||||
|
for entity, e in seen_keys.items():
|
||||||
|
detail = "%s %s client=%s %s %s -> %d (%dx in %s)" % (
|
||||||
|
e["category"], e["host"], e["client"], e["sample"], e["path"],
|
||||||
|
int(e["code"] or 0), int(e["n"]), window_label)
|
||||||
|
out.append(Finding(
|
||||||
|
rule=e["rule"], kind="novelty", severity=e["severity"],
|
||||||
|
entity=entity, detail=detail,
|
||||||
|
))
|
||||||
|
return out, counts
|
||||||
|
|
||||||
|
|
||||||
|
def rule_auth_rate(series: List[Tuple[Dict[str, Any], List[Tuple[float, float]]]],
|
||||||
|
window_label: str) -> Tuple[List[Finding], int]:
|
||||||
|
"""High-rate 401/403 per client per minute, from a LogQL 1-minute matrix.
|
||||||
|
|
||||||
|
Not "4xx" — Forgejo answers 303 to `/user/login` for every crawler and that
|
||||||
|
is the bulk of the stream. Not "any 4xx" either: 404 crawler churn is
|
||||||
|
constant (measured 4.9/min). The rule needs one client to fail auth at
|
||||||
|
≥ `HTTP_AUTH_PER_MIN` in a single minute *and* ≥ `HTTP_AUTH_WINDOW_TOTAL`
|
||||||
|
over the whole query window, i.e. a sustained attempt rather than one
|
||||||
|
mistyped password or a CI credential retry (measured: the git client's
|
||||||
|
retries peak at 1/min).
|
||||||
|
"""
|
||||||
|
out: List[Finding] = []
|
||||||
|
by_client: Dict[str, Dict[str, Any]] = {}
|
||||||
|
for labels, points in series:
|
||||||
|
client = (labels.get("client_ip") or "").strip()
|
||||||
|
if not client:
|
||||||
|
client = (labels.get("peer") or "").strip()
|
||||||
|
if not client or client in config.HTTP_EDGE_PEERS:
|
||||||
|
continue
|
||||||
|
bucket = by_client.setdefault(client, {"per_min": [], "total": 0})
|
||||||
|
for _ts, value in points:
|
||||||
|
v = int(round(value))
|
||||||
|
bucket["per_min"].append(v)
|
||||||
|
bucket["total"] += v
|
||||||
|
for client, b in by_client.items():
|
||||||
|
peak = max(b["per_min"]) if b["per_min"] else 0
|
||||||
|
if peak < config.HTTP_AUTH_PER_MIN or b["total"] < config.HTTP_AUTH_WINDOW_TOTAL:
|
||||||
|
continue
|
||||||
|
severity = "HIGH" if b["total"] >= 3 * config.HTTP_AUTH_WINDOW_TOTAL else "MEDIUM"
|
||||||
|
out.append(Finding(
|
||||||
|
rule="http-auth-brute", kind="state", severity=severity,
|
||||||
|
entity="auth-fail|%s" % client,
|
||||||
|
detail="%s: %d x 401/403 in %s (peak %d/min) - sustained auth failure"
|
||||||
|
% (client, b["total"], window_label, peak),
|
||||||
|
))
|
||||||
|
return out, len(by_client)
|
||||||
|
|
||||||
|
|
||||||
|
def cap_findings(findings: List[Finding], host: str = "*") -> Tuple[List[Finding], Optional[Finding]]:
|
||||||
|
"""Bound one tick's output; overflow becomes a single state line.
|
||||||
|
|
||||||
|
An attacker rotating source addresses can otherwise mint one fingerprint per
|
||||||
|
address. The cap is not silence — the overflow line is a state rule (24 h
|
||||||
|
cooldown), so it keeps re-announcing while the flood continues.
|
||||||
|
"""
|
||||||
|
if len(findings) <= config.HTTP_MAX_NEW_PER_TICK:
|
||||||
|
return findings, None
|
||||||
|
ordered = sorted(findings, key=lambda f: (SEVERITY_ORDER.get(f.severity, 9), f.entity))
|
||||||
|
kept = ordered[: config.HTTP_MAX_NEW_PER_TICK]
|
||||||
|
dropped = len(ordered) - len(kept)
|
||||||
|
overflow = Finding(
|
||||||
|
rule="http-flood", kind="state", severity="MEDIUM",
|
||||||
|
entity="overflow|%s" % host,
|
||||||
|
detail="%d more new client/path finding(s) suppressed this tick (cap %d)"
|
||||||
|
% (dropped, config.HTTP_MAX_NEW_PER_TICK),
|
||||||
|
)
|
||||||
|
return kept, overflow
|
||||||
|
|
||||||
|
|
||||||
|
def _now_iso() -> str:
|
||||||
|
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"classify", "client_of", "decode_path", "rule_attack_paths", "rule_auth_rate",
|
||||||
|
"cap_findings", "scanner_family", "served",
|
||||||
|
]
|
||||||
120
netsec_scan/loki.py
Normal file
120
netsec_scan/loki.py
Normal file
|
|
@ -0,0 +1,120 @@
|
||||||
|
"""Read-only Loki access through the Kubernetes API proxy.
|
||||||
|
|
||||||
|
Same access model as `prom.py`: no port-forward, no extra credentials, no
|
||||||
|
cluster writes — `kubectl get --raw` against the `logging/loki` Service proxy as
|
||||||
|
the operator. Only the (small) matching line set is returned; the filtering
|
||||||
|
happens in LogQL so the agent never pulls the whole 528 MB/day ingress stream
|
||||||
|
into this process (see `http_rules.py`).
|
||||||
|
|
||||||
|
Two shapes are used:
|
||||||
|
|
||||||
|
* `query_range(...)` for "give me the matching log lines in this window"
|
||||||
|
(attack-shape rules). Bounded by `limit`, newest first.
|
||||||
|
* `query(...)` for an instant metric query (per-client 401/403 rate, aggregated
|
||||||
|
by Loki into one series per client).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import urllib.parse
|
||||||
|
from typing import Dict, List, Tuple
|
||||||
|
|
||||||
|
from . import config
|
||||||
|
from .prom import SensorError, _which
|
||||||
|
|
||||||
|
|
||||||
|
def _classify(text: str) -> str:
|
||||||
|
low = text.lower()
|
||||||
|
if "503" in low or "service unavailable" in low or "serviceunavailable" in low:
|
||||||
|
return "loki-503"
|
||||||
|
if "timeout" in low or "timed out" in low or "deadline" in low:
|
||||||
|
return "loki-timeout"
|
||||||
|
if "connection refused" in low or "no such host" in low:
|
||||||
|
return "loki-unreachable"
|
||||||
|
return "loki-error"
|
||||||
|
|
||||||
|
|
||||||
|
def _raw(path: str) -> dict:
|
||||||
|
kubectl = _which(config.KUBECTL_CANDIDATES)
|
||||||
|
try:
|
||||||
|
proc = subprocess.run(
|
||||||
|
[kubectl, "get", "--raw", path],
|
||||||
|
capture_output=True, text=True, timeout=config.LOKI_TIMEOUT,
|
||||||
|
)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
raise SensorError("loki-timeout", "kubectl get --raw exceeded %ss" % config.LOKI_TIMEOUT)
|
||||||
|
if proc.returncode != 0:
|
||||||
|
raise SensorError(_classify(proc.stderr or proc.stdout), (proc.stderr or "").strip()[:200])
|
||||||
|
try:
|
||||||
|
return json.loads(proc.stdout)
|
||||||
|
except ValueError:
|
||||||
|
raise SensorError("loki-bad-json", proc.stdout[:120])
|
||||||
|
|
||||||
|
|
||||||
|
def _payload(payload: dict) -> dict:
|
||||||
|
if payload.get("status") != "success":
|
||||||
|
raise SensorError("loki-error", str(payload.get("error", ""))[:160])
|
||||||
|
return payload["data"]
|
||||||
|
|
||||||
|
|
||||||
|
def query_range(expr: str, start: float, end: float, limit: int = 600) -> Tuple[List[Tuple[dict, List[Tuple[str, str]]]], dict]:
|
||||||
|
"""Log lines matching `expr` in [start, end]; newest first, `limit` bounded.
|
||||||
|
|
||||||
|
Returns `(streams, summary)` where summary is Loki's own
|
||||||
|
`stats.summary` (bytes/lines processed, exec time) so the tick can report how
|
||||||
|
much it actually read rather than guessing from the window length.
|
||||||
|
"""
|
||||||
|
params = {
|
||||||
|
"query": expr,
|
||||||
|
"start": "%d000000000" % int(start),
|
||||||
|
"end": "%d000000000" % int(end),
|
||||||
|
"limit": str(int(limit)),
|
||||||
|
"direction": "backward",
|
||||||
|
}
|
||||||
|
path = config.LOKI_PROXY + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params)
|
||||||
|
payload = _raw(path)
|
||||||
|
data = _payload(payload)
|
||||||
|
out: List[Tuple[dict, List[Tuple[str, str]]]] = []
|
||||||
|
for stream in data.get("result") or []:
|
||||||
|
values = [(str(v[0]), str(v[1])) for v in (stream.get("values") or []) if len(v) >= 2]
|
||||||
|
out.append((stream.get("stream") or {}, values))
|
||||||
|
summary = ((payload.get("stats") or {}).get("summary") or {})
|
||||||
|
return out, summary
|
||||||
|
|
||||||
|
|
||||||
|
def query(expr: str, at: float) -> List[Tuple[dict, float]]:
|
||||||
|
"""Instant metric query -> [(labels, value)] (0 series on no match)."""
|
||||||
|
params = {"query": expr, "time": "%d000000000" % int(at)}
|
||||||
|
path = config.LOKI_PROXY + "/loki/api/v1/query?" + urllib.parse.urlencode(params)
|
||||||
|
data = _payload(_raw(path))
|
||||||
|
out: List[Tuple[dict, float]] = []
|
||||||
|
for series in data.get("result") or []:
|
||||||
|
try:
|
||||||
|
out.append((series.get("metric") or {}, float(series["value"][1])))
|
||||||
|
except (KeyError, IndexError, ValueError):
|
||||||
|
continue
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def query_matrix(expr: str, start: float, end: float, step: int) -> List[Tuple[dict, List[Tuple[float, float]]]]:
|
||||||
|
"""Range metric query -> [(labels, [(ts, value)])]."""
|
||||||
|
params = {
|
||||||
|
"query": expr,
|
||||||
|
"start": "%d000000000" % int(start),
|
||||||
|
"end": "%d000000000" % int(end),
|
||||||
|
"step": str(int(step)),
|
||||||
|
}
|
||||||
|
path = config.LOKI_PROXY + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params)
|
||||||
|
data = _payload(_raw(path))
|
||||||
|
out: List[Tuple[dict, List[Tuple[float, float]]]] = []
|
||||||
|
for series in data.get("result") or []:
|
||||||
|
values: List[Tuple[float, float]] = []
|
||||||
|
for point in series.get("values") or []:
|
||||||
|
try:
|
||||||
|
values.append((float(point[0]), float(point[1])))
|
||||||
|
except (IndexError, ValueError):
|
||||||
|
continue
|
||||||
|
out.append((series.get("metric") or {}, values))
|
||||||
|
return out
|
||||||
|
|
@ -32,6 +32,9 @@ def build(state: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
"egress_tuples": sorted(egress),
|
"egress_tuples": sorted(egress),
|
||||||
"top_new_destinations": new_dsts[-10:],
|
"top_new_destinations": new_dsts[-10:],
|
||||||
"seen_fingerprints_cumulative": len(state.get("seen", {})),
|
"seen_fingerprints_cumulative": len(state.get("seen", {})),
|
||||||
|
# Gateway access-log rules (§4d): how much the tick scanned, how many
|
||||||
|
# candidate lines it matched, and what the rules counted today.
|
||||||
|
"http": day.get("http") or {},
|
||||||
# The baseline this sensor actually holds: which files it consumed and
|
# The baseline this sensor actually holds: which files it consumed and
|
||||||
# the window they cover. "no prior in ~Xh" comes from this, never from a
|
# the window they cover. "no prior in ~Xh" comes from this, never from a
|
||||||
# guess.
|
# guess.
|
||||||
|
|
|
||||||
4
run.sh
4
run.sh
|
|
@ -1,6 +1,8 @@
|
||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
# netsec-scan entrypoint. Runs from the repo root so `python3 -m netsec_scan`
|
# netsec-scan entrypoint. Runs from the repo root so `python3 -m netsec_scan`
|
||||||
# resolves the package; stdout is the alert, stderr is diagnostics.
|
# resolves the package; stdout is the alert, stderr is diagnostics.
|
||||||
|
# `dirname "$0"`, not a hard-coded path: a git worktree (or a moved checkout)
|
||||||
|
# must run its own code, not whatever lives in ~/Projects/netsec-agent.
|
||||||
set -u
|
set -u
|
||||||
cd /home/lancelot/Projects/netsec-agent || exit 1
|
cd "$(dirname "$0")" || exit 1
|
||||||
exec python3 -m netsec_scan "$@"
|
exec python3 -m netsec_scan "$@"
|
||||||
|
|
|
||||||
237
tests/test_http_rules.py
Normal file
237
tests/test_http_rules.py
Normal file
|
|
@ -0,0 +1,237 @@
|
||||||
|
"""Gateway access-log rules: classification, FP suppression, rate, caps.
|
||||||
|
|
||||||
|
Fixtures are real lines from the live stream (2026-11-27), including the four
|
||||||
|
Forgejo shapes that a substring rule gets wrong: `.git/info/refs`, a browse URL
|
||||||
|
ending in `.gitignore`, one ending in `.env.example` behind an RSS route, and a
|
||||||
|
`*-credentials.yaml` file view.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
from netsec_scan import config, http_rules
|
||||||
|
|
||||||
|
|
||||||
|
def rec(path, code=404, host="siriusdevops.com", client="203.0.113.7",
|
||||||
|
ua="Mozilla/5.0", method="GET", peer="10.10.0.1", client_ip=None):
|
||||||
|
return {
|
||||||
|
"path": path, "response_code": code, "authority": host, "method": method,
|
||||||
|
"user_agent": ua, "peer": peer,
|
||||||
|
"client_ip": client if client_ip is None else client_ip,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class TestClassification(unittest.TestCase):
|
||||||
|
def test_secret_probe_from_calm_day(self):
|
||||||
|
# measured 2026-11-27: the 91.92.47.0/24 scanner, all 404
|
||||||
|
for path in ("/.env", "/backup/.env", "/api/app/.env", "/.aws/credentials",
|
||||||
|
"/bedrock-credentials.json", "/service-account.json",
|
||||||
|
"/.git/credentials", "/latest/meta-data/iam/security-credentials"):
|
||||||
|
cat, sev, rule = http_rules.classify(rec(path))
|
||||||
|
self.assertIn(cat, ("secret-file", "vcs-probe"), path)
|
||||||
|
self.assertEqual(sev, "MEDIUM", path)
|
||||||
|
|
||||||
|
def test_served_secret_is_high(self):
|
||||||
|
cat, sev, rule = http_rules.classify(rec("/.env", code=200))
|
||||||
|
self.assertEqual((cat, sev, rule), ("secret-file", "HIGH", "http-secret-probe"))
|
||||||
|
|
||||||
|
def test_traversal_in_path_is_high_only_when_served(self):
|
||||||
|
cat, sev, _ = http_rules.classify(rec("/../../etc/passwd", code=200))
|
||||||
|
self.assertEqual((cat, sev), ("traversal", "HIGH"))
|
||||||
|
cat, sev, _ = http_rules.classify(rec("/%2e%2e%2f%2e%2e%2fetc%2fpasswd", code=404))
|
||||||
|
self.assertEqual((cat, sev), ("traversal", "MEDIUM"))
|
||||||
|
|
||||||
|
def test_traversal_in_query_string_is_not_served_high(self):
|
||||||
|
"""`/?file=../../.env` on a static site answers 200 regardless."""
|
||||||
|
cat, sev, _ = http_rules.classify(rec("/?file=../../../etc/passwd", code=200))
|
||||||
|
self.assertEqual((cat, sev), ("traversal", "MEDIUM"))
|
||||||
|
|
||||||
|
def test_sqli(self):
|
||||||
|
for path in ("/index.php?q=union+select+1,2",
|
||||||
|
"/?id=1%27+or+1%3D1--",
|
||||||
|
"/item?id=1 union all select user,pass from users",
|
||||||
|
"/x.php?id=1;sleep(5)"):
|
||||||
|
cat, sev, rule = http_rules.classify(rec(path))
|
||||||
|
self.assertEqual(cat, "sqli", path)
|
||||||
|
self.assertEqual(rule, "http-sqli")
|
||||||
|
|
||||||
|
def test_nul_byte(self):
|
||||||
|
cat, sev, _ = http_rules.classify(rec("/.env%00.txt"))
|
||||||
|
self.assertEqual(cat, "nul-byte")
|
||||||
|
self.assertEqual(sev, "MEDIUM") # 400/404: attempt, not a read
|
||||||
|
|
||||||
|
def test_backup_extensions(self):
|
||||||
|
for path in ("/backup.zip", "/db.sql", "/site.tar.gz", "/config.php.bak",
|
||||||
|
"/credentials.old"):
|
||||||
|
cat, sev, rule = http_rules.classify(rec(path))
|
||||||
|
self.assertEqual(rule, "http-backup-probe", path)
|
||||||
|
self.assertEqual(sev, "LOW", path)
|
||||||
|
|
||||||
|
def test_scanner_user_agents(self):
|
||||||
|
for ua, sev in (("sqlmap/1.8#stable (https://sqlmap.org)", "HIGH"),
|
||||||
|
("Mozilla/5.00 (Nikto/2.5.0)", "HIGH"),
|
||||||
|
("zgrab/0.x", "LOW")):
|
||||||
|
cat, severity, rule = http_rules.classify(rec("/", code=200, ua=ua))
|
||||||
|
self.assertEqual(rule, "http-scanner-ua", ua)
|
||||||
|
self.assertEqual(severity, sev, ua)
|
||||||
|
self.assertTrue(cat.startswith("scanner-ua:"))
|
||||||
|
|
||||||
|
def test_ordinary_traffic_is_none(self):
|
||||||
|
for path, ua in (
|
||||||
|
("/", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/153.0"),
|
||||||
|
("/user/login", "Mozilla/5.0 (compatible; GPTBot/1.4; +https://openai.com/gptbot)"),
|
||||||
|
("/api/v1/repos/sirius/homek8s", "git/2.56.0"),
|
||||||
|
("/index.html", "connect-go/1.17.0 (go1.23.3)")):
|
||||||
|
self.assertIsNone(http_rules.classify(rec(path, code=200, ua=ua)), path)
|
||||||
|
|
||||||
|
|
||||||
|
class TestForgejoFalsePositives(unittest.TestCase):
|
||||||
|
"""The shapes that made a naive rule unusable on this stream."""
|
||||||
|
|
||||||
|
def assertNone(self, path, code=303):
|
||||||
|
self.assertIsNone(
|
||||||
|
http_rules.classify(rec(path, code=code, host="forgejo.siriusdevops.com",
|
||||||
|
client="137.118.156.124", ua="git/2.56.0")),
|
||||||
|
path)
|
||||||
|
|
||||||
|
def test_smart_http_git_endpoints(self):
|
||||||
|
for path in ("/sirius/homek8s.git/info/refs?service=git-upload-pack",
|
||||||
|
"/sirius/netsec-agent.git/info/refs?service=git-receive-pack",
|
||||||
|
"/sirius/homek8s.git/git-upload-pack",
|
||||||
|
"/sirius/homek8s.git/git-receive-pack"):
|
||||||
|
self.assertNone(path, code=200)
|
||||||
|
|
||||||
|
def test_browse_urls_carry_dangerous_filenames(self):
|
||||||
|
for path in (
|
||||||
|
"/sirius/onionwire/raw/commit/adcf52b8e48d9e0240896ef4289e540d40e98f8e/.gitignore",
|
||||||
|
"/mayx/blog/blame/commit/7785bc18c726c2757965874696fd0279cca57d2b/.gitlab-ci.yml",
|
||||||
|
"/sirius/gcloud-lab/commit/87632b22478417bdfd94d71e70fe752845adda4f/immediate-backup.yaml",
|
||||||
|
"/sirius/gcloud-lab/raw/commit/752d173a07eb698f661e8a8eb2f899a124a4cae5/apps/base/customer1/hermes-db/memory-db-credentials.yaml",
|
||||||
|
"/sirius/homek8s/blame/branch/wt/t_013fce30/.gitignore",
|
||||||
|
"/sirius/osint-dashboard/rss/branch/osint-dashboard/t_45362857-osint-hud-counts-shortcuts-terminator-zo/.env.example",
|
||||||
|
"/sirius/homek8s/compare/feat/anonymize-customer1...master?style=unified",
|
||||||
|
"/sirius/onionwire/-/archive/main/onionwire-main.tar.gz"):
|
||||||
|
self.assertNone(path)
|
||||||
|
|
||||||
|
def test_same_shapes_on_a_static_host_are_probes(self):
|
||||||
|
cat, sev, rule = http_rules.classify(rec("/.env", code=404))
|
||||||
|
self.assertEqual(rule, "http-secret-probe")
|
||||||
|
self.assertEqual(sev, "MEDIUM")
|
||||||
|
|
||||||
|
def test_git_endpoint_style_probe_on_another_host_is_vcs(self):
|
||||||
|
cat, _sev, rule = http_rules.classify(
|
||||||
|
rec("/.git/config", code=404, host="siriusdevops.com"))
|
||||||
|
self.assertEqual(cat, "vcs-probe")
|
||||||
|
self.assertEqual(rule, "http-vcs-probe")
|
||||||
|
|
||||||
|
|
||||||
|
class TestClientAttribution(unittest.TestCase):
|
||||||
|
def test_client_ip_wins(self):
|
||||||
|
self.assertEqual(http_rules.client_of(rec("/", client="198.51.100.9")),
|
||||||
|
"198.51.100.9")
|
||||||
|
|
||||||
|
def test_peer_is_the_fallback_for_internal_requests(self):
|
||||||
|
self.assertEqual(http_rules.client_of(rec("/", client_ip="", peer="10.10.0.3")),
|
||||||
|
"10.10.0.3")
|
||||||
|
|
||||||
|
def test_cloudflare_edge_without_client_ip_is_unattributable(self):
|
||||||
|
self.assertIsNone(http_rules.client_of(rec("/", client_ip="", peer="10.10.0.1")))
|
||||||
|
|
||||||
|
def test_x_forwarded_for_is_never_the_key(self):
|
||||||
|
r = rec("/", client_ip="", peer="10.10.0.3")
|
||||||
|
r["x_forwarded_for"] = "1.2.3.4,10.10.0.1"
|
||||||
|
self.assertEqual(http_rules.client_of(r), "10.10.0.3")
|
||||||
|
|
||||||
|
|
||||||
|
class TestAttackPathFindings(unittest.TestCase):
|
||||||
|
def test_one_finding_per_client_and_category_not_per_path(self):
|
||||||
|
records = [rec("/.env"), rec("/backup/.env"), rec("/api/.env.local"),
|
||||||
|
rec("/.git/config"), rec("/.env", client="198.51.100.9")]
|
||||||
|
findings, counts = http_rules.rule_attack_paths(records, "10m")
|
||||||
|
self.assertEqual(len(findings), 3) # 2 categories x 2 clients
|
||||||
|
secret = [f for f in findings if f.entity.startswith("secret-file")]
|
||||||
|
self.assertEqual(len(secret), 2)
|
||||||
|
self.assertTrue(any("(3x in 10m)" in f.detail for f in secret))
|
||||||
|
self.assertEqual(counts["http-secret-probe"], 4)
|
||||||
|
self.assertEqual(counts["http-vcs-probe"], 1)
|
||||||
|
|
||||||
|
def test_fingerprint_is_stable_and_path_independent(self):
|
||||||
|
a, _ = http_rules.rule_attack_paths([rec("/.env")], "10m")
|
||||||
|
b, _ = http_rules.rule_attack_paths(
|
||||||
|
[rec("/another/.env.production", code=200)], "10m")
|
||||||
|
self.assertEqual(a[0].fingerprint, b[0].fingerprint)
|
||||||
|
|
||||||
|
def test_unattributable_client_is_keyed_but_never_the_edge_ip(self):
|
||||||
|
records = [rec("/.env", client_ip="", peer="10.10.0.1")]
|
||||||
|
findings, _ = http_rules.rule_attack_paths(records, "10m")
|
||||||
|
self.assertIn("unknown", findings[0].entity)
|
||||||
|
self.assertNotIn("10.10.0.1", findings[0].entity)
|
||||||
|
|
||||||
|
def test_cap_collapses_a_flood_into_one_state_line(self):
|
||||||
|
records = [rec("/.env", client="198.51.100.%d" % i) for i in range(1, 21)]
|
||||||
|
findings, _ = http_rules.rule_attack_paths(records, "10m")
|
||||||
|
kept, overflow = http_rules.cap_findings(findings)
|
||||||
|
self.assertEqual(len(kept), config.HTTP_MAX_NEW_PER_TICK)
|
||||||
|
self.assertIsNotNone(overflow)
|
||||||
|
self.assertEqual(overflow.rule, "http-flood")
|
||||||
|
self.assertEqual(overflow.kind, "state")
|
||||||
|
self.assertIn("8 more", overflow.detail)
|
||||||
|
|
||||||
|
def test_under_the_cap_produces_no_overflow(self):
|
||||||
|
findings, _ = http_rules.rule_attack_paths([rec("/.env")], "10m")
|
||||||
|
kept, overflow = http_rules.cap_findings(findings)
|
||||||
|
self.assertEqual(kept, findings)
|
||||||
|
self.assertIsNone(overflow)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAuthRate(unittest.TestCase):
|
||||||
|
def series(self, client, per_minute):
|
||||||
|
return [({"client_ip": client, "peer": "10.10.0.1"},
|
||||||
|
[(float(i * 60), float(v)) for i, v in enumerate(per_minute)])]
|
||||||
|
|
||||||
|
def test_ci_credential_retry_is_below_the_floor(self):
|
||||||
|
"""Measured: the git client retries 3/min, 25/hour - must stay silent."""
|
||||||
|
findings, n = http_rules.rule_auth_rate(self.series("137.118.156.124", [3, 3, 3, 3, 3]), "5m")
|
||||||
|
self.assertEqual(findings, [])
|
||||||
|
self.assertEqual(n, 1)
|
||||||
|
|
||||||
|
def test_single_minute_spike_below_total_is_silent(self):
|
||||||
|
# 19 in one minute, 19 total: neither the per-minute nor the total floor
|
||||||
|
findings, _ = http_rules.rule_auth_rate(self.series("198.51.100.5", [19, 0, 0, 0, 0]), "5m")
|
||||||
|
self.assertEqual(findings, [])
|
||||||
|
|
||||||
|
def test_sustained_brute_force_fires_once(self):
|
||||||
|
findings, _ = http_rules.rule_auth_rate(
|
||||||
|
self.series("198.51.100.5", [30, 2, 1, 0, 0]), "5m")
|
||||||
|
self.assertEqual(len(findings), 1)
|
||||||
|
self.assertEqual(findings[0].rule, "http-auth-brute")
|
||||||
|
self.assertEqual(findings[0].kind, "state")
|
||||||
|
self.assertIn("peak 30/min", findings[0].detail)
|
||||||
|
|
||||||
|
def test_heavy_brute_force_is_high(self):
|
||||||
|
findings, _ = http_rules.rule_auth_rate(
|
||||||
|
self.series("198.51.100.5", [60, 60, 60, 0, 0]), "5m")
|
||||||
|
self.assertEqual(findings[0].severity, "HIGH")
|
||||||
|
|
||||||
|
def test_internal_client_uses_peer(self):
|
||||||
|
matrix = [({"client_ip": "", "peer": "10.10.0.3"},
|
||||||
|
[(0.0, 40.0), (60.0, 5.0)])]
|
||||||
|
findings, _ = http_rules.rule_auth_rate(matrix, "5m")
|
||||||
|
self.assertEqual(len(findings), 1)
|
||||||
|
self.assertIn("10.10.0.3", findings[0].detail)
|
||||||
|
|
||||||
|
def test_edge_peer_is_not_a_client(self):
|
||||||
|
matrix = [({"client_ip": "", "peer": "10.10.0.1"},
|
||||||
|
[(0.0, 400.0), (60.0, 400.0)])]
|
||||||
|
self.assertEqual(http_rules.rule_auth_rate(matrix, "5m")[0], [])
|
||||||
|
|
||||||
|
|
||||||
|
class TestDecode(unittest.TestCase):
|
||||||
|
def test_double_encoding_is_decoded(self):
|
||||||
|
self.assertEqual(http_rules.decode_path("/%252f.env"), "//.env")
|
||||||
|
self.assertEqual(http_rules.decode_path("/%2f.env"), "//.env")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Loading…
Reference in a new issue