[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7A674XF2THRRKEMSNEJC4KE":3,"skill-same:01M7A674XF2THRRKEMSNEJC4KE":93},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":16,"sourceHtmlUrl":17,"categories":18,"keywords":19,"publishedAt":20,"linkOnly":21,"markdownContent":22,"markdownBody":23,"frontMatter":24,"refName":56,"commitSha":57,"skillDirectory":58,"forksCount":14,"repositoryHtmlUrl":59,"repositoryHomepageUrl":6,"ownerHtmlUrl":60,"ownerBlogUrl":6,"ownerDescription":61,"updatedAt":62,"install":63,"resources":76},"01M7A674XF2THRRKEMSNEJC4KE","detecting-modbus-protocol-anomalies",null,"Detect anomalies in Modbus\u002FTCP and Modbus RTU industrial traffic via function code monitoring, register range validation, timing analysis, and deep packet inspection, using Zeek's Modbus analyzer, Suricata IDS with OT rules, and Python Markov chain models of normal transaction sequences. Use for deploying Modbus IDS in OT environments, baselining polling patterns, investigating suspicious Modbus traffic, or building function code allowlists.","NeelakshSaxena\u002FVayu","NeelakshSaxena","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F87892838?v=4","01M7A3B9YFS6F6N9DD1787DT86","Neelaksh Saxena","01M7A3B9ZKBT09MNMPX2XN69BY",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: detecting-modbus-protocol-anomalies\ndescription: Detect anomalies in Modbus\u002FTCP and Modbus RTU industrial traffic via function code monitoring, register range validation, timing analysis, and deep packet inspection, using Zeek's Modbus analyzer, Suricata IDS with OT rules, and Python Markov chain models of normal transaction sequences. Use for deploying Modbus IDS in OT environments, baselining polling patterns, investigating suspicious Modbus traffic, or building function code allowlists.\ndomain: cybersecurity\nsubdomain: ot-ics-security\ntags:\n- ot-security\n- ics\n- scada\n- industrial-control\n- iec62443\n- modbus\n- protocol-anomaly\nversion: 1.0.0\nauthor: mahipal\nlicense: Apache-2.0\nnist_ai_rmf:\n- MEASURE-2.7\n- MAP-5.1\n- MANAGE-2.4\natlas_techniques:\n- AML.T0070\n- AML.T0066\n- AML.T0082\nnist_csf:\n- PR.IR-01\n- DE.CM-01\n- ID.AM-05\n- GV.OC-02\nmitre_attack:\n- T1078\n- T1190\n- T1059\n- T0816\n- T0836\n---\n\n# Detecting Modbus Protocol Anomalies\n\n## When to Use\n\n- When deploying Modbus-specific intrusion detection in an OT environment\n- When building baseline models for deterministic Modbus polling patterns\n- When investigating suspicious Modbus traffic flagged by OT monitoring tools\n- When implementing function code allowlisting on industrial firewalls\n- When detecting unauthorized Modbus write commands that could manipulate process setpoints\n\n**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).\n\n## Prerequisites\n\n- Network SPAN\u002FTAP access to monitor Modbus\u002FTCP traffic (port 502)\n- Zeek (formerly Bro) with Modbus protocol analyzer or Suricata with OT rulesets\n- Python 3.9+ with scapy and pymodbus for custom analysis\n- Baseline capture of normal Modbus traffic (minimum 1-2 weeks)\n- Documentation of authorized Modbus clients, function codes, and register maps\n\n## Workflow\n\n### Step 1: Capture and Parse Modbus Traffic\n\nDeploy passive monitoring to capture all Modbus\u002FTCP traffic and parse it into structured records for analysis.\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"Modbus Protocol Anomaly Detection System.\n\nMonitors Modbus\u002FTCP traffic for anomalies including unauthorized\nfunction codes, unusual register access, timing deviations,\nand rogue client devices.\n\"\"\"\n\nimport json\nimport struct\nimport sys\nimport time\nfrom collections import defaultdict, deque\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\nfrom statistics import mean, stdev\n\ntry:\n    from scapy.all import sniff, rdpcap, IP, TCP\nexcept ImportError:\n    print(\"Install scapy: pip install scapy\")\n    sys.exit(1)\n\n\nMODBUS_FUNCTION_CODES = {\n    1: (\"Read Coils\", \"read\"),\n    2: (\"Read Discrete Inputs\", \"read\"),\n    3: (\"Read Holding Registers\", \"read\"),\n    4: (\"Read Input Registers\", \"read\"),\n    5: (\"Write Single Coil\", \"write\"),\n    6: (\"Write Single Register\", \"write\"),\n    7: (\"Read Exception Status\", \"diagnostic\"),\n    8: (\"Diagnostics\", \"diagnostic\"),\n    11: (\"Get Comm Event Counter\", \"diagnostic\"),\n    12: (\"Get Comm Event Log\", \"diagnostic\"),\n    15: (\"Write Multiple Coils\", \"write\"),\n    16: (\"Write Multiple Registers\", \"write\"),\n    17: (\"Report Slave ID\", \"diagnostic\"),\n    22: (\"Mask Write Register\", \"write\"),\n    23: (\"Read\u002FWrite Multiple Registers\", \"read_write\"),\n    43: (\"Encapsulated Interface Transport\", \"diagnostic\"),\n}\n\n\n@dataclass\nclass ModbusAnomaly:\n    timestamp: str\n    anomaly_type: str\n    severity: str\n    src_ip: str\n    dst_ip: str\n    unit_id: int\n    func_code: int\n    detail: str\n    mitre_technique: str = \"\"\n\n\n@dataclass\nclass ModbusSession:\n    \"\"\"Tracks state for a Modbus master-slave session.\"\"\"\n    src_ip: str\n    dst_ip: str\n    func_codes_seen: dict = field(default_factory=lambda: defaultdict(int))\n    register_ranges: set = field(default_factory=set)\n    intervals: list = field(default_factory=lambda: deque(maxlen=500))\n    last_timestamp: float = 0\n    request_count: int = 0\n    write_count: int = 0\n\n\nclass ModbusAnomalyDetector:\n    \"\"\"Detects anomalies in Modbus\u002FTCP traffic.\"\"\"\n\n    def __init__(self):\n        self.sessions = {}\n        self.baseline_sessions = {}\n        self.anomalies = []\n        self.authorized_clients = set()\n        self.authorized_func_codes = {}  # per-session allowed FCs\n        self.packet_count = 0\n\n    def set_authorized_clients(self, clients):\n        \"\"\"Set list of authorized Modbus client IPs.\"\"\"\n        self.authorized_clients = set(clients)\n\n    def set_authorized_func_codes(self, session_key, func_codes):\n        \"\"\"Set allowed function codes for a specific session.\"\"\"\n        self.authorized_func_codes[session_key] = set(func_codes)\n\n    def load_baseline(self, baseline_file):\n        \"\"\"Load baseline profiles from previous capture analysis.\"\"\"\n        with open(baseline_file) as f:\n            baseline = json.load(f)\n        for key, data in baseline.get(\"modbus_baselines\", {}).items():\n            self.baseline_sessions[key] = data\n            self.authorized_func_codes[key] = set(data.get(\"allowed_function_codes\", []))\n        print(f\"[*] Loaded {len(self.baseline_sessions)} Modbus baselines\")\n\n    def process_packet(self, pkt):\n        \"\"\"Process a single packet for Modbus anomaly detection.\"\"\"\n        if not pkt.haslayer(TCP) or not pkt.haslayer(IP):\n            return\n\n        # Check for Modbus\u002FTCP (port 502)\n        if pkt[TCP].dport != 502 and pkt[TCP].sport != 502:\n            return\n\n        payload = bytes(pkt[TCP].payload)\n        if len(payload) \u003C 8:\n            return\n\n        self.packet_count += 1\n        timestamp = float(pkt.time)\n        ts_str = datetime.fromtimestamp(timestamp).isoformat()\n\n        # Parse MBAP header\n        try:\n            trans_id = struct.unpack(\">H\", payload[0:2])[0]\n            proto_id = struct.unpack(\">H\", payload[2:4])[0]\n            length = struct.unpack(\">H\", payload[4:6])[0]\n            unit_id = payload[6]\n            func_code = payload[7]\n        except (IndexError, struct.error):\n            return\n\n        # Determine direction\n        if pkt[TCP].dport == 502:\n            src_ip = pkt[IP].src\n            dst_ip = pkt[IP].dst\n            is_request = True\n        else:\n            src_ip = pkt[IP].dst\n            dst_ip = pkt[IP].src\n            is_request = False\n\n        if not is_request:\n            return  # Only analyze requests\n\n        session_key = f\"{src_ip}->{dst_ip}\"\n\n        # Get or create session\n        if session_key not in self.sessions:\n            self.sessions[session_key] = ModbusSession(src_ip=src_ip, dst_ip=dst_ip)\n\n        session = self.sessions[session_key]\n        session.request_count += 1\n        session.func_codes_seen[func_code] += 1\n\n        # ── Anomaly Detection Rules ──\n\n        # Rule 1: Unauthorized Modbus client\n        if self.authorized_clients and src_ip not in self.authorized_clients:\n            self.anomalies.append(ModbusAnomaly(\n                timestamp=ts_str,\n                anomaly_type=\"UNAUTHORIZED_CLIENT\",\n                severity=\"critical\",\n                src_ip=src_ip, dst_ip=dst_ip,\n                unit_id=unit_id, func_code=func_code,\n                detail=f\"Modbus request from unauthorized client {src_ip}\",\n                mitre_technique=\"T0886 - Remote Services\",\n            ))\n\n        # Rule 2: Unauthorized function code\n        allowed_fcs = self.authorized_func_codes.get(session_key)\n        if allowed_fcs and func_code not in allowed_fcs:\n            fc_info = MODBUS_FUNCTION_CODES.get(func_code, (f\"Unknown FC{func_code}\", \"unknown\"))\n            severity = \"critical\" if fc_info[1] == \"write\" else \"high\"\n            self.anomalies.append(ModbusAnomaly(\n                timestamp=ts_str,\n                anomaly_type=\"UNAUTHORIZED_FUNCTION_CODE\",\n                severity=severity,\n                src_ip=src_ip, dst_ip=dst_ip,\n                unit_id=unit_id, func_code=func_code,\n                detail=f\"FC {func_code} ({fc_info[0]}) not in allowlist {sorted(allowed_fcs)}\",\n                mitre_technique=\"T0855 - Unauthorized Command Message\",\n            ))\n\n        # Rule 3: Write operation detection\n        if func_code in (5, 6, 15, 16, 22, 23):\n            session.write_count += 1\n            fc_name = MODBUS_FUNCTION_CODES.get(func_code, (\"Unknown\", \"\"))[0]\n\n            # Extract register address\n            if len(payload) >= 10:\n                register_addr = struct.unpack(\">H\", payload[8:10])[0]\n                session.register_ranges.add((func_code, register_addr))\n\n                self.anomalies.append(ModbusAnomaly(\n                    timestamp=ts_str,\n                    anomaly_type=\"WRITE_OPERATION\",\n                    severity=\"high\",\n                    src_ip=src_ip, dst_ip=dst_ip,\n                    unit_id=unit_id, func_code=func_code,\n                    detail=f\"Write: {fc_name} to register {register_addr} from {src_ip}\",\n                    mitre_technique=\"T0836 - Modify Parameter\",\n                ))\n\n        # Rule 4: Timing anomaly\n        if session.last_timestamp > 0:\n            interval = (timestamp - session.last_timestamp) * 1000  # ms\n            session.intervals.append(interval)\n\n            baseline = self.baseline_sessions.get(session_key)\n            if baseline and len(session.intervals) > 10:\n                expected_interval = baseline.get(\"polling_interval_avg_sec\", 0) * 1000\n                expected_std = baseline.get(\"polling_interval_stddev\", 0) * 1000\n\n                if expected_std > 0:\n                    z_score = abs(interval - expected_interval) \u002F expected_std\n                    if z_score > 5.0:\n                        self.anomalies.append(ModbusAnomaly(\n                            timestamp=ts_str,\n                            anomaly_type=\"TIMING_ANOMALY\",\n                            severity=\"medium\",\n                            src_ip=src_ip, dst_ip=dst_ip,\n                            unit_id=unit_id, func_code=func_code,\n                            detail=(\n                                f\"Interval {interval:.0f}ms vs baseline \"\n                                f\"{expected_interval:.0f}ms (z={z_score:.1f})\"\n                            ),\n                            mitre_technique=\"T0831 - Manipulation of Control\",\n                        ))\n\n        # Rule 5: Protocol violation - invalid protocol ID\n        if proto_id != 0:\n            self.anomalies.append(ModbusAnomaly(\n                timestamp=ts_str,\n                anomaly_type=\"PROTOCOL_VIOLATION\",\n                severity=\"high\",\n                src_ip=src_ip, dst_ip=dst_ip,\n                unit_id=unit_id, func_code=func_code,\n                detail=f\"Non-standard protocol ID {proto_id} (expected 0)\",\n                mitre_technique=\"T0830 - Man in the Middle\",\n            ))\n\n        # Rule 6: Broadcast write (unit ID 0)\n        if unit_id == 0 and func_code in (5, 6, 15, 16):\n            self.anomalies.append(ModbusAnomaly(\n                timestamp=ts_str,\n                anomaly_type=\"BROADCAST_WRITE\",\n                severity=\"critical\",\n                src_ip=src_ip, dst_ip=dst_ip,\n                unit_id=unit_id, func_code=func_code,\n                detail=\"Broadcast write command (unit ID 0) affects ALL slaves\",\n                mitre_technique=\"T0855 - Unauthorized Command Message\",\n            ))\n\n        session.last_timestamp = timestamp\n\n    def analyze_pcap(self, pcap_file):\n        \"\"\"Analyze pcap file for Modbus anomalies.\"\"\"\n        print(f\"[*] Analyzing {pcap_file}...\")\n        packets = rdpcap(pcap_file)\n        for pkt in packets:\n            self.process_packet(pkt)\n        print(f\"[*] Processed {self.packet_count} Modbus packets\")\n\n    def generate_report(self):\n        \"\"\"Generate anomaly detection report.\"\"\"\n        print(f\"\\n{'='*70}\")\n        print(\"MODBUS PROTOCOL ANOMALY DETECTION REPORT\")\n        print(f\"{'='*70}\")\n        print(f\"Packets analyzed: {self.packet_count}\")\n        print(f\"Sessions tracked: {len(self.sessions)}\")\n        print(f\"Anomalies detected: {len(self.anomalies)}\")\n\n        severity_counts = defaultdict(int)\n        type_counts = defaultdict(int)\n        for a in self.anomalies:\n            severity_counts[a.severity] += 1\n            type_counts[a.anomaly_type] += 1\n\n        print(f\"\\nBy Severity:\")\n        for sev in [\"critical\", \"high\", \"medium\", \"low\"]:\n            if severity_counts[sev]:\n                print(f\"  {sev.upper()}: {severity_counts[sev]}\")\n\n        print(f\"\\nBy Type:\")\n        for atype, count in sorted(type_counts.items(), key=lambda x: -x[1]):\n            print(f\"  {atype}: {count}\")\n\n        print(f\"\\nTop Anomalies:\")\n        for a in self.anomalies[:15]:\n            print(f\"  [{a.severity.upper()}] {a.anomaly_type}: {a.detail}\")\n\n\nif __name__ == \"__main__\":\n    detector = ModbusAnomalyDetector()\n\n    if len(sys.argv) > 1:\n        # Load baseline if provided\n        if len(sys.argv) > 2:\n            detector.load_baseline(sys.argv[2])\n        detector.analyze_pcap(sys.argv[1])\n        detector.generate_report()\n    else:\n        print(\"Usage: python modbus_detector.py \u003Cpcap_file> [baseline.json]\")\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| Modbus\u002FTCP | Industrial protocol running on TCP port 502, consisting of an MBAP header and PDU with function code and data |\n| Function Code | Modbus command identifier (FC1-4: reads, FC5-6\u002F15-16: writes, FC8: diagnostics) determining the operation type |\n| MBAP Header | Modbus Application Protocol header containing transaction ID, protocol ID (0x0000), length, and unit ID |\n| Unit ID | Modbus address (0-247) identifying the target slave device; unit ID 0 is broadcast to all slaves |\n| Register Map | Vendor-specific mapping of Modbus register addresses to process variables (e.g., register 40001 = reactor temperature) |\n| Function Code Allowlist | Security policy defining which Modbus function codes are permitted from each source IP to each target device |\n\n## Tools & Systems\n\n- **Zeek Modbus Analyzer**: Network security monitor with built-in Modbus\u002FTCP protocol analysis and logging\n- **Suricata with ET Open ICS rules**: IDS\u002FIPS with Modbus-specific detection rules for command injection and anomalies\n- **Wireshark Modbus Dissector**: Protocol analyzer with full Modbus\u002FTCP and Modbus RTU decoding\n- **PyModbus**: Python Modbus library for building custom monitoring and testing tools\n\n## Output Format\n\n```\nModbus Protocol Anomaly Detection Report\n==========================================\nCapture Period: YYYY-MM-DD to YYYY-MM-DD\nPackets Analyzed: [N]\nSessions: [N]\n\nANOMALIES: [N]\n  UNAUTHORIZED_CLIENT: [N]\n  UNAUTHORIZED_FUNCTION_CODE: [N]\n  WRITE_OPERATION: [N]\n  TIMING_ANOMALY: [N]\n  BROADCAST_WRITE: [N]\n```\n","# Detecting Modbus Protocol Anomalies\n\n## When to Use\n\n- When deploying Modbus-specific intrusion detection in an OT environment\n- When building baseline models for deterministic Modbus polling patterns\n- When investigating suspicious Modbus traffic flagged by OT monitoring tools\n- When implementing function code allowlisting on industrial firewalls\n- When detecting unauthorized Modbus write commands that could manipulate process setpoints\n\n**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).\n\n## Prerequisites\n\n- Network SPAN\u002FTAP access to monitor Modbus\u002FTCP traffic (port 502)\n- Zeek (formerly Bro) with Modbus protocol analyzer or Suricata with OT rulesets\n- Python 3.9+ with scapy and pymodbus for custom analysis\n- Baseline capture of normal Modbus traffic (minimum 1-2 weeks)\n- Documentation of authorized Modbus clients, function codes, and register maps\n\n## Workflow\n\n### Step 1: Capture and Parse Modbus Traffic\n\nDeploy passive monitoring to capture all Modbus\u002FTCP traffic and parse it into structured records for analysis.\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"Modbus Protocol Anomaly Detection System.\n\nMonitors Modbus\u002FTCP traffic for anomalies including unauthorized\nfunction codes, unusual register access, timing deviations,\nand rogue client devices.\n\"\"\"\n\nimport json\nimport struct\nimport sys\nimport time\nfrom collections import defaultdict, deque\nfrom dataclasses import dataclass, field\nfrom datetime import datetime\nfrom statistics import mean, stdev\n\ntry:\n    from scapy.all import sniff, rdpcap, IP, TCP\nexcept ImportError:\n    print(\"Install scapy: pip install scapy\")\n    sys.exit(1)\n\n\nMODBUS_FUNCTION_CODES = {\n    1: (\"Read Coils\", \"read\"),\n    2: (\"Read Discrete Inputs\", \"read\"),\n    3: (\"Read Holding Registers\", \"read\"),\n    4: (\"Read Input Registers\", \"read\"),\n    5: (\"Write Single Coil\", \"write\"),\n    6: (\"Write Single Register\", \"write\"),\n    7: (\"Read Exception Status\", \"diagnostic\"),\n    8: (\"Diagnostics\", \"diagnostic\"),\n    11: (\"Get Comm Event Counter\", \"diagnostic\"),\n    12: (\"Get Comm Event Log\", \"diagnostic\"),\n    15: (\"Write Multiple Coils\", \"write\"),\n    16: (\"Write Multiple Registers\", \"write\"),\n    17: (\"Report Slave ID\", \"diagnostic\"),\n    22: (\"Mask Write Register\", \"write\"),\n    23: (\"Read\u002FWrite Multiple Registers\", \"read_write\"),\n    43: (\"Encapsulated Interface Transport\", \"diagnostic\"),\n}\n\n\n@dataclass\nclass ModbusAnomaly:\n    timestamp: str\n    anomaly_type: str\n    severity: str\n    src_ip: str\n    dst_ip: str\n    unit_id: int\n    func_code: int\n    detail: str\n    mitre_technique: str = \"\"\n\n\n@dataclass\nclass ModbusSession:\n    \"\"\"Tracks state for a Modbus master-slave session.\"\"\"\n    src_ip: str\n    dst_ip: str\n    func_codes_seen: dict = field(default_factory=lambda: defaultdict(int))\n    register_ranges: set = field(default_factory=set)\n    intervals: list = field(default_factory=lambda: deque(maxlen=500))\n    last_timestamp: float = 0\n    request_count: int = 0\n    write_count: int = 0\n\n\nclass ModbusAnomalyDetector:\n    \"\"\"Detects anomalies in Modbus\u002FTCP traffic.\"\"\"\n\n    def __init__(self):\n        self.sessions = {}\n        self.baseline_sessions = {}\n        self.anomalies = []\n        self.authorized_clients = set()\n        self.authorized_func_codes = {}  # per-session allowed FCs\n        self.packet_count = 0\n\n    def set_authorized_clients(self, clients):\n        \"\"\"Set list of authorized Modbus client IPs.\"\"\"\n        self.authorized_clients = set(clients)\n\n    def set_authorized_func_codes(self, session_key, func_codes):\n        \"\"\"Set allowed function codes for a specific session.\"\"\"\n        self.authorized_func_codes[session_key] = set(func_codes)\n\n    def load_baseline(self, baseline_file):\n        \"\"\"Load baseline profiles from previous capture analysis.\"\"\"\n        with open(baseline_file) as f:\n            baseline = json.load(f)\n        for key, data in baseline.get(\"modbus_baselines\", {}).items():\n            self.baseline_sessions[key] = data\n            self.authorized_func_codes[key] = set(data.get(\"allowed_function_codes\", []))\n        print(f\"[*] Loaded {len(self.baseline_sessions)} Modbus baselines\")\n\n    def process_packet(self, pkt):\n        \"\"\"Process a single packet for Modbus anomaly detection.\"\"\"\n        if not pkt.haslayer(TCP) or not pkt.haslayer(IP):\n            return\n\n        # Check for Modbus\u002FTCP (port 502)\n        if pkt[TCP].dport != 502 and pkt[TCP].sport != 502:\n            return\n\n        payload = bytes(pkt[TCP].payload)\n        if len(payload) \u003C 8:\n            return\n\n        self.packet_count += 1\n        timestamp = float(pkt.time)\n        ts_str = datetime.fromtimestamp(timestamp).isoformat()\n\n        # Parse MBAP header\n        try:\n            trans_id = struct.unpack(\">H\", payload[0:2])[0]\n            proto_id = struct.unpack(\">H\", payload[2:4])[0]\n            length = struct.unpack(\">H\", payload[4:6])[0]\n            unit_id = payload[6]\n            func_code = payload[7]\n        except (IndexError, struct.error):\n            return\n\n        # Determine direction\n        if pkt[TCP].dport == 502:\n            src_ip = pkt[IP].src\n            dst_ip = pkt[IP].dst\n            is_request = True\n        else:\n            src_ip = pkt[IP].dst\n            dst_ip = pkt[IP].src\n            is_request = False\n\n        if not is_request:\n            return  # Only analyze requests\n\n        session_key = f\"{src_ip}->{dst_ip}\"\n\n        # Get or create session\n        if session_key not in self.sessions:\n            self.sessions[session_key] = ModbusSession(src_ip=src_ip, dst_ip=dst_ip)\n\n        session = self.sessions[session_key]\n        session.request_count += 1\n        session.func_codes_seen[func_code] += 1\n\n        # ── Anomaly Detection Rules ──\n\n        # Rule 1: Unauthorized Modbus client\n        if self.authorized_clients and src_ip not in self.authorized_clients:\n            self.anomalies.append(ModbusAnomaly(\n                timestamp=ts_str,\n                anomaly_type=\"UNAUTHORIZED_CLIENT\",\n                severity=\"critical\",\n                src_ip=src_ip, dst_ip=dst_ip,\n                unit_id=unit_id, func_code=func_code,\n                detail=f\"Modbus request from unauthorized client {src_ip}\",\n                mitre_technique=\"T0886 - Remote Services\",\n            ))\n\n        # Rule 2: Unauthorized function code\n        allowed_fcs = self.authorized_func_codes.get(session_key)\n        if allowed_fcs and func_code not in allowed_fcs:\n            fc_info = MODBUS_FUNCTION_CODES.get(func_code, (f\"Unknown FC{func_code}\", \"unknown\"))\n            severity = \"critical\" if fc_info[1] == \"write\" else \"high\"\n            self.anomalies.append(ModbusAnomaly(\n                timestamp=ts_str,\n                anomaly_type=\"UNAUTHORIZED_FUNCTION_CODE\",\n                severity=severity,\n                src_ip=src_ip, dst_ip=dst_ip,\n                unit_id=unit_id, func_code=func_code,\n                detail=f\"FC {func_code} ({fc_info[0]}) not in allowlist {sorted(allowed_fcs)}\",\n                mitre_technique=\"T0855 - Unauthorized Command Message\",\n            ))\n\n        # Rule 3: Write operation detection\n        if func_code in (5, 6, 15, 16, 22, 23):\n            session.write_count += 1\n            fc_name = MODBUS_FUNCTION_CODES.get(func_code, (\"Unknown\", \"\"))[0]\n\n            # Extract register address\n            if len(payload) >= 10:\n                register_addr = struct.unpack(\">H\", payload[8:10])[0]\n                session.register_ranges.add((func_code, register_addr))\n\n                self.anomalies.append(ModbusAnomaly(\n                    timestamp=ts_str,\n                    anomaly_type=\"WRITE_OPERATION\",\n                    severity=\"high\",\n                    src_ip=src_ip, dst_ip=dst_ip,\n                    unit_id=unit_id, func_code=func_code,\n                    detail=f\"Write: {fc_name} to register {register_addr} from {src_ip}\",\n                    mitre_technique=\"T0836 - Modify Parameter\",\n                ))\n\n        # Rule 4: Timing anomaly\n        if session.last_timestamp > 0:\n            interval = (timestamp - session.last_timestamp) * 1000  # ms\n            session.intervals.append(interval)\n\n            baseline = self.baseline_sessions.get(session_key)\n            if baseline and len(session.intervals) > 10:\n                expected_interval = baseline.get(\"polling_interval_avg_sec\", 0) * 1000\n                expected_std = baseline.get(\"polling_interval_stddev\", 0) * 1000\n\n                if expected_std > 0:\n                    z_score = abs(interval - expected_interval) \u002F expected_std\n                    if z_score > 5.0:\n                        self.anomalies.append(ModbusAnomaly(\n                            timestamp=ts_str,\n                            anomaly_type=\"TIMING_ANOMALY\",\n                            severity=\"medium\",\n                            src_ip=src_ip, dst_ip=dst_ip,\n                            unit_id=unit_id, func_code=func_code,\n                            detail=(\n                                f\"Interval {interval:.0f}ms vs baseline \"\n                                f\"{expected_interval:.0f}ms (z={z_score:.1f})\"\n                            ),\n                            mitre_technique=\"T0831 - Manipulation of Control\",\n                        ))\n\n        # Rule 5: Protocol violation - invalid protocol ID\n        if proto_id != 0:\n            self.anomalies.append(ModbusAnomaly(\n                timestamp=ts_str,\n                anomaly_type=\"PROTOCOL_VIOLATION\",\n                severity=\"high\",\n                src_ip=src_ip, dst_ip=dst_ip,\n                unit_id=unit_id, func_code=func_code,\n                detail=f\"Non-standard protocol ID {proto_id} (expected 0)\",\n                mitre_technique=\"T0830 - Man in the Middle\",\n            ))\n\n        # Rule 6: Broadcast write (unit ID 0)\n        if unit_id == 0 and func_code in (5, 6, 15, 16):\n            self.anomalies.append(ModbusAnomaly(\n                timestamp=ts_str,\n                anomaly_type=\"BROADCAST_WRITE\",\n                severity=\"critical\",\n                src_ip=src_ip, dst_ip=dst_ip,\n                unit_id=unit_id, func_code=func_code,\n                detail=\"Broadcast write command (unit ID 0) affects ALL slaves\",\n                mitre_technique=\"T0855 - Unauthorized Command Message\",\n            ))\n\n        session.last_timestamp = timestamp\n\n    def analyze_pcap(self, pcap_file):\n        \"\"\"Analyze pcap file for Modbus anomalies.\"\"\"\n        print(f\"[*] Analyzing {pcap_file}...\")\n        packets = rdpcap(pcap_file)\n        for pkt in packets:\n            self.process_packet(pkt)\n        print(f\"[*] Processed {self.packet_count} Modbus packets\")\n\n    def generate_report(self):\n        \"\"\"Generate anomaly detection report.\"\"\"\n        print(f\"\\n{'='*70}\")\n        print(\"MODBUS PROTOCOL ANOMALY DETECTION REPORT\")\n        print(f\"{'='*70}\")\n        print(f\"Packets analyzed: {self.packet_count}\")\n        print(f\"Sessions tracked: {len(self.sessions)}\")\n        print(f\"Anomalies detected: {len(self.anomalies)}\")\n\n        severity_counts = defaultdict(int)\n        type_counts = defaultdict(int)\n        for a in self.anomalies:\n            severity_counts[a.severity] += 1\n            type_counts[a.anomaly_type] += 1\n\n        print(f\"\\nBy Severity:\")\n        for sev in [\"critical\", \"high\", \"medium\", \"low\"]:\n            if severity_counts[sev]:\n                print(f\"  {sev.upper()}: {severity_counts[sev]}\")\n\n        print(f\"\\nBy Type:\")\n        for atype, count in sorted(type_counts.items(), key=lambda x: -x[1]):\n            print(f\"  {atype}: {count}\")\n\n        print(f\"\\nTop Anomalies:\")\n        for a in self.anomalies[:15]:\n            print(f\"  [{a.severity.upper()}] {a.anomaly_type}: {a.detail}\")\n\n\nif __name__ == \"__main__\":\n    detector = ModbusAnomalyDetector()\n\n    if len(sys.argv) > 1:\n        # Load baseline if provided\n        if len(sys.argv) > 2:\n            detector.load_baseline(sys.argv[2])\n        detector.analyze_pcap(sys.argv[1])\n        detector.generate_report()\n    else:\n        print(\"Usage: python modbus_detector.py \u003Cpcap_file> [baseline.json]\")\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| Modbus\u002FTCP | Industrial protocol running on TCP port 502, consisting of an MBAP header and PDU with function code and data |\n| Function Code | Modbus command identifier (FC1-4: reads, FC5-6\u002F15-16: writes, FC8: diagnostics) determining the operation type |\n| MBAP Header | Modbus Application Protocol header containing transaction ID, protocol ID (0x0000), length, and unit ID |\n| Unit ID | Modbus address (0-247) identifying the target slave device; unit ID 0 is broadcast to all slaves |\n| Register Map | Vendor-specific mapping of Modbus register addresses to process variables (e.g., register 40001 = reactor temperature) |\n| Function Code Allowlist | Security policy defining which Modbus function codes are permitted from each source IP to each target device |\n\n## Tools & Systems\n\n- **Zeek Modbus Analyzer**: Network security monitor with built-in Modbus\u002FTCP protocol analysis and logging\n- **Suricata with ET Open ICS rules**: IDS\u002FIPS with Modbus-specific detection rules for command injection and anomalies\n- **Wireshark Modbus Dissector**: Protocol analyzer with full Modbus\u002FTCP and Modbus RTU decoding\n- **PyModbus**: Python Modbus library for building custom monitoring and testing tools\n\n## Output Format\n\n```\nModbus Protocol Anomaly Detection Report\n==========================================\nCapture Period: YYYY-MM-DD to YYYY-MM-DD\nPackets Analyzed: [N]\nSessions: [N]\n\nANOMALIES: [N]\n  UNAUTHORIZED_CLIENT: [N]\n  UNAUTHORIZED_FUNCTION_CODE: [N]\n  WRITE_OPERATION: [N]\n  TIMING_ANOMALY: [N]\n  BROADCAST_WRITE: [N]\n```\n",{"name":5,"tags":25,"author":33,"domain":34,"license":15,"version":35,"nist_csf":36,"subdomain":41,"description":7,"nist_ai_rmf":42,"mitre_attack":46,"atlas_techniques":52},[26,27,28,29,30,31,32],"ot-security","ics","scada","industrial-control","iec62443","modbus","protocol-anomaly","mahipal","cybersecurity","1.0.0",[37,38,39,40],"PR.IR-01","DE.CM-01","ID.AM-05","GV.OC-02","ot-ics-security",[43,44,45],"MEASURE-2.7","MAP-5.1","MANAGE-2.4",[47,48,49,50,51],"T1078","T1190","T1059","T0816","T0836",[53,54,55],"AML.T0070","AML.T0066","AML.T0082","main","7540bbccf0c1ded6156a467b02c95b61ad62413f",".agents\u002Fskills\u002Fdetecting-modbus-protocol-anomalies","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena","Currently exploring the intersection of tech","2026-09-11 03:02:31",{"source":8,"skillName":5,"commands":64,"prompt":74,"zipAvailable":75},[65,68,71],{"tool":66,"command":67},"npx","npx skills add NeelakshSaxena\u002FVayu --skill detecting-modbus-protocol-anomalies",{"tool":69,"command":70},"bunx","bunx skills add NeelakshSaxena\u002FVayu --skill detecting-modbus-protocol-anomalies",{"tool":72,"command":73},"pnpm","pnpm dlx skills add NeelakshSaxena\u002FVayu --skill detecting-modbus-protocol-anomalies","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002FSKILL.md",true,[77,81,87],{"path":78,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":16},"LICENSE","许可证",11255,{"path":82,"resourceType":83,"resourceTypeDesc":84,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002Fapi-reference.md","REFERENCE","参考文档",1662,"https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002Freferences\u002Fapi-reference.md",{"path":88,"resourceType":89,"resourceTypeDesc":90,"sizeBytes":91,"sourceHtmlUrl":92},"scripts\u002Fagent.py","SCRIPT","脚本",5512,"https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002Fscripts\u002Fagent.py",[94,101,108,115,122,129],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":20},"01M7ACCCVNCFKMA9X6D15X6G98","runpodctl","Runpod CLI for managing GPU\u002FCPU workloads from the terminal — pods, serverless endpoints, templates, network volumes, Hub deploys, models, SSH, and file transfer (send\u002Freceive). Use for terminal\u002FCI\u002Fscripting, Hub browse\u002Fdeploy, SSH setup, `doctor`, or when the Runpod MCP tools are not connected. For structured tool calls in an MCP-enabled session, prefer runpod-mcp.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpodctl\u002FSKILL.md",[],[],{"skillNo":102,"name":103,"nameZh":6,"description":104,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":105,"categories":106,"keywords":107,"publishedAt":20},"01M7ACC63SRHEA5KMCHSMZK2TC","runpod","Start here for any Runpod task — running GPU\u002FCPU pods, deploying serverless endpoints, templates, network volumes, building images, or understanding how Runpod works. Routes to the right skill (runpod-mcp, runpodctl, flash, companion-clis, runpod-usage, runpod-templates, runpod-migrate) and indexes two dozen live-verified end-to-end examples (golden paths) — use it when the lane is unclear, and for any multi-step or provisioning task even when it is not.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod\u002FSKILL.md",[],[],{"skillNo":109,"name":110,"nameZh":6,"description":111,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":112,"categories":113,"keywords":114,"publishedAt":20},"01M7ACC0Q1C89N9BZBV91CTQTF","runpod-usage","How Runpod works and how to work it — pods vs serverless, GPU\u002FVRAM selection, storage, building a container, networking, plus the agentic pod development loop (provision → ssh-exec → set up → poll readiness) and on-pod install hygiene (uv\u002Fapt). Use to answer \"how does X work\", \"which GPU\", \"how do I build a container\", or \"how do I stand up a workload on a pod\". Guidance, not a tool — execute with runpodctl, runpod-mcp, or flash.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod-usage\u002FSKILL.md",[],[],{"skillNo":116,"name":117,"nameZh":6,"description":118,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":119,"categories":120,"keywords":121,"publishedAt":20},"01M7ACBRPE345GF5GM5B8P8RRC","runpod-templates","Runpod's official prebuilt pod templates (ComfyUI, PyTorch, and others): what each image ships, which ports and paths it uses, how to pick one, how to pin a version, and what is missing on first boot. Use when a task says \"run \u003CX> on a pod\" and an official template already covers it, instead of building an image — and when a user needs help with or wants to fix something about a Runpod template they are already running (won't boot, can't reach the UI, missing models, wrong CUDA line, broken ComfyUI workflow metadata on imported workflows): start here and route onward. Deploy with runpodctl or runpod-mcp; end-to-end walkthroughs live in the runpod router's golden paths.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod-templates\u002FSKILL.md",[],[],{"skillNo":123,"name":124,"nameZh":6,"description":125,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":20},"01M7ACBJATHKVX1TWES2F44GY8","runpod-migrate","Migrate a codebase from the Runpod GraphQL API or REST v1 to REST v2 — inventory which parts use which API version, rewrite the call sites, flag breaking changes, and verify. Use when someone asks to move to v2, asks what v2 would change, or asks which Runpod API their code is on. For managing infrastructure rather than migrating code, use runpod-mcp or runpodctl.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod-migrate\u002FSKILL.md",[],[],{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":133,"categories":134,"keywords":135,"publishedAt":20},"01M7ACBC7GHVH6T9YEAPCG2AP8","runpod-mcp","Manage Runpod infrastructure — pods, serverless endpoints, jobs, templates, network volumes, container-registry auth, GPU\u002FCPU catalog, and billing — via the Runpod MCP server's structured tool calls. Use when the Runpod MCP tools (create-pod, list-endpoints, …) are connected in this session, or to connect them (hosted OAuth or local npx). Prefer this over runpodctl for plain infra CRUD when MCP is available; use runpodctl for the terminal, file transfer, or SSH setup.","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Frunpod-mcp\u002FSKILL.md",[],[]]