npx skills add mukul975/Anthropic-Cybersecurity-SkillsMITRE ATT&CK
When to Use
- When conducting vulnerability assessments in OT environments with legacy controllers
- When implementing continuous vulnerability monitoring without impacting process availability
- When preparing for IEC 62443 or NERC CIP compliance audits requiring vulnerability data
- When evaluating risk-based patching priorities for OT assets
- When validating that compensating controls protect unpatched ICS devices
Do not use for aggressive active scanning of production PLCs (can crash legacy controllers), for IT vulnerability scanning using standard Nessus profiles on OT networks, or for penetration testing of live OT systems (see performing-ics-penetration-testing).
Prerequisites
- Tenable OT Security (formerly Tenable.ot/Indegy) or equivalent OT-safe scanning platform
- Passive monitoring sensor deployed on SPAN/TAP at OT network segments
- Lab-tested scanning profiles verified against each device type before production use
- Change management approval and maintenance window for any active scanning
- Vendor warranty verification to confirm scanning will not void support agreements
Workflow
Step 1: Deploy Passive Vulnerability Detection
Passive monitoring identifies vulnerabilities without sending any packets to OT devices.
#!/usr/bin/env python3
"""OT Safe Vulnerability Scanner Orchestrator.
Coordinates passive monitoring, native protocol queries, and carefully
controlled active scanning for OT vulnerability assessment without
disrupting industrial operations.
"""
import json
import csv
import sys
from datetime import datetime
from typing import Dict, List, Optional
try:
import requests
except ImportError:
print("Install requests: pip install requests")
sys.exit(1)
class OTVulnerabilityScanner:
"""Safe OT vulnerability scanning orchestrator."""
SCAN_SAFETY_LEVELS = {
"passive": {
"description": "Observe network traffic only, zero risk to devices",
"risk_level": "NONE",
"methods": ["traffic_fingerprinting", "protocol_analysis", "version_detection"],
"requires_window": False,
},
"native_query": {
"description": "Query devices using native industrial protocols",
"risk_level": "MINIMAL",
"methods": ["modbus_device_id", "s7_szl_read", "cip_identity", "bacnet_whois"],
"requires_window": True,
},
"controlled_active": {
"description": "Standard vulnerability checks with OT-safe profiles",
"risk_level": "LOW-MODERATE",
"methods": ["credentialed_scan", "banner_grab", "service_detection"],
"requires_window": True,
},
}
def __init__(self, tenable_url: str, api_key: str, verify_ssl: bool = True):
self.tenable_url = tenable_url.rstrip("/")
self.session = requests.Session()
self.session.headers.update({
"X-ApiKeys": f"accessKey={api_key}",
"Content-Type": "application/json",
})
self.session.verify = verify_ssl
self.findings = []
def check_safety_prerequisites(self, scan_level: str, target_subnet: str) -> dict:
"""Verify safety prerequisites before scanning."""
checks = {
"scan_level": scan_level,
"target": target_subnet,
"safety_level": self.SCAN_SAFETY_LEVELS[scan_level],
"checks_passed": [],
"checks_failed": [],
"approved": False,
}
prerequisites = [
{
"name": "Lab validation complete",
"description": "Scan profile tested against each device type in lab environment",
"required_for": ["native_query", "controlled_active"],
},
{
"name": "Vendor warranty verified",
"description": "Scanning will not void vendor support agreements",
"required_for": ["native_query", "controlled_active"],
},
{
"name": "Change management approved",
"description": "Change ticket approved for scanning activity",
"required_for": ["native_query", "controlled_active"],
},
{
"name": "Maintenance window confirmed",
"description": "Operations team confirms acceptable scanning window",
"required_for": ["controlled_active"],
},
{
"name": "Rollback plan documented",
"description": "Procedure to stop scan and recover if device becomes unresponsive",
"required_for": ["controlled_active"],
},
{
"name": "SIS excluded from scope",
"description": "Safety Instrumented Systems are never actively scanned",
"required_for": ["passive", "native_query", "controlled_active"],
},
]
for prereq in prerequisites:
if scan_level in prereq["required_for"]:
checks["checks_passed"].append(prereq["name"])
return checks
def run_passive_assessment(self, site_id: str):
"""Run passive vulnerability assessment using traffic analysis."""
print(f"[*] Running passive vulnerability assessment for site {site_id}")
print(f"[*] Safety Level: NONE - no packets sent to OT devices")
try:
resp = self.session.get(
f"{self.tenable_url}/api/v1/assets",
params={"site_id": site_id}
)
resp.raise_for_status()
assets = resp.json().get("assets", [])
for asset in assets:
asset_id = asset.get("id")
vuln_resp = self.session.get(
f"{self.tenable_url}/api/v1/assets/{asset_id}/vulnerabilities"
)
if vuln_resp.status_code == 200:
vulns = vuln_resp.json().get("vulnerabilities", [])
for vuln in vulns:
self.findings.append({
"asset": asset.get("name", "Unknown"),
"ip": asset.get("ip_address", ""),
"type": asset.get("type", ""),
"vendor": asset.get("vendor", ""),
"cve": vuln.get("cve_id", ""),
"severity": vuln.get("severity", ""),
"cvss": vuln.get("cvss_score", 0),
"description": vuln.get("description", ""),
"detection_method": "passive",
"remediation": vuln.get("remediation", ""),
})
print(f"[+] Passive assessment complete: {len(self.findings)} vulnerabilities found")
except requests.RequestException as e:
print(f"[!] API error: {e}")
def generate_prioritized_report(self, output_file: str):
"""Generate risk-prioritized vulnerability report for OT environment."""
self.findings.sort(key=lambda x: x.get("cvss", 0), reverse=True)
print(f"\n{'='*70}")
print("OT VULNERABILITY ASSESSMENT REPORT")
print(f"{'='*70}")
print(f"Date: {datetime.now().isoformat()}")
print(f"Total Findings: {len(self.findings)}")
severity_counts = {}
for f in self.findings:
sev = f.get("severity", "Unknown")
severity_counts[sev] = severity_counts.get(sev, 0) + 1
print(f"\nSeverity Distribution:")
for sev in ["Critical", "High", "Medium", "Low"]:
print(f" {sev}: {severity_counts.get(sev, 0)}")
# Risk-based prioritization considering OT context
print(f"\n--- RISK-PRIORITIZED FINDINGS ---")
print(f"(Prioritized by CVSS score and OT impact)")
for i, finding in enumerate(self.findings[:20], 1):
print(f"\n {i}. [{finding['severity']}] {finding['cve']}")
print(f" Asset: {finding['asset']} ({finding['ip']})")
print(f" Vendor: {finding['vendor']} | Type: {finding['type']}")
print(f" CVSS: {finding['cvss']}")
print(f" Detection: {finding['detection_method']}")
print(f" Description: {finding['description'][:100]}")
if finding.get("remediation"):
print(f" Remediation: {finding['remediation'][:100]}")
# Export to CSV
if output_file:
with open(output_file, "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=self.findings[0].keys())
writer.writeheader()
writer.writerows(self.findings)
print(f"\n[+] Report exported to {output_file}")
if __name__ == "__main__":
scanner = OTVulnerabilityScanner(
tenable_url="https://tenable-ot.plant.local",
api_key="your-api-key-here",
verify_ssl=True,
)
# Always start with passive assessment
safety_check = scanner.check_safety_prerequisites("passive", "10.10.0.0/16")
print(f"Safety prerequisites: {json.dumps(safety_check, indent=2)}")
scanner.run_passive_assessment(site_id="plant-01")
scanner.generate_prioritized_report("ot_vulnerabilities.csv")Key Concepts
| Term | Definition |
|---|---|
| Passive Vulnerability Detection | Identifying vulnerabilities by analyzing mirrored traffic without sending any packets to OT devices |
| Native Protocol Query | Using industrial protocols (Modbus FC43, S7 SZL Read, CIP Get Attribute) to safely extract device information |
| OT-Safe Scan Profile | Vulnerability scanner configuration designed and lab-tested to avoid crashing industrial controllers |
| Compensating Control | Alternative security measure protecting an unpatched OT asset (firewall DPI, network isolation) |
| CVSS in OT Context | Standard CVSS scores adjusted for OT impact considering safety, availability, and physical consequences |
| Tenable OT Security | Purpose-built OT vulnerability management platform using passive and native protocol-based detection |
Output Format
OT VULNERABILITY ASSESSMENT REPORT
=====================================
Date: YYYY-MM-DD
Scope: [network segments]
Method: [Passive/Native Query/Controlled Active]
VULNERABILITY SUMMARY:
Critical: [count]
High: [count]
Medium: [count]
Low: [count]
TOP RISK FINDINGS:
1. [CVE] - [CVSS] - [Asset] - [Description]
UNPATACHABLE ASSETS REQUIRING COMPENSATING CONTROLS:
[Asset] - [Reason] - [Recommended Control]
PATCH PRIORITIZATION:
Immediate: [list]
Next Window: [list]
Acceptable Risk: [list with justification]References and resources
Everything below is rendered for inspection. Script files are read-only and never run.
References 1
api-reference.md1.5 KB
API Reference — Performing OT Vulnerability Scanning Safely
Libraries Used
- socket: Rate-limited TCP port scanning
- subprocess: Execute tshark (passive), nmap (OT-safe settings)
- time: Rate limiting between scan probes
- xml.etree.ElementTree: Parse nmap XML output
CLI Interface
python agent.py passive [--interface eth0] [--duration 60]
python agent.py tcp --target 192.168.1.10 [--rate 0.5]
python agent.py nmap --target 192.168.1.0/24 [--timing T1]
python agent.py checklist --target 192.168.1.0/24Core Functions
passive_discovery(interface, duration) — Zero-packet host discovery
Uses tshark to capture and analyze existing traffic. No packets sent.
safe_tcp_scan(target, ports, rate_limit) — Rate-limited scanning
Default 500ms between probes. Skips high-risk protocols (DNP3, IEC 104).
nmap_safe_scan(target, timing) — OT-safe nmap configuration
Settings: T1 timing, version-light, max-retries 1, 500ms scan-delay. Only T0/T1/T2 allowed — T3+ prohibited for OT.
pre_scan_checklist(target) — 10-step safety checklist
OT Protocol Safety Classification
| Port | Protocol | Scan Risk | Safe to Scan |
|---|---|---|---|
| 502 | Modbus | LOW | Yes |
| 4840 | OPC-UA | LOW | Yes |
| 47808 | BACnet | LOW | Yes |
| 102 | S7Comm | MEDIUM | Yes (careful) |
| 44818 | EtherNet/IP | MEDIUM | Yes (careful) |
| 20000 | DNP3 | HIGH | No — skip |
| 2404 | IEC 104 | HIGH | No — skip |
Dependencies
System: tshark, nmap (optional) No Python packages required.
Scripts 1
agent.py7.7 KB
#!/usr/bin/env python3
"""Agent for performing OT vulnerability scanning safely — passive and rate-limited approaches."""
import json
import argparse
import subprocess
import socket
import time
from datetime import datetime
OT_SAFE_PORTS = {
502: {"protocol": "Modbus", "risk": "LOW", "safe_scan": True},
102: {"protocol": "S7Comm", "risk": "MEDIUM", "safe_scan": True},
4840: {"protocol": "OPC-UA", "risk": "LOW", "safe_scan": True},
44818: {"protocol": "EtherNet/IP", "risk": "MEDIUM", "safe_scan": True},
47808: {"protocol": "BACnet", "risk": "LOW", "safe_scan": True},
20000: {"protocol": "DNP3", "risk": "HIGH", "safe_scan": False},
2404: {"protocol": "IEC 60870-5-104", "risk": "HIGH", "safe_scan": False},
}
def passive_discovery(interface="eth0", duration=60):
"""Perform passive network discovery without sending packets."""
cmd = ["tshark", "-i", interface, "-a", f"duration:{duration}",
"-T", "fields", "-e", "ip.src", "-e", "ip.dst", "-e", "tcp.dstport",
"-e", "eth.src", "-e", "frame.protocols", "-Y", "ip"]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=duration + 30)
hosts = {}
for line in result.stdout.strip().splitlines():
parts = line.split("\t")
if len(parts) >= 3:
src, dst, port = parts[0], parts[1], parts[2]
for ip in (src, dst):
if ip and ip not in hosts:
hosts[ip] = {"ports": set(), "protocols": set(), "mac": ""}
if ip == dst and port:
hosts[ip]["ports"].add(port)
if len(parts) > 3 and parts[3]:
hosts.get(src, {}).setdefault("mac", parts[3])
if len(parts) > 4:
hosts.get(dst, {}).setdefault("protocols", set()).add(parts[4])
return {
"method": "passive", "interface": interface, "duration_sec": duration,
"hosts_discovered": len(hosts),
"hosts": [{
"ip": ip, "ports": sorted(list(d.get("ports", set())))[:20],
"mac": d.get("mac", ""),
} for ip, d in list(hosts.items())[:50]],
}
except FileNotFoundError:
return {"error": "tshark not found — install Wireshark"}
except Exception as e:
return {"error": str(e)}
def safe_tcp_scan(target, ports=None, rate_limit=0.5):
"""Perform rate-limited TCP SYN scan safe for OT environments."""
if ports is None:
ports = list(OT_SAFE_PORTS.keys()) + [80, 443, 22, 8080]
results = []
for port in ports:
ot_info = OT_SAFE_PORTS.get(port, {})
if ot_info.get("safe_scan") is False:
results.append({"port": port, "protocol": ot_info.get("protocol", ""), "status": "SKIPPED_UNSAFE"})
continue
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3)
try:
sock.connect((target, port))
results.append({"port": port, "status": "open", "protocol": ot_info.get("protocol", "")})
except (socket.timeout, ConnectionRefusedError, OSError):
pass
finally:
sock.close()
time.sleep(rate_limit)
return {
"target": target, "method": "rate_limited_tcp",
"rate_limit_sec": rate_limit, "ports_scanned": len(ports),
"open_ports": [r for r in results if r.get("status") == "open"],
"skipped_unsafe": [r for r in results if r.get("status") == "SKIPPED_UNSAFE"],
"timestamp": datetime.utcnow().isoformat(),
}
def nmap_safe_scan(target, timing="T1"):
"""Run nmap with OT-safe settings (low timing, no scripts)."""
ot_ports = ",".join(str(p) for p in OT_SAFE_PORTS.keys())
cmd = ["nmap", f"-{timing}", "-sV", "--version-light", "-p", ot_ports,
"--max-retries", "1", "--host-timeout", "60s",
"--scan-delay", "500ms", "-oX", "-", target]
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
import xml.etree.ElementTree as ET
root = ET.fromstring(result.stdout)
hosts = []
for host in root.findall(".//host"):
addr = host.find("address").get("addr", "") if host.find("address") is not None else ""
ports = []
for port in host.findall(".//port"):
state = port.find("state")
service = port.find("service")
if state is not None and state.get("state") == "open":
ports.append({
"port": int(port.get("portid", 0)),
"service": service.get("name", "") if service is not None else "",
"product": service.get("product", "") if service is not None else "",
})
if ports:
hosts.append({"ip": addr, "services": ports})
return {"target": target, "timing": timing, "hosts": hosts, "scan_settings": "OT-safe: low timing, version-light, max-retries 1"}
except FileNotFoundError:
return {"error": "nmap not found"}
except Exception as e:
return {"error": str(e)}
def pre_scan_checklist(target):
"""Generate pre-scan safety checklist for OT environments."""
return {
"target": target,
"timestamp": datetime.utcnow().isoformat(),
"checklist": [
{"step": 1, "task": "Obtain written authorization from asset owner and OT team", "required": True},
{"step": 2, "task": "Identify all safety-critical systems (SIS/ESD) — exclude from scanning", "required": True},
{"step": 3, "task": "Review OT asset inventory for fragile devices (legacy PLCs)", "required": True},
{"step": 4, "task": "Schedule scan during planned maintenance window", "required": True},
{"step": 5, "task": "Configure scan with T1/T2 timing — NEVER use T4/T5", "required": True},
{"step": 6, "task": "Disable aggressive service detection scripts", "required": True},
{"step": 7, "task": "Set maximum rate limit (500ms+ between probes)", "required": True},
{"step": 8, "task": "Have OT engineer monitoring process during scan", "required": True},
{"step": 9, "task": "Prepare rollback/emergency shutdown procedures", "required": True},
{"step": 10, "task": "Start with passive discovery before active scanning", "required": True},
],
}
def main():
parser = argparse.ArgumentParser(description="Safe OT Vulnerability Scanning Agent")
sub = parser.add_subparsers(dest="command")
p = sub.add_parser("passive", help="Passive network discovery")
p.add_argument("--interface", default="eth0")
p.add_argument("--duration", type=int, default=60)
t = sub.add_parser("tcp", help="Safe rate-limited TCP scan")
t.add_argument("--target", required=True)
t.add_argument("--rate", type=float, default=0.5, help="Seconds between probes")
n = sub.add_parser("nmap", help="OT-safe nmap scan")
n.add_argument("--target", required=True)
n.add_argument("--timing", default="T1", choices=["T0", "T1", "T2"])
c = sub.add_parser("checklist", help="Pre-scan safety checklist")
c.add_argument("--target", required=True)
args = parser.parse_args()
if args.command == "passive":
result = passive_discovery(args.interface, args.duration)
elif args.command == "tcp":
result = safe_tcp_scan(args.target, rate_limit=args.rate)
elif args.command == "nmap":
result = nmap_safe_scan(args.target, args.timing)
elif args.command == "checklist":
result = pre_scan_checklist(args.target)
else:
parser.print_help()
return
print(json.dumps(result, indent=2, default=str))
if __name__ == "__main__":
main()