TExcelTAD

Suricata and Snort Rules

Suricata and Snort are the two widely used open-source signature IDS/IPS engines, and their rule languages are close relatives: a rule written for one usually needs only small changes for the other. Rules are the defender's way of saying "this, in traffic, means trouble". Reading them lets you understand an alert (what exactly matched?), judge whether it is a false positive, and write your own for threats specific to your network. This lesson takes the rule format apart, builds a tiny matcher in Python to make the semantics concrete, and shows how rules are tested.

Anatomy of a rule

text
alert http $EXTERNAL_NET any -> $HOME_NET any (msg:"LAB Cleartext password in HTTP POST body"; flow:established,to_server; http.method; content:"POST"; http.request_body; content:"password="; nocase; classtype:policy-violation; sid:1000001; rev:2;)
Part Example Meaning
action alert also drop, reject (IPS mode), pass (exempt)
protocol http tcp, udp, icmp, ip, or an application protocol Suricata recognises (http, tls, dns, smb, ssh, …)
source, port $EXTERNAL_NET any variables from the configuration (HOME_NET = your networks); any, lists [80,443], negation !
direction -> <> for both directions
destination, port $HOME_NET any
msg text the alert's title
flow established,to_server only packets of established TCP sessions going to the server
sticky buffer http.method; then content:"POST"; the following content is matched in that parsed field, not in raw bytes (Snort 3 uses similar names; Snort 2 used modifiers such as http_method)
content "password=" bytes to find; |0d 0a| writes hex bytes
modifiers nocase, depth, offset, distance, within, startswith where and how the content must match
pcre "/\.\.\//" a regular expression when content isn't enough (slower; anchor it to a content first)
classtype, priority policy-violation category and severity
sid, rev 1000001, 2 rule ID and revision; local rules conventionally use 1,000,000 and up

Every content match must succeed for the rule to fire (logical AND); a rule set is many rules, and a packet or stream can trigger several. Engines are fast because each rule has a cheap fast pattern (its most distinctive content) checked first with a multi-pattern matcher; only candidates get the full evaluation.

A matcher in miniature

The program implements a small subset of this language (header, flow direction, content with nocase, depth and offset, pcre) and runs four lab rules over sample payloads: the two requests from the lab capture http.pcap, a path-traversal attempt, an FTP login and a scanner probe like the ones in Nmap Connect Scans on Loopback. All payloads are synthetic lab traffic.

python · try it yourself
import re, ipaddress

HOME_NET = ipaddress.ip_network("10.10.0.0/16")
RULES = r'''
alert tcp any any -> $HOME_NET 80 (msg:"LAB cleartext password in HTTP POST"; flow:to_server; content:"POST "; depth:5; content:"password="; nocase; sid:1000001; rev:2;)
alert tcp any any -> $HOME_NET 80 (msg:"LAB path traversal in URI"; flow:to_server; content:"GET "; depth:4; pcre:"/^GET [^ ]*\.\.\//"; sid:1000002; rev:1;)
alert tcp any any -> $HOME_NET 21 (msg:"LAB FTP cleartext login"; flow:to_server; content:"PASS "; depth:5; sid:1000003; rev:1;)
alert tcp any any -> $HOME_NET 80 (msg:"LAB Nmap HTTP probe"; flow:to_server; content:"/nmaplowercheck"; sid:1000004; rev:1;)
'''

def parse(line):
    head, opts = re.match(r"(\w+ \w+ \S+ \S+ -> \S+ \S+) \((.*)\)
quot;, line).groups() action, proto, src, sport, _, dst, dport = head.split() rule = {"action": action, "dst": dst, "dport": dport, "checks": [], "opts": {}} for opt in re.findall(r'(\w+)(?::("(?:[^"\\]|\\.)*"|[^;]*))?;', opts): key, val = opt[0], opt[1].strip('"') if key == "content": rule["checks"].append({"content": val.encode()}) elif key in ("nocase", "depth", "offset") and rule["checks"]: rule["checks"][-1][key] = int(val) if val else True elif key == "pcre": body, flags = val[1:].rsplit("/", 1) rule["checks"].append({"pcre": re.compile(body.encode(), re.I if "i" in flags else 0)}) else: rule["opts"][key] = val return rule def match(rule, pkt): if rule["dst"] == "$HOME_NET" and ipaddress.ip_address(pkt["dst"]) not in HOME_NET: return False if rule["dport"] != "any" and int(rule["dport"]) != pkt["dport"]: return False if rule["opts"].get("flow") == "to_server" and not pkt["to_server"]: return False data = pkt["payload"] for c in rule["checks"]: if "pcre" in c: if not c["pcre"].search(data): return False continue start = c.get("offset", 0) end = start + c["depth"] if "depth" in c else len(data) hay, needle = data[start:end], c["content"] if c.get("nocase"): hay, needle = hay.lower(), needle.lower() if needle not in hay: return False return True rules = [parse(l) for l in RULES.strip().splitlines()] packets = [ ("10.10.0.5", "10.10.0.10", 80, True, b"GET / HTTP/1.1\r\nHost: www.lab.test\r\n\r\n"), ("10.10.0.5", "10.10.0.10", 80, True, b"POST /login HTTP/1.1\r\nHost: www.lab.test\r\n\r\nuser=alice&Password=lab-only-123"), ("198.51.100.9", "10.10.0.10", 80, True, b"GET /static/../../etc/passwd HTTP/1.1\r\n\r\n"), ("10.10.0.5", "10.10.0.60", 21, True, b"PASS lab-only-ftp\r\n"), ("198.51.100.9", "10.10.0.10", 80, True, b"GET /nmaplowercheck1767225600 HTTP/1.1\r\n\r\n"), ("10.10.0.10", "10.10.0.5", 80, False, b"HTTP/1.1 200 OK\r\n\r\n<p>password= field explained</p>"), ] for i, (src, dst, dport, to_server, payload) in enumerate(packets, 1): pkt = {"dst": dst, "dport": dport, "to_server": to_server, "payload": payload} hits = [f'[{r["opts"]["sid"]}] {r["opts"]["msg"]}' for r in rules if match(r, pkt)] print(f"#{i} {src:>12} -> {dst}:{dport:<3} {payload[:28]!r:34} {'; '.join(hits) or '-'}")
#1    10.10.0.5 -> 10.10.0.10:80  b'GET / HTTP/1.1\r\nHost: www.la'  -
#2    10.10.0.5 -> 10.10.0.10:80  b'POST /login HTTP/1.1\r\nHost: '  [1000001] LAB cleartext password in HTTP POST
#3 198.51.100.9 -> 10.10.0.10:80  b'GET /static/../../etc/passwd'    [1000002] LAB path traversal in URI
#4    10.10.0.5 -> 10.10.0.60:21  b'PASS lab-only-ftp\r\n'           [1000003] LAB FTP cleartext login
#5 198.51.100.9 -> 10.10.0.10:80  b'GET /nmaplowercheck176722560'    [1000004] LAB Nmap HTTP probe
#6   10.10.0.10 -> 10.10.0.5:80  b'HTTP/1.1 200 OK\r\n\r\n<p>passwo' -

Each line of output is an alert decision you can explain. Packet 2 matched rule 1000001 although the field is written Password=, because of nocase. Packet 6 contains password= too, but it is a response (to the client), and flow:to_server keeps the rule quiet: a good example of how one option removes a whole class of false positives. The real engines add what the toy lacks: TCP stream reassembly (a pattern split across two packets still matches), protocol parsing (the http.* buffers are decoded and normalised, so %2e%2e%2f is seen as ../), and thousands of rules evaluated at line rate.

The same idea with tshark

A display filter can play the role of a content match when you want to check a capture quickly. This session asks the lab capture which frames would trigger rule 1000001:

bash · try it yourself
tshark -r $SAMPLES/pcap/http.pcap -Y 'tcp.dstport == 80 && tcp.payload contains "POST " && tcp.payload matches "(?i)password="' \
  -T fields -e frame.number -e ip.src -e ip.dst -e http.request.uri
14	10.10.0.5	10.10.0.10	/login

Testing a rule

On a sensor, rules are tested against captures before deployment (lab session, Suricata 8 on the sensor ids01.lab.test, offline mode on the lab capture):

console
analyst@ids01:~$ suricata -T -S local.rules -c /etc/suricata/suricata.yaml
Notice: suricata: Configuration provided was successfully loaded. Exiting.
analyst@ids01:~$ suricata -r http.pcap -S local.rules -l ./out -k none
analyst@ids01:~$ jq -c 'select(.event_type=="alert") | {ts: .timestamp, src: .src_ip, dst: .dest_ip, sid: .alert.signature_id, msg: .alert.signature}' out/eve.json
{"ts":"2026-01-15T10:00:01.000750+0000","src":"10.10.0.5","dst":"10.10.0.10","sid":1000001,"msg":"LAB Cleartext password in HTTP POST body"}

-T checks the rule syntax and configuration, -r replays a capture, and eve.json is Suricata's structured event log (alerts plus protocol metadata), which is what the SIEM ingests. A test set of captures with "must alert" and "must not alert" cases, run on every rule change, is the rule-writing equivalent of unit tests.

Snort 3 runs the same kind of test with snort -c snort.lua -R local.rules -r http.pcap -A alert_fast, and its rules differ mostly in buffer names and a few options.

How rules are kept useful

  • Start from a maintained rule set (Emerging Threats Open for Suricata, the Snort community and subscriber rules) and add local rules with your own sid range.
  • Disable rules for services you don't run, and enable protocol parsers you need (app-layer settings).
  • Prefer protocol buffers (http.uri, tls.sni, dns.query) to raw content: more precise and resistant to evasion.
  • Version-control local rules with tests and a reviewer, as with firewall rules.

Pitfalls

  • A content without position constraints in a large buffer: slow and false-positive prone.
  • pcre without a fast-pattern content: every packet pays the regex cost.
  • Rules that match the attacker's tool (a User-Agent string) instead of the attack: trivial to evade.
  • Forgetting that encrypted traffic hides payloads; use TLS metadata (tls.sni, ja3.hash/ja4 where supported) instead.

Practice

1. Write a lab rule that alerts on Telnet logins to the printer 10.10.0.40.

alert tcp any any -> 10.10.0.40 23 (msg:"LAB Telnet session to printer"; flow:established,to_server; sid:1000010; rev:1;). Any Telnet session is a policy violation there, so no content is needed (add threshold/detection_filter if it fires per packet).

2. Add a packet ("198.51.100.9", "10.10.0.10", 80, True, b"GET /a/%2e%2e/%2e%2e/etc/passwd HTTP/1.1\r\n\r\n"). Does rule 1000002 fire? What does Suricata do differently?

No: the toy matches raw bytes and the dots are URL-encoded. Suricata's http.uri buffer is normalised (decoded), so a rule on that buffer would see ../ and fire.

3. Why does flow:to_server reduce false positives in rule 1000001?

Pages and responses often mention "password=" (help pages, JavaScript, documentation); only requests sent to the server carry submitted credentials.

Test yourself

In alert http $EXTERNAL_NET any -> $HOME_NET any (...), what does $HOME_NET stand for?

  1. The Internet
  2. A configured variable listing your own networks
  3. The sensor's address
  4. Any address

What does the nocase modifier do?

  1. Ignores the packet's case
  2. Makes the preceding content match case-insensitively
  3. Disables the rule
  4. Matches only uppercase

Why didn't packet 6 (a response containing 'password=') trigger rule 1000001?

  1. It was encrypted
  2. flow:to_server restricts the rule to client-to-server traffic
  3. Its port was wrong
  4. nocase was missing

What does suricata -T do?

  1. Captures traffic
  2. Tests the configuration and rules, then exits
  3. Starts inline mode
  4. Updates rules