monitoring-scada-modbus-traffic-anomalies
Monitors Modbus TCP traffic on SCADA and ICS networks to detect anomalous function code usage, unauthorized register writes, and suspicious communication patterns. The analyst uses deep packet inspection with pymodbus, Scapy, and Zeek to baseline normal PLC/RTU communication behavior, then applies statistical and rule-based anomaly detection to identify reconnaissance, parameter manipulation, and denial-of-service attacks targeting Modbus devices on port 502. Activates for requests involving Modbus traffic analysis, SCADA network monitoring, ICS anomaly detection, PLC security monitoring, or OT network threat detection.
What this skill does
# Monitoring SCADA Modbus Traffic Anomalies
## When to Use
- Monitoring OT/ICS networks for unauthorized Modbus commands targeting PLCs, RTUs, or HMIs
- Detecting reconnaissance activity such as Modbus device enumeration (function code 43, Read Device Identification)
- Identifying unauthorized write operations (function codes 05, 06, 15, 16) to coils and holding registers that could alter physical process parameters
- Baselining normal Modbus communication patterns and alerting on deviations in function code distribution, register access ranges, or timing intervals
- Investigating suspected sabotage or insider threats manipulating SCADA process values through Modbus register writes
**Do not use** on networks without authorization from the asset owner, for active injection or fuzzing against production SCADA systems, or as a replacement for safety-instrumented systems (SIS) that provide physical process protection.
## Prerequisites
- Network tap or SPAN port on the OT network segment carrying Modbus TCP traffic (port 502)
- Python 3.9+ with pymodbus (>=3.6), scapy (>=2.5), and pandas for traffic analysis
- Zeek (formerly Bro) installed with the Modbus protocol analyzer enabled for passive traffic logging
- Wireshark or tshark for initial packet capture and validation of Modbus frame structure
- A baseline period of normal operations (minimum 48-72 hours) to establish communication profiles per device pair
- Network diagram identifying Modbus master-slave relationships, device IP addresses, and expected function code usage
## Workflow
### Step 1: Capture and Parse Modbus TCP Traffic
Establish passive monitoring on the OT network segment and begin capturing Modbus TCP frames:
- **Configure network tap**: Position the monitoring interface on the SPAN port mirroring the VLAN carrying Modbus TCP traffic between HMI/SCADA servers and PLCs. Verify bidirectional traffic capture with `tcpdump -i eth0 port 502 -c 100 -w modbus_capture.pcap`.
- **Parse Modbus TCP frame structure**: Each Modbus TCP frame contains a 7-byte MBAP (Modbus Application Protocol) header followed by the PDU. The MBAP header includes:
- Transaction Identifier (2 bytes): Matches requests to responses
- Protocol Identifier (2 bytes): Always 0x0000 for Modbus
- Length (2 bytes): Number of following bytes including Unit ID
- Unit Identifier (1 byte): Slave device address (0-247)
- **Extract function codes with Scapy**: Use Scapy's Modbus contrib module to dissect captured packets and extract function codes, register addresses, and values:
```python
from scapy.all import rdpcap, TCP
from scapy.contrib.modbus import ModbusADURequest, ModbusADUResponse
packets = rdpcap("modbus_capture.pcap")
for pkt in packets:
if pkt.haslayer(ModbusADURequest):
adu = pkt[ModbusADURequest]
print(f"Src: {pkt['IP'].src} -> Dst: {pkt['IP'].dst} "
f"Unit: {adu.unitId} FuncCode: {adu.funcCode}")
```
- **Enable Zeek Modbus logging**: Configure Zeek with `@load policy/protocols/modbus/known-masters-slaves` to generate `modbus.log` entries containing timestamp, source/destination IPs, function code, and exception responses. This provides continuous passive logging without custom scripting.
- **Validate frame integrity**: Check for malformed Modbus frames where the MBAP length field does not match the actual PDU length, Protocol Identifier is not 0x0000, or Unit Identifier falls outside the expected range for the monitored network.
### Step 2: Baseline Normal Communication Patterns
Build a behavioral profile of legitimate Modbus traffic to distinguish normal operations from anomalies:
- **Catalog function code distribution**: Record the frequency of each function code per source-destination pair over the baseline period. In typical SCADA environments, read operations (FC 01-04) vastly outnumber write operations (FC 05, 06, 15, 16), often at ratios exceeding 100:1. A sudden increase in write function codes is a strong indicator of process manipulation.
```
Normal baseline example (72-hour period):
HMI (10.1.1.10) -> PLC (10.1.1.50):
FC 03 (Read Holding Registers): 432,180 packets (97.2%)
FC 04 (Read Input Registers): 10,540 packets (2.4%)
FC 06 (Write Single Register): 1,780 packets (0.4%)
FC 16 (Write Multiple Registers): 0 packets (0.0%)
FC 43 (Read Device ID): 0 packets (0.0%)
```
- **Map register address ranges**: Document which holding register and coil address ranges each master polls. PLCs typically expose specific register blocks for monitoring (e.g., registers 0-99 for process values, 100-199 for setpoints). Access to registers outside the documented range indicates reconnaissance or misconfiguration.
- **Establish timing profiles**: Calculate the polling interval (mean, standard deviation) for each master-slave pair. SCADA polling is highly periodic, typically 100ms to 5s intervals. Deviations greater than 3 standard deviations from the mean suggest network issues or injected traffic from a rogue master.
- **Identify authorized masters**: Record all IP addresses that initiate Modbus requests (master role). In a properly segmented OT network, only the HMI server and engineering workstation should act as Modbus masters. Any new source IP sending Modbus requests is immediately suspicious.
- **Register value ranges**: For critical process registers (temperatures, pressures, flow rates, setpoints), record the observed minimum, maximum, mean, and standard deviation during normal operations. Values outside the physical process bounds indicate either sensor failure or malicious manipulation.
### Step 3: Detect Function Code Anomalies
Apply rule-based and statistical detection to identify suspicious function code usage:
- **Unauthorized write detection**: Alert when a Modbus write function code (05, 06, 15, 16) originates from a source IP not in the authorized writers list, or when write operations exceed the baseline frequency threshold:
```python
WRITE_FUNCTION_CODES = {5, 6, 15, 16}
AUTHORIZED_WRITERS = {"10.1.1.10", "10.1.1.11"} # HMI and engineering WS
def check_unauthorized_write(src_ip, function_code):
if function_code in WRITE_FUNCTION_CODES and src_ip not in AUTHORIZED_WRITERS:
return {
"alert": "UNAUTHORIZED_MODBUS_WRITE",
"severity": "CRITICAL",
"src_ip": src_ip,
"function_code": function_code,
"description": f"Write FC {function_code} from unauthorized source {src_ip}"
}
return None
```
- **Reconnaissance detection**: Function code 43 (Read Device Identification) and function code 08 (Diagnostics) are rarely used during normal operations. Any occurrence from a non-engineering workstation indicates device enumeration. Also detect sequential scanning where a single source queries multiple Unit IDs within a short window.
- **Exception response monitoring**: Modbus exception codes (01: Illegal Function, 02: Illegal Data Address, 03: Illegal Data Value) in responses indicate the master sent an invalid request. A burst of exception responses suggests fuzzing or protocol-level attacks:
```
Exception response correlation:
- Isolated exception (1-2 per hour): Normal operational error
- Burst (>10 per minute): Active scanning or fuzzing attempt
- Continuous (>100 per hour): Denial-of-service or tool malfunction
```
- **Forbidden function code detection**: Some environments prohibit certain function codes entirely. Function codes 07 (Read Exception Status), 08 (Diagnostics), 17 (Report Slave ID), and 43 (Read Device Identification) are diagnostic functions that should not appear in production SCADA traffic. Alert on any occurrence.
- **Function code frequency anomaly**: Calculate the chi-squared statistic comparing the observed function code distribution against the baseline distribution. A significant deviation (p < 0.01) triggers an alert even if no indiviRelated in Security
mac-ops
IncludedComprehensive macOS workstation operations — diagnose kernel panics, identify failing drives, audit launchd startup items, decode wake reasons, triage TCC permission denials, manage APFS snapshots, recover from no-boot. Use for: Mac is slow, slow bootup, won't boot, kernel panic, kernel_task hot, mds_stores CPU, photoanalysisd, cloudd, login loop, gray screen, sleep wake failure, drive failing, IO errors, APFS snapshots eating space, Time Machine local snapshots, Spotlight indexing, launchd, LaunchAgent, LaunchDaemon, login items, TCC permissions, Full Disk Access, Screen Recording denied, Gatekeeper, quarantine, com.apple.quarantine, app is damaged, helper tool, /Library/PrivilegedHelperTools, pmset, wake reasons, dark wake, sysdiagnose, panic.ips, DiagnosticReports, configuration profile, MDM profile, remote diagnostics over SSH.
a11y-audit
IncludedRun accessibility audits on web projects combining automated scanning (axe-core, Lighthouse) with WCAG 2.1 AA compliance mapping, manual check guidance, and structured reporting. Output is configurable: markdown report only, markdown plus machine-readable JSON, or markdown plus issue tracker integration. Use this skill whenever the user mentions "accessibility audit", "a11y audit", "WCAG audit", "accessibility check", "compliance scan", or asks to check a web project for accessibility issues. Also trigger when the user wants to verify WCAG conformance or map findings to a specific standard (CAN-ASC-6.2, EN 301 549, ADA/AODA).
erpclaw
IncludedAI-native ERP system with self-extending OS. Full accounting, invoicing, inventory, purchasing, tax, billing, HR, payroll, advanced accounting (ASC 606/842, intercompany, consolidation), and financial reporting. 413 actions across 14 domains, 43 expansion modules. Constitutional guardrails, adversarial audit, schema migration. Double-entry GL, immutable audit trail, US GAAP.
assess
IncludedAssesses and rates quality 0-10 across multiple dimensions (correctness, maintainability, security, performance, testability, simplicity) with pros/cons analysis. Compares against project conventions and prior decisions from memory. Produces structured evaluation reports with actionable improvement suggestions. Use when evaluating code, designs, architectures, or comparing alternative approaches.
spring-boot-security-jwt
IncludedProvides JWT authentication and authorization patterns for Spring Boot 3.5.x covering token generation with JJWT, Bearer/cookie authentication, database/OAuth2 integration, and RBAC/permission-based access control using Spring Security 6.x. Use when implementing authentication or authorization in Spring Boot applications.
code-hardcode-audit
IncludedDetect hardcoded values, magic numbers, and leaked secrets. TRIGGERS - hardcode audit, magic numbers, PLR2004, secret scanning.