[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6ETBYCKNEBYV77N4DHV9QNY":3,"skill-same:01M6ETBYCKNEBYV77N4DHV9QNY":109},{"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":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":70,"commitSha":71,"skillDirectory":72,"forksCount":14,"repositoryHtmlUrl":73,"repositoryHomepageUrl":74,"ownerHtmlUrl":75,"ownerBlogUrl":6,"ownerDescription":76,"updatedAt":77,"install":78,"resources":91},"01M6ETBYCKNEBYV77N4DHV9QNY","detecting-dnp3-protocol-anomalies",null,"Detect anomalies in DNP3 (Distributed Network Protocol 3) communications used in SCADA systems by monitoring for unauthorized control commands, firmware update attempts, protocol violations, and deviations from baseline traffic patterns using deep packet inspection and machine learning approaches.","henriquescastilho\u002Fmy-claude","henriquescastilho","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F153296945?v=4","01M6ESH7EXPXTH9CVQ4K16SRG8","Henrique Scheer","01M6ESH7JHEK2PTNNH4HEH787Z",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fdetecting-dnp3-protocol-anomalies\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"protocol","dnp3","detecting dnp3 protocol anomalies","machine","cybersecurity","deep","map","cm","aml","learning","analysis","t1059","ics","ot-security","ids","firmware","protocol-analysis","pr","distributed","machine learning","2026-11-10 10:12:30",false,"---\nname: detecting-dnp3-protocol-anomalies\ndescription: 'Detect anomalies in DNP3 (Distributed Network Protocol 3) communications\n  used in SCADA systems by monitoring for unauthorized control commands, firmware\n  update attempts, protocol violations, and deviations from baseline traffic patterns\n  using deep packet inspection and machine learning approaches.\n\n  '\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":44,"author":48,"domain":23,"license":15,"version":49,"nist_csf":50,"subdomain":55,"description":56,"nist_ai_rmf":57,"mitre_attack":61,"atlas_techniques":67},[32,31,20,45,46,35,47,33],"scada","anomaly-detection","energy-sector","mahipal","1.0",[51,52,53,54],"PR.IR-01","DE.CM-01","ID.AM-05","GV.OC-02","ot-ics-security","Detect anomalies in DNP3 (Distributed Network Protocol 3) communications used in SCADA systems by monitoring for unauthorized control commands, firmware update attempts, protocol violations, and deviations from baseline traffic patterns using deep packet inspection and machine learning approaches.\n",[58,59,60],"MEASURE-2.7","MEASURE-2.5","MAP-5.1",[62,63,64,65,66],"T1078","T1190","T1059","T0816","T0836",[68,69],"AML.T0043","AML.T0018","main","7925716f065257435fdb12e97f7e52842147d5ad",".claude\u002Fskills\u002Fdetecting-dnp3-protocol-anomalies","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude","https:\u002F\u002Fclaude.com\u002Fclaude-code","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho","Software · Applied AI · Quantitative Modeling · Building with Claude.","2026-06-10 12:24:46",{"source":8,"skillName":5,"commands":79,"prompt":89,"zipAvailable":90},[80,83,86],{"tool":81,"command":82},"npx","npx skills add henriquescastilho\u002Fmy-claude --skill detecting-dnp3-protocol-anomalies",{"tool":84,"command":85},"bunx","bunx skills add henriquescastilho\u002Fmy-claude --skill detecting-dnp3-protocol-anomalies",{"tool":87,"command":88},"pnpm","pnpm dlx skills add henriquescastilho\u002Fmy-claude --skill detecting-dnp3-protocol-anomalies","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fdetecting-dnp3-protocol-anomalies\u002FSKILL.md",true,[92,97,103],{"path":93,"resourceType":93,"resourceTypeDesc":94,"sizeBytes":95,"sourceHtmlUrl":96},"LICENSE","许可证",11255,"https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fdetecting-dnp3-protocol-anomalies\u002FLICENSE",{"path":98,"resourceType":99,"resourceTypeDesc":100,"sizeBytes":101,"sourceHtmlUrl":102},"references\u002Fapi-reference.md","REFERENCE","参考文档",1671,"https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fdetecting-dnp3-protocol-anomalies\u002Freferences\u002Fapi-reference.md",{"path":104,"resourceType":105,"resourceTypeDesc":106,"sizeBytes":107,"sourceHtmlUrl":108},"scripts\u002Fagent.py","SCRIPT","脚本",5737,"https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.claude\u002Fskills\u002Fdetecting-dnp3-protocol-anomalies\u002Fscripts\u002Fagent.py",[110,137,142,147,169,193],{"skillNo":111,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":114,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":39},"01M6F0B6XPQ65AX2X0DWK8KT3E","markitdown","Convert files and office documents to Markdown. Supports PDF, DOCX, PPTX, XLSX, images (with OCR), audio (with transcription), HTML, CSV, JSON, XML, ZIP, YouTube URLs, EPubs and more.","MIT","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-writer\u002Fskills\u002Fmarkitdown\u002FSKILL.md",[],[112,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136],"docx","PDF","pptx","xlsx","documents","csv","ocr","Audio","Bash","markdown","convert","read","write","edit","html","images","files","youtube","with",{"skillNo":138,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":114,"licenseFileUrl":6,"sourceHtmlUrl":139,"categories":140,"keywords":141,"publishedAt":39},"01M6F06SBHR9F0SDWE282Y8075","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-writer\u002Fscientific_writer\u002F.claude\u002Fskills\u002Fmarkitdown\u002FSKILL.md",[],[112,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136],{"skillNo":143,"name":112,"nameZh":6,"description":113,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":114,"licenseFileUrl":6,"sourceHtmlUrl":144,"categories":145,"keywords":146,"publishedAt":39},"01M6F02D4R14EJAPBWVDF9J9VQ","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-writer\u002F.claude\u002Fskills\u002Fmarkitdown\u002FSKILL.md",[],[112,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136],{"skillNo":148,"name":149,"nameZh":6,"description":150,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":114,"licenseFileUrl":6,"sourceHtmlUrl":151,"categories":152,"keywords":153,"publishedAt":39},"01M6F000KS6YB4MKS774G4R8ND","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-skills\u002Fscientific-skills\u002Fzarr-python\u002FSKILL.md",[],[154,155,156,157,158,159,160,161,162,163,164,165,166,167,168],"python","zarr python","storage","integration","s3","gcs","cloud","dask","parallel","pipelines","arrays","numpy","scientific computing","scale","scientific",{"skillNo":170,"name":171,"nameZh":6,"description":172,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":114,"licenseFileUrl":6,"sourceHtmlUrl":173,"categories":174,"keywords":175,"publishedAt":39},"01M6EZZJWFXM1GR78KTW6J0DN8","what-if-oracle","Run structured What-If scenario analysis with multi-branch possibility exploration. Use this skill when the user asks speculative questions like \"what if...\", \"what would happen if...\", \"what are the possibilities\", \"explore scenarios\", \"scenario analysis\", \"possibility space\", \"what could go wrong\", \"best case \u002F worst case\", \"risk analysis\", \"contingency planning\", \"strategic options\", or any question about uncertain futures. Also trigger when the user faces a fork-in-the-road decision, wants to stress-test an idea, or needs to think through consequences before committing.","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-skills\u002Fscientific-skills\u002Fwhat-if-oracle\u002FSKILL.md",[],[176,177,178,179,180,181,29,182,183,184,185,129,130,186,187,188,189,190,191,192],"oracle","what if oracle","go","run","ux","futures","explore","decision","branch","question","idea","exploration","options","stress-test","strategies","scenario","stress",{"skillNo":194,"name":195,"nameZh":6,"description":196,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":114,"licenseFileUrl":6,"sourceHtmlUrl":197,"categories":198,"keywords":199,"publishedAt":39},"01M6EZZCXAEB49RXGQCJX5E8GB","venue-templates","Access comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.","https:\u002F\u002Fgithub.com\u002Fhenriquescastilho\u002Fmy-claude\u002Fblob\u002Fmain\u002F.codex\u002Fvendor_imports\u002Fclaude\u002Fmarketplaces\u002Fclaude-scientific-skills\u002Fscientific-skills\u002Fvenue-templates\u002FSKILL.md",[],[200,201,202,203,204,205,206,207,126,208,129,130,131,209,210,211,212,213,168,214],"templates","venue templates","research","guidelines","NeurIPS","ICML","LaTeX","science","access","proposals","Academic","requirements","formatting","journal","chi"]