[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GXMF4V03WMYHW9K7ZM9J6A":3,"skill-same:01M6GXMF4V03WMYHW9K7ZM9J6A":89},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":38,"linkOnly":39,"markdownContent":40,"markdownBody":41,"frontMatter":42,"refName":51,"commitSha":52,"skillDirectory":53,"forksCount":54,"repositoryHtmlUrl":55,"repositoryHomepageUrl":6,"ownerHtmlUrl":56,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":57,"install":58,"resources":71},"01M6GXMF4V03WMYHW9K7ZM9J6A","detecting-modbus-protocol-anomalies",null,"This skill covers detecting anomalies in Modbus\u002FTCP 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.","micsapp\u002Fmicstec-skills","micsapp","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F82411001?v=4","01M6GWCFQ6D3PV8EHNY62NN5VW","01M6GWCFVE1PA5HG0DKC7AMFJ3",4,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002FSKILL.md",[],[18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37],"modbus","detecting","detecting modbus protocol anomalies","protocol","protocol-anomaly","cybersecurity","timing","register","chain","deep","Rules","analysis","code","python","ics","ot-security","suricata","ids","Zeek","tcp","2026-11-10 10:12:30",false,"---\nname: detecting-modbus-protocol-anomalies\ndescription: >\n  This skill covers detecting anomalies in Modbus\u002FTCP and Modbus RTU communications\n  in industrial control systems. It addresses function code monitoring, register\n  range validation, timing analysis, unauthorized client detection, and deep packet\n  inspection for malformed Modbus frames. The skill leverages Zeek with Modbus protocol\n  analyzers, Suricata IDS with OT rules, and custom Python-based detection using\n  Markov chain models for normal Modbus transaction sequences.\ndomain: cybersecurity\nsubdomain: ot-ics-security\ntags: [ot-security, ics, scada, industrial-control, iec62443, modbus, protocol-anomaly]\nversion: 1.0.0\nauthor: mahipal\nlicense: Apache-2.0\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":43,"author":47,"domain":23,"license":14,"version":48,"subdomain":49,"description":50},[33,32,44,45,46,18,22],"scada","industrial-control","iec62443","mahipal","1.0.0","ot-ics-security","This skill covers detecting anomalies in Modbus\u002FTCP 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.\n","master","3f5d983eb4ef375b749adcd6b07ec03bd82ae8a8","_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-modbus-protocol-anomalies",0,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills","https:\u002F\u002Fgithub.com\u002Fmicsapp","2026-03-20 11:24:18",{"source":8,"skillName":5,"commands":59,"prompt":69,"zipAvailable":70},[60,63,66],{"tool":61,"command":62},"npx","npx skills add micsapp\u002Fmicstec-skills --skill detecting-modbus-protocol-anomalies",{"tool":64,"command":65},"bunx","bunx skills add micsapp\u002Fmicstec-skills --skill detecting-modbus-protocol-anomalies",{"tool":67,"command":68},"pnpm","pnpm dlx skills add micsapp\u002Fmicstec-skills --skill detecting-modbus-protocol-anomalies","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002FSKILL.md",true,[72,77,83],{"path":73,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":76},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002FLICENSE",{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"references\u002Fapi-reference.md","REFERENCE","参考文档",1662,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002Freferences\u002Fapi-reference.md",{"path":84,"resourceType":85,"resourceTypeDesc":86,"sizeBytes":87,"sourceHtmlUrl":88},"scripts\u002Fagent.py","SCRIPT","脚本",5512,"https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002F_universal\u002Fcybersecurity-skills\u002Fskills\u002Fdetecting-modbus-protocol-anomalies\u002Fscripts\u002Fagent.py",[90,118,139,159,177,202],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":38},"01M6HBTJ02FXBFG9NYEHHYAP52","azure-apim-architecture","Analyzes and explains Azure API Management architecture decisions for enterprise API marketplace implementations using VNet Internal mode, Front Door, hybrid authentication, and multi-environment strategies. Use when discussing APIM component selection, network topology, cost optimization, or comparing alternatives like workspaces vs instances, VNet Internal vs External mode, or Front Door vs Application Gateway.","MIT","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fazure-apim-architecture\u002FSKILL.md",[],[98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117],"architecture","azure","azure apim architecture","component","authentication","gateway","topology","Optimization","network","api","team","environment","multi-environment","workspaces","instances","selection","strategies","azure api management","mode","for",{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":38},"01M6HBT7J4H082JEEA670B3EQ9","apiops-deployment","Guides deployment of Azure API Management infrastructure using Infrastructure as Code (Bicep\u002FTerraform), CI\u002FCD pipelines (GitHub Actions\u002FAzure DevOps), and APIOps workflows. Use when deploying APIM, creating pipelines, or implementing dev→test→prod promotion strategies.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapiops-deployment\u002FSKILL.md",[],[125,126,127,128,99,129,30,130,131,132,133,134,107,108,114,135,136,115,137,138],"deployment","apiops deployment","workflows","azure devops","infrastructure","infrastructure as code","actions","ci","github actions","github-actions","as","guides","CI\u002FCD","implementing",{"skillNo":140,"name":141,"nameZh":6,"description":142,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":143,"categories":144,"keywords":145,"publishedAt":38},"01M6HBT2HEA23THNE9E00GYQBE","apim-policy-authoring","Creates production-ready Azure API Management policy XML for authentication (OAuth 2.0, JWT validation, subscription keys), rate limiting, CORS configuration, error handling, and API transformations. Use when implementing API security, access control, or request\u002Fresponse processing logic.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapim-policy-authoring\u002FSKILL.md",[],[146,147,148,149,99,102,107,108,150,151,152,153,154,155,156,115,157,158,138,117],"policy","authoring","apim policy authoring","security","access","use","ready","api security","Access Control","error","processing","cors configuration","production-ready",{"skillNo":160,"name":161,"nameZh":6,"description":162,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":163,"categories":164,"keywords":165,"publishedAt":38},"01M6HBSY65SB29J9WE9KYD0K6T","api-security-review","Reviews Azure API Management configurations for security vulnerabilities, OWASP API Security Top 10 compliance, VNet Internal mode validation, Private Link verification, and Azure Security Benchmark alignment. Use when performing security audits, pre-deployment validation, or compliance reviews.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fcopilot-agent-skills\u002F.github\u002Fskills\u002Fapi-security-review\u002FSKILL.md",[],[166,149,167,107,153,168,99,125,169,170,171,172,108,173,115,174,175,176,116,117],"review","security review","api security review","benchmark","verification","owasp","owasp-api","alignment","azure security","reviews","top",{"skillNo":178,"name":179,"nameZh":6,"description":180,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":181,"categories":182,"keywords":183,"publishedAt":38},"01M6HBSRW4PDFE6K4F8JYPZQ05","jira-cli","Interact with Jira from the command line to create, list, view, edit, and transition issues, manage sprints and epics, and perform common Jira workflows. Use when the user asks about Jira tasks, tickets, issues, sprints, or needs to manage project work items.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fjira-cli\u002FSKILL.md",[],[184,185,186,127,187,188,189,190,107,191,192,193,194,195,196,197,198,199,200,201],"cli","jira","jira cli","init","tasks","create","issues","common","work","command","edit","list","view","project","project work","token","line","sprints",{"skillNo":203,"name":204,"nameZh":6,"description":205,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":94,"licenseFileUrl":6,"sourceHtmlUrl":206,"categories":207,"keywords":208,"publishedAt":38},"01M6HBSNS3JHMW603G47TWE31H","calculator","Performs arbitrary-precision arithmetic calculations including addition, subtraction, multiplication, division, and exponents. Use when the user asks to calculate, compute, or evaluate math expressions, or when precise decimal arithmetic is needed to avoid floating-point errors.","https:\u002F\u002Fgithub.com\u002Fmicsapp\u002Fmicstec-skills\u002Fblob\u002Fmaster\u002Fcopilot-cli\u002Fawesome-copilot-agents\u002Fskills\u002Fcalculator\u002FSKILL.md",[],[204,209,210,211,212,213,214,151,215,216],"npm","js","calculate","node","math","user","compute","errors"]