Skip to content

SSZcreate/Pentab_server / .agents/skills/cybersecurity/skills/detecting-modbus-command-injection-attacks

detecting-modbus-command-injection-attacks

Verified

Detect command injection against Modbus TCP/RTU in ICS/SCADA environments by monitoring unauthorized writes, anomalous function codes, malformed frames, and deviations from communication baselines using ICS-aware IDS and deep packet inspection. Use when deploying IDS for Modbus OT networks, investigating unauthorized PLC register/coil changes, or responding to FrostyGoop-style Modbus attacks.

FileKindSize
LICENSEother11.0 KB
SKILL.mdskill md20.1 KB
references/api-reference.mdmarkdown1.6 KB
scripts/agent.pyscript5.1 KB

scripts/agent.py

View on GitHub
#!/usr/bin/env python3
"""Modbus command injection detection agent for ICS/SCADA environments.

Analyzes Modbus TCP traffic for unauthorized write operations, function code
abuse, and anomalous register access patterns using Zeek logs or pcap analysis.
"""

import argparse
import json
from collections import Counter, defaultdict
from datetime import datetime

MODBUS_FUNCTIONS = {
    1: ("Read Coils", "read"), 2: ("Read Discrete Inputs", "read"),
    3: ("Read Holding Registers", "read"), 4: ("Read Input Registers", "read"),
    5: ("Write Single Coil", "write"), 6: ("Write Single Register", "write"),
    15: ("Write Multiple Coils", "write"), 16: ("Write Multiple Registers", "write"),
    8: ("Diagnostics", "diagnostic"), 17: ("Report Server ID", "diagnostic"),
    22: ("Mask Write Register", "write"), 23: ("Read/Write Multiple", "write"),
    43: ("Read Device ID", "diagnostic"),
}

DANGEROUS_FUNCTIONS = {5, 6, 15, 16, 22, 23}
DIAGNOSTIC_FUNCTIONS = {8, 17, 43}


def parse_zeek_modbus_log(filepath):
    events = []
    with open(filepath, "r") as f:
        headers = None
        for line in f:
            if line.startswith("#fields"):
                headers = line.strip().split("\t")[1:]
                continue
            if line.startswith("#"):
                continue
            if not headers:
                continue
            fields = line.strip().split("\t")
            if len(fields) >= len(headers):
                events.append(dict(zip(headers, fields)))
    return events


def analyze_modbus_traffic(events, authorized_masters=None):
    findings = []
    fc_counter = Counter()
    write_ops = []
    src_dst = defaultdict(int)

    for evt in events:
        src = evt.get("id.orig_h", "")
        dst = evt.get("id.resp_h", "")
        fc_str = evt.get("func", evt.get("function", ""))
        try:
            fc = int(fc_str)
        except (ValueError, TypeError):
            continue

        fc_info = MODBUS_FUNCTIONS.get(fc, (f"Unknown({fc})", "unknown"))
        fc_counter[fc_info[0]] += 1
        src_dst[f"{src}->{dst}"] += 1

        if authorized_masters and src not in authorized_masters:
            findings.append({
                "type": "unauthorized_master",
                "source": src, "destination": dst,
                "function": fc_info[0], "function_code": fc,
                "severity": "CRITICAL" if fc in DANGEROUS_FUNCTIONS else "HIGH",
            })

        if fc in DANGEROUS_FUNCTIONS:
            write_ops.append({
                "timestamp": evt.get("ts", ""),
                "source": src, "destination": dst,
                "function": fc_info[0], "function_code": fc,
            })

        if fc not in MODBUS_FUNCTIONS:
            findings.append({
                "type": "unknown_function_code",
                "source": src, "function_code": fc,
                "severity": "HIGH",
                "description": f"Non-standard Modbus function code: {fc}",
            })

    return {
        "total_events": len(events),
        "function_distribution": dict(fc_counter),
        "write_operations": write_ops,
        "communication_pairs": dict(src_dst),
        "findings": findings,
    }


def detect_write_floods(events, threshold=20, window_seconds=60):
    findings = []
    src_writes = defaultdict(list)
    for evt in events:
        fc_str = evt.get("func", "0")
        try:
            fc = int(fc_str)
        except ValueError:
            continue
        if fc in DANGEROUS_FUNCTIONS:
            src = evt.get("id.orig_h", "")
            try:
                ts = float(evt.get("ts", "0"))
            except ValueError:
                continue
            src_writes[src].append(ts)

    for src, timestamps in src_writes.items():
        timestamps.sort()
        for i in range(len(timestamps) - threshold):
            if timestamps[i + threshold] - timestamps[i] <= window_seconds:
                findings.append({
                    "type": "write_flood",
                    "source": src,
                    "writes_in_window": threshold,
                    "window_seconds": window_seconds,
                    "severity": "CRITICAL",
                    "description": f">{threshold} write commands in {window_seconds}s from {src}",
                })
                break
    return findings


def main():
    parser = argparse.ArgumentParser(description="Modbus Command Injection Detector")
    parser.add_argument("--zeek-log", required=True, help="Zeek modbus.log file")
    parser.add_argument("--authorized-masters", nargs="+", help="Authorized master IPs")
    parser.add_argument("--flood-threshold", type=int, default=20)
    args = parser.parse_args()

    masters = set(args.authorized_masters) if args.authorized_masters else None
    events = parse_zeek_modbus_log(args.zeek_log)
    analysis = analyze_modbus_traffic(events, masters)
    floods = detect_write_floods(events, args.flood_threshold)

    results = {
        "timestamp": datetime.utcnow().isoformat() + "Z",
        **analysis,
        "write_floods": floods,
        "total_findings": len(analysis["findings"]) + len(floods),
    }
    print(json.dumps(results, indent=2))


if __name__ == "__main__":
    main()
writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deploymentStars: 318kUpdated Claude CodeCodexVerifiedInstall
xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved.Stars: 196kUpdated Claude CodeCodexVerifiedInstall
shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release.Stars: 117kUpdated Claude CodeCodexVerifiedInstall