# Modbus Security Testing

> Use when testing Modbus TCP or Modbus RTU security on an authorized OT lab or plant segment. Covers Modbus function code enumeration, unit ID discovery, holding register and coil mapping, detection of unsafe writes, and proof that a device accepts unauthenticated reads or writes. Also use when port 502 is open and you must show exactly what an unauthenticated network peer can do, without disturbing a live process.

- Skill: `mizazhaider-ceh/modbus-security-testing` (Agent Skill)
- Install (CLI): `npx get-skill add mizazhaider-ceh/modbus-security-testing`
- Raw SKILL.md: https://api.skillmd.com/api/skills/mizazhaider-ceh/modbus-security-testing/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Product & Planning
- Author: mizazhaider-ceh (https://skillmd.com/u/mizazhaider-ceh)
- Updated: 2026-11-22
- Page: https://skillmd.com/skills/mizazhaider-ceh/modbus-security-testing

---


Modbus has no authentication, so testing it is really testing the
network around it. Anyone who can reach a Modbus device can usually
read its registers and, on many devices, write them too. This sub-skill
turns the parent modbus-security overview into a test plan. It covers
read-only enumeration first, then write testing only where it is
explicitly authorized, on a lab device or in a maintenance window.

Safety warning. Modbus writes move real machinery. Never test writes
against a live process without written authorization, an operations
contact on call, and an agreed rollback value for every register you
touch. If operations says no, stay read-only and report the exposure
from the read results alone. Fragile devices can fault on unusual
function codes, so scan slowly and stop at the first sign of trouble.

## Quick Workflow

1. Get written authorization naming the segment, the test window, the
   devices in scope, and whether any write is permitted at all.
2. Start passive. Capture Modbus traffic from a span port and learn
   the unit IDs, function codes, and poll rates already in use.
3. Discover Modbus TCP devices with a slow scan for port 502 on the
   authorized segment only.
4. Enumerate function codes read-only. Record which codes each unit ID
   answers and which return an exception.
5. Map registers to process meaning with operations. Note holding
   registers, input registers, coils, and discrete inputs separately.
6. Check for unsafe exposure. Can an unauthenticated peer read set
   points, write coils, or issue diagnostic and restart functions.
7. If writes are authorized, test one register at a time on a lab
   device first, record the before value, write, verify, and restore.
8. Report each device with its unit IDs, answered function codes,
   mapped registers, and the exact network fix that would block it.

## 1. Passive capture first

Passive capture tells you what normal looks like before you send
anything, and it avoids waking fragile devices with a scan.

```bash
# Passive Modbus capture from a SPAN port on the authorized segment
sudo tshark -i eth0 -f "tcp port 502" -w /tmp/modbus_passive.pcap &
echo $! > /tmp/modbus_passive.pid
# Let it run through at least one full poll cycle, then stop it
# kill $(cat /tmp/modbus_passive.pid)
tshark -r /tmp/modbus_passive.pcap -Y "modbus" \
  -T fields -e ip.src -e ip.dst -e modbus.unit_id -e modbus.func_code \
  | sort | uniq -c | sort -nr | head -40
```

```bash
# Slow, OT-safe discovery for Modbus TCP on the authorized segment only
sudo nmap -sS -p 502 --open -T2 --max-retries 1 \
  192.168.10.0/24 -oN /tmp/modbus_testing_disc.txt
grep -B2 open /tmp/modbus_testing_disc.txt | head -40
```

## 2. Read-only function code enumeration

A Modbus TCP request is a short MBAP header plus a protocol data
unit. The function code is the first byte of that unit, and the unit
ID selects which device behind a gateway answers. The script below
uses only the Python standard library, sends read requests, and
treats an exception response as a useful answer, not a failure.

```python
#!/usr/bin/env python3
"""Read-only Modbus TCP function code probe (stdlib only)."""
import socket
import struct

HOST = "192.168.10.20"
PORT = 502
UNIT_ID = 1

READ_CODES = {
    1: ("read coils", 0, 8),
    2: ("read discrete inputs", 0, 8),
    3: ("read holding registers", 0, 4),
    4: ("read input registers", 0, 4),
}

def request(func, address, quantity):
    pdu = struct.pack(">BHH", func, address, quantity)
    header = struct.pack(">HHHB", 1, 0, len(pdu) + 1, UNIT_ID)
    sock = socket.create_connection((HOST, PORT), timeout=5)
    try:
        sock.sendall(header + pdu)
        data = sock.recv(256)
    finally:
        sock.close()
    if len(data) < 8:
        return "no usable response"
    resp_func = data[7]
    if resp_func & 0x80:
        return "exception code %d" % data[8]
    return "answered, %d bytes" % len(data)

for func, (label, address, quantity) in READ_CODES.items():
    print("function %d (%s): %s" % (func, label, request(func, address, quantity)))
```

## 3. Register mapping with operations

Raw register numbers mean nothing without process context. Map them
with the operations team, and record the engineering unit, the safe
range, and what happens if the value changes.

```python
#!/usr/bin/env python3
"""Register map template that forces a safety note per register."""
registers = [
    {"address": 40001, "kind": "holding", "meaning": "pump speed set point",
     "unit": "percent", "safe_range": "0 to 100",
     "if_changed": "pump speed changes, check process impact first"},
    {"address": 40002, "kind": "holding", "meaning": "tank level alarm threshold",
     "unit": "cm", "safe_range": "50 to 200",
     "if_changed": "alarm may silence or trigger falsely"},
    {"address": 0, "kind": "coil", "meaning": "pump start stop",
     "unit": "on or off", "safe_range": "as commanded by operator only",
     "if_changed": "pump starts or stops immediately"},
]
for reg in registers:
    print("%s %s - %s (%s, safe range %s)" % (
        reg["kind"], reg["address"], reg["meaning"],
        reg["unit"], reg["safe_range"]))
    print("  if changed: %s" % reg["if_changed"])
```

## 4. Write testing, lab only, with rollback

This block is a guard pattern, not a write exploit. It refuses to run
unless the operator confirms the target is a lab device, records the
before value, and restores it. On a live device, replace this whole
step with a report entry that says writes were not tested.

```bash
# Lab-only write test guard: answer the prompts honestly or stop
read -r -p "Is this a lab device with no live process (yes or no)? " LAB
if [ "$LAB" != "yes" ]; then
  echo "Stopping. Write testing is lab only without a maintenance window."
  exit 1
fi
read -r -p "Operations contact name on call: " OPS
read -r -p "Register to test and its known good value: " REGVAL
echo "Operator on call: $OPS"
echo "Register and rollback value recorded: $REGVAL"
echo "Test one register, verify the change, then restore $REGVAL before moving on."
```

## Edge cases

- Gateway unit IDs. One IP address can hide many devices behind a
  serial gateway. A scan that finds one open port 502 may still miss
  ten unit IDs, so enumerate unit IDs 1 through 247 read-only on a
  lab gateway before declaring the map complete.
- Exception code 2 means illegal data address, not a closed device.
  It proves the device heard you and checked the address, which is
  itself useful enumeration evidence.
- Exception code 3 means illegal data value. The function is
  supported but the quantity or address range was wrong, so narrow
  the request rather than marking the function absent.
- Modbus RTU over serial. There is no TCP port to scan. Work from a
  serial capture or a documented gateway map, and never inject RTU
  frames onto a live serial bus without operations approval.
- Devices that fault on scans. Some older PLCs stop responding after
  rapid or malformed requests. If a device goes quiet, stop testing,
  tell operations at once, and record the exact request that
  preceded the fault.
- Write function codes 5, 6, 15, and 16. Treat a device that answers
  any of them as write capable until proven otherwise, even if no
  write was actually performed during the test.

## Key references

- Modbus Application Protocol Specification, function codes and
  exception codes, from the Modbus Organization.
- NIST SP 800-82 Rev 3, Guide to Operational Technology Security,
  for OT testing constraints and safety first assessment practice.
- IEC 62443 zone and conduit concepts, for the network controls that
  must compensate for Modbus having no authentication.
- Parent skill modbus-security, for device discovery and the
  broader Modbus assessment method this sub-skill extends.

