From 6b69b1eabf308ea833f953bf5c226404516cd6e7 Mon Sep 17 00:00:00 2001 From: David Papp Date: Mon, 30 Nov 2026 10:59:42 +0100 Subject: [PATCH] feat(use-cases): axon scan detection pipeline and threat-score blocking Two flow_by_axon sets beyond axon-flow's single file: - axon-scan-detection: four files in one pipeline, axon.stash and shared dictionaries counting over time windows. Tags outbound-portscan (25+ ports of one host), outbound-sweep (one uncommon port on 40+ hosts) and inbound-subnet-scan (3+ addresses of one /24 on 15+ ports). Tags only. - axon-threat-block: allow_block on, blocks an outside source with a threat score of 50-89 once it trips the IDS, the traffic classifier or 10+ ports. test/threat.mmdb is written by make-threat-mmdb.py. Each has a test.sh that runs live traffic between two network namespaces, with a control per check. The blocking test uses the benchmarking range 198.18.0.0/15: Synapse never bans a documentation address. Both tests need tcpdump, which AF_PACKET capture uses to compile its filter. --- README.md | 10 ++ use-cases/README.md | 2 + use-cases/axon-scan-detection/00_common.lua | 22 +++ .../10_outbound_portscan.lua | 34 +++++ .../axon-scan-detection/20_outbound_sweep.lua | 42 ++++++ .../30_inbound_subnet_scan.lua | 48 ++++++ use-cases/axon-scan-detection/README.md | 76 ++++++++++ use-cases/axon-scan-detection/config.yaml | 59 ++++++++ use-cases/axon-scan-detection/test.sh | 138 ++++++++++++++++++ use-cases/axon-threat-block/README.md | 79 ++++++++++ use-cases/axon-threat-block/config.yaml | 51 +++++++ use-cases/axon-threat-block/test.sh | 123 ++++++++++++++++ .../test/make-threat-mmdb.py | 90 ++++++++++++ use-cases/axon-threat-block/test/threat.mmdb | Bin 0 -> 1116 bytes use-cases/axon-threat-block/threat_block.lua | 56 +++++++ 15 files changed, 830 insertions(+) create mode 100644 use-cases/axon-scan-detection/00_common.lua create mode 100644 use-cases/axon-scan-detection/10_outbound_portscan.lua create mode 100644 use-cases/axon-scan-detection/20_outbound_sweep.lua create mode 100644 use-cases/axon-scan-detection/30_inbound_subnet_scan.lua create mode 100644 use-cases/axon-scan-detection/README.md create mode 100644 use-cases/axon-scan-detection/config.yaml create mode 100755 use-cases/axon-scan-detection/test.sh create mode 100644 use-cases/axon-threat-block/README.md create mode 100644 use-cases/axon-threat-block/config.yaml create mode 100755 use-cases/axon-threat-block/test.sh create mode 100644 use-cases/axon-threat-block/test/make-threat-mmdb.py create mode 100644 use-cases/axon-threat-block/test/threat.mmdb create mode 100644 use-cases/axon-threat-block/threat_block.lua diff --git a/README.md b/README.md index aa8308f..e56d2e4 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,16 @@ is at [docs.gen0sec.com](https://docs.gen0sec.com). - [Lua snippets on flows](./use-cases/axon-flow/): an axon snippet runs on every flow the smart firewall evaluated and tags it. Needs Synapse 0.8.10 built with the `axon` feature. +- [Scan detection with a snippet pipeline](./use-cases/axon-scan-detection/): + four axon files in one pipeline count in shared dictionaries and tag + outgoing port scans and sweeps and an outside /24 that scans together, with + a script that runs each scan and a control. Needs Synapse 0.8.10 built with + the `axon` feature. +- [Blocking on a threat score plus evidence](./use-cases/axon-threat-block/): an + axon snippet blocks an outside source with a middling threat score once it + also trips the IDS, the traffic classifier or a port count, with a script + that checks what it blocks and what it leaves. Needs Synapse 0.8.10 built + with the `axon` feature and an API key. ### Being updated diff --git a/use-cases/README.md b/use-cases/README.md index c275400..0e44ab6 100644 --- a/use-cases/README.md +++ b/use-cases/README.md @@ -30,6 +30,8 @@ closest to what you want and copy it. Every set uses placeholder values | [`kubernetes-cert-manager`](./kubernetes-cert-manager/) | proxy | no | a privileged proxy pod, Kubernetes cluster | A `SynapseProxy` of the Synapse operator serving an Ingress with a certificate from cert-manager, and the proxy picking up a renewed certificate without a restart; needs Synapse operator 0.2.0 (not released yet) and Synapse 0.8.8 or later | | [`axon-access`](./axon-access/) | proxy | no | none: the demo listens on port 8090 | A Lua snippet on every request the WAF allowed: block a path, rate-limit a client with a shared dictionary, tag a scanner in the access log; needs Synapse 0.8.10 built with the `axon` feature | | [`axon-flow`](./axon-flow/) | agent | no | the same as `smart-firewall` | A Lua snippet on every flow the smart firewall evaluated: tag a flow with a named expression and by field; needs Synapse 0.8.10 built with the `axon` feature | +| [`axon-scan-detection`](./axon-scan-detection/) | agent | no | the same as `smart-firewall` | A pipeline of Lua snippets with shared dictionaries that tags outgoing port scans and sweeps and an outside /24 scanning together; tags only; needs Synapse 0.8.10 built with the `axon` feature | +| [`axon-threat-block`](./axon-threat-block/) | agent | yes | the same as `smart-firewall` | A Lua snippet that blocks an outside source with a threat score of 50-89 once it also trips the IDS, the traffic classifier or 10+ ports; needs Synapse 0.8.10 built with the `axon` feature | "Privileges" lists what the set's own config needs; the installation guide lists what the container image needs on top. Installation is covered in the diff --git a/use-cases/axon-scan-detection/00_common.lua b/use-cases/axon-scan-detection/00_common.lua new file mode 100644 index 0000000..627b051 --- /dev/null +++ b/use-cases/axon-scan-detection/00_common.lua @@ -0,0 +1,22 @@ +-- Stage 0 of the pipeline: work out once per flow what every later stage +-- needs, and hand it down in axon.stash, a table that lives for this one +-- flow and is shared by every stage of the pipeline. +-- +-- stash.syn a client's opening SYN (SYN without ACK) +-- stash.inbound an outside source reaching a HOME_NET address +-- stash.outbound a HOME_NET source reaching an outside address +-- +-- "Outside" and "home" come from ids.address_vars.HOME_NET in config.yaml. +-- A stage returns nil or { tag = "..." }; tags add up across the stages. + +local ctx = axon.ctx +local s = axon.stash + +local flags = ctx.tcp_flags +s.syn = ctx.proto == 6 and flags ~= nil and (flags & 0x12) == 0x02 + +local src_home, dst_home = ctx.ids_src_home_net, ctx.ids_dst_home_net +s.inbound = src_home == false and dst_home == true +s.outbound = src_home == true and dst_home == false + +return nil diff --git a/use-cases/axon-scan-detection/10_outbound_portscan.lua b/use-cases/axon-scan-detection/10_outbound_portscan.lua new file mode 100644 index 0000000..05a73af --- /dev/null +++ b/use-cases/axon-scan-detection/10_outbound_portscan.lua @@ -0,0 +1,34 @@ +-- outbound-portscan: one of your hosts opening connections to many ports of +-- one outside host (a vertical scan), as a compromised or misused machine +-- does. +-- +-- Counts the distinct destination ports of each (source, destination) pair +-- for WINDOW seconds from the pair's first connection, and tags the flow +-- that reaches PORTS, once per pair every REPEAT seconds. + +local PORTS = 25 +local WINDOW = 600 +local REPEAT = 3600 + +local s = axon.stash +if not (s.syn and s.outbound) then + return nil +end +local seen, counts = axon.shared.scan_seen, axon.shared.scan_counts +if not seen or not counts then + return nil +end + +local ctx = axon.ctx +local pair = ctx.src_ip .. ">" .. ctx.dst_ip +-- add() succeeds only for a key that is not there yet: a port not yet seen +-- for this pair in the window. +if not seen:add("vp|" .. pair .. "|" .. ctx.dst_port, true, WINDOW) then + return nil +end +local n = counts:incr("vp|" .. pair, 1, 0, WINDOW) +if n and n >= PORTS and seen:add("vp!" .. pair, true, REPEAT) then + axon.log.warn("outbound-portscan " .. pair .. " ports=" .. n) + return { tag = "outbound-portscan" } +end +return nil diff --git a/use-cases/axon-scan-detection/20_outbound_sweep.lua b/use-cases/axon-scan-detection/20_outbound_sweep.lua new file mode 100644 index 0000000..540e645 --- /dev/null +++ b/use-cases/axon-scan-detection/20_outbound_sweep.lua @@ -0,0 +1,42 @@ +-- outbound-sweep: one of your hosts opening connections to one port on many +-- outside hosts (a horizontal scan for SSH, RDP, SMB, databases, ...). +-- +-- Web, DNS, mail, time, push and VPN ports are left out: browsers and apps +-- reach hundreds of hosts on those. Counts the distinct destinations of each +-- (source, port) for WINDOW seconds and tags the flow that reaches HOSTS, +-- once per (source, port) every REPEAT seconds. + +local HOSTS = 40 +local WINDOW = 600 +local REPEAT = 3600 + +local COMMON = { + [53] = true, [80] = true, [123] = true, [443] = true, [853] = true, + [465] = true, [587] = true, [993] = true, [995] = true, [5223] = true, + [5228] = true, [3478] = true, [8080] = true, [8443] = true, [51820] = true, +} + +local s = axon.stash +if not (s.syn and s.outbound) then + return nil +end +local ctx = axon.ctx +local port = ctx.dst_port +if COMMON[port] then + return nil +end +local seen, counts = axon.shared.scan_seen, axon.shared.scan_counts +if not seen or not counts then + return nil +end + +local key = ctx.src_ip .. ":" .. port +if not seen:add("hs|" .. key .. "|" .. ctx.dst_ip, true, WINDOW) then + return nil +end +local n = counts:incr("hs|" .. key, 1, 0, WINDOW) +if n and n >= HOSTS and seen:add("hs!" .. key, true, REPEAT) then + axon.log.warn("outbound-sweep " .. key .. " hosts=" .. n) + return { tag = "outbound-sweep" } +end +return nil diff --git a/use-cases/axon-scan-detection/30_inbound_subnet_scan.lua b/use-cases/axon-scan-detection/30_inbound_subnet_scan.lua new file mode 100644 index 0000000..2f2640a --- /dev/null +++ b/use-cases/axon-scan-detection/30_inbound_subnet_scan.lua @@ -0,0 +1,48 @@ +-- inbound-subnet-scan: several addresses of one outside /24 that together +-- probe many ports of your network. Internet-wide scanners spread a scan +-- over dozens of addresses, each touching a few ports an hour, so no single +-- address reaches a per-source port-count rule. Summed per /24 they stand +-- out, and the tag names the network to block. +-- +-- Counts the distinct destination ports and the distinct source addresses +-- of each /24 for WINDOW seconds from its first probe, and tags the flow +-- that reaches both PORTS and SOURCES, once per /24 every REPEAT seconds. +-- IPv4 only. + +local PORTS = 15 +local SOURCES = 3 +local WINDOW = 3600 +local REPEAT = 21600 + +local s = axon.stash +if not (s.syn and s.inbound) then + return nil +end +local seen, counts = axon.shared.scan_seen, axon.shared.scan_counts +if not seen or not counts then + return nil +end + +local ctx = axon.ctx +local src = ctx.src_ip +local a, b, c = string.match(src, "^(%d+)%.(%d+)%.(%d+)%.%d+$") +if not a then + return nil +end +local net = a .. "." .. b .. "." .. c .. ".0/24" + +local ports = counts:get("snp|" .. net) +if seen:add("snp|" .. net .. "|" .. ctx.dst_port, true, WINDOW) then + ports = counts:incr("snp|" .. net, 1, 0, WINDOW) +end +local sources = counts:get("sns|" .. net) +if seen:add("sns|" .. net .. "|" .. src, true, WINDOW) then + sources = counts:incr("sns|" .. net, 1, 0, WINDOW) +end + +if ports and sources and ports >= PORTS and sources >= SOURCES + and seen:add("sn!" .. net, true, REPEAT) then + axon.log.warn("inbound-subnet-scan " .. net .. " ports=" .. ports .. " sources=" .. sources) + return { tag = "inbound-subnet-scan" } +end +return nil diff --git a/use-cases/axon-scan-detection/README.md b/use-cases/axon-scan-detection/README.md new file mode 100644 index 0000000..6d310f7 --- /dev/null +++ b/use-cases/axon-scan-detection/README.md @@ -0,0 +1,76 @@ +# axon: scan detection with a snippet pipeline + +Tag port scans and sweeps, outgoing and incoming, with a pipeline of short Lua +files that count over time windows in shared dictionaries. Needs Synapse +0.8.10 or later, **built with the `axon` cargo feature**, and with +`amygdala-reactor` (in the standard packages), on Linux. For one snippet +file and named expressions, start with [axon-flow](../axon-flow/). + +The pipeline (`files:` in `config.yaml`) runs these files in order on every +flow the smart firewall evaluated: + +| File | Tag | When | +|---|---|---| +| `00_common.lua` | none | Works out once per flow whether it is a client's opening SYN, and whether it goes from home to outside or from outside to home, and hands that to the other stages in `axon.stash` | +| `10_outbound_portscan.lua` | `outbound-portscan` | One home host opens connections to 25+ ports of one outside host within 10 minutes (a vertical scan) | +| `20_outbound_sweep.lua` | `outbound-sweep` | One home host opens connections to one port on 40+ outside hosts within 10 minutes (a horizontal scan). Web, DNS, mail, time, push and VPN ports are left out | +| `30_inbound_subnet_scan.lua` | `inbound-subnet-scan` | 3+ addresses of one outside /24 probe 15+ ports of your network within an hour. Internet-wide scanners spread a scan over many addresses, each touching a few ports, so no single address reaches a per-source rule | + +Each tag is given once per pair, port or /24 per hour (six hours for the /24), +so a long scan is one entry, not one per connection. + +Things to know: + +- **Home and outside** come from `ids.address_vars.HOME_NET`. Put all your + networks there, public addresses included. The IDS does not have to be on. +- **A pipeline is one snippet in stages.** The files share one Lua VM, one time + limit and one error budget. Tags add up in order; an error in any stage + leaves the flow unannotated. At most 16 files. +- **`axon.stash`** is a table that lives for one flow and is shared by its + stages. Use it to work something out once (here, the direction). +- **Shared dictionaries** (`snippet.shared_dicts`) keep counts across flows. + `add` writes a key only when it is not there yet, so "a port not seen for + this pair" is one call. `incr` counts, and the key keeps the expiry it got + when it was created, so a window runs from its first event. `entries` is a + number of keys; a full dictionary drops its least recently used keys first. + The dictionaries live in the process: a restart empties them, a reload + (`SIGHUP`) keeps them. +- **Thresholds** are the constants at the top of each file. Change them there. +- **Every stage only tags.** A tag is an `axon:` log entry next to the + smart firewall's matches, in `events.log` and the CEF output. The stages also + log one line with the numbers behind a tag, such as + `outbound-portscan 10.0.0.5>198.51.100.1 ports=25`, to the application log. + To block, see [axon-threat-block](../axon-threat-block/). + +The privileges, kernel and interface settings are those of the +[smart-firewall](../smart-firewall/) set, which this config is based on. + +## Test + +`test.sh` runs this set's `ids:` and `snippet:` blocks on live captured +traffic: + +```sh +sudo SYNAPSE_BIN=/path/to/synapse ./test.sh # "ok" or "FAIL" per check, exit 1 if any fails +``` + +It needs root, `ip`, `python3` and `tcpdump` (the agent compiles its +AF_PACKET filter with `tcpdump -dd`), and a Synapse built with `axon`. It +makes two network namespaces joined by a veth pair and runs the agent in one, +with AF_PACKET capture and `firewall.mode: none`. From the other it runs each +scan and a control that must not be tagged: + +| Traffic | Expected | +|---|---| +| 10.0.0.5 to 30 ports of 198.51.100.1 | one `outbound-portscan` | +| 10.0.0.5 to 20 ports of 198.51.100.2 | no tag | +| 10.0.0.5 to port 2222 on 50 hosts | one `outbound-sweep` | +| 10.0.0.5 to port 443 on the same 50 hosts | no tag | +| five addresses of 203.0.113.0/24, 20 ports in all, then two more addresses on 10 more ports | one `inbound-subnet-scan` | +| five addresses of 198.18.0.0/24, 10 ports in all | no tag | + +The host's interfaces and firewall are not touched, and the namespaces are +removed when it ends. + +To see the test fail, change `local PORTS = 25` to `local PORTS = 35` in +`10_outbound_portscan.lua` and run it again. diff --git a/use-cases/axon-scan-detection/config.yaml b/use-cases/axon-scan-detection/config.yaml new file mode 100644 index 0000000..7cf74cf --- /dev/null +++ b/use-cases/axon-scan-detection/config.yaml @@ -0,0 +1,59 @@ +# axon-scan-detection: a pipeline of Lua snippets that tags port scans and +# sweeps on every flow the smart firewall evaluated. Needs Synapse 0.8.10 or +# later, built with the `axon` feature (and with `amygdala-reactor`, which the +# standard packages have). +mode: agent + +firewall: + enabled: true + mode: xdp + amygdala: + enabled: true + backend: auto + +capture: + enabled: true + interface: eth0 + +# The snippets read "home" and "outside" from HOME_NET +# (axon.ctx.ids_src_home_net / ids_dst_home_net). Put your own networks here, +# public addresses included. The IDS does not need to be on for this. +ids: + address_vars: + HOME_NET: "[10.0.0.0/8,172.16.0.0/12,192.168.0.0/16]" + EXTERNAL_NET: "!$HOME_NET" + +logging: + level: info + file_logging_enabled: true + log_directory: "/var/log/synapse" + events_log_format: json + eventbridge_log: + enabled: true + +snippet: + enabled: true + # Stop the start when the snippets cannot load, instead of running without. + required: true + + # Process-wide dictionaries the stages count in. A name that is not declared + # here reads as nil in a snippet. `entries` is a number of keys, not bytes; + # a full dictionary drops its least recently used keys first. + shared_dicts: + - name: scan_seen + entries: 200000 + - name: scan_counts + entries: 50000 + + flow_by_axon: + # A pipeline: the files run in this order on every flow, in one Lua VM, + # as one snippet split into stages. Tags add up; axon.stash carries + # values from one stage to the next for the same flow. + files: + - 00_common.lua + - 10_outbound_portscan.lua + - 20_outbound_sweep.lua + - 30_inbound_subnet_scan.lua + # Off: the stages only tag. A tag is an `axon:` log entry next to + # the smart firewall's own matches. + allow_block: false diff --git a/use-cases/axon-scan-detection/test.sh b/use-cases/axon-scan-detection/test.sh new file mode 100755 index 0000000..d6408c4 --- /dev/null +++ b/use-cases/axon-scan-detection/test.sh @@ -0,0 +1,138 @@ +#!/bin/sh +# Check the scan-detection pipeline on live captured traffic. Exit 1 if any +# check fails. +# sudo SYNAPSE_BIN=/path/to/synapse ./test.sh +# +# Needs root, ip (iproute2), python3 and tcpdump (the agent compiles its +# AF_PACKET filter with `tcpdump -dd`). Everything runs in two network +# namespaces made for the run and joined by a veth pair: the agent captures +# on its end with AF_PACKET and `firewall.mode: none`, so the host's +# interfaces and firewall are not touched. The namespaces are removed on exit. +# The agent runs this set's `ids:` and `snippet:` blocks as they are: +# HOME_NET is the private ranges, so 10.0.0.0/24 is "home" and the +# documentation ranges are "outside". +set -u +cd "$(dirname "$0")" || exit 2 +here=$(pwd) +bin=${SYNAPSE_BIN:-synapse} +bin=$(command -v "$bin") || { echo "error: synapse binary not found; set SYNAPSE_BIN" >&2; exit 2; } +[ "$(id -u)" -eq 0 ] || { echo "error: run as root (AF_PACKET capture and network namespaces)" >&2; exit 2; } +for t in ip python3 tcpdump; do command -v $t >/dev/null || { echo "error: $t is required" >&2; exit 2; }; done + +id=$$ +cli=axs-cli-$id srv=axs-srv-$id vc=axsc$id vs=axss$id +work=$(mktemp -d) || exit 2 +apid='' +cleanup() { + if [ -n "$apid" ] && [ "$apid" -gt 1 ] && kill -0 "$apid" 2>/dev/null; then + kill -TERM "$apid"; sleep 1 + kill -0 "$apid" 2>/dev/null && kill -KILL "$apid" + fi + ip netns del "$cli" 2>/dev/null + ip netns del "$srv" 2>/dev/null + rm -rf -- "${work:?}" +} +trap cleanup EXIT INT TERM + +# --- two namespaces. The client holds the scanning addresses: a home host +# (10.0.0.5) and outside addresses in three /24s. The server holds a home +# target (10.0.0.1) and the outside hosts the home host reaches. +ip netns add "$cli" && ip netns add "$srv" && ip link add "$vc" type veth peer name "$vs" || exit 2 +ip link set "$vc" netns "$cli" && ip link set "$vs" netns "$srv" || exit 2 +ip -n "$cli" addr add 10.0.0.5/24 dev "$vc" +for i in 11 12 13 14 15 21 22; do ip -n "$cli" addr add 203.0.113.$i/32 dev "$vc"; done +for i in 11 12 13 14 15; do ip -n "$cli" addr add 198.18.0.$i/32 dev "$vc"; done +ip -n "$srv" addr add 10.0.0.1/24 dev "$vs" +for i in $(seq 1 59); do ip -n "$srv" addr add 198.51.100.$i/32 dev "$vs"; done +for n in "$cli" "$srv"; do ip -n "$n" link set lo up; done +ip -n "$cli" link set "$vc" up +ip -n "$srv" link set "$vs" up +ip -n "$cli" route add 198.51.100.0/24 dev "$vc" +ip -n "$srv" route add 203.0.113.0/24 dev "$vs" +ip -n "$srv" route add 198.18.0.0/24 dev "$vs" + +# --- the agent: this set's ids: and snippet: blocks, captured on the veth +cp ./*.lua "$work"/ +chmod 644 "$work"/*.lua +{ + cat < "$work/config.yaml" +(cd "$work" && exec ip netns exec "$srv" "$bin" -c config.yaml --firewall-mode none >"$work/agent.out" 2>&1) & +apid=$! + +logs() { cat "$work/agent.out" "$work"/logs/*.log 2>/dev/null; } +i=0 +until logs | grep -q "AF_PACKET capture thread running on '$vs'"; do + i=$((i + 1)) + [ $i -le 60 ] || { echo "FAIL the capture did not start"; logs | tail -20; exit 1; } + sleep 1 +done + +# syn SRC DST PORT...: one connection attempt per port, closed at once. A +# closed port answers with a reset; the agent sees the SYN either way. +syn() { + ip netns exec "$cli" python3 -I - "$@" <<'EOF' +import socket, sys +src, dst, ports = sys.argv[1], sys.argv[2], sys.argv[3:] +for p in ports: + s = socket.socket(); s.bind((src, 0)); s.settimeout(1) + try: s.connect((dst, int(p))) + except OSError: pass + s.close() +EOF +} + +# Outbound port scan: 30 ports of one outside host. Control: 20 ports of another. +syn 10.0.0.5 198.51.100.1 $(seq 1001 1030) +syn 10.0.0.5 198.51.100.2 $(seq 2001 2020) +# Outbound sweep: port 2222 on 50 outside hosts. Control: port 443 on the same hosts. +for h in $(seq 10 59); do syn 10.0.0.5 198.51.100.$h 2222; done +for h in $(seq 10 59); do syn 10.0.0.5 198.51.100.$h 443; done +# Inbound /24 scan: five addresses of 203.0.113.0/24, four ports each (20 ports). +for i in 11 12 13 14 15; do syn 203.0.113.$i 10.0.0.1 $(seq $((3000 + i * 4)) $((3003 + i * 4))); done +# Control: five addresses of 198.18.0.0/24, but 10 ports in all. +for i in 11 12 13 14 15; do syn 198.18.0.$i 10.0.0.1 $((4000 + i * 2)) $((4001 + i * 2)); done +# Two more addresses of the tagged /24 on 10 more ports: still one tag. +for i in 21 22; do syn 203.0.113.$i 10.0.0.1 $(seq 5001 5010); done +sleep 3 + +fail=0 +ok() { echo "ok $1"; } +bad() { echo "FAIL $1"; fail=1; } +# One record per tag in events.log (the log lines also reach stdout and app.log). +events() { cat "$work"/logs/events.log 2>/dev/null; } +tags() { events | grep -F "\"rule_id\":\"axon:$1\"" | grep -c -F "\"src_ip\":\"$2"; } + +logs | grep -q "generation 1 loaded" && ok "the pipeline loaded" || bad "the pipeline did not load" +logs | grep -q "flow_by_axon (4 stages)" && ok "four stages" || bad "the pipeline does not have four stages" + +[ "$(tags outbound-portscan 10.0.0.5)" -eq 1 ] && ok "30 ports of one outside host: tagged outbound-portscan, once" \ + || bad "outbound-portscan: expected 1 tag, got $(tags outbound-portscan 10.0.0.5)" +logs | grep -q "outbound-portscan 10.0.0.5>198.51.100.2" && bad "20 ports of one host were tagged" \ + || ok "20 ports of one host: not tagged" + +[ "$(tags outbound-sweep 10.0.0.5)" -eq 1 ] && ok "port 2222 on 50 outside hosts: tagged outbound-sweep, once" \ + || bad "outbound-sweep: expected 1 tag, got $(tags outbound-sweep 10.0.0.5)" +logs | grep -q "outbound-sweep 10.0.0.5:443" && bad "port 443 on 50 hosts was tagged" \ + || ok "port 443 on 50 hosts: not tagged (a common port)" + +n=$(tags inbound-subnet-scan 203.0.113.) +[ "$n" -eq 1 ] && ok "five addresses of 203.0.113.0/24 on 20 ports: tagged inbound-subnet-scan, once" \ + || bad "inbound-subnet-scan for 203.0.113.0/24: expected 1 tag, got $n" +[ "$(tags inbound-subnet-scan 198.18.0.)" -gt 0 ] && bad "198.18.0.0/24 (10 ports) was tagged" \ + || ok "five addresses of 198.18.0.0/24 on 10 ports: not tagged" + +events | grep -F '"rule_id":"axon:' | grep -qv -F '"action":"log"' && bad "a tag was not log only" || ok "every tag is log only" +logs | grep "axon\[flow\]" | grep -q -i -E "error|fail" && bad "a snippet error" || ok "no snippet error" + +exit $fail diff --git a/use-cases/axon-threat-block/README.md b/use-cases/axon-threat-block/README.md new file mode 100644 index 0000000..6148ea0 --- /dev/null +++ b/use-cases/axon-threat-block/README.md @@ -0,0 +1,79 @@ +# axon: block on a threat score plus evidence + +Block an outside source whose threat score is in the middle band, 50 to 89, +once it also misbehaves on your network. Needs Synapse 0.8.10 or later, +**built with the `axon` cargo feature**, with `amygdala-reactor` (in the +standard packages), on Linux, and an API key for the platform's threat +database. For a snippet that only tags, see [axon-flow](../axon-flow/). + +A policy rule such as `threat.score ge 90 and threat.advice eq "block"` takes +the clear cases. Below 90, a score alone is weak evidence. `threat_block.lua` +blocks a source in that band only when it also does one of these: + +| Evidence | Field | Logged as | +|---|---|---| +| An IDS alert | `axon.ctx.ids_alert_count > 0` | `why=ids` | +| A scan verdict of the traffic classifier, 50+ | `axon.ctx.ml_traffic_scan` | `why=ml-scan` | +| A brute-force verdict of the traffic classifier, 50+ | `axon.ctx.ml_traffic_bruteforce` | `why=ml-bruteforce` | +| 10+ destination ports | `axon.ctx.flow_unique_dst_ports` | `why=ports` | + +Only flows from outside to home are judged (`HOME_NET` decides both), and a +flow the smart firewall already drops is left alone. The thresholds are the +constants at the top of the file. + +Things to know: + +- **`allow_block: true`** is what lets the snippet enforce. With it, the + snippet's `{ action = "block", tag = "threat-suspect" }` becomes the smart + firewall's per-address drop, a ban whose length the penalty model sets (and + lengthens for a source that comes back). Without it the same verdict is + recorded as a log entry, so you can run the snippet in observe mode first. +- **What is never banned:** the never-ban guard skips `HOME_NET` and the + host's own addresses, and the ban path refuses private, CGNAT, link-local, + documentation and other reserved ranges. An explicit smart-firewall allow + overrides the snippet. +- **A ban drops everything from that address**, including the replies to + connections your own hosts open to it. Block only where nothing of yours + answers unsolicited connections from that kind of source, or keep + `allow_block` off for a while and read what it would have blocked. +- **The record.** A block is an `axon:threat-suspect` entry in `events.log` + and the CEF output, with action `block` and the ban length (`ban_secs`). + The snippet also logs the reason once per source per hour, such as + `threat-suspect block 198.18.0.5 score=70 why=ports`, to the application + log. + +The privileges, kernel and interface settings are those of the +[smart-firewall](../smart-firewall/) set, which this config is based on. + +## Test + +`test.sh` runs this set's `ids:` and `snippet:` blocks on live captured +traffic: + +```sh +sudo SYNAPSE_BIN=/path/to/synapse ./test.sh # "ok" or "FAIL" per check, exit 1 if any fails +``` + +It needs root, `ip`, `python3` and `tcpdump` (the agent compiles its +AF_PACKET filter with `tcpdump -dd`), and a Synapse built with `axon`. It +makes two network namespaces joined by a veth pair and runs the agent in one, +with AF_PACKET capture and `firewall.mode: none`: a block goes through the +ban path and is recorded with its ban length, but there is no kernel backend +to apply it, so the record's action reads `notice`. The threat database is +[`test/threat.mmdb`](./test/threat.mmdb), written by +[`test/make-threat-mmdb.py`](./test/make-threat-mmdb.py): + +| Source | Threat score | Ports | Expected | +|---|---|---|---| +| 198.18.0.5 | 70 | 15 | blocked from the 10th port on | +| 198.18.0.6 | 70 | 5 | not blocked: no evidence | +| 198.19.0.5 | 95 | 15 | not blocked by the snippet: above the band | +| 198.19.1.5 | none | 15 | not blocked | + +The sources are in the benchmarking range (RFC 2544) rather than a +documentation range, because a documentation address is never banned. The +host's interfaces and firewall are not touched, and the namespaces are removed +when it ends. + +To see the test fail, set `allow_block: false` in `config.yaml` and run it +again: the verdict is then a log entry, not a block. diff --git a/use-cases/axon-threat-block/config.yaml b/use-cases/axon-threat-block/config.yaml new file mode 100644 index 0000000..0194b4e --- /dev/null +++ b/use-cases/axon-threat-block/config.yaml @@ -0,0 +1,51 @@ +# axon-threat-block: a Lua snippet that blocks an outside source with a +# middling threat score once it also misbehaves. Needs Synapse 0.8.10 or +# later, built with the `axon` feature (and with `amygdala-reactor`, which +# the standard packages have), and the platform's threat database. +mode: agent + +firewall: + enabled: true + mode: xdp + amygdala: + enabled: true + backend: auto + +capture: + enabled: true + interface: eth0 + +# The snippet blocks outside sources only: HOME_NET is home. Put your own +# networks here, public addresses included. Its addresses are never banned. +ids: + address_vars: + HOME_NET: "[10.0.0.0/8,172.16.0.0/12,192.168.0.0/16]" + EXTERNAL_NET: "!$HOME_NET" + +# The threat scores come from the platform's threat database, which the agent +# downloads with an API key: replace the placeholder with your key, or leave +# it empty and set the API_KEY environment variable. Never commit a real key. +platform: + api_key: YOUR_API_KEY + +logging: + level: info + file_logging_enabled: true + log_directory: "/var/log/synapse" + events_log_format: json + +snippet: + enabled: true + # Stop the start when the snippet cannot load, instead of running without it. + required: true + + shared_dicts: + # Sources whose reason was logged in the last hour. + - name: threat_seen + entries: 20000 + + flow_by_axon: + file: threat_block.lua + # On: the snippet's { action = "block" } becomes a smart-firewall drop of + # the source address. Off, the same verdict is recorded as a log entry. + allow_block: true diff --git a/use-cases/axon-threat-block/test.sh b/use-cases/axon-threat-block/test.sh new file mode 100755 index 0000000..daa7981 --- /dev/null +++ b/use-cases/axon-threat-block/test.sh @@ -0,0 +1,123 @@ +#!/bin/sh +# Check threat_block.lua on live captured traffic. Exit 1 if any check fails. +# sudo SYNAPSE_BIN=/path/to/synapse ./test.sh +# +# Needs root, ip (iproute2), python3 and tcpdump (the agent compiles its +# AF_PACKET filter with `tcpdump -dd`). Everything runs in two network +# namespaces made for the run and joined by a veth pair: the agent captures +# on its end with AF_PACKET and `firewall.mode: none`, so the host's +# interfaces and firewall are not touched, and a block is recorded, not +# enforced. The namespaces are removed on exit. The agent runs this set's +# `ids:` and `snippet:` blocks as they are, with test/threat.mmdb as its +# threat database (198.18.0.0/24 scored 70, 198.19.0.0/24 scored 95). The +# sources are in the benchmarking range (RFC 2544), not a documentation range: +# Synapse never bans a documentation, private or CGNAT address. +set -u +cd "$(dirname "$0")" || exit 2 +here=$(pwd) +bin=${SYNAPSE_BIN:-synapse} +bin=$(command -v "$bin") || { echo "error: synapse binary not found; set SYNAPSE_BIN" >&2; exit 2; } +[ "$(id -u)" -eq 0 ] || { echo "error: run as root (AF_PACKET capture and network namespaces)" >&2; exit 2; } +for t in ip python3 tcpdump; do command -v $t >/dev/null || { echo "error: $t is required" >&2; exit 2; }; done + +id=$$ +cli=axt-cli-$id srv=axt-srv-$id vc=axtc$id vs=axts$id +work=$(mktemp -d) || exit 2 +apid='' +cleanup() { + if [ -n "$apid" ] && [ "$apid" -gt 1 ] && kill -0 "$apid" 2>/dev/null; then + kill -TERM "$apid"; sleep 1 + kill -0 "$apid" 2>/dev/null && kill -KILL "$apid" + fi + ip netns del "$cli" 2>/dev/null + ip netns del "$srv" 2>/dev/null + rm -rf -- "${work:?}" +} +trap cleanup EXIT INT TERM + +# --- two namespaces: outside sources in the client, a home target (10.0.0.1) +# in the server +ip netns add "$cli" && ip netns add "$srv" && ip link add "$vc" type veth peer name "$vs" || exit 2 +ip link set "$vc" netns "$cli" && ip link set "$vs" netns "$srv" || exit 2 +for a in 198.18.0.5 198.18.0.6 198.19.0.5 198.19.1.5; do ip -n "$cli" addr add $a/32 dev "$vc"; done +ip -n "$srv" addr add 10.0.0.1/24 dev "$vs" +for n in "$cli" "$srv"; do ip -n "$n" link set lo up; done +ip -n "$cli" link set "$vc" up +ip -n "$srv" link set "$vs" up +ip -n "$cli" route add 10.0.0.0/24 dev "$vc" +for net in 198.18.0.0/15; do ip -n "$srv" route add $net dev "$vs"; done + +# --- the agent: this set's ids: and snippet: blocks, captured on the veth +cp threat_block.lua test/threat.mmdb "$work"/ +chmod 644 "$work/threat_block.lua" +{ + cat < "$work/config.yaml" +(cd "$work" && exec ip netns exec "$srv" "$bin" -c config.yaml --firewall-mode none >"$work/agent.out" 2>&1) & +apid=$! + +logs() { cat "$work/agent.out" "$work"/logs/*.log 2>/dev/null; } +i=0 +until logs | grep -q "AF_PACKET capture thread running on '$vs'"; do + i=$((i + 1)) + [ $i -le 60 ] || { echo "FAIL the capture did not start"; logs | tail -20; exit 1; } + sleep 1 +done + +# syn SRC PORT...: one connection attempt to 10.0.0.1 per port, closed at once. +syn() { + ip netns exec "$cli" python3 -I - "$@" <<'EOF' +import socket, sys +src, ports = sys.argv[1], sys.argv[2:] +for p in ports: + s = socket.socket(); s.bind((src, 0)); s.settimeout(1) + try: s.connect(("10.0.0.1", int(p))) + except OSError: pass + s.close() +EOF +} +syn 198.18.0.5 $(seq 3001 3015) # score 70, 15 ports: blocked from the 10th port +syn 198.18.0.6 $(seq 3101 3105) # score 70, 5 ports: no evidence, not blocked +syn 198.19.0.5 $(seq 3201 3215) # score 95: above the band, left to the policy +syn 198.19.1.5 $(seq 3301 3315) # no score: not blocked +sleep 3 + +fail=0 +ok() { echo "ok $1"; } +bad() { echo "FAIL $1"; fail=1; } +# One record per verdict in events.log (the log lines also reach stdout and +# app.log). A block carries the snippet's verdict and the ban's length; with +# `firewall.mode: none` there is no kernel backend to apply it, so its action +# reads "notice" here, where an enforcing agent writes "block". +events() { cat "$work"/logs/events.log 2>/dev/null; } +blocks() { + events | grep -F '"rule_id":"axon:threat-suspect"' | grep -F "\"src_ip\":\"$1\"" \ + | grep -F 'snippet: block' | grep -c -F '"ban_secs":' +} + +logs | grep -q "generation 1 loaded" && ok "the snippet loaded" || bad "the snippet did not load" +n=$(blocks 198.18.0.5) +[ "$n" -ge 1 ] && ok "score 70 and 10+ ports: blocked ($n flows)" || bad "198.18.0.5 was not blocked" +[ "$n" -le 6 ] && ok "no block before the 10th port" || bad "198.18.0.5 was blocked on more than its 10th to 15th port ($n)" +[ "$(logs | grep -c "threat-suspect block 198.18.0.5 score=70 why=ports")" -ge 1 ] \ + && ok "the reason is logged: score=70 why=ports" || bad "no reason line for 198.18.0.5" +[ "$(blocks 198.18.0.6)" -eq 0 ] && ok "score 70 and 5 ports: not blocked" || bad "198.18.0.6 was blocked without evidence" +[ "$(blocks 198.19.0.5)" -eq 0 ] && ok "score 95: not blocked by the snippet" || bad "198.19.0.5 (score 95) was blocked by the snippet" +[ "$(blocks 198.19.1.5)" -eq 0 ] && ok "no score: not blocked" || bad "198.19.1.5 (no score) was blocked" +logs | grep "axon\[flow\]" | grep -q -i -E "error|fail" && bad "a snippet error" || ok "no snippet error" + +exit $fail diff --git a/use-cases/axon-threat-block/test/make-threat-mmdb.py b/use-cases/axon-threat-block/test/make-threat-mmdb.py new file mode 100644 index 0000000..8955060 --- /dev/null +++ b/use-cases/axon-threat-block/test/make-threat-mmdb.py @@ -0,0 +1,90 @@ +"""Write threat.mmdb, the test's threat database, in the shape of the +platform's threat feed: + + 198.18.0.0/24 score 70 inside the snippet's band (50-89) + 198.19.0.0/24 score 95 above it: left to a policy rule + any other unknown + +The networks are the benchmarking range (RFC 2544), not the documentation +ranges: Synapse never bans a documentation, private or CGNAT address, so a +block of one would be refused and the test could not see it. + +Scores are unsigned 32-bit integers, which every Synapse release decodes. +The MMDB writer is part of this file, with no dependencies. + + python3 make-threat-mmdb.py (from this directory) +""" + +import ipaddress + +NETWORKS = { + "198.18.0.0/24": {"score": 70, "action": "block", "reason_code": "TEST_MIDDLE"}, + "198.19.0.0/24": {"score": 95, "action": "block", "reason_code": "TEST_HIGH"}, +} + + +def ctrl(type_no, size): + head, extra = (size, b"") if size < 29 else (29, bytes([size - 29])) + if type_no <= 7: + return bytes([(type_no << 5) | head]) + extra + return bytes([head, type_no - 7]) + extra + + +def encode(value, uint=6): + if isinstance(value, int): + raw = value.to_bytes({5: 2, 6: 4, 9: 8}[uint], "big").lstrip(b"\0") + return ctrl(uint, len(raw)) + raw + if isinstance(value, str): + raw = value.encode() + return ctrl(2, len(raw)) + raw + if isinstance(value, list): + return ctrl(11, len(value)) + b"".join(encode(v) for v in value) + if isinstance(value, tuple): # (uint type, value) for metadata integers + return encode(value[1], value[0]) + return ctrl(7, len(value)) + b"".join(encode(k) + encode(v) for k, v in value.items()) + + +def build(): + data, offsets = b"", [] + for record in NETWORKS.values(): + offsets.append(len(data)) + data += encode(record) + # IPv6 tree with IPv4 at ::/96; a record is a node index, the node count + # for "no data", or node count + 16 + an offset into the data section. + nodes = [[None, None]] + for network, offset in zip(NETWORKS, offsets): + net = ipaddress.ip_network(network) + bits = int.from_bytes(b"\0" * 12 + net.network_address.packed, "big") + depth, node = 96 + net.prefixlen, 0 + for i in range(depth): + bit = (bits >> (127 - i)) & 1 + if i == depth - 1: + nodes[node][bit] = ("data", offset) + else: + if nodes[node][bit] is None: + nodes.append([None, None]) + nodes[node][bit] = ("node", len(nodes) - 1) + node = nodes[node][bit][1] + count = len(nodes) + + def value(r): + return count if r is None else (r[1] if r[0] == "node" else count + 16 + r[1]) + + tree = b"".join(value(a).to_bytes(3, "big") + value(b).to_bytes(3, "big") for a, b in nodes) + metadata = { + "binary_format_major_version": (5, 2), + "binary_format_minor_version": (5, 0), + "build_epoch": (9, 1796040000), + "database_type": "IP-Metadata", + "description": {"en": "example threat database for the axon-threat-block test"}, + "ip_version": (5, 6), + "languages": [], + "node_count": (6, count), + "record_size": (5, 24), + } + return tree + b"\0" * 16 + data + b"\xab\xcd\xefMaxMind.com" + encode(metadata) + + +if __name__ == "__main__": + with open("threat.mmdb", "wb") as f: + f.write(build()) diff --git a/use-cases/axon-threat-block/test/threat.mmdb b/use-cases/axon-threat-block/test/threat.mmdb new file mode 100644 index 0000000000000000000000000000000000000000..2c699885ed69c69d0836651790145797fc6f90ad GIT binary patch literal 1116 zcmZ|NS#r}r5P;z!n6QR@Nm#|cI_&!vg6&vV1c8_}1TmH-wqjcn(m2>*%MmyNdFBpO zjER;LK6LevO+oW?q)Cp3g;5(nK( zC`2SgTZorrVoXqD3uo{Ze!vdS;%j_^Z}A@P<~2F8R^#+x40a h8B|-csuGbY1?f)G#k2ywFqiHr-Ja(p{;Zns{|SNF= BLOCK_SCORE then + return nil +end + +local why +if (ctx.ids_alert_count or 0) > 0 then + why = "ids" +elseif (ctx.ml_traffic_scan or 0) >= ML then + why = "ml-scan" +elseif (ctx.ml_traffic_bruteforce or 0) >= ML then + why = "ml-bruteforce" +elseif (ctx.flow_unique_dst_ports or 0) >= PORTS then + why = "ports" +else + return nil +end + +local seen = axon.shared.threat_seen +if seen and seen:add(ctx.src_ip, true, REPEAT) then + axon.log.info("threat-suspect block " .. ctx.src_ip .. " score=" .. score .. " why=" .. why) +end +return { action = "block", tag = "threat-suspect" }