π‘οΈ Deep Packet Inspection, Behavioral Telemetry & Real-Time Threat Interception
While stateful firewalls regulate IP-to-port pathways and enforce boundary access control, they cannot determine whether legitimate traffic over permitted ports (e.g., HTTP on 80/443) carries an SQL injection exploit, a memory corruption buffer overflow, or an encrypted Command-and-Control (C2) beacon. Intrusion Detection Systems (IDS) and Intrusion Prevention Systems (IPS) provide this missing visibility through Deep Packet Inspection (DPI). Operating either out-of-band as a passive network sensor (IDS via SPAN ports or optical TAPs) or directly in-line as an active traffic gate (IPS via network bridges or kernel bypass interfaces), these engines reconstruct fragmented IP packets, reassemble bidirectional TCP streams, normalize application protocols, and match wire traffic against thousands of signature rules. The discipline centers around two industry-standard open-source engines: Snort (the classic signature-driven inspection standard developed by Sourcefire/Cisco) and Suricata (the modern, high-throughput, multithreaded engine maintained by the OISF).
IDS (PASSIVE OUT-OF-BAND) VS. IPS (ACTIVE INLINE) TOPOLOGY:
1. INTRUSION DETECTION SYSTEM - IDS (PASSIVE / COPY-MODE):
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SWITCH SPAN / MIRROR PORT OR PASSIVE OPTICAL TAP β
β β
β [Router / Gateway] βββββββββββββββββββββββββββββββββββββββββββββββββββββΊ [Internal Network] β
β β β
β βΌ (Copy of Packet Stream - RX only) β
β ββββββββββββββββββββ β
β β PASSIVE IDS SENSORβ βββΊ [Alert Generation] βββΊ [SIEM / SOC Dashboard] β
β β (Snort / Suricata)β β
β ββββββββββββββββββββ β
β β’ Latency Impact : ZERO. Main packet stream is completely untouched by sensor processing. β
β β’ Failure Mode : Fail-Open. If sensor crashes or runs out of CPU, user traffic is unharmedβ
β β’ Primary Weakness : Cannot prevent initial exploit packet! Can only reactively send TCP RSTs.β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
2. INTRUSION PREVENTION SYSTEM - IPS (ACTIVE / INLINE GATEWAY):
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β INLINE "BUMP-IN-THE-WIRE" (AF_PACKET / NFQUEUE / DPDK) β
β β
β [Router / Gateway] βββΊ [Interface eth0] βββΊ [IPS ENGINE] βββΊ [Interface eth1] βββΊ [Network] β
β (DPI Inspection) β
β β β
β (If Exploit Signature Matches) β
β βΌ β
β [DROP PACKET HERE] β
β β
β β’ Latency Impact : Direct. Every single packet experiences serialization & parsing latency. β
β β’ Failure Mode : Fail-Closed (Hardware bypass NICs required to mechanically bridge links).β
β β’ Core Strength : True Prevention. The malicious payload is dropped before reaching target.β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SNORT RULE SPECIFICATION FORMAT:
action proto src_ip src_port direction dst_ip dst_port ( rule_options; )
βββββββ βββββ ββββββ ββββββββ βββββββββ ββββββ ββββββββ ββββββββββββββββ
[ 1 ] [2] [3] [4] [5] [6] [7] [8]
1. RULE HEADER COMPONENTS:
βββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββ
β HEADER FIELD β PERMITTED VALUES / EXAMPLES β PURPOSE & BEHAVIOR β
βββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββ€
β [1] Action β alert, drop, pass, reject, sdrop β Action executed when rule matches packet.β
β β (drop / reject require IPS mode) β alert: log only; drop: drop packet inlineβ
βββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββ€
β [2] Protocol β ip, icmp, tcp, udp, http, tls β L3/L4 or normalized L7 protocol stream. β
βββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββ€
β [3, 6] IP Addr β $EXTERNAL_NET, $HOME_NET, !10.0..β Source and Destination CIDR/variables. β
βββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββ€
β [4, 7] Ports β any, 80, 443, 1024:65535, !22 β Layer-4 Source and Destination port list.β
βββββββββββββββββββΌβββββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββ€
β [5] Direction β -> (Unidirectional), <> (Bidirectβ Dictates direction of traffic evaluation.β
βββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββ
2. RULE OPTIONS (PAYLOAD, METADATA & TRACKING):
β’ msg:"STRING" : Descriptive alert text displayed in SIEM dashboards.
β’ flow:to_server,established : Enforces TCP connection state; ignores handshake SYN noise.
β’ content:"STRING" : Payload pattern to search for (case-sensitive by default).
β’ nocase : Case-insensitive modifier for preceding content match.
β’ depth:N / offset:N : Bounded byte search window from start of packet/payload.
β’ distance:N / within:N : Relative search parameters from previous content match position.
β’ pcre:"/REGEX/Ui" : Perl-Compatible Regular Expression for complex pattern matching.
β’ classtype:CLASS_NAME : Attack classification taxonomy (e.g., web-application-attack).
β’ sid:INTEGER : Unique Snort Rule Identifier (<1000000 reserved; >=1000000 custom).
β’ rev:INTEGER : Revision number tracking updates to the signature logic.
# ==============================================================================
# RULE 1: DETECTION OF SQL INJECTION IN HTTP GET REQUESTS (UNION SELECT / OR 1=1)
# Inspects normalized HTTP URI buffers to defeat URL-encoding obfuscation (%20, %27)
# ==============================================================================
alert tcp $EXTERNAL_NET any -> $HOME_NET $HTTP_PORTS (
msg:"ATTACK-WEB-SQLI Inbound SQL Injection UNION SELECT Attempt";
flow:to_server,established;
http_uri;
content:"UNION",nocase;
content:"SELECT",nocase,distance:1,within:20;
pcre:"/UNION(\s+|\/\*.*?\*\/)+SELECT/Ui";
metadata:service http, policy balanced-ips drop;
classtype:web-application-attack;
sid:1000001;
rev:1;
)
# ==============================================================================
# RULE 2: DETECTION OF TCP SYN SCANNING (NMAP -sS) ON SENSITIVE SERVICES
# Detects inbound SYN packets arriving with non-standard TCP window sizes (e.g. 1024)
# ==============================================================================
alert tcp $EXTERNAL_NET any -> $HOME_NET 22 (
msg:"SCAN-NMAP Potential Nmap SYN Stealth Scan on SSH Port";
flags:S,12;
window:1024;
flow:stateless;
threshold:type threshold, track by_src, count 5, seconds 10;
classtype:attempted-recon;
sid:1000002;
rev:2;
)
# ==============================================================================
# RULE 3: DETECTION OF LINUX INTERACTIVE BASH REVERSE SHELL TRANSMISSION
# Detects outbound interactive shell output over non-standard external ports
# ==============================================================================
drop tcp $HOME_NET any -> $EXTERNAL_NET !22 (
msg:"EXPLOIT-POST Shell Spawned - Linux /bin/sh Interactive Prompt Detected";
flow:to_client,established;
content:"/bin/sh",fast_pattern;
content:"uid=";
content:"gid=";
content:"groups=";
classtype:successful-admin;
sid:1000003;
rev:1;
)
suricata.yaml configuration, AF_PACKET kernel-bypass ring buffers, and worker thread pinning for wire-rate 10Gbps+ packet capture.
# ==============================================================================
# SURICATA MULTITHREADED PACKET ACQUISITION & ENGINE TUNING
# Mode: "workers" (Each thread handles full packet capture, decoding, and rules)
# ==============================================================================
vars:
address-groups:
HOME_NET: "[192.168.1.0/24,10.0.0.0/8]"
EXTERNAL_NET: "!$HOME_NET"
HTTP_SERVERS: "$HOME_NET"
# Default rule paths
default-rule-path: /var/lib/suricata/rules
rule-files:
- suricata.rules
- /etc/suricata/rules/custom.rules
# ------------------------------------------------------------------------------
# HIGH-SPEED PACKET CAPTURE: AF_PACKET WITH RING BUFFERS & CLUSTER FANOUT
# ------------------------------------------------------------------------------
af-packet:
- interface: eth0
threads: auto # Creates 1 worker thread per available physical CPU core
cluster-id: 99
cluster-type: cluster_flow # Distributes flows across cores using 5-tuple hash
defrag: yes # Reassembles IP fragments before inspection
use-mmap: yes # Uses memory-mapped ring buffers (Zero-Copy)
mmap-locked: yes # Locks memory pages in RAM to prevent disk paging latency
tpacket-v3: yes # Linux TPACKET_V3 batch ring buffer optimization
ring-size: 2048 # Number of frames allocated per ring buffer
# ------------------------------------------------------------------------------
# SURICATA THREADING MODEL: AFFINITY & CPU PINNING
# ------------------------------------------------------------------------------
threading:
set-cpu-affinity: yes
cpu-affinity:
- management-cpu-set:
cpu: [ 0 ] # Core 0 handles management, metrics, and log flushing
- worker-cpu-set:
cpu: [ 1, 2, 3, 4, 5, 6, 7 ] # Cores 1-7 dedicated exclusively to packet DPI
prio:
default: "high"
ClientHello and generating JA3/JA4 cryptographic fingerprint hashes to identify malicious C2 frameworks (like Cobalt Strike) inside encrypted TLS flows.
# ==============================================================================
# 1. MATCHING FORGED TLS SNI DOMAINS WITHOUT DECRYPTION
# Inspects cleartext ClientHello metadata during the initial TLS handshake
# ==============================================================================
alert tls $HOME_NET any -> $EXTERNAL_NET 443 (
msg:"MALWARE-C2 Suspicious Domain Requested in TLS ClientHello SNI";
flow:to_server,established;
tls.sni;
content:"c2-dark-command.top",nocase;
classtype:trojan-activity;
sid:2000001;
rev:1;
)
# ==============================================================================
# 2. JA3 CLIENT HELLO FINGERPRINT MATCHING
# JA3 constructs an MD5 hash of:
# SSLVersion,CipherSuites,Extensions,EllipticCurves,EllipticCurvePointFormats
# Even if malware uses rotating domain names or IP addresses, its TLS client
# stack implementation produces an identical, immutable JA3 hash!
# ==============================================================================
alert tls $HOME_NET any -> $EXTERNAL_NET 443 (
msg:"MALWARE-CNC Cobalt Strike Malleable C2 Default JA3 Fingerprint Detected";
flow:to_server,established;
ja3.hash;
content:"a0e9f5d64349fb13191bc781f81f42e1";
metadata:threat_actor CobaltStrike, confidence high;
classtype:command-and-control;
sid:2000002;
rev:3;
)
# ==============================================================================
# 3. HTTP DECODED BUFFER INSPECTION: SUSPICIOUS USER-AGENT DETECTION
# Matches custom python or curl scripts operating unauthorized internal scrapers
# ==============================================================================
alert http $HOME_NET any -> $EXTERNAL_NET any (
msg:"POLICY-SUSPICIOUS Non-Standard Python Scraper User-Agent";
flow:to_server,established;
http.user_agent;
content:"python-requests",nocase,startswith;
classtype:policy-violation;
sid:2000003;
rev:1;
)
eve.json (Extensible Event Format). Explains how flow metadata, HTTP headers, TLS handshakes, and alert events are emitted as structured JSON objects for ingestion by Splunk, Elasticsearch, and Logstash.
{
"timestamp": "2026-11-04T09:12:44.882190+0530",
"flow_id": 140294819024810,
"in_iface": "eth0",
"event_type": "alert",
"src_ip": "198.51.100.44",
"src_port": 54122,
"dest_ip": "192.168.1.50",
"dest_port": 80,
"proto": "TCP",
"alert": {
"action": "allowed",
"gid": 1,
"signature_id": 1000001,
"rev": 1,
"signature": "ATTACK-WEB-SQLI Inbound SQL Injection UNION SELECT Attempt",
"category": "Web Application Attack",
"severity": 1
},
"http": {
"hostname": "api.nikita-infotech.com",
"url": "/v1/students?search=1%27%20UNION%20SELECT%20username,password%20FROM%20users--",
"http_user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"http_method": "GET",
"protocol": "HTTP/1.1",
"status": 200,
"length": 1420
},
"app_proto": "http",
"flow": {
"pkts_toserver": 4,
"pkts_toclient": 6,
"bytes_toserver": 420,
"bytes_toclient": 1840,
"start": "2026-11-04T09:12:44.750102+0530"
}
}
threshold and suppress directives in threshold.conf to limit alert volumes, rate-limit scans, and exclude authorized vulnerability scanning nodes.
# ==============================================================================
# IDS/IPS TUNING & THRESHOLD CONFIGURATION: PREVENTING ALERT STORMS
# ==============================================================================
# ------------------------------------------------------------------------------
# 1. TYPE: LIMIT
# Alerts on the first M occurrences during an interval, then suppresses alerts
# until the interval expires. Used for high-volume chatty signatures.
# ------------------------------------------------------------------------------
threshold gen_id 1, sig_id 1000001, type limit, track by_src, count 1, seconds 60
# ------------------------------------------------------------------------------
# 2. TYPE: THRESHOLD
# Alerts ONLY AFTER the signature matches at least N times within the window.
# Used for detecting brute-force attempts and port sweeps while ignoring isolated hits.
# ------------------------------------------------------------------------------
threshold gen_id 1, sig_id 1000002, type threshold, track by_src, count 10, seconds 5
# ------------------------------------------------------------------------------
# 3. TYPE: BOTH
# Combines threshold and limit: Alerts once after N matches occur, then goes quiet
# for the rest of the duration.
# ------------------------------------------------------------------------------
threshold gen_id 1, sig_id 1000003, type both, track by_dst, count 5, seconds 30
# ------------------------------------------------------------------------------
# 4. SUPPRESSION DIRECTIVES: WHITELISTING AUTHORIZED SECURITY SCANNERS
# Suppresses alerts for specific rules when generated by authorized internal Nessus/Qualys scanners.
# ------------------------------------------------------------------------------
# Suppress Rule 1000001 (SQLi) when source is authorized scanner 10.0.0.25
suppress gen_id 1, sig_id 1000001, track by_src, ip 10.0.0.25
# Suppress Rule 1000002 (Port Scan) for the entire internal security team subnet
suppress gen_id 1, sig_id 1000002, track by_src, ip 10.0.50.0/24
from scapy.all import Ether, IP, TCP, Raw, wrpcap
import time
def generate_sqli_test_pcap(output_file: str = "sqli_test.pcap"):
"""
Constructs a 3-way handshake + HTTP GET payload with an SQLi payload
to verify that Snort Rule 1000001 triggers as expected.
"""
client_ip = "198.51.100.44"
server_ip = "192.168.1.50"
c_port = 54122
s_port = 80
mac_src = "00:0c:29:ab:cd:ef"
mac_dst = "00:0c:29:12:34:56"
packets = []
# 1. TCP SYN
syn = Ether(src=mac_src, dst=mac_dst) / IP(src=client_ip, dst=server_ip) / \
TCP(sport=c_port, dport=s_port, flags="S", seq=1000)
packets.append(syn)
# 2. TCP SYN-ACK
syn_ack = Ether(src=mac_dst, dst=mac_src) / IP(src=server_ip, dst=client_ip) / \
TCP(sport=s_port, dport=c_port, flags="SA", seq=5000, ack=1001)
packets.append(syn_ack)
# 3. TCP ACK (Handshake Complete)
ack = Ether(src=mac_src, dst=mac_dst) / IP(src=client_ip, dst=server_ip) / \
TCP(sport=c_port, dport=s_port, flags="A", seq=1001, ack=5001)
packets.append(ack)
# 4. HTTP GET Request with SQL Injection Payload
http_payload = (
"GET /v1/students?search=1%27%20UNION%20SELECT%20username,password%20FROM%20users-- HTTP/1.1\r\n"
"Host: api.nikita-infotech.com\r\n"
"User-Agent: Mozilla/5.0\r\n"
"Accept: */*\r\n\r\n"
)
http_pkt = Ether(src=mac_src, dst=mac_dst) / IP(src=client_ip, dst=server_ip) / \
TCP(sport=c_port, dport=s_port, flags="PA", seq=1001, ack=5001) / \
Raw(load=http_payload)
packets.append(http_pkt)
wrpcap(output_file, packets)
print(f"[β] Successfully exported {len(packets)} synthetic packets to {output_file}")
print(f"[*] Test offline with Snort: snort -c /etc/snort/snort.lua -r {output_file} -A alert_fast")
print(f"[*] Test offline with Suricata: suricata -c /etc/suricata/suricata.yaml -r {output_file} -k none")
if __name__ == "__main__":
generate_sqli_test_pcap("sqli_test.pcap")
IDS/IPS FAILURE MODES & DIAGNOSTIC TRIAGE:
// ==============================================================================
// PITFALL 1: ASYMMETRIC ROUTING BLINDNESS (THE HALF-FLOW DEFECT)
// SYMPTOM: Snort/Suricata generates ZERO alerts for established TCP exploits.
// CAUSE: Outbound traffic leaves via Switch A; inbound returns via Switch B.
// If the sensor only listens to a TAP on Switch A, it never sees the SYN-ACK return packets!
// Because the TCP 3-way handshake is incomplete, flow:established rules NEVER trigger!
// FIX: Aggregate taps using a Network Packet Broker (NPB) to merge forward and return
// flows into a unified physical inspection port, or place the sensor inline.
// ==============================================================================
// ==============================================================================
// PITFALL 2: NIC HARDWARE CHECKSUM OFFLOAD SILENTLY DROPPING TRAFFIC
// SYMPTOM: tcpdump displays packets on the interface, but Suricata processes 0 packets!
// CAUSE: When a NIC uses Hardware RX Checksum Offloading, incoming packets arrive
// in driver space with unchecked or dummy checksum values (0x0000). Suricata validates
// checksums in software by default, detects invalid checksums, and DROPS every packet!
// FIX: In suricata.yaml, disable checksum checking or turn off offloads via ethtool:
// $ sudo ethtool -K eth0 rx off tx off gro off lro off
// OR run Suricata with the -k none flag (ignore checksums).
// ==============================================================================
// ==============================================================================
// PITFALL 3: UN-OPTIMIZED FAST-PATTERN SEARCH CRIPPLING SENSOR CPU
// SYMPTOM: Sensor CPU utilization hits 100%; dropped packet counter increases rapidly.
// CAUSE: A rule uses a tiny content match: content:"GET"; content:"/admin/exec.php";
// Snort/Suricata chooses the SHORTEST pattern ("GET") for initial MPM (Multi-Pattern Matcher).
// Since almost every HTTP packet contains "GET", the engine executes expensive full regex
// evaluations on every single packet!
// FIX: Use fast_pattern on the most unique, longest string:
// content:"/admin/exec.php",fast_pattern;
// ==============================================================================
IDS/IPS ENGINE & SIGNATURE SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β CAPABILITY / DIRECTIVE β SNORT 3 SYNTAX β SURICATA SYNTAX β OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Execution Engine Model β Multithreaded (libdaq 3.0) β Multithreaded β Line-rate packet capture, β
β β Packet thread allocation β (AF_PACKET / eBPFβ scales across physical cores β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Flow Tracking β flow:established,to_server β flow:established β Matches only valid, active β
β β β β TCP connections β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β HTTP URI Buffer β http_uri; content:"/admin" β http.uri; β Decodes percent-encoding β
β β β β (%20, %27) before matching β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Fast-Pattern Selection β fast_pattern β fast_pattern β Forces multi-pattern matcher β
β β β β to match longest unique stringβ
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β TLS SNI Matching β tls_sni; content:"domain" β tls.sni; β Matches requested domain in β
β β β β cleartext TLS ClientHello β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β JA3 Fingerprinting β ja3_hash β ja3.hash; β Fingerprints TLS client stack β
β β β β to detect malware / C2 agents β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Event Logging Output β alert_json / unified2 β eve.json (EVE) β Structured JSON for direct β
β β β β ingestion into SIEM / ELK β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Rate-Limit Alert Tuning β threshold:type limit β threshold.config β Suppresses alert storms and β
β β β β prevents SOC alert fatigue β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 IDS/IPS ENGINEERING PRINCIPLES: β
β 1. Always evaluate flow state: Use flow:established to ignore unestablished connection noise. β
β 2. Use normalized protocol buffers: Match http_uri or http_client_body rather than raw payloads to β
β defeat evasion and encoding obfuscation. β
β 3. Optimize with fast_pattern: Pin the longest, most unique string to the initial hardware search. β
β 4. Track encrypted threats with JA3/SNI: Identify malicious actors on TLS ports without full decrypt. β
β 5. Tune signatures before enforcing drops: Test new rules in alert-only mode before converting to drop β
β to avoid impacting production business traffic. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ