[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7A61CE22VR9YEDV1FFR59MQ":3,"skill-same:01M7A61CE22VR9YEDV1FFR59MQ":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},"01M7A61CE22VR9YEDV1FFR59MQ","detecting-dnp3-protocol-anomalies",null,"Detect anomalies in DNP3 communications used in SCADA\u002FICS systems by monitoring unauthorized control commands, firmware update attempts, protocol violations, and deviations from baseline traffic using deep packet inspection and machine learning approaches. Use when securing energy-sector or other OT\u002FICS networks, investigating suspicious DNP3 master\u002Foutstation activity, or building an anomaly-based IDS for industrial control traffic.","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-dnp3-protocol-anomalies\u002FLICENSE","https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdetecting-dnp3-protocol-anomalies\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: detecting-dnp3-protocol-anomalies\ndescription: Detect anomalies in DNP3 communications used in SCADA\u002FICS systems by monitoring unauthorized control commands, firmware update attempts, protocol violations, and deviations from baseline traffic using deep packet inspection and machine learning approaches. Use when securing energy-sector or other OT\u002FICS networks, investigating suspicious DNP3 master\u002Foutstation activity, or building an anomaly-based IDS for industrial control traffic.\ndomain: cybersecurity\nsubdomain: ot-ics-security\ntags:\n- ot-security\n- ics\n- dnp3\n- scada\n- anomaly-detection\n- protocol-analysis\n- energy-sector\n- ids\nversion: '1.0'\nauthor: mahipal\nlicense: Apache-2.0\natlas_techniques:\n- AML.T0043\n- AML.T0018\nnist_ai_rmf:\n- MEASURE-2.7\n- MEASURE-2.5\n- MAP-5.1\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 DNP3 Protocol Anomalies\n\n## When to Use\n\n- When monitoring SCADA systems in the energy sector where DNP3 is the primary protocol\n- When building detection rules for DNP3-based attacks against RTUs and substations\n- When investigating suspected unauthorized control commands sent via DNP3\n- When deploying IDS with DNP3 deep packet inspection at utility substations\n- When responding to alerts from OT monitoring platforms about DNP3 traffic anomalies\n\n**Do not use** for non-DNP3 protocol monitoring (see detecting-modbus-command-injection-attacks for Modbus), for DNP3 Secure Authentication configuration (separate implementation), or for protocol-agnostic network anomaly detection.\n\n## Prerequisites\n\n- Network TAP\u002FSPAN on DNP3 communication segments (TCP port 20000 or serial)\n- Baseline of normal DNP3 traffic patterns (masters, outstations, poll intervals, function codes)\n- Suricata or Zeek with DNP3 protocol parser enabled\n- Understanding of DNP3 function codes and object groups used in the environment\n- DNP3 communication topology map (master-to-outstation relationships)\n\n## Workflow\n\n### Step 1: Analyze DNP3 Traffic for Anomalies\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"DNP3 Protocol Anomaly Detector.\n\nMonitors DNP3 communications for unauthorized control commands,\nprotocol violations, and deviations from established baselines.\nSupports both TCP and serial DNP3 deployments.\n\"\"\"\n\nimport struct\nimport sys\nimport json\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom typing import Dict, List, Optional, Set\n\ntry:\n    from scapy.all import rdpcap, IP, TCP\nexcept ImportError:\n    print(\"Install scapy: pip install scapy\")\n    sys.exit(1)\n\n\n# DNP3 Function Codes\nDNP3_FUNCTIONS = {\n    0x00: \"Confirm\", 0x01: \"Read\", 0x02: \"Write\",\n    0x03: \"Select\", 0x04: \"Operate\", 0x05: \"Direct Operate\",\n    0x06: \"Direct Operate No Ack\", 0x07: \"Immediate Freeze\",\n    0x08: \"Immediate Freeze No Ack\", 0x09: \"Freeze and Clear\",\n    0x0A: \"Freeze and Clear No Ack\", 0x0B: \"Freeze at Time\",\n    0x0C: \"Freeze at Time No Ack\", 0x0D: \"Cold Restart\",\n    0x0E: \"Warm Restart\", 0x0F: \"Initialize Data\",\n    0x10: \"Initialize Application\", 0x11: \"Start Application\",\n    0x12: \"Stop Application\", 0x13: \"Save Configuration\",\n    0x14: \"Enable Unsolicited\", 0x15: \"Disable Unsolicited\",\n    0x16: \"Assign Class\", 0x17: \"Delay Measurement\",\n    0x18: \"Record Current Time\", 0x19: \"Open File\",\n    0x1A: \"Close File\", 0x1B: \"Delete File\",\n    0x1C: \"Get File Info\", 0x1D: \"Authenticate File\",\n    0x1E: \"Abort File\", 0x81: \"Response\", 0x82: \"Unsolicited Response\",\n}\n\n# High-risk function codes that should trigger alerts\nDNP3_CRITICAL_FUNCTIONS = {\n    0x02,  # Write\n    0x03, 0x04, 0x05, 0x06,  # Select\u002FOperate\u002FDirect Operate\n    0x0D,  # Cold Restart\n    0x0E,  # Warm Restart\n    0x0F,  # Initialize Data\n    0x10,  # Initialize Application\n    0x12,  # Stop Application\n    0x19, 0x1A, 0x1B,  # File operations (firmware update)\n}\n\n\nclass DNP3AnomalyDetector:\n    \"\"\"Detects anomalies in DNP3 protocol communications.\"\"\"\n\n    def __init__(self, baseline_file: Optional[str] = None):\n        self.alerts = []\n        self.sessions = defaultdict(lambda: {\n            \"packet_count\": 0,\n            \"function_codes\": defaultdict(int),\n            \"control_commands\": 0,\n            \"file_operations\": 0,\n            \"restarts\": 0,\n        })\n        self.packet_count = 0\n        self.dnp3_count = 0\n\n        self.authorized_masters: Set[str] = set()\n        self.authorized_pairs: Dict[str, Set[str]] = defaultdict(set)\n        self.baseline_functions: Dict[str, Set[int]] = defaultdict(set)\n\n        if baseline_file:\n            self.load_baseline(baseline_file)\n\n    def load_baseline(self, filepath: str):\n        \"\"\"Load DNP3 communication baseline.\"\"\"\n        with open(filepath, \"r\") as f:\n            baseline = json.load(f)\n\n        for entry in baseline.get(\"authorized_communications\", []):\n            master = entry[\"master_ip\"]\n            outstation = entry[\"outstation_ip\"]\n            self.authorized_masters.add(master)\n            self.authorized_pairs[master].add(outstation)\n            self.baseline_functions[f\"{master}->{outstation}\"] = set(\n                entry.get(\"expected_function_codes\", [0x00, 0x01])\n            )\n\n    def parse_dnp3_header(self, payload: bytes) -> Optional[dict]:\n        \"\"\"Parse DNP3 data link layer and transport\u002Fapplication headers.\"\"\"\n        if len(payload) \u003C 10:\n            return None\n\n        # DNP3 Data Link Layer: start(2) + length(1) + control(1) + dest(2) + source(2) + crc(2)\n        start_bytes = struct.unpack(\">H\", payload[0:2])[0]\n        if start_bytes != 0x0564:\n            return None\n\n        length = payload[2]\n        control = payload[3]\n        dest_addr = struct.unpack(\"\u003CH\", payload[4:6])[0]\n        source_addr = struct.unpack(\"\u003CH\", payload[6:8])[0]\n\n        direction = \"Master->Outstation\" if (control & 0x80) else \"Outstation->Master\"\n\n        result = {\n            \"length\": length,\n            \"control\": control,\n            \"direction\": direction,\n            \"dest_addr\": dest_addr,\n            \"source_addr\": source_addr,\n            \"is_master\": bool(control & 0x80),\n        }\n\n        # Parse transport and application layer (after CRC bytes)\n        if len(payload) >= 12:\n            transport_header = payload[10]\n            if len(payload) >= 13:\n                app_control = payload[11]\n                func_code = payload[12]\n                result[\"function_code\"] = func_code\n                result[\"function_name\"] = DNP3_FUNCTIONS.get(\n                    func_code, f\"Unknown (0x{func_code:02x})\"\n                )\n\n        return result\n\n    def analyze_packet(self, pkt):\n        \"\"\"Analyze a packet for DNP3 anomalies.\"\"\"\n        self.packet_count += 1\n\n        if not pkt.haslayer(IP) or not pkt.haslayer(TCP):\n            return\n\n        tcp = pkt[TCP]\n        if tcp.dport != 20000 and tcp.sport != 20000:\n            return\n\n        payload = bytes(tcp.payload)\n        if not payload:\n            return\n\n        dnp3 = self.parse_dnp3_header(payload)\n        if not dnp3:\n            return\n\n        self.dnp3_count += 1\n        src_ip = pkt[IP].src\n        dst_ip = pkt[IP].dst\n        session_key = f\"{src_ip}->{dst_ip}\"\n        session = self.sessions[session_key]\n        session[\"packet_count\"] += 1\n\n        func_code = dnp3.get(\"function_code\")\n        if func_code is not None:\n            session[\"function_codes\"][func_code] += 1\n\n            # Detection 1: Unauthorized DNP3 master\n            if dnp3.get(\"is_master\") and self.authorized_masters:\n                if src_ip not in self.authorized_masters:\n                    self.alerts.append({\n                        \"severity\": \"CRITICAL\",\n                        \"type\": \"UNAUTHORIZED_DNP3_MASTER\",\n                        \"src\": src_ip, \"dst\": dst_ip,\n                        \"function\": dnp3.get(\"function_name\"),\n                        \"description\": f\"Unauthorized DNP3 master {src_ip} communicating with outstation {dst_ip}\",\n                        \"mitre\": \"T0869 - Standard Application Layer Protocol\",\n                    })\n\n            # Detection 2: Cold\u002FWarm restart command\n            if func_code in (0x0D, 0x0E):\n                session[\"restarts\"] += 1\n                restart_type = \"Cold\" if func_code == 0x0D else \"Warm\"\n                self.alerts.append({\n                    \"severity\": \"CRITICAL\",\n                    \"type\": \"DNP3_RESTART_COMMAND\",\n                    \"src\": src_ip, \"dst\": dst_ip,\n                    \"function\": f\"{restart_type} Restart\",\n                    \"description\": f\"{restart_type} restart command sent to outstation {dst_ip} (addr {dnp3['dest_addr']})\",\n                    \"mitre\": \"T0816 - Device Restart\u002FShutdown\",\n                })\n\n            # Detection 3: File operations (potential firmware update)\n            if func_code in (0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E):\n                session[\"file_operations\"] += 1\n                self.alerts.append({\n                    \"severity\": \"CRITICAL\",\n                    \"type\": \"DNP3_FILE_OPERATION\",\n                    \"src\": src_ip, \"dst\": dst_ip,\n                    \"function\": dnp3.get(\"function_name\"),\n                    \"description\": f\"File operation on outstation {dst_ip} - potential firmware update or PIPEDREAM indicator\",\n                    \"mitre\": \"T0839 - Module Firmware\",\n                })\n\n            # Detection 4: Control commands (Select\u002FOperate)\n            if func_code in (0x03, 0x04, 0x05, 0x06):\n                session[\"control_commands\"] += 1\n                if session_key in self.baseline_functions:\n                    if func_code not in self.baseline_functions[session_key]:\n                        self.alerts.append({\n                            \"severity\": \"HIGH\",\n                            \"type\": \"UNEXPECTED_CONTROL_COMMAND\",\n                            \"src\": src_ip, \"dst\": dst_ip,\n                            \"function\": dnp3.get(\"function_name\"),\n                            \"description\": f\"Control command {dnp3.get('function_name')} not in baseline for {session_key}\",\n                            \"mitre\": \"T0855 - Unauthorized Command Message\",\n                        })\n\n            # Detection 5: Anomalous function code for this pair\n            if session_key in self.baseline_functions:\n                if func_code not in self.baseline_functions[session_key]:\n                    if func_code not in (0x00, 0x81, 0x82):  # Exclude common response codes\n                        self.alerts.append({\n                            \"severity\": \"MEDIUM\",\n                            \"type\": \"ANOMALOUS_FUNCTION_CODE\",\n                            \"src\": src_ip, \"dst\": dst_ip,\n                            \"function\": dnp3.get(\"function_name\"),\n                            \"description\": f\"Function code 0x{func_code:02x} not in baseline\",\n                            \"mitre\": \"T0855 - Unauthorized Command Message\",\n                        })\n\n    def generate_report(self):\n        \"\"\"Generate DNP3 anomaly detection report.\"\"\"\n        print(f\"\\n{'='*70}\")\n        print(\"DNP3 PROTOCOL ANOMALY DETECTION REPORT\")\n        print(f\"{'='*70}\")\n        print(f\"Analysis Time: {datetime.now().isoformat()}\")\n        print(f\"Total Packets: {self.packet_count}\")\n        print(f\"DNP3 Packets: {self.dnp3_count}\")\n        print(f\"Alerts: {len(self.alerts)}\")\n\n        print(f\"\\n--- DNP3 SESSION SUMMARY ---\")\n        for key, session in self.sessions.items():\n            print(f\"\\n  {key}\")\n            print(f\"    Packets: {session['packet_count']}\")\n            funcs = [DNP3_FUNCTIONS.get(f, f\"0x{f:02x}\") for f in session[\"function_codes\"]]\n            print(f\"    Functions: {', '.join(funcs)}\")\n            print(f\"    Control Commands: {session['control_commands']}\")\n            print(f\"    File Operations: {session['file_operations']}\")\n            print(f\"    Restart Commands: {session['restarts']}\")\n\n        if self.alerts:\n            print(f\"\\n--- ALERTS ---\")\n            for alert in self.alerts:\n                print(f\"\\n  [{alert['severity']}] {alert['type']}\")\n                print(f\"    {alert['src']} -> {alert['dst']}\")\n                print(f\"    Function: {alert['function']}\")\n                print(f\"    Detail: {alert['description']}\")\n                print(f\"    MITRE ICS: {alert.get('mitre', 'N\u002FA')}\")\n\n\nif __name__ == \"__main__\":\n    detector = DNP3AnomalyDetector(\n        baseline_file=sys.argv[2] if len(sys.argv) > 2 else None\n    )\n\n    if len(sys.argv) >= 2:\n        print(f\"[*] Analyzing: {sys.argv[1]}\")\n        packets = rdpcap(sys.argv[1])\n        for pkt in packets:\n            detector.analyze_packet(pkt)\n        detector.generate_report()\n    else:\n        print(\"Usage: python dnp3_detector.py \u003Ccapture.pcap> [baseline.json]\")\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| DNP3 | Distributed Network Protocol version 3, the predominant SCADA protocol in the energy sector for communication between masters and outstations |\n| Outstation | DNP3 slave device (typically an RTU or IED) that responds to master station polls and commands |\n| Select-Before-Operate | DNP3 safety mechanism requiring a Select command before an Operate, preventing accidental control actions |\n| Cold Restart (FC 0x0D) | DNP3 command that fully restarts an outstation, resetting all configuration -- a high-risk denial-of-service operation |\n| DNP3 Secure Authentication | Optional DNP3 extension (SA v5) adding HMAC-based authentication to prevent command spoofing |\n| PIPEDREAM | ICS attack framework with DNP3 capabilities for manipulating outstations and performing firmware updates |\n\n## Output Format\n\n```\nDNP3 ANOMALY DETECTION REPORT\n================================\nAnalysis Period: [start] to [end]\nMonitoring Point: [substation\u002Fsegment]\n\nTRAFFIC SUMMARY:\n  DNP3 Packets: [count]\n  Unique Master-Outstation Pairs: [count]\n  Control Commands: [count]\n  File Operations: [count]\n\nALERTS:\n  [CRITICAL] Unauthorized DNP3 master [IP]\n  [CRITICAL] Cold restart command to outstation [addr]\n  [HIGH] Unexpected control command from [IP]\n\nRECOMMENDATIONS:\n  1. Deploy DNP3 Secure Authentication (SA v5)\n  2. Block unauthorized sources at firewall\n  3. Enable DNP3 DPI on industrial firewall\n```\n","# Detecting DNP3 Protocol Anomalies\n\n## When to Use\n\n- When monitoring SCADA systems in the energy sector where DNP3 is the primary protocol\n- When building detection rules for DNP3-based attacks against RTUs and substations\n- When investigating suspected unauthorized control commands sent via DNP3\n- When deploying IDS with DNP3 deep packet inspection at utility substations\n- When responding to alerts from OT monitoring platforms about DNP3 traffic anomalies\n\n**Do not use** for non-DNP3 protocol monitoring (see detecting-modbus-command-injection-attacks for Modbus), for DNP3 Secure Authentication configuration (separate implementation), or for protocol-agnostic network anomaly detection.\n\n## Prerequisites\n\n- Network TAP\u002FSPAN on DNP3 communication segments (TCP port 20000 or serial)\n- Baseline of normal DNP3 traffic patterns (masters, outstations, poll intervals, function codes)\n- Suricata or Zeek with DNP3 protocol parser enabled\n- Understanding of DNP3 function codes and object groups used in the environment\n- DNP3 communication topology map (master-to-outstation relationships)\n\n## Workflow\n\n### Step 1: Analyze DNP3 Traffic for Anomalies\n\n```python\n#!\u002Fusr\u002Fbin\u002Fenv python3\n\"\"\"DNP3 Protocol Anomaly Detector.\n\nMonitors DNP3 communications for unauthorized control commands,\nprotocol violations, and deviations from established baselines.\nSupports both TCP and serial DNP3 deployments.\n\"\"\"\n\nimport struct\nimport sys\nimport json\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom typing import Dict, List, Optional, Set\n\ntry:\n    from scapy.all import rdpcap, IP, TCP\nexcept ImportError:\n    print(\"Install scapy: pip install scapy\")\n    sys.exit(1)\n\n\n# DNP3 Function Codes\nDNP3_FUNCTIONS = {\n    0x00: \"Confirm\", 0x01: \"Read\", 0x02: \"Write\",\n    0x03: \"Select\", 0x04: \"Operate\", 0x05: \"Direct Operate\",\n    0x06: \"Direct Operate No Ack\", 0x07: \"Immediate Freeze\",\n    0x08: \"Immediate Freeze No Ack\", 0x09: \"Freeze and Clear\",\n    0x0A: \"Freeze and Clear No Ack\", 0x0B: \"Freeze at Time\",\n    0x0C: \"Freeze at Time No Ack\", 0x0D: \"Cold Restart\",\n    0x0E: \"Warm Restart\", 0x0F: \"Initialize Data\",\n    0x10: \"Initialize Application\", 0x11: \"Start Application\",\n    0x12: \"Stop Application\", 0x13: \"Save Configuration\",\n    0x14: \"Enable Unsolicited\", 0x15: \"Disable Unsolicited\",\n    0x16: \"Assign Class\", 0x17: \"Delay Measurement\",\n    0x18: \"Record Current Time\", 0x19: \"Open File\",\n    0x1A: \"Close File\", 0x1B: \"Delete File\",\n    0x1C: \"Get File Info\", 0x1D: \"Authenticate File\",\n    0x1E: \"Abort File\", 0x81: \"Response\", 0x82: \"Unsolicited Response\",\n}\n\n# High-risk function codes that should trigger alerts\nDNP3_CRITICAL_FUNCTIONS = {\n    0x02,  # Write\n    0x03, 0x04, 0x05, 0x06,  # Select\u002FOperate\u002FDirect Operate\n    0x0D,  # Cold Restart\n    0x0E,  # Warm Restart\n    0x0F,  # Initialize Data\n    0x10,  # Initialize Application\n    0x12,  # Stop Application\n    0x19, 0x1A, 0x1B,  # File operations (firmware update)\n}\n\n\nclass DNP3AnomalyDetector:\n    \"\"\"Detects anomalies in DNP3 protocol communications.\"\"\"\n\n    def __init__(self, baseline_file: Optional[str] = None):\n        self.alerts = []\n        self.sessions = defaultdict(lambda: {\n            \"packet_count\": 0,\n            \"function_codes\": defaultdict(int),\n            \"control_commands\": 0,\n            \"file_operations\": 0,\n            \"restarts\": 0,\n        })\n        self.packet_count = 0\n        self.dnp3_count = 0\n\n        self.authorized_masters: Set[str] = set()\n        self.authorized_pairs: Dict[str, Set[str]] = defaultdict(set)\n        self.baseline_functions: Dict[str, Set[int]] = defaultdict(set)\n\n        if baseline_file:\n            self.load_baseline(baseline_file)\n\n    def load_baseline(self, filepath: str):\n        \"\"\"Load DNP3 communication baseline.\"\"\"\n        with open(filepath, \"r\") as f:\n            baseline = json.load(f)\n\n        for entry in baseline.get(\"authorized_communications\", []):\n            master = entry[\"master_ip\"]\n            outstation = entry[\"outstation_ip\"]\n            self.authorized_masters.add(master)\n            self.authorized_pairs[master].add(outstation)\n            self.baseline_functions[f\"{master}->{outstation}\"] = set(\n                entry.get(\"expected_function_codes\", [0x00, 0x01])\n            )\n\n    def parse_dnp3_header(self, payload: bytes) -> Optional[dict]:\n        \"\"\"Parse DNP3 data link layer and transport\u002Fapplication headers.\"\"\"\n        if len(payload) \u003C 10:\n            return None\n\n        # DNP3 Data Link Layer: start(2) + length(1) + control(1) + dest(2) + source(2) + crc(2)\n        start_bytes = struct.unpack(\">H\", payload[0:2])[0]\n        if start_bytes != 0x0564:\n            return None\n\n        length = payload[2]\n        control = payload[3]\n        dest_addr = struct.unpack(\"\u003CH\", payload[4:6])[0]\n        source_addr = struct.unpack(\"\u003CH\", payload[6:8])[0]\n\n        direction = \"Master->Outstation\" if (control & 0x80) else \"Outstation->Master\"\n\n        result = {\n            \"length\": length,\n            \"control\": control,\n            \"direction\": direction,\n            \"dest_addr\": dest_addr,\n            \"source_addr\": source_addr,\n            \"is_master\": bool(control & 0x80),\n        }\n\n        # Parse transport and application layer (after CRC bytes)\n        if len(payload) >= 12:\n            transport_header = payload[10]\n            if len(payload) >= 13:\n                app_control = payload[11]\n                func_code = payload[12]\n                result[\"function_code\"] = func_code\n                result[\"function_name\"] = DNP3_FUNCTIONS.get(\n                    func_code, f\"Unknown (0x{func_code:02x})\"\n                )\n\n        return result\n\n    def analyze_packet(self, pkt):\n        \"\"\"Analyze a packet for DNP3 anomalies.\"\"\"\n        self.packet_count += 1\n\n        if not pkt.haslayer(IP) or not pkt.haslayer(TCP):\n            return\n\n        tcp = pkt[TCP]\n        if tcp.dport != 20000 and tcp.sport != 20000:\n            return\n\n        payload = bytes(tcp.payload)\n        if not payload:\n            return\n\n        dnp3 = self.parse_dnp3_header(payload)\n        if not dnp3:\n            return\n\n        self.dnp3_count += 1\n        src_ip = pkt[IP].src\n        dst_ip = pkt[IP].dst\n        session_key = f\"{src_ip}->{dst_ip}\"\n        session = self.sessions[session_key]\n        session[\"packet_count\"] += 1\n\n        func_code = dnp3.get(\"function_code\")\n        if func_code is not None:\n            session[\"function_codes\"][func_code] += 1\n\n            # Detection 1: Unauthorized DNP3 master\n            if dnp3.get(\"is_master\") and self.authorized_masters:\n                if src_ip not in self.authorized_masters:\n                    self.alerts.append({\n                        \"severity\": \"CRITICAL\",\n                        \"type\": \"UNAUTHORIZED_DNP3_MASTER\",\n                        \"src\": src_ip, \"dst\": dst_ip,\n                        \"function\": dnp3.get(\"function_name\"),\n                        \"description\": f\"Unauthorized DNP3 master {src_ip} communicating with outstation {dst_ip}\",\n                        \"mitre\": \"T0869 - Standard Application Layer Protocol\",\n                    })\n\n            # Detection 2: Cold\u002FWarm restart command\n            if func_code in (0x0D, 0x0E):\n                session[\"restarts\"] += 1\n                restart_type = \"Cold\" if func_code == 0x0D else \"Warm\"\n                self.alerts.append({\n                    \"severity\": \"CRITICAL\",\n                    \"type\": \"DNP3_RESTART_COMMAND\",\n                    \"src\": src_ip, \"dst\": dst_ip,\n                    \"function\": f\"{restart_type} Restart\",\n                    \"description\": f\"{restart_type} restart command sent to outstation {dst_ip} (addr {dnp3['dest_addr']})\",\n                    \"mitre\": \"T0816 - Device Restart\u002FShutdown\",\n                })\n\n            # Detection 3: File operations (potential firmware update)\n            if func_code in (0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E):\n                session[\"file_operations\"] += 1\n                self.alerts.append({\n                    \"severity\": \"CRITICAL\",\n                    \"type\": \"DNP3_FILE_OPERATION\",\n                    \"src\": src_ip, \"dst\": dst_ip,\n                    \"function\": dnp3.get(\"function_name\"),\n                    \"description\": f\"File operation on outstation {dst_ip} - potential firmware update or PIPEDREAM indicator\",\n                    \"mitre\": \"T0839 - Module Firmware\",\n                })\n\n            # Detection 4: Control commands (Select\u002FOperate)\n            if func_code in (0x03, 0x04, 0x05, 0x06):\n                session[\"control_commands\"] += 1\n                if session_key in self.baseline_functions:\n                    if func_code not in self.baseline_functions[session_key]:\n                        self.alerts.append({\n                            \"severity\": \"HIGH\",\n                            \"type\": \"UNEXPECTED_CONTROL_COMMAND\",\n                            \"src\": src_ip, \"dst\": dst_ip,\n                            \"function\": dnp3.get(\"function_name\"),\n                            \"description\": f\"Control command {dnp3.get('function_name')} not in baseline for {session_key}\",\n                            \"mitre\": \"T0855 - Unauthorized Command Message\",\n                        })\n\n            # Detection 5: Anomalous function code for this pair\n            if session_key in self.baseline_functions:\n                if func_code not in self.baseline_functions[session_key]:\n                    if func_code not in (0x00, 0x81, 0x82):  # Exclude common response codes\n                        self.alerts.append({\n                            \"severity\": \"MEDIUM\",\n                            \"type\": \"ANOMALOUS_FUNCTION_CODE\",\n                            \"src\": src_ip, \"dst\": dst_ip,\n                            \"function\": dnp3.get(\"function_name\"),\n                            \"description\": f\"Function code 0x{func_code:02x} not in baseline\",\n                            \"mitre\": \"T0855 - Unauthorized Command Message\",\n                        })\n\n    def generate_report(self):\n        \"\"\"Generate DNP3 anomaly detection report.\"\"\"\n        print(f\"\\n{'='*70}\")\n        print(\"DNP3 PROTOCOL ANOMALY DETECTION REPORT\")\n        print(f\"{'='*70}\")\n        print(f\"Analysis Time: {datetime.now().isoformat()}\")\n        print(f\"Total Packets: {self.packet_count}\")\n        print(f\"DNP3 Packets: {self.dnp3_count}\")\n        print(f\"Alerts: {len(self.alerts)}\")\n\n        print(f\"\\n--- DNP3 SESSION SUMMARY ---\")\n        for key, session in self.sessions.items():\n            print(f\"\\n  {key}\")\n            print(f\"    Packets: {session['packet_count']}\")\n            funcs = [DNP3_FUNCTIONS.get(f, f\"0x{f:02x}\") for f in session[\"function_codes\"]]\n            print(f\"    Functions: {', '.join(funcs)}\")\n            print(f\"    Control Commands: {session['control_commands']}\")\n            print(f\"    File Operations: {session['file_operations']}\")\n            print(f\"    Restart Commands: {session['restarts']}\")\n\n        if self.alerts:\n            print(f\"\\n--- ALERTS ---\")\n            for alert in self.alerts:\n                print(f\"\\n  [{alert['severity']}] {alert['type']}\")\n                print(f\"    {alert['src']} -> {alert['dst']}\")\n                print(f\"    Function: {alert['function']}\")\n                print(f\"    Detail: {alert['description']}\")\n                print(f\"    MITRE ICS: {alert.get('mitre', 'N\u002FA')}\")\n\n\nif __name__ == \"__main__\":\n    detector = DNP3AnomalyDetector(\n        baseline_file=sys.argv[2] if len(sys.argv) > 2 else None\n    )\n\n    if len(sys.argv) >= 2:\n        print(f\"[*] Analyzing: {sys.argv[1]}\")\n        packets = rdpcap(sys.argv[1])\n        for pkt in packets:\n            detector.analyze_packet(pkt)\n        detector.generate_report()\n    else:\n        print(\"Usage: python dnp3_detector.py \u003Ccapture.pcap> [baseline.json]\")\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| DNP3 | Distributed Network Protocol version 3, the predominant SCADA protocol in the energy sector for communication between masters and outstations |\n| Outstation | DNP3 slave device (typically an RTU or IED) that responds to master station polls and commands |\n| Select-Before-Operate | DNP3 safety mechanism requiring a Select command before an Operate, preventing accidental control actions |\n| Cold Restart (FC 0x0D) | DNP3 command that fully restarts an outstation, resetting all configuration -- a high-risk denial-of-service operation |\n| DNP3 Secure Authentication | Optional DNP3 extension (SA v5) adding HMAC-based authentication to prevent command spoofing |\n| PIPEDREAM | ICS attack framework with DNP3 capabilities for manipulating outstations and performing firmware updates |\n\n## Output Format\n\n```\nDNP3 ANOMALY DETECTION REPORT\n================================\nAnalysis Period: [start] to [end]\nMonitoring Point: [substation\u002Fsegment]\n\nTRAFFIC SUMMARY:\n  DNP3 Packets: [count]\n  Unique Master-Outstation Pairs: [count]\n  Control Commands: [count]\n  File Operations: [count]\n\nALERTS:\n  [CRITICAL] Unauthorized DNP3 master [IP]\n  [CRITICAL] Cold restart command to outstation [addr]\n  [HIGH] Unexpected control command from [IP]\n\nRECOMMENDATIONS:\n  1. Deploy DNP3 Secure Authentication (SA v5)\n  2. Block unauthorized sources at firewall\n  3. Enable DNP3 DPI on industrial firewall\n```\n",{"name":5,"tags":25,"author":34,"domain":35,"license":15,"version":36,"nist_csf":37,"subdomain":42,"description":7,"nist_ai_rmf":43,"mitre_attack":47,"atlas_techniques":53},[26,27,28,29,30,31,32,33],"ot-security","ics","dnp3","scada","anomaly-detection","protocol-analysis","energy-sector","ids","mahipal","cybersecurity","1.0",[38,39,40,41],"PR.IR-01","DE.CM-01","ID.AM-05","GV.OC-02","ot-ics-security",[44,45,46],"MEASURE-2.7","MEASURE-2.5","MAP-5.1",[48,49,50,51,52],"T1078","T1190","T1059","T0816","T0836",[54,55],"AML.T0043","AML.T0018","main","7540bbccf0c1ded6156a467b02c95b61ad62413f",".agents\u002Fskills\u002Fdetecting-dnp3-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-dnp3-protocol-anomalies",{"tool":69,"command":70},"bunx","bunx skills add NeelakshSaxena\u002FVayu --skill detecting-dnp3-protocol-anomalies",{"tool":72,"command":73},"pnpm","pnpm dlx skills add NeelakshSaxena\u002FVayu --skill detecting-dnp3-protocol-anomalies","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdetecting-dnp3-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","参考文档",1671,"https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdetecting-dnp3-protocol-anomalies\u002Freferences\u002Fapi-reference.md",{"path":88,"resourceType":89,"resourceTypeDesc":90,"sizeBytes":91,"sourceHtmlUrl":92},"scripts\u002Fagent.py","SCRIPT","脚本",5737,"https:\u002F\u002Fgithub.com\u002FNeelakshSaxena\u002FVayu\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fdetecting-dnp3-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",[],[]]