detecting-modbus-protocol-anomalies
This skill covers detecting anomalies in Modbus/TCP and Modbus RTU communications in industrial control systems. It addresses function code monitoring, register range validation, timing analysis, unauthorized client detection, and deep packet inspection for malformed Modbus frames. The skill leverages Zeek with Modbus protocol analyzers, Suricata IDS with OT rules, and custom Python-based detection using Markov chain models for normal Modbus transaction sequences.
What this skill does
# Detecting Modbus Protocol Anomalies
## When to Use
- When deploying Modbus-specific intrusion detection in an OT environment
- When building baseline models for deterministic Modbus polling patterns
- When investigating suspicious Modbus traffic flagged by OT monitoring tools
- When implementing function code allowlisting on industrial firewalls
- When detecting unauthorized Modbus write commands that could manipulate process setpoints
**Do not use** for securing Modbus communications end-to-end (Modbus has no native security; see implementing-network-segmentation-for-ot for firewall-based controls), for non-Modbus protocol monitoring (see detecting-anomalies-in-industrial-control-systems for multi-protocol), or for active fuzzing of Modbus implementations (see performing-plc-firmware-security-analysis).
## Prerequisites
- Network SPAN/TAP access to monitor Modbus/TCP traffic (port 502)
- Zeek (formerly Bro) with Modbus protocol analyzer or Suricata with OT rulesets
- Python 3.9+ with scapy and pymodbus for custom analysis
- Baseline capture of normal Modbus traffic (minimum 1-2 weeks)
- Documentation of authorized Modbus clients, function codes, and register maps
## Workflow
### Step 1: Capture and Parse Modbus Traffic
Deploy passive monitoring to capture all Modbus/TCP traffic and parse it into structured records for analysis.
```python
#!/usr/bin/env python3
"""Modbus Protocol Anomaly Detection System.
Monitors Modbus/TCP traffic for anomalies including unauthorized
function codes, unusual register access, timing deviations,
and rogue client devices.
"""
import json
import struct
import sys
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field
from datetime import datetime
from statistics import mean, stdev
try:
from scapy.all import sniff, rdpcap, IP, TCP
except ImportError:
print("Install scapy: pip install scapy")
sys.exit(1)
MODBUS_FUNCTION_CODES = {
1: ("Read Coils", "read"),
2: ("Read Discrete Inputs", "read"),
3: ("Read Holding Registers", "read"),
4: ("Read Input Registers", "read"),
5: ("Write Single Coil", "write"),
6: ("Write Single Register", "write"),
7: ("Read Exception Status", "diagnostic"),
8: ("Diagnostics", "diagnostic"),
11: ("Get Comm Event Counter", "diagnostic"),
12: ("Get Comm Event Log", "diagnostic"),
15: ("Write Multiple Coils", "write"),
16: ("Write Multiple Registers", "write"),
17: ("Report Slave ID", "diagnostic"),
22: ("Mask Write Register", "write"),
23: ("Read/Write Multiple Registers", "read_write"),
43: ("Encapsulated Interface Transport", "diagnostic"),
}
@dataclass
class ModbusAnomaly:
timestamp: str
anomaly_type: str
severity: str
src_ip: str
dst_ip: str
unit_id: int
func_code: int
detail: str
mitre_technique: str = ""
@dataclass
class ModbusSession:
"""Tracks state for a Modbus master-slave session."""
src_ip: str
dst_ip: str
func_codes_seen: dict = field(default_factory=lambda: defaultdict(int))
register_ranges: set = field(default_factory=set)
intervals: list = field(default_factory=lambda: deque(maxlen=500))
last_timestamp: float = 0
request_count: int = 0
write_count: int = 0
class ModbusAnomalyDetector:
"""Detects anomalies in Modbus/TCP traffic."""
def __init__(self):
self.sessions = {}
self.baseline_sessions = {}
self.anomalies = []
self.authorized_clients = set()
self.authorized_func_codes = {} # per-session allowed FCs
self.packet_count = 0
def set_authorized_clients(self, clients):
"""Set list of authorized Modbus client IPs."""
self.authorized_clients = set(clients)
def set_authorized_func_codes(self, session_key, func_codes):
"""Set allowed function codes for a specific session."""
self.authorized_func_codes[session_key] = set(func_codes)
def load_baseline(self, baseline_file):
"""Load baseline profiles from previous capture analysis."""
with open(baseline_file) as f:
baseline = json.load(f)
for key, data in baseline.get("modbus_baselines", {}).items():
self.baseline_sessions[key] = data
self.authorized_func_codes[key] = set(data.get("allowed_function_codes", []))
print(f"[*] Loaded {len(self.baseline_sessions)} Modbus baselines")
def process_packet(self, pkt):
"""Process a single packet for Modbus anomaly detection."""
if not pkt.haslayer(TCP) or not pkt.haslayer(IP):
return
# Check for Modbus/TCP (port 502)
if pkt[TCP].dport != 502 and pkt[TCP].sport != 502:
return
payload = bytes(pkt[TCP].payload)
if len(payload) < 8:
return
self.packet_count += 1
timestamp = float(pkt.time)
ts_str = datetime.fromtimestamp(timestamp).isoformat()
# Parse MBAP header
try:
trans_id = struct.unpack(">H", payload[0:2])[0]
proto_id = struct.unpack(">H", payload[2:4])[0]
length = struct.unpack(">H", payload[4:6])[0]
unit_id = payload[6]
func_code = payload[7]
except (IndexError, struct.error):
return
# Determine direction
if pkt[TCP].dport == 502:
src_ip = pkt[IP].src
dst_ip = pkt[IP].dst
is_request = True
else:
src_ip = pkt[IP].dst
dst_ip = pkt[IP].src
is_request = False
if not is_request:
return # Only analyze requests
session_key = f"{src_ip}->{dst_ip}"
# Get or create session
if session_key not in self.sessions:
self.sessions[session_key] = ModbusSession(src_ip=src_ip, dst_ip=dst_ip)
session = self.sessions[session_key]
session.request_count += 1
session.func_codes_seen[func_code] += 1
# ── Anomaly Detection Rules ──
# Rule 1: Unauthorized Modbus client
if self.authorized_clients and src_ip not in self.authorized_clients:
self.anomalies.append(ModbusAnomaly(
timestamp=ts_str,
anomaly_type="UNAUTHORIZED_CLIENT",
severity="critical",
src_ip=src_ip, dst_ip=dst_ip,
unit_id=unit_id, func_code=func_code,
detail=f"Modbus request from unauthorized client {src_ip}",
mitre_technique="T0886 - Remote Services",
))
# Rule 2: Unauthorized function code
allowed_fcs = self.authorized_func_codes.get(session_key)
if allowed_fcs and func_code not in allowed_fcs:
fc_info = MODBUS_FUNCTION_CODES.get(func_code, (f"Unknown FC{func_code}", "unknown"))
severity = "critical" if fc_info[1] == "write" else "high"
self.anomalies.append(ModbusAnomaly(
timestamp=ts_str,
anomaly_type="UNAUTHORIZED_FUNCTION_CODE",
severity=severity,
src_ip=src_ip, dst_ip=dst_ip,
unit_id=unit_id, func_code=func_code,
detail=f"FC {func_code} ({fc_info[0]}) not in allowlist {sorted(allowed_fcs)}",
mitre_technique="T0855 - Unauthorized Command Message",
))
# Rule 3: Write operation detection
if func_code in (5, 6, 15, 16, 22, 23):
session.write_count += 1
fc_name = MODBUS_FUNCTION_CODES.get(func_code, ("Unknown", ""))[0]
# Extract register address
if len(payload) >= 10:
register_addr = struct.unpack(">H", payload[8:10])[0]
session.register_ranges.add((func_code, register_addr))
self.anomalies.append(ModbusAnomaly(
timestamp=ts_str,
anomaly_type="WRITE_OPERATION",
severity="high",
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.