Post

SOC Lab 5: Zeek and Suricata

SOC Lab 5: Zeek and Suricata

Toolchain: Zeek 8.2.1, Suricata 8.0.6 (libhtp 8.0.6), ET Open ruleset, jq, Docker Compose Environment: Linux, four containers, one monitored Docker bridge Series: Part 1 ran Snort 3 passive, Part 2 pushed it inline, Part 3 wrote Sigma rules, Part 4 wrote YARA rules for the artifact. This part stands up the two engines a real NSM sensor actually runs, side by side, and joins their output.

Snort saw the packets. Sigma saw the logs. YARA saw the files. Something fed all three: the network security monitor. Production SOCs run two engines on the wire, not one, because each answers a question the other cannot.

Suricata is a signature engine: is this known-bad? No rule match, no output [2]. Zeek is a protocol and behaviour engine: what happened? It turns every connection into a structured record (conn, http, dns, ssl, files, and dozens more), malicious or not [1]. Suricata’s output is a verdict. Zeek’s is evidence.

They are complements, so production lands both on the same span port. This post does the same: one Docker bridge, two containers tapping it from the host, five traffic scenarios, and a join key that fuses both outputs into one timeline.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
                      docker bridge  br-f00653ae2c26   (172.30.0.0/24)
                                                      
  nsm-attacker             tap                    tap              nsm-victim
  172.30.0.3  -------------+-----------------------+-------------  172.30.0.2
                           |                       |                 nginx
              AF_PACKET    |                       |    AF_PACKET
                           v                       v
                    +--------------+        +--------------+
                    | nsm-suricata |        |   nsm-zeek   |
                    |  signatures  |        |  protocols   |
                    |              |        |  + behaviour |
                    +------+-------+        +------+-------+
                           |                       |
                      eve.json                 conn.log
                      fast.log                 http.log dns.log
                      stats.log                files.log pe.log
                           |                   notice.log
                           \          |          /
                            \         |         /
                             v        v        v
                          community_id join   (1:in96FqiN1m+0ATa8PM6rkGohCQg=)

Roadmap

Nine steps, in the order they were run. Each one ends with the evidence it produced, so you can tell whether yours worked before moving on.

  1. Build the lab. Four containers on one bridge, a payload to serve, and five scenario scripts to generate traffic.
  2. Configure and verify both sensors. Zeek site policy, Suricata with ET Open plus eleven local rules, and proof that both are actually seeing packets.
  3. Scenario 01, recon. A SYN sweep and an NSE service probe. Produces the threshold rule firing, the scanner User-Agent rules, and the raw-versus-normalized traversal finding.
  4. Scenario 02, web attack. Four hand-written requests, four single-shot signature matches.
  5. Scenario 03, the beacon. Everything signature-based misses it, so this step writes a stateful Zeek detector first, then runs the traffic against it. This is the core of the post.
  6. Scenario 04, DNS. Long high-entropy query labels, and the shape-versus-content distinction.
  7. Scenario 05, payload delivery. A real executable over HTTP, and the three silent truncation limits that stand between you and an intact sample.
  8. Join the two sensors. One Community ID, one flow, both engines.
  9. Close the loop with Part 4. Both extracted copies through the mimikatz YARA rule.

Two things before starting. Every output below is from a real run, and nothing is committed to the blog repository: the build section pulls the executable from the Part 4 lab directory. Nothing else is external, and no container holds state worth keeping, so any step can be rebuilt from scratch.

Two Engines, Not Two IDSs

The two tools are not interchangeable, and treating them as “two IDSs” wastes both.

 ZeekSuricata
question answeredwhat happened on this network?is this traffic known-bad?
unit of outputone record per session or transactionone alert per rule match
silent when nothing maliciousno, it logs everythingyes, that is the default
rule languageTuring-complete Zeek script with state, tables, timerssignature language over decoded protocol fields
stateful behaviour detectionyes, this is its strengthpossible (threshold), but not the model
file extractionextract-all-files, with hashing in files.logfile-store, driven by rule keyword or force-filestore
typical volumelarge, everything is a rowsmall, only matches
what it cannot dotell you something is malicioustell you a beacon is happening

That last row is the argument for running both. A signature engine is structurally blind to a beacon: there is no malicious string in an ordinary GET / HTTP/1.1 repeated every two seconds. The signal is the repetition, and Zeek keeps state. Scenario 03 is where that plays out.

1
2
3
4
5
6
7
8
  the same eight HTTP transactions

  Suricata:  8 x { "event_type":"http", "status":200 }     0 alerts
                           |
                           |  nothing matched a signature
                           v
  Zeek:      1 x NSM_Beacon::Possible_Beaconing
             "6 samples, mean 2.00s, jitter 0.00s (cv 0.00)"

Both are correct. One is a verdict engine with no verdict to give; the other is an evidence engine that noticed a shape.

Build the Lab

One directory, one compose file, five scenario scripts. Four containers, no second SIEM, no orchestration. The Part 1 Elastic stack is still up on the same box and neither sensor needs it.

1
2
mkdir -p ~/Documents/Hacking/SOC/zeek-suricata-lab/{suricata/config,zeek/config,zeek/scripts/nsm,traffic/scenarios,traffic/payload}
cd ~/Documents/Hacking/SOC/zeek-suricata-lab

The compose file defines the victim, the attacker and the two sensors. Host networking on the sensors is deliberate: it lets them open the Docker bridge carrying monitored traffic, the container equivalent of a SPAN port.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# docker-compose.yml
# ==============================================================
# SOC Lab 5 - Zeek + Suricata Network Security Monitoring
#
# Two sensors, one wire. The monitored bridge carries the
# attacker/victim traffic; both sensors tap it from the host.
# ==============================================================

services:

  # ============================================================
  # VICTIM (the host under observation)
  # ============================================================
  victim:
    image: nginx:alpine
    container_name: nsm-victim
    restart: unless-stopped
    networks:
      monitored:
        ipv4_address: 172.30.0.2
    volumes:
      - ./traffic/payload:/usr/share/nginx/html/payload:ro

  # ============================================================
  # ATTACKER (the test machine that generates the traffic)
  # ============================================================
  attacker:
    build:
      context: ./traffic
      dockerfile: Dockerfile.attacker
    image: nsm-attacker:latest
    container_name: nsm-attacker
    restart: unless-stopped
    command: ["sleep", "infinity"]

    # NET_RAW is what a SYN scan needs. NET_ADMIN is here for a subtler
    # reason: Kali's /usr/lib/nmap/nmap carries file capabilities
    # (cap_net_raw,cap_net_admin,cap_net_bind_service +eip), and at execve
    # the kernel requires the file's capability set to be a subset of the
    # process bounding set. Docker's default bounding set drops NET_ADMIN,
    # so nmap dies with "Operation not permitted" before it reads its own
    # arguments. Granting NET_ADMIN puts the bounding set back in range.
    cap_add:
      - NET_RAW
      - NET_ADMIN
    networks:
      monitored:
        ipv4_address: 172.30.0.3
    volumes:
      - ./traffic/scenarios:/opt/scenarios:ro

  # ============================================================
  # SURICATA - signature sensor
  #
  # Host networking is intentional: it lets the sensor open the
  # Docker bridge carrying the monitored traffic, exactly like a
  # SPAN port on a switch.
  # ============================================================
  suricata:
    image: jasonish/suricata:8.0.6-amd64
    container_name: nsm-suricata
    restart: unless-stopped
    network_mode: host
    cap_add:
      - NET_ADMIN
      - NET_RAW
      - SYS_NICE
    environment:
      - PUID=1000
      - PGID=1000
    volumes:
      - ./suricata/config:/etc/suricata
      - ./suricata/lib:/var/lib/suricata
      - ./suricata/logs:/var/log/suricata
    command:
      - -i
      - ${MONITORED_IFACE}
      - -v

  # ============================================================
  # ZEEK - protocol/behaviour sensor
  # ============================================================
  zeek:
    image: zeek/zeek:8.2.1
    container_name: nsm-zeek
    restart: unless-stopped
    network_mode: host
    cap_add:
      - NET_ADMIN
      - NET_RAW
    working_dir: /usr/local/zeek/logs
    volumes:
      - ./zeek/config/local.zeek:/usr/local/zeek/share/zeek/site/local.zeek:ro
      - ./zeek/scripts/nsm:/usr/local/zeek/share/zeek/site/nsm:ro
      - ./zeek/logs:/usr/local/zeek/logs
    # -C: ignore bad checksums. The Docker bridge is backed by veth pairs
    # that advertise checksum offload but never fill it in, so Zeek would
    # discard every packet. Same trap as lab 2.
    command:
      - zeek
      - -C
      - -i
      - ${MONITORED_IFACE}
      - local

networks:
  monitored:
    name: nsm-monitored
    driver: bridge
    ipam:
      config:
        - subnet: 172.30.0.0/24

Read the bridge name off the host once the network is up, and put it in .env:

1
2
docker compose up -d victim attacker
docker network inspect nsm-monitored -f '' | cut -c1-12
1
f00653ae2c26
1
2
# .env
MONITORED_IFACE=br-f00653ae2c26

That name is not stable. docker compose down removes the network; the next up builds a new bridge with a new ID, and both sensors keep capturing on an interface that no longer exists, silently. Lab 1 hit the same thing. Sensors quiet after a rebuild: check this first.

Attacker image, a small Kali with the traffic generators:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# traffic/Dockerfile.attacker
FROM kalilinux/kali-rolling

ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get update \
 && apt-get install -y --no-install-recommends \
      nmap \
      curl \
      dnsutils \
      netcat-openbsd \
      python3 \
      iputils-ping \
      iproute2 \
      tcpdump \
      ethtool \
 && apt-get clean \
 && rm -rf /var/lib/apt/lists/*

CMD ["sleep", "infinity"]

The victim serves one file, a real Windows executable renamed to look like an update. Reuse the Part 4 sample:

1
2
cp ~/Documents/Hacking/SOC/yara-lab/samples/mimikatz.exe traffic/payload/update.exe
sha256sum traffic/payload/update.exe
1
61c0810a23580cf492a6ba4f7654566108331e7a4134c968c2d6a05261b2d8a1  traffic/payload/update.exe

That hash threads through the post: the closing section feeds both extracted copies back into the Part 4 YARA rules.

Finally the five scripts that generate the traffic. They are what the sensors get to observe for the rest of the lab.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# traffic/scenarios/01-recon.sh
#!/usr/bin/env bash
# Scenario 1: reconnaissance against the monitored host.
set -e
TARGET=${TARGET:-172.30.0.2}

echo "[*] SYN scan, first 1000 ports"
nmap -sS -p 1-1000 --max-retries 1 --min-rate 200 "$TARGET" -oN /tmp/recon-syn.txt >/dev/null
grep -E "^(Nmap scan|Not shown|[0-9]+/tcp)" /tmp/recon-syn.txt | head -8

echo
echo "[*] service probe with the NSE http-enum script"
nmap -sV -p 80 --script http-enum "$TARGET" -oN /tmp/recon-nse.txt >/dev/null
grep -E "Nmap scan|^80/tcp|http-enum|/" /tmp/recon-nse.txt | head -12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# traffic/scenarios/02-web.sh
#!/usr/bin/env bash
# Scenario 2: web attack requests against the monitored host.
set -e
TARGET=${TARGET:-172.30.0.2}

send() {
  echo "  -> $1 $2"
  curl -s -o /dev/null --max-time 5 "$@" || true
}

send -A "sqlmap/1.8#stable" "http://$TARGET/?id=1%27%20OR%20%271%27%3D%271"
send -A "Nikto/2.5.0"       "http://$TARGET/"
send                        "http://$TARGET/?q=1+union+select+password+from+users"
send --path-as-is           "http://$TARGET/../../etc/passwd"

echo
echo "[*] web attack requests sent"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# traffic/scenarios/03-beacon.sh
#!/usr/bin/env bash
# Scenario 3: a beacon.
#
# Regular interval, consistent destination, ordinary HTTP. No
# malicious string anywhere in this traffic, which is the point:
# nothing here can be matched by a signature.
set -e
TARGET=${TARGET:-172.30.0.2}
COUNT=${COUNT:-8}
INTERVAL=${INTERVAL:-2}

echo "[*] beaconing to $TARGET every ${INTERVAL}s, $COUNT times"
python3 - "$TARGET" "$COUNT" "$INTERVAL" <<'PY'
import sys, time, urllib.request

target, count, interval = sys.argv[1], int(sys.argv[2]), float(sys.argv[3])

start = time.time()

for i in range(1, count + 1):
    started = time.time()
    try:
        urllib.request.urlopen(f"http://{target}/", timeout=3).read()
    except Exception as exc:
        print(f"  beacon {i}/{count} failed: {exc}")
        continue
    # urllib does not pool connections here, so each iteration is a
    # fresh TCP connection: exactly what a real implant does.
    print(f"  beacon {i}/{count} sent at t+{started - start:.2f}s")
    time.sleep(interval)
PY
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# traffic/scenarios/04-dns.sh
#!/usr/bin/env bash
# Scenario 4: the shape of DNS tunnelling.
#
# Encoded payloads are long and high entropy. The queries never
# resolve, because nothing on this segment answers for the domain.
# A real tunnel would have a server at the other end.
set -e
TARGET=${TARGET:-172.30.0.2}

echo "[*] long-label DNS queries to $TARGET"
for i in 1 2 3 4 5; do
  LABEL=$(head -c 40 /dev/urandom | base32 | tr -d '=' | tr 'A-Z' 'a-z' | cut -c1-40)
  echo "  query: ${LABEL}.exfil.example"
  dig +time=1 +tries=1 "@$TARGET" "${LABEL}.exfil.example" A >/dev/null 2>&1 || true
done
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# traffic/scenarios/05-download.sh
#!/usr/bin/env bash
# Scenario 5: payload delivery over HTTP.
#
# Both sensors extract a copy: Suricata via file-store, Zeek via
# extract-all-files. Both copies go to the lab 4 YARA rules.
#
# RATE is not a detail. On a Docker bridge the victim serves 1.3 MB
# in about ten milliseconds, faster than either sensor's capture
# socket can absorb: both silently truncate and hand you a hash that
# matches nothing. Throttling to a realistic rate is what makes the
# sample complete. Set RATE=0 to reproduce the truncation instead.
set -e
TARGET=${TARGET:-172.30.0.2}
RATE=${RATE:-100k}

echo "[*] downloading payload from http://$TARGET/payload/update.exe (limit ${RATE:-none})"
if [ "$RATE" = "0" ]; then
  curl -s -o /tmp/update.exe --max-time 30 "http://$TARGET/payload/update.exe"
else
  curl -s -o /tmp/update.exe --max-time 60 --limit-rate "$RATE" "http://$TARGET/payload/update.exe"
fi
ls -l /tmp/update.exe
sha256sum /tmp/update.exe

That is the whole lab environment. Nothing below requires rebuilding anything, only starting the sensors and running the next script.

Configure and Verify Both Sensors

Two config files do the real work: Zeek’s site policy and Suricata’s local ruleset. Both sensors are configured by file, so they start after those files exist. Build the attacker image and bring the whole stack up:

1
2
3
4
docker compose build attacker
docker compose up -d
docker exec nsm-attacker ip -brief addr show eth0
docker logs nsm-suricata 2>&1 | tail -5

Each engine gets a section below, and each ends with proof it is running.

Zeek: logs as a database

Zeek does not detect, it describes. Every session becomes a record in conn.log; protocol analyzers decompose it into http.log, dns.log, ssl.log, ssh.log, pe.log. The file analysis framework adds files.log: every file on the wire, with size, MIME type and hashes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  packets
     |
     v
  +---------------------------------------------------+
  | session: conn.log      id.orig_h, id.resp_p, ...   |
  |   |                                                |
  |   +-- HTTP  -> http.log    method, uri, status     |
  |   |     |                                          |
  |   |     +-- body -> files.log   sha256, mime, size |
  |   |            |                                   |
  |   |            +-- PE analyzers -> pe.log          |
  |   |                                               |
  |   +-- DNS   -> dns.log     query, qtype, rcode     |
  |   +-- TLS   -> ssl.log     ja3, ja3s, sni          |
  +---------------------------------------------------+
                     |
                     v
        site policy (local.zeek) decides what else runs
        + community_id   + our beacon script

Output format decides whether any of that is usable downstream. Zeek’s native TSV plus a separate header file needs a parser; the JSON policy removes that step [1]:

# zeek/config/local.zeek
##! Site policy for SOC Lab 5.
##!
##! Zeek ships a large default policy set. This file is the site
##! customisation layer: it decides what gets logged, in what
##! format, and which of our own scripts run on top.

# Installation-wide salt used when Zeek hashes file IDs. Not a
# secret here, because the lab is not a production sensor.
redef digest_salt = "soc-lab-5-replace-me";

# --------------------------------------------------------------
# OUTPUT FORMAT
# --------------------------------------------------------------

# One JSON object per line instead of Zeek's native TSV. This is
# the single setting that decides whether logs drop straight into
# a SIEM or need a parser in front of them.
@load policy/tuning/json-logs

# --------------------------------------------------------------
# SENSOR HEALTH
# --------------------------------------------------------------

# A sensor that silently drops packets is worse than no sensor.
# These two write the evidence into capture_loss.log and stats.log.
@load policy/misc/capture-loss
@load policy/misc/stats

# --------------------------------------------------------------
# FILES
# --------------------------------------------------------------

# md5/sha1/sha256 into files.log for every file Zeek sees.
@load policy/frameworks/files/hash-all-files

# Keep a copy on disk under extract_files/, so a scanner can look
# at what crossed the wire after the fact.
@load policy/frameworks/files/extract-all-files

# --------------------------------------------------------------
# CORRELATION
# --------------------------------------------------------------

# Add community_id to conn.log. Suricata writes the identical
# value into eve.json, which is what lets the two sensors be
# joined on something better than a tuple and a timestamp.
@load policy/protocols/conn/community-id-logging

# --------------------------------------------------------------
# LOCAL DETECTION
# --------------------------------------------------------------

# Our own behavioural detection, the layer signatures cannot cover.
# Written before scenario 03 runs.
@load nsm/detect-beacon

Confirm Zeek sees traffic rather than failing quietly:

1
docker exec nsm-zeek zeek --version
1
zeek version 8.2.1
1
cat zeek/logs/reporter.log
1
2
{"ts":1789089672.297246,"level":"Reporter::INFO","message":"received termination signal","location":""}
{"ts":1789089672.297246,"level":"Reporter::INFO","message":"14153 packets received on interface br-f00653ae2c26, 0 (0.00%) dropped, 10 (0.07%) not processed","location":""}

Zero dropped is the number you want. capture_loss.log gives the same assurance over time:

1
cat zeek/logs/capture_loss.log
1
{"ts":1789089734.667745,"ts_delta":60.00020217895508,"peer":"zeek","gaps":0,"acks":2700,"percent_lost":0.0}

A live conn.log line, one object per session:

1
jq -c 'select(."id.orig_p"==47426)' zeek/logs/conn.log
1
{"ts":1789090336.987097,"uid":"CBU3pl2Iz4osPTdy88","id.orig_h":"172.30.0.3","id.orig_p":47426,"id.resp_h":"172.30.0.2","id.resp_p":80,"proto":"tcp","service":"http","duration":21.988802909851074,"orig_bytes":92,"resp_bytes":1355524,"conn_state":"SF","local_orig":true,"local_resp":true,"missed_bytes":0,"history":"ShADadtWWFf","orig_pkts":140,"orig_ip_bytes":7440,"resp_pkts":1002,"resp_ip_bytes":1410724,"ip_proto":6,"community_id":"1:1hGbY0Oi0OgxGT4sZ0G+n1DIoQI="}

orig_bytes: 92 against resp_bytes: 1355524: a client asked for something small and got 1.3 MB back. conn_state: SF is a normal close, service: http the analyzer Zeek attached. Opening context for an investigation in one line, with no rules.

A jq trap worth knowing

jq 1.8.2 parses ."id.resp_p" and .id.resp_p differently. The dotted form is nested access: .id.resp_p means .["id"]["resp_p"] and returns null against Zeek’s flat keys.

1
2
jq -c 'select(.id.resp_p==47426) | .uid' zeek/logs/conn.log   # -> nothing
jq -c 'select(."id.resp_p"==47426) | .uid' zeek/logs/conn.log # -> "CBU3pl2Iz4osPTdy88"

Every Zeek field with a dot in its name needs the quoted form. Find it at 2am and it costs an hour.

Suricata: signatures and sticky buffers

Suricata matches a ruleset against decoded protocol state and writes eve.json, fast.log, stats.log [4]. This lab runs the community ET Open ruleset plus eleven rules of its own [9].

1
docker exec nsm-suricata suricata --build-info | head -3
1
2
3
This is Suricata version 8.0.6 RELEASE
Features: NFQ PCAP_SET_BUFF AF_PACKET HAVE_PACKET_FANOUT LIBCAP_NG LIBNET1.1 HAVE_HTP_URI_NORMALIZE_HOOK PCRE_JIT HAVE_NSS HTTP2_DECOMPRESSION HAVE_LUA HAVE_JA3 HAVE_JA4 HAVE_LIBJANSSON TLS TLS_C11 MAGIC RUST POPCNT64 
compiled with LibHTP v8.0.6

Pull the community ruleset once, then check what loaded:

1
2
docker exec nsm-suricata suricata-update
docker logs nsm-suricata 2>&1 | grep 'rules successfully loaded' | tail -1
1
Info: detect: 2 rule files processed. 52732 rules successfully loaded, 0 rules failed, 0 rules skipped

52,732 rules: 52,721 ET Open, 11 local. Check the zero after every edit. A rule with a syntax error is not a broken sensor, it is a rule that never fires and never complains. Same failure mode as the ASCII YARA rule in Part 4.

The local ruleset

Eleven rules, SIDs 1000101 to 1000111, each demonstrating something a signature can or cannot do. The excerpt below covers the ones the scenarios fire. 1000104, 1000105 and 1000108 are the same shapes again; 1000111 appears in scenario 01, where it earns its place.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# suricata/config/local.rules  (excerpt)

# --------------------------------------------------------------
# PIPELINE SANITY
# --------------------------------------------------------------

alert icmp any any -> $HOME_NET any ( \
    msg:"SOCLAB ICMP echo request to monitored host"; \
    itype:8; \
    classtype:misc-activity; \
    sid:1000101; rev:1;)

# --------------------------------------------------------------
# RECON
# --------------------------------------------------------------

# A SYN sweep is a rate, not a packet. A single SYN is normal
# traffic; twenty from one source in ten seconds is a scanner.
# This is what the threshold keyword exists for.
alert tcp any any -> $HOME_NET any ( \
    msg:"SOCLAB possible SYN port scan (20 SYNs/10s from one source)"; \
    flags:S; \
    threshold: type both, track by_src, count 20, seconds 10; \
    classtype:attempted-recon; \
    sid:1000102; rev:1;)

# The scanner announces itself in the User-Agent of its HTTP
# probes. Cheap to write, cheap to run, and it fires on the
# first request rather than the twentieth.
alert http any any -> $HOME_NET any ( \
    msg:"SOCLAB HTTP scanner user agent"; \
    flow:established,to_server; \
    http.user_agent; content:"Nmap Scripting Engine"; nocase; \
    classtype:attempted-recon; \
    sid:1000103; rev:1;)

# --------------------------------------------------------------
# WEB ATTACK
# --------------------------------------------------------------

alert http any any -> $HOME_NET any ( \
    msg:"SOCLAB SQL injection indicators in URI"; \
    flow:established,to_server; \
    http.uri; content:"' OR '"; nocase; \
    classtype:web-application-attack; \
    sid:1000106; rev:1;)

alert http any any -> $HOME_NET any ( \
    msg:"SOCLAB union select in URI"; \
    flow:established,to_server; \
    http.uri; content:"union"; nocase; content:"select"; nocase; distance:0; \
    classtype:web-application-attack; \
    sid:1000107; rev:1;)

# --------------------------------------------------------------
# DNS
# --------------------------------------------------------------

# A 35+ character first label is not how humans name hosts.
# It is how tunnelled payloads are encoded. Catches the shape,
# not the content, and deliberately blunt: this is the rule we
# later tune against Zeek's dns.log.
alert dns any any -> any any ( \
    msg:"SOCLAB long DNS query label (possible tunnelling)"; \
    dns.query; pcre:"/^[a-z0-9]{35,}\./i"; \
    classtype:policy-violation; \
    sid:1000109; rev:1;)

# --------------------------------------------------------------
# PAYLOAD DELIVERY
# --------------------------------------------------------------

# An executable pulled over plain HTTP. The SOC wants this even
# when the file is unknown, because it is the moment of delivery.
#
# 'filestore' is what makes this rule do something file-store
# alone does not. With file-store enabled but no rule carrying the
# keyword, Suricata still computes the hash and writes the
# fileinfo record, and stores nothing: hash-only samples, with
# "stored": false in eve.json as the only sign. Add the keyword
# and the bytes land in the filestore directory, filed under
# their sha256.
#
# It is also the right shape for production. You do not want a
# sensor writing every PDF and JPEG on a busy network to disk. You
# want the one executable that arrived over plain HTTP at 03:00.
alert http any any -> $HOME_NET any ( \
    msg:"SOCLAB executable download over HTTP"; \
    flow:established,to_client; \
    fileext:"exe"; \
    filestore; \
    classtype:trojan-activity; \
    sid:1000110; rev:2;)

Three things carry the weight:

Sticky buffers. http.user_agent; content:"Nmap Scripting Engine"; does not search the packet [3]. It enters the http.user_agent buffer and searches there. That distinction is the point: a match anywhere in the stream would fire on the request header and on the same bytes echoed back in a response body. The buffer asserts the match landed in the right place. Suricata ships one for http.uri, http.uri.raw, http.host, http.header, http.request_body, http.response_body, dns.query, tls.sni and more.

threshold, not pattern. A port scan is a rate, not a packet. No single SYN is evidence of anything. threshold: type both, track by_src, count 20, seconds 10 counts per source address and fires when the count crosses twenty inside ten seconds. type both alerts once at the crossing and once at the end of the window, which is why a scan produces a handful of alerts rather than one per packet.

fileext versus fileext:. The engine reads the extension out of the HTTP response and compares it, which is why fileext:"exe" catches /payload/update.exe however the URL is encoded [3].

Both sensors are now up, configured and verified. Everything from here is traffic.

Scenario 01, Recon

1
docker exec nsm-attacker bash /opt/scenarios/01-recon.sh

The script does two things: a SYN sweep over the first 1000 ports, then an NSE service probe with the http-enum wordlist. The SYN sweep is what rule 1000102 was written for.

1
grep -c '1000102' suricata/logs/fast.log
1
6

Six alerts against a sweep of a thousand ports. One alert per SYN would be a thousand rows of the same finding. type both alerts once at the crossing and once at the end of each window, which is what collapses a scan into a handful of rows.

The probe that follows is the interesting half, and it produces three separate findings.

The community ruleset already had the Nmap User-Agent

1
2
grep -c '2024364' suricata/logs/fast.log
grep -c '1000103' suricata/logs/fast.log
1
2
4595
3236

Four thousand five hundred and ninety-five hits on ET Open rule 2024364 against 3,236 on the local 1000103. Both detect the same Nmap Scripting Engine User-Agent, counted against the same traffic. The community ruleset already covered it.

That is not wasted work, it is how you find out a rule you were about to write already exists. Check before you author. The ratio is skewed because the ET rule matches on a looser pattern and the local one on the exact string, but either would have carried the detection.

The Cisco false positive, and the one-command close

The http-enum wordlist also tripped a community rule that has nothing to do with this lab:

1
09/11/2026-01:14:24.062641  [**] [1:2033089:2] ET EXPLOIT Cisco RV320/RV325 Config Disclosure Attempt Inbound (CVE-2019-1653) [**] [Classification: Attempted Administrator Privilege Gain] [Priority: 1] {TCP} 172.30.0.3:54210 -> 172.30.0.2:80

A Cisco router CVE alert, priority 1, fired against an nginx container. The wordlist requested /cgi-bin/config.exp, the path the ET rule matches: the community ruleset doing exactly what it was written to do, pattern-matching a suspicious path regardless of what answers it.

The analyst’s job is to close it, and the close takes one command, because Zeek recorded the outcome of the very request Suricata alerted on:

1
jq -c 'select(.uri|test("config.exp")) | {uri, status_code}' zeek/logs/http.log
1
{"uri":"/cgi-bin/config.exp","status_code":404}

Not Found. No Cisco router on this segment, the path does not exist on the server that answered, nothing disclosed. One query closes the alert as benign with evidence rather than a guess:

1
jq -r '.status_code' zeek/logs/http.log | sort | uniq -c | sort -rn
1
2
3
4
   2194 404
     39 null
     38 200
      9 400

2,280 requests, all but thirty-eight a 404. That is what a wordlist run against a web server looks like from the server’s side, and no signature engine shows you that shape.

Suricata raised a plausible alert that turned out wrong; Zeek’s protocol record is the evidence that disposed of it. Rule 2033089 was not buggy. It answered “is this known-bad?” and the honest answer was yes. The next question, “did it work?”, needed the other engine.

Raw versus normalized: a real finding

Two of the local rules exist to catch path traversal, SID 1000108 in http.uri and SID 1000111 in http.uri.raw. They look redundant. Running both against the real http-enum wordlist is what proved they are not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 1000108 and this rule are NOT redundant: they catch different
# halves of the same attack class, visible only when you run both
# against a real scanner wordlist.
#
# http.uri is the NORMALIZED uri. libhtp percent-decodes it, but
# path-normalizes only the path component, never the query string:
#
#   /sdk/../../../../etc/passwd      -> path, ../ collapsed
#                                       => 1000108 MISSES it
#   /x.php?file=../../../web.config  -> query, ../ survives
#                                       => 1000108 catches it
#   /x.php?path=..%2f..%2fwin.ini    -> decoded to ../ in query
#                                       => 1000108 catches it
#
# http.uri.raw is the literal request-target: nothing decoded,
# nothing collapsed. The exact complement:
#
#   /sdk/../../../../etc/passwd      -> caught
#   /x.php?path=..%2f..%2fwin.ini    -> NOT caught (no literal ../)
#
# Verified against the http-enum wordlist in scenario 1. The
# lesson: a traversal rule tested against one hand-written
# request proves nothing about which buffer you picked.
alert http any any -> $HOME_NET any ( \
    msg:"SOCLAB path traversal in RAW uri"; \
    flow:established,to_server; \
    http.uri.raw; content:"../"; \
    classtype:web-application-attack; \
    sid:1000111; rev:1;)

Both fired during the same recon run, against different requests from the same wordlist:

1
2
3
grep -E '100010[8]|1000111' suricata/logs/fast.log | head -3
grep -c '1000108' suricata/logs/fast.log
grep -c '1000111' suricata/logs/fast.log
1
2
3
4
5
09/11/2026-01:14:23.273446  [**] [1:1000111:1] SOCLAB path traversal in RAW uri [**] [Classification: Web Application Attack] [Priority: 1] {TCP} 172.30.0.3:53928 -> 172.30.0.2:80
09/11/2026-01:14:23.289104  [**] [1:1000111:1] SOCLAB path traversal in RAW uri [**] [Classification: Web Application Attack] [Priority: 1] {TCP} 172.30.0.3:53970 -> 172.30.0.2:80
09/11/2026-01:14:23.294225  [**] [1:1000111:1] SOCLAB path traversal in RAW uri [**] [Classification: Web Application Attack] [Priority: 1] {TCP} 172.30.0.3:53976 -> 172.30.0.2:80
18
25

Eighteen and twenty-five, over different requests. A normalization layer sits between the wire and your rule, and the buffer you pick decides which side of it you are on. One hand-written request proves nothing; you need a wordlist.

Recon is done. Two engines have already disagreed productively: Suricata produced a priority-1 alert Zeek dismissed in one query, and Suricata’s own local ruleset needed two buffers to cover one attack class.

Scenario 02, Web Attack

1
docker exec nsm-attacker bash /opt/scenarios/02-web.sh

Four requests, each with a different signature in it: a sqlmap User-Agent on an encoded SQL injection, a Nikto User-Agent, a union select in the query string, and a --path-as-is traversal. Every one is a plain-text match against a known-bad string.

1
grep -c -E '1000104|1000105|1000106|1000107' suricata/logs/fast.log
1
4
  • 1000104 (sqlmap UA) and 1000105 (Nikto UA) are User-Agent matches, the same technique as the Nmap rule, three lines each.
  • 1000106 (' OR ' in the URI) and 1000107 (union then select) are payload matches in http.uri.

One alert each, because each request was sent once. That is the honest ceiling of a signature test: a rule tested against one request has been tested against one request. Compare the traversal rules in scenario 01, which ran against a real wordlist and produced 18 and 25. If you want to know whether a rule works, feed it the wordlist the scanner actually uses.

Scenario 03, the Beacon

This is the scenario the post is built around. Everything so far produced a signature match; this one produces none, on purpose. Regular interval, consistent destination, ordinary HTTP. There is no malicious string in a GET / HTTP/1.1 repeated every two seconds.

Before running it, the detector has to exist. This is the one piece of code in the lab written by hand rather than configured, and it went through three versions. Each failure teaches something about stateful detection.

The first kept every timestamp ever seen per (source, destination, port) and computed the coefficient of variation over all of them. It never fired: ninety seconds earlier, recon had pushed roughly a thousand microsecond-apart connections from the same attacker to the same victim port into the same key. The mean collapsed toward zero, the variance exploded, and the real two-second beacon could not clear the threshold. Stateful detection is only as good as its state.

The second bounded the state with a sliding window (keep the most recent min_samples, discard the rest). That fixed the poisoning and produced the opposite failure: six back-to-back connections from the port scan are almost perfectly regular, so mean 0.01s and cv 0.25 had jitter alone flagging the scanner. Regularity is necessary but not sufficient. The interval also has to be one a human or an implant would set a timer to.

The third added a band on the mean interval: a beacon lives between one and sixty seconds. Notice emission, suppression keys and &redef come from Zeek’s Notice framework [7]:

# zeek/scripts/nsm/detect-beacon.zeek  (excerpt)
module NSM_Beacon;

export {
	redef enum Notice::Type += {
		## A host contacted the same destination/port several
		## times with a suspiciously regular interval.
		Possible_Beaconing,
	};

	## How many timestamps to remember per (src, dst, port). The
	## judgement is made on the gaps between them, so this is also
	## the number of samples the decision sees. Older samples are
	## dropped from the front: whatever happened before the window
	## is not allowed to influence the verdict.
	const min_samples = 6 &redef;

	## Give up on an interval longer than this. Beacons check in
	## on a schedule; a once-an-hour connection is not what this
	## script is for.
	const max_mean_interval = 60.0 &redef;

	## ...and on an interval shorter than this. A tight burst is
	## just as regular as a beacon (six connections a millisecond
	## apart have a coefficient of variation near zero), so jitter
	## alone cannot separate the two. The port scan in scenario 1
	## produced this exact false positive. A beacon has to live in
	## the range where a human or an implant would set a timer.
	const min_mean_interval = 1.0 &redef;

	## The coefficient of variation (stddev / mean) below which a
	## sequence counts as regular. Human traffic jitters far more.
	const max_jitter_ratio = 0.25 &redef;
}

type Beacon: record {
	times: vector of time &default=vector();
};

# Keyed by (source, destination, destination port), expired after
# five minutes of silence so the table cannot grow forever.
global beacons: table[addr, addr, port] of Beacon &create_expire=5min;

event new_connection(c: connection)
	{
	local o = c$id$orig_h;
	local r = c$id$resp_h;
	local p = c$id$resp_p;

	if ( [o, r, p] !in beacons )
		beacons[o, r, p] = Beacon();

	beacons[o, r, p]$times += network_time();

	# Sliding window: keep only the most recent min_samples
	# timestamps. Rebuilding the vector is how you drop from the
	# front, because a vector has no pop_front.
	if ( |beacons[o, r, p]$times| > min_samples )
		{
		local kept: vector of time = vector();
		local start = |beacons[o, r, p]$times| - min_samples;
		local k = start;
		while ( k < |beacons[o, r, p]$times| )
			{
			kept += beacons[o, r, p]$times[k];
			++k;
			}
		beacons[o, r, p]$times = kept;
		}

	local b = beacons[o, r, p];

	if ( |b$times| < min_samples )
		return;

	# Walk the timestamps and collect the gaps between them.
	local ivs: vector of double = vector();
	local i = 1;
	while ( i < |b$times| )
		{
		ivs += interval_to_double(b$times[i] - b$times[i - 1]);
		++i;
		}

	# Note the explicit index loops: iterating a vector in Zeek
	# yields its indices, not its elements.
	local sum = 0.0;
	local j = 0;
	while ( j < |ivs| )
		{
		sum += ivs[j];
		++j;
		}

	local mean = sum / |ivs|;

	# Outside the band we consider beacon-shaped, either way.
	if ( mean > max_mean_interval || mean < min_mean_interval )
		return;

	local variance = 0.0;
	local n = 0;
	while ( n < |ivs| )
		{
		variance += (ivs[n] - mean) * (ivs[n] - mean);
		++n;
		}
	variance = variance / |ivs|;

	local sd = sqrt(variance);
	local cv = sd / mean;

	if ( cv <= max_jitter_ratio )
		{
		# suppress_for defaults to an hour, and setting an
		# identifier makes that suppression per-source. On a real
		# sensor that is what you want, because an implant beacons
		# for days. In the lab it would hide the second detection
		# behind the first, so it is switched off explicitly and
		# the trade-off left visible.
		NOTICE([$note=Possible_Beaconing,
		        $src=o,
		        $dst=r,
		        $p=p,
		        $identifier=fmt("%s-%s-%s", o, r, p),
		        $suppress_for=0secs,
		        $msg=fmt("possible beaconing %s -> %s:%s, %d samples, mean %.2fs, jitter %.2fs (cv %.2f)",
		                 o, r, p, |b$times|, mean, sd, cv)]);

		# Clear the window so the pair has to re-earn the notice
		# from a fresh set of samples.
		beacons[o, r, p]$times = vector();
		}
	}

Three Zeek language details that cost time:

Vectors have no pop_front. Keeping the last N elements means building a new vector from index |v| - N onward, which the code above does explicitly.

Iterating a vector yields its indices. for ( i in v ) gives you 0, 1, 2, ..., and v[i] is the value. Every loop in the script uses explicit index arithmetic because of this.

local b = tbl[k] aliases the table record. Assigning a table element to a local does not copy it; both names refer to the same record. Mutating b mutates beacons[o, r, p], and rebinding b$times = vector() appends a second assignment to the same field. The script writes through the table key when it means to modify, and only reads through the local. Verified empirically for both append and rebind, because the failure is silent.

The logic was proven against a pcap replay before going live. A detector that will not fire on a capture where you know the answer will not be debuggable on live traffic.

Run it

1
2
docker exec nsm-attacker bash /opt/scenarios/03-beacon.sh
jq -c 'select(.note|test("Beacon")) | {msg}' zeek/logs/notice.log

The notice lands the moment the sixth beacon arrives, because min_samples = 6 is the point at which the detector has five intervals to judge:

1
2
3
4
5
{"msg":"possible beaconing 172.30.0.3 -> 172.30.0.2:80/tcp, 6 samples, mean 2.00s, jitter 0.00s (cv 0.00)"}
{"msg":"possible beaconing 172.30.0.1 -> 239.255.255.250:1900/udp, 6 samples, mean 19.01s, jitter 0.68s (cv 0.04)"}
{"msg":"possible beaconing 172.30.0.1 -> 239.255.255.250:1900/udp, 6 samples, mean 19.33s, jitter 0.51s (cv 0.03)"}
{"msg":"possible beaconing 172.30.0.1 -> 224.0.0.251:5353/udp, 6 samples, mean 20.86s, jitter 0.67s (cv 0.03)"}
{"msg":"possible beaconing 172.30.0.1 -> 239.255.255.250:1900/udp, 6 samples, mean 20.91s, jitter 2.67s (cv 0.13)"}

The first line is the detection, exact: six samples, mean 2.00s, jitter 0.00s. The other four are the Docker host itself, 172.30.0.1, sending SSDP discovery to 239.255.255.250:1900 and mDNS to 224.0.0.251:5353. Both genuinely beacon on a schedule: mean 19 to 21 seconds, cv between 0.03 and 0.13.

That is what behavioural detection looks like on first contact with a real network, and it is better to be honest about it than to tune until it looks clever. The detector is right: SSDP and mDNS are periodic beacons. What is missing is context. Production tuning would add VLAN or host role to the suppression key and exclude discovery protocols:

1
2
3
# the shape of the tuning, not shipped in the lab
if ( r in 224.0.0.0/4 || r in 239.0.0.0/8 ) return;
if ( p == 1900 || p == 5353 ) return;   # SSDP, mDNS

A behavioural detector that only ever fires on the thing you planted has never seen a real network. Four false positives from infrastructure on day one is a normal ratio to start tuning from.

The same eight transactions, and Suricata’s answer

Now the comparison the roadmap promised. Suricata logged all eight HTTP transactions with status 200:

1
2
3
jq -c 'select(.event_type=="http" and (.http.http_user_agent // "" | test("urllib")))
       | {timestamp, src_ip, dest_ip, status:.http.status}'
   suricata/logs/eve.json | tail -8
1
2
3
4
5
6
7
8
{"timestamp":"2026-09-11T01:21:49.887615+0000","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","status":200}
{"timestamp":"2026-09-11T01:21:51.890356+0000","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","status":200}
{"timestamp":"2026-09-11T01:21:53.891679+0000","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","status":200}
{"timestamp":"2026-09-11T01:21:55.893430+0000","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","status":200}
{"timestamp":"2026-09-11T01:21:57.897042+0000","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","status":200}
{"timestamp":"2026-09-11T01:21:59.898961+0000","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","status":200}
{"timestamp":"2026-09-11T01:22:01.901219+0000","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","status":200}
{"timestamp":"2026-09-11T01:22:03.903117+0000","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","status":200}

Ask Suricata for alerts in that window:

1
2
3
4
5
jq -c 'select(.event_type=="alert"
              and .timestamp > "2026-09-11T01:21:49"
              and .timestamp < "2026-09-11T01:22:05")
       | {timestamp, src_ip, sig:.alert.signature_id}'
   suricata/logs/eve.json | sort -u
1

Empty. Not “few” alerts, not “low priority” alerts. Zero. In the same window, on the same wire, Zeek emitted one notice with a mean interval of exactly 2.00 seconds, and Suricata matched 52,732 rules without one of them describing “the same request every two seconds”. That is not a thing a signature can describe. Zeek had no opinion about whether the traffic was malicious; it noticed a shape it had been told to look for.

1
jq -c 'select(.note|test("Beacon")) | .msg' zeek/logs/notice.log | head -1
1
possible beaconing 172.30.0.3 -> 172.30.0.2:80/tcp, 6 samples, mean 2.00s, jitter 0.00s (cv 0.00)

Neither engine is wrong. The practical argument for running both is stronger than “defence in depth”: they fail in different directions. Suricata fails by silence (an unknown attack matches nothing); Zeek fails by volume (everything is logged and the analyst has to find the signal). Pairing them covers the silence of one with the evidence of the other.

Scenario 04, DNS

1
docker exec nsm-attacker bash /opt/scenarios/04-dns.sh

Five queries, each with a forty-character random base32 label in front of exfil.example. Nothing on the segment answers for that domain, so they all fail to resolve, which is what a tunnel looks like when the other end is not up yet.

1
grep -c '1000109' suricata/logs/fast.log
1
5

Five alerts, one per query, from the pcre rule in the local ruleset. This is a shape rule, not a content rule: it never looks at what the label says, only that a first label is 35 characters or longer. That is deliberately blunt, and it is why the rule is worth tuning against dns.log rather than trusting as-is. Long labels have legitimate uses, and a rule that flags every one of them will not survive a week on a production sensor.

The same traffic in Zeek is a query record with a qtype and an rcode you can pivot on, which is what the tuning would be built from.

Scenario 05, Payload Delivery

1
docker exec nsm-attacker bash /opt/scenarios/05-download.sh

One file, 1,355,264 bytes, pulled over plain HTTP from /payload/update.exe. Zeek extracts with extract-all-files and hashes into files.log [5]; Suricata extracts with file-store and hashes into eve.json [4]. Both truncate it on the first attempt. Getting the sample out intact was the hardest part of the lab, and every failure was silent: a firing alert, a plausible fileinfo record, and a file that was not the file.

Limit one: libhtp

Suricata’s first extracted copy of the 1,355,264-byte payload was exactly 102,400 bytes.

1
2
jq -c 'select(.event_type=="fileinfo" and .fileinfo.size==102400) | .fileinfo' \
   suricata/logs/eve.json | head -1
1
{"filename":"/payload/update.exe","gaps":false,"state":"TRUNCATED","sha256":"e35d6596de37e5c7ea607d613f0b8ef150138bcb05ab644faee3a465018aef14","stored":false,"size":102400,"tx_id":0}

102,400 bytes is 100 KiB, and the number is not a coincidence. Suricata hands HTTP bodies to libhtp, whose shipped default caps both directions at 100 KiB:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# suricata/config/suricata.yaml
         default-config:
           personality: IDS

           # Can be specified in KiB, MiB, GiB.  Just a number
           # indicates it's in bytes.
           #
           # Shipped default is 100 KiB for both, and that number is
           # the ceiling on how much of a response body Suricata will
           # ever reassemble, which is therefore the largest file
           # file-store can write. A 1.3 MB payload comes out as
           # exactly 102400 bytes with fileinfo.state=TRUNCATED. The
           # alert still fires, so nothing looks broken, and the
           # sample you hand to YARA is not what crossed the wire.
           # Raised for the lab; tune to your own budget.
           request-body-limit: 10 MiB
           response-body-limit: 10 MiB

The limit is not the interesting part; the hash is. e35d6596de37e5c7ea607d613f0b8ef150138bcb05ab644faee3a465018aef14 is a valid SHA256 and completely useless, because it is the hash of the first 102,400 bytes and nothing on the wire ever had that hash:

1
2
head -c 102400 traffic/payload/update.exe | sha256sum
sha256sum traffic/payload/update.exe
1
2
e35d6596de37e5c7ea607d613f0b8ef150138bcb05ab644faee3a465018aef14  -
61c0810a23580cf492a6ba4f7654566108331e7a4134c968c2d6a05261b2d8a1  traffic/payload/update.exe

Worse than a null hash. A null hash is obviously missing; a fragment hash looks like an answer. The alert fired, eve.json had a fileinfo record with the right filename from the right flow, and the hash was computable, plausible, and wrong. Treat a fileinfo record as proof of extraction and you hand an analyst a 100 KB fragment of a 1.3 MB sample and call it the malware. A hash identifies a byte-for-byte copy, and this copy was not the file.

Limit two: TCP offload on the container interface

Zeek had the same problem for a different reason, and this one is a callback to Part 2.

1
cat zeek/logs/weird.log
1
{"ts":1789089775.064783,"uid":"CJLwwEuDY342jFnef","id.orig_h":"172.30.0.3","id.orig_p":58628,"id.resp_h":"172.30.0.2","id.resp_p":80,"name":"truncated_tcp_payload","notice":false,"peer":"zeek","source":"TCP"}
1
grep 'x-dosexec' zeek/logs/files.log | tail -1 | jq -c '{seen_bytes,total_bytes,missing_bytes,sha256}'
1
{"seen_bytes":345336,"total_bytes":1355264,"missing_bytes":1009928,"sha256":null}

Three hundred and forty thousand of a million and a third. The cause is the one Part 2 found in the inline Snort path: the container veth has TCP segmentation offload and generic segmentation offload enabled, so the kernel hands the driver multi-kilobyte super-frames instead of MTU-sized packets. A passive sensor reassembling TCP from those gets a stream it cannot make sense of, and Zeek says truncated_tcp_payload rather than pretending otherwise. tcpdump on the same bridge showed frames up to 46,336 bytes, far above the 1500 MTU.

One command per container:

1
2
docker exec nsm-victim   ethtool -K eth0 tso off gso off
docker exec nsm-attacker ethtool -K eth0 tso off gso off

After that, Zeek’s files.log for the same transfer:

1
{"seen_bytes":1355264,"total_bytes":1355264,"missing_bytes":0,"sha256":"61c0810a23580cf492a6ba4f7654566108331e7a4134c968c2d6a05261b2d8a1"}

Complete file, zero missing bytes, and the Part 4 mimikatz hash. Note that stats.log reported pkts_dropped: 0 throughout the broken run. Dropped-packet counters do not measure what your reassembly engine failed to understand, the blind spot that makes offload such an expensive trap.

Limit three: the stream reassembly depth

With libhtp raised and offload off, Suricata still truncated, at a new and less round number every run:

1
2
3
4
5
jq -c 'select(.event_type=="fileinfo" and .fileinfo.state=="TRUNCATED"
              and .fileinfo.size > 1000000)
       | {filename:.fileinfo.filename, size:.fileinfo.size,
          state:.fileinfo.state, sha256:.fileinfo.sha256}'
   suricata/logs/eve.json
1
2
3
4
5
{"filename":"/payload/update.exe","size":1030488,"state":"TRUNCATED","sha256":null}
{"filename":"/payload/update.exe","size":1047752,"state":"TRUNCATED","sha256":null}
{"filename":"/payload/update.exe","size":1043256,"state":"TRUNCATED","sha256":null}
{"filename":"/payload/update.exe","size":1021960,"state":"TRUNCATED","sha256":null}
{"filename":"/payload/update.exe","size":1037848,"state":"TRUNCATED","sha256":null}

All just under 1,048,576 bytes, and this time the hash is null rather than a fragment. The difference matters: the libhtp ceiling closes the body cleanly, so the record is finalised and hashed, while a stream-depth cut abandons the transfer mid-stream and Suricata declines to hash what it has. state: TRUNCATED is the only field honest in both cases.

1,048,576 is stream.reassembly.depth, shipped at 1 MiB, the wall an HTTP body hits just before the libhtp limit would ever apply [8]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# suricata/config/suricata.yaml
  reassembly:
    memcap: 256 MiB

    # ------------------------------------------------------------
    # THE THIRD AND LAST TRUNCATION LIMIT.
    #
    # Nothing in the libhtp section mentions this setting, so the
    # natural move is to raise response-body-limit to 10 MiB, watch
    # the extracted file grow, and call it fixed. It is not fixed.
    # file-store writes whatever the stream engine reassembled, and
    # the stream engine has a ceiling of its own:
    #
    #     stream.reassembly.depth
    #
    # Shipped value: 1 MiB. That is 1,048,576 bytes, and it is the
    # wall an HTTP body hits just before the libhtp limit would have
    # applied. The observed truncation was 1,021,960 bytes, under
    # the ceiling, because that is where the last reassembly chunk
    # landed.
    #
    # 0 means unlimited. This lab extracts malware samples and wants
    # the whole file; bound it to what the memcap above can afford
    # on a busy production sensor.
    # ------------------------------------------------------------
    depth: 0

A second trap sits inside the first. suricata.yaml ships a long block of commented reference configuration, and the commented stream: template sits far above the live stream: section. Editing the commented one changes nothing and raises no error. Ask the engine what it loaded:

1
docker exec nsm-suricata suricata --dump-config | grep -E 'reassembly.depth|response-body-limit'
1
2
app-layer.protocols.http.libhtp.default-config.response-body-limit = 10 MiB
stream.reassembly.depth = 0

--dump-config prints the effective value after parsing and after every include and override, authoritative for any setting you are unsure took effect. It would have saved the whole detour.

The sample that survives

With all three limits raised, Suricata’s fileinfo record for the transfer:

1
{"filename":"/payload/update.exe","sid":[1000110],"gaps":false,"state":"CLOSED","sha256":"61c0810a23580cf492a6ba4f7654566108331e7a4134c968c2d6a05261b2d8a1","stored":true,"file_id":1,"size":1355264,"tx_id":0}

state: CLOSED, size 1,355,264, full sha256, stored: true. The file is on disk under its own hash:

1
find suricata/logs/filestore -type f
1
suricata/logs/filestore/61/61c0810a23580cf492a6ba4f7654566108331e7a4134c968c2d6a05261b2d8a1

stored: true is the field to watch. Before the filestore keyword was added to the rule, Suricata computed the hash, wrote the fileinfo record, and stored nothing: stored: false, an empty filestore directory, and a correct but useless hash, because there was no file to check it against.

Join the Two Sensors

Both engines saw all five scenarios. Stitching the outputs without guessing takes a field neither engine invented: the Community ID.

It is a hash over the flow tuple (source and destination address, port and protocol, plus an optional seed), defined in a public spec, computed identically by a growing list of tools, and deliberately direction-independent so both directions of a connection produce the same value [6]. Suricata writes it into every eve.json event; Zeek writes it into conn.log when community-id-logging is loaded. The join key is exact, not a tuple-plus-timestamp heuristic.

Take the payload flow from scenario 05. Pick the Community ID out of Zeek’s conn.log for the session that carried the file:

1
2
grep '"id.orig_p":39678' zeek/logs/conn.log \
  | jq -c '{uid, bytes:"\(.orig_bytes)/\(.resp_bytes)", conn_state, community_id}'
1
{"uid":"Cm4iMlZmjyYyOKSCc","bytes":"92/1355524","conn_state":"SF","community_id":"1:in96FqiN1m+0ATa8PM6rkGohCQg="}

Search Suricata for that exact string:

1
2
3
4
5
6
7
grep -F '1:in96FqiN1m+0ATa8PM6rkGohCQg=' suricata/logs/eve.json \
  | jq -c '{event_type, src_ip, dest_ip,
            alert: (.alert.signature // null),
            url: (.http.url // null),
            file: (.fileinfo.filename // null),
            sha256: (.fileinfo.sha256 // null)}' \
  | sort -u
1
2
3
4
{"event_type":"alert","src_ip":"172.30.0.2","dest_ip":"172.30.0.3","alert":"SOCLAB executable download over HTTP","url":"/payload/update.exe","file":null,"sha256":null}
{"event_type":"fileinfo","src_ip":"172.30.0.2","dest_ip":"172.30.0.3","alert":null,"url":"/payload/update.exe","file":"/payload/update.exe","sha256":"61c0810a23580cf492a6ba4f7654566108331e7a4134c968c2d6a05261b2d8a1"}
{"event_type":"flow","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","alert":null,"url":null,"file":null,"sha256":null}
{"event_type":"http","src_ip":"172.30.0.3","dest_ip":"172.30.0.2","alert":null,"url":"/payload/update.exe","file":null,"sha256":null}

One flow, one identifier, four Suricata records plus Zeek’s connection row. Stitched: an executable was pulled over plain HTTP (Suricata alert), the file is this sha256 (Suricata fileinfo), the URL was /payload/update.exe (Suricata http), the client sent 92 bytes up and 1,355,524 down in one clean session (Zeek conn), and Zeek has an extracted copy with the same hash on disk. Neither sensor produced that story alone.

Two notes on the join.

Community IDs are direction-independent; event records are not. The same ID appears with src_ip: 172.30.0.2 on the alert (Suricata reports from the server’s side, since the rule is to_client) and src_ip: 172.30.0.3 on the http event. That is Suricata telling you which side of the conversation the event describes, not an inconsistency to fix. Any join that assumes a fixed direction silently drops half the records.

Zeek’s files.log has no community_id field. Its fields are ts, fuid, uid, id.orig_h, id.orig_p, id.resp_h, id.resp_p, source, depth, analyzers, mime_type, duration, local_orig, is_orig, seen_bytes, total_bytes, missing_bytes, overflow_bytes, timedout, md5, sha1, sha256, extracted, extracted_cutoff. The path from a file back to a flow is files.log.fuid → http.log.resp_fuids → http.log.uid → conn.log.uid → conn.log.community_id. Two hops, both exact, no timestamps.

Close the Loop with Part 4

Part 4 ended with a YARA rule that identified mimikatz by content rather than name or hash. Here is the payoff: two engines, two extraction paths, two copies of the same file, both scanned by that rule.

1
2
yara SOC/yara-lab/rules/04_mimikatz_full.yar \
     SOC/zeek-suricata-lab/suricata/logs/filestore/61/61c0810a23580cf492a6ba4f7654566108331e7a4134c968c2d6a05261b2d8a1
1
soclab_mimikatz_full SOC/zeek-suricata-lab/suricata/logs/filestore/61/61c0810a23580cf492a6ba4f7654566108331e7a4134c968c2d6a05261b2d8a1
1
2
yara SOC/yara-lab/rules/04_mimikatz_full.yar \
     SOC/zeek-suricata-lab/zeek/logs/extract_files/extract-1789091000.263654-HTTP-FZKv872ph8OQeLXrKk
1
soclab_mimikatz_full SOC/zeek-suricata-lab/zeek/logs/extract_files/extract-1789091000.263654-HTTP-FZKv872ph8OQeLXrKk

The full chain, end to end, no human in the middle:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  packets on the wire
        |
        +-- Suricata  signature match ----------> alert 1000110
        |             file-store ---------------> filestore/61/61c0810a...
        |                                        state CLOSED, sha256 matches
        |
        +-- Zeek      protocol logs ------------> conn.log  community_id
                      extract-all-files --------> extract_files/extract-...
                                                  missing_bytes 0, sha256 matches
        |
        v
  community_id join  ->  one flow, both engines, one verdict
        |
        v
  YARA (lab 4)       ->  soclab_mimikatz_full   "this is mimikatz"
        |
        v
  Sigma (lab 3)      ->  the alert that goes to the analyst

Each layer answers a question the layer below cannot. Suricata: an executable was delivered over HTTP. Zeek: here is the file, the flow, the client. YARA: the file is mimikatz. The analyst gets a ticket containing all three.

Scoreboard

Every alert from all five scenarios, from fast.log and notice.log:

SID / noticewhat it detectsalerts
2024364 (ET Open)possible Nmap User-Agent4595
1000103Nmap Scripting Engine UA3236
1000111path traversal in raw URI25
1000110executable download over HTTP18
1000108path traversal in normalized URI18
1000102SYN scan rate (threshold)6
1000109long DNS label5
2033089 (ET Open)Cisco RV320 config disclosure (CVE-2019-1653)3
1000107union select in URI1
1000106SQL injection in URI1
1000105Nikto UA1
1000104sqlmap UA1
NSM_Beacon::Possible_Beaconingperiodic connection, Zeek5

Read it by scenario. Recon dominates the volume and produces the only community false positive. Web attack and DNS contribute one alert per request. The beacon is the only row that is not a SID, and the only one that required state.

Production Notes

Run both engines, and know which one is silent. Suricata fails by silence: an attack with no signature produces no alert and the sensor looks healthy. Zeek fails by volume: the signal is buried in a million rows. Neither failure is visible from the other’s output, which is why you pair them and watch both. Zeek: capture_loss.log, stats.log. Suricata: capture.kernel_drops, the rule-load line. 0 rules failed and 0 packets dropped means the sensor is running, not that it is correct.

Verify extraction by hash, always. All three truncation limits produced a firing alert, a plausible fileinfo record, and a file that was not the file. state: TRUNCATED and a null sha256 were the only warnings; stored: false was the only sign nothing had been written. A pipeline that hands a sample to YARA, or a hash to a blocklist, without comparing the extracted size to the observed size is one config default away from acting on a fragment.

Watch for offload on every virtual interface. TSO and GSO are on by default on most container and VM interfaces and emit frames far larger than the MTU, which a passive sensor reassembles into nonsense. stats.log shows pkts_dropped: 0 while files.log shows missing_bytes: 1009928: the counters that catch this live in the file framework and weird.log, not the drop counters. Part 2 hit it inline; here it broke extraction passively. Any host with offload on does the same, which is most of them.

Ask the engine what it loaded. suricata --dump-config and zeek -NN print effective configuration after parsing and overrides. The config file is a suggestion; the running engine’s answer is the truth.

Correlate on Community ID, and mind the direction. A flow has one ID while its events have directions: the same value carries the client as source on an http event and the server as source on a to_client alert. Joins that assume a fixed orientation drop records without erroring. Where an engine does not carry the field (Zeek’s files.log), follow the keys it does carry (fuid → uid → community_id), not timestamps.

Tune behavioural detection in public. Four of five notices in the beacon scenario were the monitoring host’s own discovery traffic. That is what day one looks like. Scope suppression to the key that makes it meaningful (identifier makes it per-source, so one beaconing implant does not silence a second), and write down every exclusion with its reason, because whoever inherits the rule will otherwise delete it as noise.

The skill here is not writing rules. It is knowing which layer a question belongs to, and refusing to make one engine answer a question it is built to miss. A signature engine and a protocol engine on the same wire give you a verdict and its evidence; the join turns those into an investigation. Parts 1 through 4 built four detection layers that each see one thing. This part put two of them on the same span port and made them talk.


References

  1. Zeek documentation: the scripting language, the log framework and the policy scripts loaded in local.zeek.
  2. Suricata quickstart: installation, interface selection and the suricata-update ruleset workflow.
  3. Suricata rules format: sticky buffers, the threshold keyword and the filestore keyword used in local.rules.
  4. Suricata eve.json output: the alert, flow, http, dns, fileinfo and files event types joined in this post.
  5. Zeek files.log and the file analysis framework: fuid, seen_bytes, missing_bytes and the hashing policy scripts.
  6. Community ID specification: the direction-independent flow hash used as the cross-sensor join key.
  7. Zeek Notice framework: NOTICE, $identifier, $suppress_for and the suppression semantics discussed in the beacon section.
  8. Suricata stream.reassembly configuration: the reassembly depth that capped file extraction at 1 MiB.
  9. Emerging Threats Open ruleset: the 52,721 community signatures loaded alongside the eleven local rules.

Tags

#Zeek #Suricata #NSM #NetworkSecurityMonitoring #IDS #DetectionEngineering #CommunityID #PCAP #FileExtraction #ThreatHunting #Docker #SOC #BlueTeam

This post is licensed under CC BY 4.0 by the author.