Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

IoTtack is an open-source, Rust-based security framework designed for auditing and testing common IoT protocols, hardware implementations and smart infrastructures. The modular tool simplifies security assessments by offering automated plugins that probe everything from network layers to physical serial interfaces.

Key Features:

  • Multi-Layer Testing: Broad plugin ecosystem covering physical hardware interfaces (UART), protocol brokers (AMQP), web endpoints (HTTP) and network discoveries (mDNS, TCP).
  • Hardware Auditing: Capabilities to run automated UART baud rate scanning, serial interface fuzzing and interactive shell detection.
  • Built in Rust: Offers high performance, low-level memory safety and easy portability across target testing platforms.
  • Developer Friendly: Extensible architecture making it simple to write custom configurations and register new protocol test suites.

Over the last 15 years we contributed to various Open source projects that are the major players in that (non)-commercial sector for IoT and home automation.

  • Home Assistant: Support for MQTT, serial devices, RESTful API services, GPS, mathematical helpers, etc. Also, integrations that interfaces with micro controllers and alike. The binary sensor was something that was done front to end.
  • ESPhome: Display and sensor support
  • CircuitPython: Support for multiple RP2040-based boards
  • Expliot: Multiple plugins, documentation and frontend

The involvement around the local Hackerspace Eastermundigen and Bastelgarage multiple DIY kit were designed to give people access to the Internet of Things.

Often is a serial-to-USB convert not enough and an oscilloscope too much. There is a lot of software and tools available that could help in between. To close the gap we started to work on IoTtack. Currently we are in the process of rewriting/cleaning up/improving piece by piece to make the former inhouse solution completely Open Source.

Plugins

Plugins extend iottack with individual test and enumeration capabilities. Each plugin runs a self-contained check and reports zero or more findings with a severity level and optional evidence string.

PluginCommandSummary
amqp scaniottack amqp scanDetect an AMQP broker and test for default credentials
bacnet device-propertiesiottack bacnet device-properties --host <HOST>Read all standard Device-object properties
bacnet event-infoiottack bacnet event-info --host <HOST>Read event and alarm state of a BACnet device
bacnet find-devicesiottack bacnet find-devicesDiscover all reachable BACnet/IP devices via Who-Is broadcast
bacnet fuzziottack bacnet fuzz --host <HOST>Send malformed BACnet PDUs and report anomalous responses
bacnet infoiottack bacnet info --host <HOST>Read identification and status properties of a single BACnet/IP device
bacnet network-infoiottack bacnet network-info --host <HOST>Read BACnet network configuration of a device
bacnet object-listiottack bacnet object-list --host <HOST>Enumerate all BACnet objects and read their present values
bacnet object-propertiesiottack bacnet object-properties --host <HOST> --object <TYPE:ID>Read all standard properties of a specific BACnet object
bacnet scaniottack bacnet scanEnumerate BACnet/IP devices and read key Device-object properties
bacnet servicesiottack bacnet services --host <HOST>Read supported BACnet services and object types
ble adapteriottack ble adapterList Bluetooth adapters and report their power and discoverability state
ble deviceiottack ble device --address <ADDR>Enumerate GATT services and characteristics of a single BLE device
ble scaniottack ble scanDiscover nearby Bluetooth Low Energy devices and report their properties
ble writeiottack ble write --address <ADDR> --characteristic <UUID>Write a value to a BLE GATT characteristic or fuzz it
can dumpiottack can dumpPassively capture CAN frames and report traffic statistics and security-relevant IDs
can enumerateiottack can enumerateDiscover CAN bus devices via passive heartbeat, OBD-II broadcast, and CANopen node guarding
can scaniottack can scanPassively enumerate all active CAN IDs with frame count, rate, DLC, and payload
can sendiottack can send --id <HEX>Transmit arbitrary CAN data frames (SFF or EFF) to the bus
ftdi deviceiottack ftdi deviceEnumerate FTDI USB adapters and report chip type, chip ID, EEPROM strings and MPSSE capability
http banneriottack http bannerChecks HTTP banner and common settings
i2c readiottack i2c read --address <HEX>Read bytes from an I2C device register via an FTDI MPSSE adapter
i2c scaniottack i2c scanProbe all valid 7-bit I2C addresses via an FTDI MPSSE adapter
mcp2221 deviceiottack mcp2221 deviceEnumerate connected MCP2221/MCP2221A adapters and report USB identity and capabilities
modbus device-infoiottack modbus device-infoRead Modbus controller device identification (FC43 MEI)
modbus enumerateiottack modbus enumerateEnumerate Modbus coils, discrete inputs, and registers
modbus read-coilsiottack modbus read-coilsRead Modbus coils or discrete inputs
modbus read-registersiottack modbus read-registersRead Modbus holding or input registers
modbus write-coiliottack modbus write-coilWrite a single Modbus coil (FC05)
modbus write-registeriottack modbus write-registerWrite a value to one or more Modbus holding registers
mqttiottack mqttWork with MQTT
network mdns-scaniottack network mdns-scanDiscover mDNS/DNS-SD services on the local network
network telnetiottack network telnetConnect to a Telnet service and detect banners, login prompts and default credentials
onewire scaniottack onewire scanEnumerate 1-Wire device ROM codes via FTDI UART loopback and report family type and security relevance
platformiottack platformReport details about the host/platform environment
tcp banneriottack tcp bannerConnect to a TCP service and capture the initial banner, identifying the protocol and flagging cleartext services
tcp fuzziottack tcp fuzzSend malformed and custom payloads to a TCP service and report anomalous responses
tcp shell-detectiottack tcp shell-detectDetect interactive shell or login prompt on a TCP service
uart baud-scaniottack uart baud-scanProbe common UART baud rates to identify the active configuration
uart fuzziottack uart fuzzSend malformed and custom payloads to a UART interface and report anomalous responses
uart port-scaniottack uart port-scanDiscover serial ports available on this host
uart shell-detectiottack uart shell-detectDetect interactive shell or login prompt on a UART interface
uart terminaliottack uart terminalOpen an interactive terminal session over a UART interface
vulns bluefiiottack vuln bluefiCheck ESP for CVE-2025-27840
zigbee captureiottack zigbee captureCapture raw IEEE 802.15.4 frames
zigbee snifferiottack zigbee snifferPassively capture IEEE 802.15.4/Zigbee frames via nRF52840 dongle and report MAC-layer security weaknesses

Global options

Every plugin accepts these flags in addition to its own arguments:

FlagShortDescription
--verbose-vIncrease log verbosity; repeat for more detail (-v, -vv, -vvv)
--output <FILE>-oSave the result to a file
--format <FORMAT>-fOutput format for --output: text (default) or json

Generic

platform

Collects and reports information about the host running iottack:

  • Framework version
  • OS name, version, and codename (from /etc/os-release)
  • Kernel release (from /proc/sys/kernel/osrelease)
  • CPU architecture
  • Effective user ID - flags whether the process has root privileges
  • Available serial ports (/dev/ttyUSB*, /dev/ttyACM*, etc.)
  • USB-serial devices enumerated via sysfs, including vendor/product details

Usage

iottack platform [OPTIONS]

Options

FlagShortDefaultDescription
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack platform

Plugin name:    platform/platform
Execution time: 3ms
Status:         pass
Date:           2026-10-17 00:00:00 UTC

Host environment
  iottack release: 0.2.6
  OS: NixOS 26.11 (zokor)
  Kernel: 6.18.54
  Architecture: x86_64

Running as unprivileged user (euid=1000)
  Some serial ports or USB devices may require elevated privileges.
  Run with sudo if access is denied.

Serial ports available (1)
  /dev/ttyUSB0

USB-serial device: /dev/ttyUSB0
  0403:6001 | FT232 USB-Serial (FTDI) | sysfs: /sys/devices/...

amqp scan

Connects to the target AMQP port using the lapin client library and performs an AMQP 0-9-1 handshake. The outcome of the initial connection attempt distinguishes three cases:

  • AMQP protocol error (e.g., ACCESS_REFUSED): a broker is running and rejected the probe credentials. The service is flagged as confirmed.
  • Successful connection: a broker is running and accepted the probe credentials.
  • IO error or timeout: no broker is listening on that port.
PortService
5671AMQPS — TLS-encrypted AMQP
5672AMQP — plaintext (this plugin)
15672RabbitMQ management HTTP API and web UI

Use the http/banner plugin to probe port 15672 for the management interface.

Severity mapping

FindingSeverity
AMQP broker detectedInfo
Cleartext AMQP on port 5672High
Default credentials acceptedCritical
No default credentials acceptedInfo
Management UI hint (port 15672)Info

Usage

iottack amqp scan --host <HOST> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target hostname or IP address
--port <PORT>-p5672AMQP port
--vhost <VHOST>-V/Virtual host to authenticate against
--timeout-ms <MS>-t3000Connection timeout (ms)
--try-creds-offProbe common default credentials
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

When --try-creds is set, a list of common default credentials is probed in sequence. Each pair opens a fresh TCP connection, performs the full handshake, and closes cleanly on success.

Default credentials probed

UsernamePassword
guestguest
adminadmin
adminpassword
adminrabbitmq
rabbitmqrabbitmq
useruser
rootroot
adminguest

RabbitMQ ships with guest/guest as the built-in administrator account. Modern versions restrict it to localhost connections by default, but misconfigured or older deployments expose it on all interfaces.

Examples

Detect the broker:

$ iottack amqp scan --host 192.168.1.100
[...]
[INFO] AMQP broker on 192.168.1.100:5672
  An AMQP 0-9-1 broker is listening on 192.168.1.100:5672.

[HIGH] Cleartext AMQP on port 5672
  AMQP 0-9-1 transmits credentials and all message payloads in plaintext.
  Use AMQPS (port 5671) with TLS.

Check for default credentials:

$ iottack amqp scan --host 192.168.1.100 --try-creds
[...]
[CRITICAL] Default credentials accepted: guest/guest
  The broker on 192.168.1.100:5672 accepted guest/guest for vhost '/'.
  Change this password immediately.

Scan a non-default virtual host:

$ iottack amqp scan --host 192.168.1.100 --vhost /production --try-creds

Scan an AMQPS endpoint (port 5671 - no cleartext finding):

$ iottack amqp scan --host 192.168.1.100 --port 5671 --try-creds

Test environment

See AMQP server setup for instructions on running a local RabbitMQ instance for testing.

MQTT

To test MQTT, use mqattack. This is a dedicated tool to work with MQTT.

HTTP

HTTP (Hypertext Transfer Protocol) is the application-layer protocol that underpins web-based management interfaces, REST APIs, and over-the-air (OTA) firmware update endpoints. All common features of modern IoT devices. Even devices with no user-visible web interface often embed a lightweight HTTP server for configuration, health checks, or telemetry reporting.

How HTTP works

HTTP is a request-response protocol. A client opens a TCP connection, sends a request with a method, path, headers and optional body. Then the server replies with a status code, headers, and a response body.

GET /api/status HTTP/1.1
Host: 192.168.1.1
Accept: application/json

HTTP/1.1 200 OK
Content-Type: application/json

{"firmware":"1.4.2","uptime":86400}

Key HTTP methods in IoT assessments

MethodTypical useSecurity relevance
GETRead config, status, sensor dataUnauthenticated reads expose data
POSTSubmit commands, trigger actionsUnauthenticated writes can modify device state
PUTUpdate config or firmwareOTA endpoints are high-value targets
DELETERemove records or resetDangerous if unauthenticated

HTTP versions

VersionTransportNotes
HTTP/1.0Plain TCPNo persistent connections; common on embedded devices
HTTP/1.1Plain TCPKeep-alive, chunked transfer; most embedded web servers
HTTPS (TLS)TLS over TCPEncrypted; self-signed certificates are common on IoT
HTTP/2TLS or plain TCPRare on constrained devices

Attack surface

  • Admin panels without authentication: embedded web servers frequently expose configuration pages with no login or with default credentials that are printed on the device label.
  • Firmware version disclosure: the HTTP Server header and HTML pages often reveal exact firmware versions, enabling targeted exploitation.
  • Missing security headers: IoT web interfaces commonly omit Strict-Transport-Security, X-Frame-Options, Content-Security-Policy and X-Content-Type-Options, enabling XSS and clickjacking.
  • Unencrypted management: HTTP (not HTTPS) is used for configuration pages, exposing credentials to network eavesdroppers.
  • Unauthenticated REST APIs: /api/ endpoints that return sensor readings, device state, or accept commands without any token or session check.
  • Server-Sent Events (SSE): some devices stream live telemetry over SSE endpoints without authentication, leaking real-time operational data.

Plugins

PluginCommandSummary
http banneriottack http bannerGrab the HTTP banner and check response headers
http sseiottack http sseConsume a Server-Sent Events stream from a device endpoint

Typical workflow

  1. Grab the banner: identify the server software, check for missing security headers, and look for version strings in the response.

    iottack http banner --host 192.168.1.1 --port 80
    
  2. Check HTTPS: verify whether TLS is available and if the certificate is valid.

    iottack http banner --host 192.168.1.1 --port 443
    
  3. Probe SSE endpoints: check whether live telemetry streams require authentication.

    iottack http sse --host 192.168.1.1 --path /api/events
    

http banner

Sends a GET request to the target and inspects the response for security issues, version disclosure, and missing hardening headers.

Checks performed

CheckFindingSeverity
Server: header with version numberVersion disclosureMedium
Server: header without versionSoftware identityInfo
X-Powered-By: header presentFramework/runtime disclosureMedium
Port 80 with no HTTPS redirectCleartext HTTPHigh
Port 80 redirecting to HTTPSHTTPS redirect in placeInfo
Missing Strict-Transport-Security (port 443)No HSTSMedium
Missing X-Frame-Options / CSP frame-ancestorsNo clickjacking protectionLow
Missing X-Content-Type-OptionsMIME sniffing not disabledLow
Missing Content-Security-PolicyNo CSPLow
HTTP 401 with Basic schemeCredentials over cleartextHigh
HTTP 401 with other schemeAuth requiredInfo
Default installation page in bodyServer not customisedMedium
Cookie missing Secure or HttpOnly flagInsecure cookieMedium

Usage

iottack http http-banner --host <HOST> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target hostname or IP address
--port <PORT>-p80TCP port
--path <PATH>-u/Request path
--timeout-ms <MS>-t5000Connect and read timeout (ms)
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Examples

Check a device web interface:

$ iottack http http-banner --host 192.168.1.1
[...]
HTTP 200 OK
  Target: 192.168.1.1:80/

Server header: Apache/2.4.51 (Debian)
  Server header discloses software version. Consider suppressing or generalizing this header.

Cleartext HTTP on port 80
  Service responds to plain HTTP without redirecting to HTTPS.

Missing X-Frame-Options / CSP frame-ancestors
  No clickjacking protection header found.

Missing X-Content-Type-Options

Missing Content-Security-Policy

Check a non-standard port:

$ iottack http http-banner --host 192.168.1.1 --port 8080 --path /admin

Check HTTPS (port 443) for HSTS and security headers:

$ iottack http http-banner --host 192.168.1.1 --port 443

http sse

Connects to an HTTP EventSource endpoint and keeps the connection open for a configurable duration, collecting Server-Sent Events as they arrive. The plugin analyses the stream for security issues including open access, cleartext transmission, CORS policy, event rate, event types and potentially sensitive data disclosed in event payloads.

The SSE/EventSource protocol is commonly used by IoT firmware to push sensor readings, device state, and log messages to browser-based dashboards over a persistent HTTP connection.

Checks performed

CheckFindingSeverity
HTTP status 401 or 403Access deniedInfo
HTTP status other than 200Unexpected statusMedium
Content-Type is not text/event-streamWrong content typeMedium
Endpoint on port 80SSE stream over cleartext HTTPHigh
Endpoint reachable without credentialsOpen accessMedium
Access-Control-Allow-Origin: *Wildcard CORS policyMedium
Access-Control-Allow-Origin set to specific originCORS restrictedInfo
No Access-Control-Allow-Origin headerNo CORS headerInfo
Events receivedEvent count and rateInfo
Unique event type namesEvent typesInfo
Payload contains sensitive keywordsSensitive data in streamHigh
First event contentEvent sampleInfo

Sensitive keywords checked in event payloads: password, token, secret, key, auth, credential, private, serial.

Usage

iottack http http-sse --host <HOST> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target hostname or IP address
--port <PORT>-p80TCP port
--path <PATH>-u/eventsEventSource endpoint path
--timeout-ms <MS>-t5000Connection timeout (ms)
--duration-s <SECS>-d10How long to collect events (seconds)
--max-events <COUNT>-n100Maximum number of events to collect
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Examples

Probe a device’s default event stream for 10 seconds:

$ iottack http http-sse --host 192.168.1.1

Target a non-standard path and port, collect for 30 seconds:

$ iottack http http-sse --host 192.168.1.1 --port 8080 --path /api/events --duration-s 30

Collect up to 50 events and save the result as JSON:

$ iottack http http-sse --host 192.168.1.1 --max-events 50 --output result.json --format json

Check a device running an ESPHome web server (default port 80, path /events):

$ iottack http http-sse --host esphome-device.local

Network

The network plugins cover discovery and interaction at the IP/application layer, targeting services that IoT devices expose on a local or routed network. These plugins do not require physical access and can be run from any host with network-layer reachability to the target.

mDNS / DNS-SD

Multicast DNS (mDNS, RFC 6762) and DNS-Based Service Discovery (DNS-SD, RFC 6763) allow devices to advertise and discover services on a local network without a central DNS server. The protocol uses multicast UDP on port 5353 and is enabled by default on a large share of IoT devices, including:

  • Smart home hubs and bridges (HomeKit, Matter, Zigbee gateways)
  • IP cameras and NVRs
  • Network printers and storage (AirPrint, SMB)
  • Media renderers and speakers (Chromecast, AirPlay)
  • Industrial gateways and PLCs with web interfaces

An mDNS scan reveals the device type, model, firmware version, and open service ports. All without authentication and often without triggering any security event on the target.

Telnet

Telnet (RFC 854) is a plain-text remote terminal protocol dating from 1969. It remains widely deployed on IoT devices as a debug, management and recovery interface because it is trivial to implement in firmware.

Telnet has no built-in encryption or strong authentication. Every keystroke, including passwords, is transmitted in cleartext. An attacker with network access can passively capture sessions or perform a man-in-the-middle attack without detection.

Common findings on IoT Telnet services:

  • Default credentials: admin/admin, root/root, root/<empty>
  • No authentication: the device drops directly to a shell prompt
  • Version disclosure: banners reveal OS, kernel and BusyBox versions
  • U-Boot or recovery shells: exposed during boot on management ports

Plugins

PluginCommandSummary
network mdns-scaniottack network mdns-scanDiscover mDNS/DNS-SD services on the local network
network telnetiottack network telnetConnect to a Telnet service and detect banners, login prompts, and default credentials

Typical workflow

  1. Discover services: scan the local network segment for mDNS advertisements to build an inventory of devices and open ports.

    iottack network mdns-scan
    
  2. Check Telnet: for each device that advertises a management interface or that has port 23 open, probe for default credentials.

    iottack network telnet --host 192.168.1.1 --try-creds
    

network mdns-scan

Browses the local network for mDNS/DNS-SD service announcements and reports resolved instances with hostname, IP address, port and TXT records.

All service types are queried in parallel. Each query sends a probe every second until the timeout expires. Insecure protocols are flagged at higher severity:

Service typeLabelSeverity
_telnet._tcp.localTelnetHigh
_ftp._tcp.localFTPMedium
_http._tcp.localHTTPLow
_https._tcp.localHTTPSInfo
_ssh._tcp.localSSHInfo
_mqtt._tcp.localMQTTInfo
_coap._udp.localCoAPInfo
_hap._tcp.localHomeKit (HAP)Info
_matter._tcp.localMatterInfo
_googlecast._tcp.localChromecastInfo

Usage

iottack network mdns-scan [OPTIONS]

Options

FlagShortDefaultDescription
--timeout-secs <SECS>-t5Seconds to listen for responses
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack network mdns-scan --timeout-secs 10

Plugin name:    network/mdns-scan
Execution time: 10.01 s
Status:         pass
Date:           2026-10-17 00:00:00 UTC

HTTP: mydevice.local
  Host: mydevice.local | Address: 192.168.1.42 | Port: 80

SSH: printer.local
  Host: printer.local | Address: 192.168.1.55 | Port: 22

network telnet

Connects to a Telnet service, captures the banner, strips IAC option-negotiation bytes, and checks for login prompts, shell prompts, and default credentials. Telnet is flagged as High severity unconditionally because it transmits credentials and session data in cleartext.

Status

ResultMeaning
passConnection succeeded (findings may include Critical/High issues)
failTelnet port not reachable

Severity classification

SeverityCondition
CriticalUnauthenticated shell prompt directly accessible or default credentials accepted
HighTelnet service is open (cleartext protocol)
MediumLogin prompt detected in banner or after stimulus
InfoBanner received, or no login prompt found

Usage

iottack network telnet --host <HOST> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target IP address or hostname
--port <PORT>-p23Target port
--timeout-ms <MS>-3000Connection and read timeout in milliseconds
--try-creds-offProbe common default credentials after finding a login prompt
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity

Detection logic

  1. Connect to the target port with the configured timeout.
  2. Read up to 2048 bytes and strip IAC option-negotiation sequences, replying DONT/WONT to any WILL/DO commands.
  3. Scan the cleaned banner for login and shell prompt patterns.
  4. If no prompt is found in the initial banner, send \r\n and check the response again.
  5. If --try-creds is set and a login prompt was found, iterate the built-in credential list and check each response for a shell prompt.

Login prompt patterns

login:, Login:, username:, Username:, Password:, password:, root@, admin@, BusyBox, busybox, U-Boot, bash, sh-

Shell prompt patterns (line-start)

# , $ , root@

Default credentials tested (with --try-creds)

UsernamePassword
adminadmin
admin(empty)
rootroot
root(empty)
adminpassword
admin1234
useruser
guestguest

Examples

Basic banner grab:

iottack network telnet --host 192.168.1.1

Non-standard port with extended timeout:

iottack network telnet --host 192.168.1.1 --port 2323 --timeout-ms 5000

Banner grab and default credential check:

iottack network telnet --host 192.168.1.1 --try-creds

Save result as JSON:

iottack network telnet --host 192.168.1.1 --try-creds \
  --format json --output telnet-result.json

Example output

No authentication required — shell directly accessible:

Plugin name:    network/telnet
Execution time: 0.31 s
Status:         pass

[HIGH] Telnet service open on 192.168.1.1:23
  Telnet transmits credentials and data in cleartext.
  Replace with SSH wherever possible.

[INFO] Telnet banner
  Banner received from 192.168.1.1:23.
  Evidence: "OpenWrt login:"

[CRITICAL] Unauthenticated shell on Telnet
  A root/shell prompt is directly accessible on 192.168.1.1:23 with no login required.

Login prompt found and default credentials accepted:

Plugin name:    network/telnet
Execution time: 2.14 s
Status:         pass

[HIGH] Telnet service open on 192.168.1.1:23
  Telnet transmits credentials and data in cleartext.
  Replace with SSH wherever possible.

[INFO] Telnet banner
  Banner received from 192.168.1.1:23.
  Evidence: "BusyBox v1.36.1 (2024-01-15) built-in shell (ash)\nlogin:"

[MEDIUM] Login prompt detected
  A login prompt is accessible on 192.168.1.1:23. Test default credentials.

[CRITICAL] Default credentials accepted: admin/admin
  Telnet on 192.168.1.1:23 accepted admin/admin and returned a shell prompt.
  Evidence: "Password: \r\n# "

TCP

TCP (Transmission Control Protocol) is the transport layer backbone of most IoT network communication. Unlike UDP, TCP provides ordered, reliable, connection-oriented delivery which makes it the protocol of choice for industrial control systems, remote management interfaces, telemetry pipelines and proprietary device APIs.

How TCP works

A TCP connection is established with a three-way handshake:

Client  ->  SYN       ->  Server
Client  <-  SYN-ACK   <-  Server
Client  ->  ACK       ->  Server
          (connection open)

Once open, both sides can exchange data streams freely until either party sends a FIN (orderly close) or RST (abrupt reset). Each octet in the stream carries a sequence number and the receiver acknowledges receipt which guaranteeing that data arrives complete and in order.

Ports and IoT services

IoT devices commonly expose TCP services on well-known and vendor-specific ports:

PortProtocolRisk if exposed
22SSHLow (if hardened); High if default credentials
23TelnetHigh - cleartext credentials and session data
80 / 8080HTTPMedium - admin panel, firmware info disclosure
443 / 8443HTTPSLow (if TLS valid); Medium if self-signed
502Modbus/TCPHigh - unauthenticated PLC register access
1883MQTTHigh - unauthenticated message broker
4840OPC-UAMedium - depends on authentication mode
6379RedisHigh - no auth by default in older versions
9100Raw print/JetDirectMedium - direct print access

Attack surface

  • Banner disclosure: many services announce their software name and version in the first bytes sent after connection. This enables targeted exploitation.
  • Cleartext protocols: Telnet, plain HTTP, MQTT (port 1883) and Modbus/TCP transmit credentials and data without encryption.
  • Unauthenticated access: industrial protocols (Modbus, DNP3, BACnet) were designed for isolated networks and have no built-in authentication.
  • Default credentials: management interfaces (SSH, HTTP admin panels, Redis) often ship with well-known default credentials.
  • Fuzzing: many embedded TCP stacks have limited input validation. Sending malformed or oversized payloads can reveal crashes or unexpected behavior.

Plugins

PluginCommandSummary
tcp banneriottack tcp bannerConnect and capture the service banner; identify protocol and flag cleartext services
tcp shell-detectiottack tcp shell-detectDetect an interactive shell or login prompt on a TCP port
tcp fuzziottack tcp fuzzSend malformed payloads and report anomalous responses

Typical workflow

  1. Banner grab: identify what is listening on each open port.

    iottack tcp banner --host 192.168.1.1 --ports 22,23,80,502,1883,8080
    
  2. Shell detection: check whether a port exposes an unauthenticated shell or a login prompt accepting default credentials.

    iottack tcp shell-detect --host 192.168.1.1 --port 23
    
  3. Fuzz: send malformed inputs to look for crashes or unexpected behavior.

    iottack tcp fuzz --host 192.168.1.1 --port 8080
    

tcp banner

Opens a TCP connection to the target and reads the first bytes the service sends on connection (the banner). If the service sends nothing, a set of protocol-specific probes is tried in sequence until one matches.

The banner is compared against known signatures to identify the service. Cleartext and unauthenticated protocols are flagged with an elevated severity.

Identified protocols

ProtocolDetection methodSeverity
SSHBanner prefix SSH-Info
FTP220 + server stringsHigh
TelnetIAC option negotiation bytesHigh
SMTP220 + ESMTP keywordsMedium
POP3+OK prefixMedium
IMAP* OK prefixMedium
VNCRFB 0 prefixHigh
HTTPActive probe - GET / HTTP/1.0Low
RedisActive probe - PINGHigh
MQTTActive probe - CONNECT packetHigh
Modbus/TCPActive probe - Read Holding RegistersHigh

Unrecognized banners that contain version strings are reported as Medium (information disclosure); all other unknown services are Info.

Severity mapping

FindingSeverity
FTP, Telnet, VNC, Redis, MQTT, Modbus/TCPHigh
SMTP, POP3, IMAPMedium
Unknown service with version disclosureMedium
HTTP serviceLow
SSH serviceInfo
Unknown service, no version infoInfo
No banner receivedInfo

Usage

iottack network tcp-banner --host <HOST> --port <PORT> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H-Target hostname or IP address
--net <CIDR>-n-IPv4 CIDR subnet to sweep, e.g., 192.168.1.0/24. Overrides --host
--port <PORT>-p80Single TCP port, used when --ports/--all-ports are absent
--ports <PORTS>-P-Port list or ranges: 22,80,443, 8080-8090, 22,8000...9000
--all-ports-AoffSweep all TCP ports 1-65535; overrides --port and --ports
--timeout-ms <MS>-t3000Connect and read timeout (ms); use 200-500 ms for sweeps
--probe <PROBE>-(empty)Data to send after connecting. empty means passive read
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Port option precedence: --all-ports > --ports > --port.

--host and --net are mutually exclusive. --net takes precedence when both are given.

During subnet or port sweeps, active probes (the protocol-specific request/response pairs for HTTP, Redis, MQTT and Modbus) are skipped. Only the passive banner read is performed per host/port combination to keep the sweep fast.

Examples

Grab the banner from an SSH service:

$ iottack network tcp-banner --host 192.168.1.1 --port 22
[...]
SSH on 192.168.1.1:22
  Banner: SSH-2.0-OpenSSH_8.9p1

Check for an MQTT broker with no authentication:

$ iottack network tcp-banner --host 192.168.1.100 --port 1883
[...]
MQTT on 192.168.1.100:1883
  Banner: ...
  Evidence: " \u{2}\0\u{5}"

Sweep a /24 for open port 22 (short timeout to keep the scan fast):

$ iottack network tcp-banner --net 192.168.1.0/24 --port 22 --timeout-ms 300
[...]
SSH on 192.168.1.1:22
  Banner: SSH-2.0-OpenSSH_8.9p1
SSH on 192.168.1.42:22
  Banner: SSH-2.0-dropbear_2022.83
Open port 192.168.1.100:22
  TCP connection accepted but no banner received.

Scan a single host across common IoT ports:

$ iottack network tcp-banner --host 192.168.1.1 \
    --ports 22,23,80,443,502,1883,8080,8883
[...]
SSH on 192.168.1.1:22
  Banner: SSH-2.0-dropbear
Telnet on 192.168.1.1:23
  Banner: ...
Modbus/TCP on 192.168.1.1:502
  Banner: ..

Sweep a subnet across multiple ports:

$ iottack network tcp-banner --net 10.0.0.0/24 \
    --ports 22,80,502,1883 --timeout-ms 400

Full port sweep of a single target:

$ iottack network tcp-banner --host 192.168.1.1 --all-ports --timeout-ms 300

Send a custom probe string to a single host:

$ iottack network tcp-banner --host 192.168.1.1 --port 9999 \
    --probe "HELLO\r\n"

tcp fuzz

Connects to a TCP host and port, sends a sequence of payloads, and inspects each response for patterns that indicate crashes, errors, shell exposure, or any user-defined string. The built-in payload set covers common vulnerability classes (null bytes, long strings, format strings, shell metacharacters, boundary values, control characters). When --charset or --wordlist is supplied the built-in set is replaced so only the specified payloads are sent. Named payload sets (--payload-set) always add to whatever is already configured.

Use --reconnect to open a fresh TCP connection for every payload. Useful when the service closes the connection after each message, or when you want to avoid session state between payloads.

Status

ResultMeaning
passAt least one payload produced an interesting response (Medium severity)
failA High/Critical pattern matched (crash, shell prompt) or no response matched at all

Severity classification

SeverityMatched patterns
Criticalfault, panic, exception, stack, crash, abort, segfault, overflow
Highroot@, # , $ , login:, password:
MediumEverything else (error, invalid, user --pattern strings)

Usage

iottack tcp fuzz --host <HOST> --port <PORT> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target hostname or IP address
--port <PORT>-p(required)Target TCP port
--timeout-ms <MS>-3000Connect and read timeout in milliseconds
--reconnect-roffOpen a new TCP connection for every payload
--iterations <N>-1Times to repeat the full payload set
--charset <CHARS>-c-Characters to fuzz. Generates one payload per character per length step (replaces built-ins)
--length <N>-l16Maximum repeat length for charset payloads
--wordlist <PATH>-w-Wordlist file, one payload per line (replaces built-ins)
--suffix <BYTES>-s-Bytes appended to every payload, e.g., \r\n for line-oriented services
--pattern <STRING>--Extra response pattern to flag as interesting
--delay-ms <MS>-d0Delay between payloads in milliseconds
--payload-set <SETS>--Named payload sets to add, comma-separated (digits, lowercase, uppercase, ascii)
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity (repeat for debug/trace)

Examples

Built-in payload set

iottack tcp fuzz --host 192.168.1.1 --port 4444

Reconnect mode for stateless services

Some services (HTTP/1.0, custom embedded daemons) close the connection after each exchange. Use --reconnect to open a fresh connection per payload:

iottack tcp fuzz --host 192.168.1.1 --port 9999 --reconnect

Charset fuzzing against a line-oriented service

Generate every combination of the given characters up to the specified length and append \r\n so the service processes each entry as a line:

iottack tcp fuzz --host 192.168.1.1 --port 4444 \
  --charset "abcdefghijklmnopqrstuvwxyz" \
  --length 4 \
  --suffix '\r\n' \
  --pattern 'OK'

Wordlist fuzzing

iottack tcp fuzz --host 192.168.1.1 --port 4444 \
  --wordlist /path/to/commands.txt \
  --suffix '\r\n' \
  --delay-ms 100

Named payload sets

Four built-in named sets are available. Each set sends one payload per character (single byte). When specified, built-in payloads are replaced unless a wordlist or charset is also given.

Set nameContents
digits0–9, one payload per digit
lowercasea–z, one payload per letter
uppercaseA–Z, one payload per letter
asciiAll 95 printable ASCII characters (0x20-0x7E), one per character

Send each uppercase letter individually as a single-byte payload:

iottack tcp fuzz --host 192.168.1.1 --port 4444 \
  --payload-set uppercase \
  --delay-ms 200

Combine several sets:

iottack tcp fuzz --host 192.168.1.1 --port 4444 \
  --payload-set digits,lowercase,uppercase \
  --suffix '\r\n'

Save result as JSON

iottack tcp fuzz --host 192.168.1.1 --port 4444 \
  --format json --output tcp-fuzz.json

Wordlist format

Plain text, one payload per line. Blank lines and lines starting with # are skipped. The line is sent as-is (without a trailing newline unless --suffix adds one).

# commands.txt
help
version
admin
reboot

Example output

Plugin name:    tcp/fuzz
Execution time: 3.41 s
Status:         fail

[HIGH] Interesting response to null-byte payload
  192.168.1.1:4444 responded with patterns [login:] after receiving the null-byte payload.
  Evidence: "login: "

[MEDIUM] Interesting response to 'AAAA...' payload
  192.168.1.1:4444 responded with patterns [error] after receiving the 'AAAA...' payload.
  Evidence: "error: invalid input"

tcp shell-detect

Connects to a TCP host and port, reads the initial banner, then sends a configurable stimulus (default: \r\n) up to --attempts times and checks all received output for shell and login prompt patterns.

Unauthenticated root shells are reported as Critical. Login prompts are reported as High with a suggestion to test default credentials. Other interactive prompts (e.g., $, >) are reported as Medium. Boot messages are reported as Info and do not affect the status.

Status

ResultMeaning
passConnection succeeded (findings may include Critical/High/Medium issues)
failNo response received after banner read and all stimulus attempts

Severity classification

SeverityCondition
Critical# or root@ present — unauthenticated root shell directly accessible
Highlogin:, Login:, Password:, password: present. Login prompt exposed
MediumOther shell indicators matched ($ , > , bash, sh-, etc.)
InfoBoot messages detected, or service responded but no prompt found

Usage

iottack tcp shell-detect --host <HOST> --port <PORT> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target hostname or IP address
--port <PORT>-p(required)Target TCP port
--timeout-ms <MS>-3000Connect and read timeout in milliseconds
--attempts <N>-3Number of stimulus attempts after the initial banner
--stimulus <BYTES>-S\r\nBytes to send as stimulus, e.g. \r\n or help\r\n
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity

Detection logic

  1. Connect to the target host and port with the configured timeout.
  2. Read the initial banner (up to 8 KiB).
  3. Send the configured stimulus up to --attempts times, collecting all responses.
  4. Search the combined output for shell and login prompt patterns.
  5. Classify the highest severity match found.

Shell patterns

# , $ , > , bash, sh-, ash, busybox, root@, admin@, BusyBox, U-Boot, Press ENTER, press enter, Hit any key

Login prompt patterns

login:, Login:, Password:, password:

Boot message patterns (Info only)

Booting, booting, Starting, Loading, Kernel, U-Boot, GRUB, init:, systemd

Examples

Basic shell detection on a custom TCP port:

iottack tcp shell-detect --host 192.168.1.1 --port 4444

Non-default port with extended timeout and more attempts:

iottack tcp shell-detect --host 192.168.1.1 --port 2323 \
  --timeout-ms 5000 --attempts 5

Send a custom stimulus to wake the service:

iottack tcp shell-detect --host 192.168.1.1 --port 9999 \
  --stimulus 'help\r\n'

Save result as JSON:

iottack tcp shell-detect --host 192.168.1.1 --port 4444 \
  --format json --output shell-detect.json

Example output

Unauthenticated root shell directly accessible:

Plugin name:    tcp/shell-detect
Execution time: 0.24 s
Status:         pass

[CRITICAL] Unauthenticated root shell on 192.168.1.1:4444
  A root shell is directly accessible on 192.168.1.1:4444 with no authentication required.
  Evidence: "root@device:~# "

Login prompt exposed:

Plugin name:    tcp/shell-detect
Execution time: 0.31 s
Status:         pass

[HIGH] Login prompt exposed on 192.168.1.1:2323
  A login prompt is accessible on 192.168.1.1:2323.
  Test default credentials with 'iottack network telnet --try-creds'.
  Evidence: "OpenWrt login: "

Device still booting:

Plugin name:    tcp/shell-detect
Execution time: 3.01 s
Status:         fail

[INFO] Boot messages detected
  Device appears to be booting (matched: Starting, systemd).
  Evidence: "Starting kernel ...\n[  0.000000] Linux version 5.15"

UART

UART (Universal Asynchronous Receiver-Transmitter) is the most common low-level serial interface found on embedded hardware. Almost every IoT device exposes a UART header on its PCB. It is used for boot log output, firmware flashing and factory debugging.

How UART works

UART transmits data one bit at a time over two wires:

  • TX (transmit)
  • RX (receive).

The two sides agree on a set of parameters before communication:

ParameterTypical IoT valueNotes
Baud rate115200Also common: 9600, 57600, 38400, 19200
Data bits8Almost always 8
ParityNoneN - no parity bit
Stop bits18N1 is the de-facto standard
Flow controlNoneHardware (RTS/CTS) rarely used on IoT

A single character frame looks like:

IDLE  START  D0  D1  D2  D3  D4  D5  D6  D7  STOP  IDLE
HIGH    LOW  ...data bits (LSB first)...       HIGH  HIGH

The line is held HIGH when idle. A START bit (LOW) signals the beginning of a frame; the receiver samples each data bit at the agreed baud rate; a STOP bit (HIGH) closes the frame. Because there is no clock line, both sides must be configured to the same baud rate before they can communicate that making baud rate discovery the first step in any UART assessment.

Physical access

Accessing a UART interface requires:

  1. Locating the header: look for unpopulated 3-5 pin headers near the main SoC on the PCB. Common pinouts are GND/TX/RX/VCC (3.3 V or 5 V). A logic analyzer or oscilloscope can confirm which pin is TX by observing activity during boot.
  2. Matching voltage: most modern SoCs use 3.3 V logic. Connecting a 5 V adapter directly can damage the device. Always verify with a multimeter.
  3. USB-to-UART adapter: a CP2102, CH340 or FTDI adapter is required to connect the device to a host PC. Connect device TX to adapter RX and vice versa; share a common ground.

Attack surface

UART is extremely high-value for hardware security assessments:

  • Boot log disclosure: the bootloader and kernel print extensive diagnostic output including memory map, partition layout, kernel version and mount points before any authentication is required.
  • U-Boot shell: if the bootloader is not locked, pressing a key during the countdown drops into a U-Boot prompt with full memory read/write access.
  • Root shell: many devices drop directly to a root shell on the UART console with no login prompt. No credentials required.
  • Firmware recovery: UART is typically used for factory re-flashing, meaning it can be used to extract or replace firmware.
  • Baud rate unknown: the baud rate is not transmitted in-band. If it is not printed on the PCB silkscreen, it must be discovered by scanning common values or measuring the bit period with a logic analyzer.

Plugins

PluginCommandSummary
uart port-scaniottack uart port-scanDiscover serial ports available on the host
uart baud-scaniottack uart baud-scanProbe common baud rates to find the active configuration
uart shell-detectiottack uart shell-detectDetect interactive shell or login prompt on the UART interface
uart terminaliottack uart terminalOpen an interactive terminal session over UART
uart fuzziottack uart fuzzSend malformed payloads and report anomalous responses

Typical workflow

  1. Find the port: list serial adapters visible to the OS.

    iottack uart port-scan
    
  2. Find the baud rate: scan common rates and capture the first output.

    iottack uart baud-scan --port /dev/ttyUSB0
    
  3. Detect the console type: check whether the port exposes a shell or login prompt.

    iottack uart shell-detect --port /dev/ttyUSB0 --baud 115200
    
  4. Interact: open an interactive terminal to explore the device.

    iottack uart terminal --port /dev/ttyUSB0 --baud 115200
    

uart - baud-scan

Probe common UART baud rates to identify the active configuration.

Usage

iottack uart baud-scan --port <PATH> [OPTIONS]

Description

Opens the target serial port at each standard baud rate in sequence, sends a stimulus (\r\n\r\nAT\r\n), and checks whether the response contains printable ASCII. Reports all baud rates that produce readable output.

Baud rates probed (in order): 115200, 57600, 38400, 19200, 9600, 4800, 2400, 1200, 230400, 460800, 921600, 300

Options

FlagShortDefaultDescription
--port <PATH>-p(required)Serial port device, e.g. /dev/ttyUSB0
--timeout-ms <MS>-500Read timeout per baud rate in milliseconds
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack uart baud-scan --port /dev/ttyUSB0

Plugin name:    uart/baud-scan
Execution time: 6.23 s
Status:         pass

UART active at 115200 baud
  Port /dev/ttyUSB0 responded with readable ASCII at 115200 baud.
  Evidence: "OpenWrt login: "

uart fuzz

Sends a sequence of payloads through a serial port and inspects each response for patterns that indicate crashes, errors, shell exposure, or any user-defined string. The built-in payload set covers common vulnerability classes (null bytes, long strings, format strings, shell metacharacters, boundary values, control characters). When --charset or --wordlist is supplied the built-in set is replaced so only the specified payloads are sent. Named payload sets (--payload-set) always add to whatever is already configured.

Status

ResultMeaning
passAt least one payload produced an interesting response (Medium severity)
failA High/Critical pattern matched (crash, shell prompt) or no response matched at all

Severity classification

SeverityMatched patterns
Criticalfault, panic, exception, stack, crash, abort, segfault, overflow
Highroot@, # , $ , login:, password:
MediumEverything else (error, invalid, user --pattern strings)

Usage

iottack uart fuzz --port <PATH> [OPTIONS]

Options

FlagShortDefaultDescription
--port <PATH>-p(required)Serial port device, e.g. /dev/ttyUSB0
--baud-rate <BAUD>-b115200Baud rate
--timeout-ms <MS>-500Read timeout per payload in milliseconds
--iterations <N>-1Times to repeat the full payload set
--charset <CHARS>-c-Characters to fuzz — generates one payload per character per length step (replaces built-ins)
--length <N>-l16Maximum repeat length for charset payloads
--wordlist <PATH>-w-Wordlist file, one payload per line (replaces built-ins)
--suffix <BYTES>-s-Bytes appended to every payload, e.g. \r\n for line-oriented shells
--pattern <STRING>--Extra response pattern to flag as interesting
--delay-ms <MS>-d0Delay between payloads in milliseconds
--payload-set <SETS>--Named payload sets to add, comma-separated (digits, lowercase, uppercase, ascii)
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity (repeat for debug/trace)

Examples

Built-in payload set

iottack uart fuzz --port /dev/ttyUSB0

Charset fuzzing against a line-oriented shell

Generate every combination of the given characters up to length 8 (a, b, …, aa, ab, …, zz, aaa, …), append \r\n so the shell processes each entry, and flag any response containing Set command. Total payloads = |charset|¹ + |charset|² + … + |charset|^length — keep --length small for large charsets.

iottack uart fuzz --port /dev/ttyUSB0 \
  --charset "abcdefghijklmnopqrstuvwxyz0123456789" \
  --length 8 \
  --suffix '\r\n' \
  --pattern 'Set command '

Wordlist fuzzing

iottack uart fuzz --port /dev/ttyUSB0 \
  --wordlist /path/to/commands.txt \
  --suffix '\r\n' \
  --delay-ms 100

Named payload sets

Four built-in named sets are available. Unlike --charset and --wordlist, named sets always add to the active payload list — they never replace the built-in set (or a wordlist/charset if one is also specified).

Set nameContents
digits1234567890 repeated to lengths 10, 64, 256
lowercasea–z repeated to lengths 26, 64, 256
uppercaseA–Z repeated to lengths 26, 64, 256
asciiAll 95 printable ASCII characters (0x20–0x7E), lengths 95, 128, 256

Add the digits set on top of the built-in payloads:

iottack uart fuzz --port /dev/ttyUSB0 \
  --payload-set digits \
  --suffix '\r\n'

Combine several sets at once using a comma-separated list:

iottack uart fuzz --port /dev/ttyUSB0 \
  --payload-set digits,lowercase,uppercase,ascii \
  --suffix '\r\n' \
  --delay-ms 50

Use named sets alongside a wordlist (the wordlist replaces the built-ins, the named sets are appended on top):

iottack uart fuzz --port /dev/ttyUSB0 \
  --wordlist commands.txt \
  --payload-set digits,ascii \
  --suffix '\r\n'

Wordlist format

Plain text, one payload per line. Blank lines and lines starting with # are skipped. The line is sent as-is (without a trailing newline unless --suffix adds one).

# commands.txt
help
version
debug
admin
reboot

Demo

The XIAO RP2040 target runs a CircuitPython shell that controls an onboard NeoPixel LED. The shell accepts a handful of commands (red, green, blue, off, abc, x) and echoes Hit - <command> for each recognized one. Unknown commands produce Unknown command: '...'.

The commands are not documented. The goal is to discover them via fuzzing.

Step 1: Discover single-character commands

--charset now generates every combination of the given characters up to the specified length: a, b, …, aa, ab, …, aaa, aab, abc, etc.

Start with --length 1 to find single-character commands quickly:

iottack uart fuzz --port /dev/ttyACM0 \
  --charset "abcdefghijklmnopqrstuvwxyz0123456789" \
  --length 1 \
  --suffix '\r\n' \
  --pattern 'Hit -' \
  --delay-ms 250

x triggers a Hit - response, so the plugin reports pass:

Plugin name:    uart/fuzz
Execution time: 9.25 s
Status:         pass
Date:           2026-10-17 12:15:34 UTC

Interesting response to 'x' payload
  /dev/ttyACM0 responded with patterns [Hit -] after receiving the 'x' payload.
  Evidence: "x\nHit - x\nxiao> "

Step 2: Discover multi-character commands

Extend to --length 3 to reach commands like abc (3 chars) and off (3 chars). For a 26-letter charset this generates 26 + 676 + 17 576 = 18 278 payloads — use a generous --delay-ms to avoid overwhelming the device:

iottack uart fuzz --port /dev/ttyACM0 \
  --charset "abcdefghijklmnopqrstuvwxyz" \
  --length 3 \
  --suffix '\r\n' \
  --pattern 'Hit -' \
  --delay-ms 50

abc, off, red and all other 1-3-letter commands are found. Commands longer than 3 characters (blue, green) require increasing --length to 5, or use a wordlist for targeted enumeration.

Step 3: Targeted wordlist

Once candidate commands are known, switch to a wordlist for exact matches:

iottack uart fuzz --port /dev/ttyACM0 \
  --wordlist commands.txt \
  --suffix '\r\n' \
  --pattern 'Hit -' \
  --delay-ms 100

commands.txt:

red
green
blue
abc
rainbow
off
reboot
factory-reset

Only red, green, blue, off, and abc produce Hit - responses; the others return Unknown command:.

uart port-scan

Scans /dev/ for character devices whose names match known UART naming patterns:

PrefixInterface
ttyUSB*USB-to-serial (FTDI, CH340, CP210x, …)
ttyACM*USB CDC ACM (Arduino, modems)
ttyAMA*ARM PL011 UART (Raspberry Pi, …)
ttymxc*NXP i.MX SoC UART
ttyO*TI OMAP UART
ttyMSM*Qualcomm UART
ttySAC*Samsung SoC UART
ttyS*Native 16550 UART

Pass --verify to attempt opening each discovered port at 9600 baud, confirming whether it is accessible without elevated privileges.

Usage

iottack uart port-scan [OPTIONS]

Options

FlagShortDefaultDescription
--verify-offTry to open each port to confirm accessibility
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack uart port-scan --verify

Plugin name:    uart/port-scan
Execution time: 12ms
Status:         pass

Serial port available: /dev/ttyUSB0
  /dev/ttyUSB0 is present and can be opened.

uart shell-detect

Connects at the configured baud rate, sends newlines to wake the device, and inspects the response for shell and login prompt patterns. Makes multiple attempts to handle devices that need time to produce output.

Findings are classified as follows:

FindingSeverityCondition
Unauthenticated root shellCritical# or root@ present in output
Login prompt exposedHighlogin:, Password:, etc. present
Interactive promptMediumOther shell patterns matched
Boot messagesInfoBoot-time keywords detected
No response-No output after all attempts

Usage

iottack uart shell-detect --port <PATH> [OPTIONS]

Options

FlagShortDefaultDescription
--port <PATH>-p(required)Serial port device, e.g., /dev/ttyUSB0
--baud-rate <BAUD>-b115200Baud rate to connect at
--attempts <N>-3Number of stimulus attempts
--timeout-ms <MS>-500Read timeout per attempt in milliseconds
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack uart shell-detect --port /dev/ttyUSB0 --baud-rate 115200

Plugin name:    uart/shell-detect
Execution time: 1.52 s
Status:         pass

Login prompt exposed on UART
  A login prompt is accessible on /dev/ttyUSB0 at 115200 baud.
  Default or weak credentials should be tested.
  Evidence: "OpenWrt login: "

uart terminal

Connects to the serial port and bridges your terminal to the device: everything you type is forwarded byte-for-byte to the device, and everything the device sends is printed to stdout.

Press Ctrl+D (EOF) to end the session. The plugin also exits cleanly if the device is reset or unplugged mid-session.

No findings are reported — this plugin is an interactive utility, not an automated check.

Usage

iottack uart terminal --port <PATH> [OPTIONS]

Options

FlagShortDefaultDescription
--port <PATH>-p(required)Serial port device, e.g. /dev/ttyUSB0
--baud-rate <BAUD>-b115200Baud rate
--timeout-ms <MS>-50Read timeout in milliseconds

Example

$ iottack uart terminal --port /dev/ttyUSB0 --baud-rate 115200
[iottack] connected to /dev/ttyUSB0 at 115200 baud - Ctrl+D to exit

OpenWrt login: root
Password:
BusyBox v1.36.1 (2024-01-12) built-in shell (ash)

root@OpenWrt:~# uname -a
Linux OpenWrt 6.1.74 #0 SMP ...

root@OpenWrt:~#
[iottack] session ended

Tips

  • Run uart baud-scan first if you do not know the baud rate.
  • Run uart shell-detect to confirm a shell is present before opening a terminal.
  • If the device echoes your input back, check whether the firmware has local echo enabled; most IoT shells do not.
  • For devices that require \r\n line endings, prefix your commands accordingly or configure your terminal emulator before launching this plugin.

Bluetooth

Bluetooth is a short-range wireless technology found in a wide range of IoT devices like consumer electronics, medical equipment, industrial sensors, smart home hubs and wearables. It covers two distinct protocol stacks that share the same 2.4 GHz radio band but are otherwise independent:

VariantFull nameTypical rangeCommon IoT use
BLEBluetooth Low Energy (Bluetooth 4.0+)10-100 mSensors, beacons, wearables, locks
BR/EDRBasic Rate / Enhanced Data Rate (“Classic”)10-100 mAudio, serial-port emulation (SPP), HID

Most modern IoT devices use BLE exclusively. Some use both stacks (dual-mode).

Attack surface

Bluetooth introduces attack surface at several layers:

  • Unauthenticated pairing: many devices use Just Works pairing, which provides no MITM protection and requires no user confirmation.
  • Open GATT services: BLE devices expose services and characteristics over GATT. Read/write access is often unrestricted, leaking sensor data or accepting firmware payloads without authentication.
  • Advertising data: devices broadcast their name, manufacturer data, and service UUIDs continuously. This data can reveal device type, firmware version, and vendor without any connection.
  • Classic Bluetooth flaws: pre-2017 BR/EDR stacks may be vulnerable to the BlueBorne family of remote code execution and information disclosure vulnerabilities (CVE-2017-0781 through CVE-2017-1000251).
  • Vendor backdoors: some chipsets expose undocumented HCI commands that can be used to read memory, disable security, or write arbitrary data (e.g. CVE-2025-27840 on ESP32).

Plugins

PluginCommandSummary
ble adapteriottack ble adapterList Bluetooth adapters and report their power and discoverability state
ble scaniottack ble scanDiscover nearby BLE devices and report advertising data
ble deviceiottack ble deviceEnumerate GATT services and characteristics of a single BLE device
ble writeiottack ble writeWrite a value to a BLE GATT characteristic or fuzz it

Requirements

BLE plugins require a Bluetooth adapter visible to the host OS and the bluetoothd daemon running. On Linux, bluetoothd is part of BlueZ. Some operations (adapter power control, raw HCI access) require root or membership in the bluetooth group.

# Verify BlueZ is running
systemctl status bluetooth

# List adapters
iottack ble adapter

Typical workflow

  1. Scan: discover what devices are in range and note their addresses and advertised service UUIDs.

    iottack ble scan --timeout 15
    
  2. Enumerate: connect to a device and list all GATT services and characteristics, including their properties (read, write, notify).

    iottack ble device --address AA:BB:CC:DD:EE:FF
    
  3. Read/write: interact with specific characteristics. A writable characteristic with no authentication is a direct finding.

    iottack ble write --address AA:BB:CC:DD:EE:FF \
        --characteristic 0000fff1-0000-1000-8000-00805f9b34fb \
        --value 0x0100
    

ble adapter

Connects to the BlueZ daemon via D-Bus and enumerates every Bluetooth adapter registered with the system. For each adapter the following properties are collected:

  • Address: MAC address of the adapter
  • Alias: human-readable name assigned to the adapter
  • Powered: whether the adapter is currently powered on
  • Discoverable: whether the adapter broadcasts its presence to nearby devices
  • Pairable: whether the adapter accepts pairing requests
  • Class: Bluetooth device class (when available)
  • Modalias: USB/PCI hardware identifier in source:vVENDORpPRODUCTdDEVICE form (when available)

Findings are classified as follows:

FindingSeverityCondition
Adapter powered and discoverableMediumAdapter is on and broadcasting
Adapter details (powered, not discoverable)LowAdapter is on but not broadcasting
Adapter details (not powered)InfoAdapter is off
No adapters foundInfoNo Bluetooth hardware detected
Bluetooth not availableInfoBlueZ daemon unreachable

Requirements

  • BlueZ daemon (bluetoothd) must be running.
  • The D-Bus system bus must be accessible (no special privileges required).

Usage

iottack ble adapter

Options

FlagShortDefaultDescription
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity

Example

$ iottack ble adapter

Plugin name:    ble/adapter
Execution time: 0.12 s
Status:         pass

[INFO] 1 Bluetooth adapter(s) found
  Use 'iottack ble scan' to discover nearby BLE devices.

[MEDIUM] hci0 (AA:BB:CC:DD:EE:FF)
  Address:      AA:BB:CC:DD:EE:FF
  Alias:        My Laptop
  Powered:      yes
  Discoverable: yes
  Pairable:     yes
  Class:        0x00000000
  Modalias:     usb:v1D6Bp0246d0540

[MEDIUM] Adapter hci0 is powered and discoverable
  A discoverable Bluetooth adapter can be detected and probed by any
  nearby device. Disable discoverability when not actively pairing to
  reduce the attack surface.

ble scan

Starts an active BLE discovery session on the selected adapter and listens for advertising packets for the configured duration. Each newly seen device address triggers a finding that captures:

  • Address: Bluetooth MAC address of the device
  • Name: advertised device name (falls back to alias if name is absent)
  • Connected: whether the device currently has an active connection
  • Paired: whether the device is already paired with the host
  • RSSI: received signal strength in dBm (when reported by the adapter)
  • TX Power: transmit power level in dBm (when included in the advertisement)
  • UUIDs: advertised GATT service UUIDs

Findings are classified as follows:

FindingSeverityCondition
Device detailsMediumDevice is connected or paired
Device detailsInfoUnknown / unrecognised device
Summary countInfoAlways emitted at end of scan
No devices foundInfoScan completed with zero results
Bluetooth not availableInfoBlueZ daemon unreachable
No adapters foundInfoNo Bluetooth hardware detected
Cannot start scanInfoAdapter powered off or busy

Requirements

  • BlueZ daemon (bluetoothd) must be running.
  • The D-Bus system bus must be accessible (no special privileges required).
  • At least one powered Bluetooth adapter must be present on the host.

Usage

iottack ble scan

Options

FlagShortDefaultDescription
--timeout <SECS>-t10Scan duration in seconds
--adapter <NAME>-afirst availableAdapter to use, e.g. hci0
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity

Examples

Scan with the default 10-second window:

iottack ble scan

Scan for 30 seconds using a specific adapter:

iottack ble scan --timeout 30 --adapter hci1

Save results as JSON:

iottack ble scan --timeout 20 --format json --output results.json

Example output:

$ iottack ble scan --timeout 5

Plugin name:    ble/scan
Execution time: 5.03 s
Status:         pass

[INFO] AA:BB:CC:11:22:33
  Address:   AA:BB:CC:11:22:33
  Name:      n/a
  Connected: no
  Paired:    no
  RSSI:      -74 dBm

[MEDIUM] My Phone (DD:EE:FF:44:55:66)
  Address:   DD:EE:FF:44:55:66
  Name:      My Phone
  Connected: yes
  Paired:    yes
  RSSI:      -52 dBm
  TX Power:  4 dBm
  UUIDs:     0000110b-0000-1000-8000-00805f9b34fb, 0000110e-0000-1000-8000-00805f9b34fb

[INFO] 2 BLE device(s) discovered
  Scan completed on adapter hci0 after 5 second(s).

Remediation

Devices appearing as Medium are already connected or paired with the host. Unpair devices that are no longer in use:

bluetoothctl remove <ADDRESS>

For devices with sensitive service UUIDs, verify the device is authorised before allowing further interaction.

ble device

Establishes a GATT connection to the given device address and walks every service and characteristic. For each characteristic the following are captured:

  • UUID: 128-bit or short-form GATT UUID
  • Flags: property flags: read, write, write-no-rsp, notify, indicate
  • Value: raw bytes and printable ASCII representation (readable characteristics only)

Findings are classified as follows:

FindingSeverityCondition
Connected to deviceInfoConnection established
Service (primary)LowEach primary GATT service
Service (secondary)InfoEach secondary GATT service
Summary countInfoAlways emitted at end
Cannot connectInfoDevice unreachable or out of range
No GATT servicesInfoDevice reported empty profile
Bluetooth not availableInfoBlueZ daemon unreachable

The plugin disconnects from the device after enumeration unless --no-disconnect is given.

Requirements

  • BlueZ daemon (bluetoothd) must be running.
  • The D-Bus system bus must be accessible (no special privileges required).
  • The target device must be advertising and within range.

Usage

iottack ble device --address AA:BB:CC:DD:EE:FF

Options

FlagShortDefaultDescription
--address <ADDR>-drequiredBluetooth address of the target device
--adapter <NAME>-afirst availableAdapter to use, e.g. hci0
--no-disconnect-offLeave the device connected after enumeration
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity

Examples

Enumerate a device found via iottack ble scan:

iottack ble device --address AA:BB:CC:DD:EE:FF

Keep the connection open after the scan:

iottack ble device --address AA:BB:CC:DD:EE:FF --no-disconnect

Save the full profile as JSON:

iottack ble device --address AA:BB:CC:DD:EE:FF --format json --output device.json

Example output:

$ iottack ble device --address DD:EE:FF:44:55:66

Plugin name:    ble/device
Execution time: 3.21 s
Status:         pass

[INFO] Connected to My Sensor
  Address: DD:EE:FF:44:55:66
  Name:    My Sensor
  Paired:  no
  RSSI:    -58 dBm

[LOW] Service 0000180a-0000-1000-8000-00805f9b34fb
  UUID:    0000180a-0000-1000-8000-00805f9b34fb
  Primary: yes
  Characteristics: 3
  00002a29-0000-1000-8000-00805f9b34fb [read] value=41 63 6d 65 (Acme)
  00002a24-0000-1000-8000-00805f9b34fb [read] value=53 65 6e 73 6f 72 (Sensor)
  00002a26-0000-1000-8000-00805f9b34fb [read] value=31 2e 30 (1.0)

[LOW] Service 0000181a-0000-1000-8000-00805f9b34fb
  UUID:    0000181a-0000-1000-8000-00805f9b34fb
  Primary: yes
  Characteristics: 2
  00002a6e-0000-1000-8000-00805f9b34fb [read, notify] value=0d 01 (...)
  00002a6f-0000-1000-8000-00805f9b34fb [read, notify] value=64 00 (d.)

[INFO] 2 GATT service(s) enumerated
  Device DD:EE:FF:44:55:66 on adapter hci0.

ble write

Writes a value to a specific GATT characteristic on a Bluetooth Low Energy device or fuzzes it with the built-in payload set.

The plugin connects to the given device, locates the characteristic by UUID across all GATT services and operates in one of two modes:

Single-write mode (default): writes the supplied --value once and reports success or failure. The value is treated as a UTF-8 string. Pass --hex to supply raw bytes.

Fuzz mode (--fuzz): iterates the built-in payload set (null bytes, long strings, format strings, boundary values, control characters) and writes each one to the characteristic. After each write the characteristic is read back if it is readable, and the response is scanned for error strings, crash indicators and shell prompts. A --wordlist or --charset can replace the built-in set.

Findings are classified as follows:

FindingSeverityCondition
Write successfulInfoSingle write completed
Write failedLowWrite rejected by the device
Interesting responseMedium–CriticalFuzz response matched a pattern
No interesting responsesInfoFuzz completed with no matches
Characteristic not writableLowCharacteristic lacks write property
Characteristic not foundInfoUUID absent from device profile
Cannot connectInfoDevice unreachable or out of range
Bluetooth not availableInfoBlueZ daemon unreachable

Requirements

  • BlueZ daemon (bluetoothd) must be running.
  • The D-Bus system bus must be accessible (no special privileges required).
  • The target device must be advertising and within range.

Usage

iottack ble write --address <ADDR> --characteristic <UUID> --value <DATA>
iottack ble write --address <ADDR> --characteristic <UUID> --fuzz

Options

FlagShortDefaultDescription
--address <ADDR>-drequiredBluetooth address of the target device
--characteristic <UUID>-crequiredGATT characteristic UUID to write
--value <DATA>-V""Value to write (ignored with --fuzz)
--hex-xoffTreat --value as hex bytes, e.g., ff00ab
--no-response-noffWrite-without-response for every write
--adapter <NAME>-afirst availableAdapter to use, e.g., hci0
--no-disconnect-offLeave device connected after the operation
--fuzz-foffEnable fuzz mode
--iterations <N>-1Times to repeat the payload set (fuzz mode)
--charset <CHARS>--Characters to fuzz (fuzz mode)
--length <N>-l16Max repeat length for charset payloads
--wordlist <PATH>-w-Wordlist file. Replaces built-in payloads
--delay-ms <MS>-0Delay between payloads in ms (fuzz mode)
--suffix <BYTES>-s-Bytes appended to every payload, e.g., \r\n
--pattern <STRING>--Extra response pattern to flag (fuzz mode)
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity

Examples

Write the string R to set an LED color on the IoTTack target board:

iottack ble write \
  --address DD:EE:FF:44:55:66 \
  --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
  --value R

Write raw bytes using hex notation:

iottack ble write \
  --address DD:EE:FF:44:55:66 \
  --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
  --value "52 00" --hex

Fuzz with the built-in payload set:

iottack ble write \
  --address DD:EE:FF:44:55:66 \
  --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
  --fuzz

Fuzz with a custom wordlist and a 50 ms delay between payloads:

iottack ble write \
  --address DD:EE:FF:44:55:66 \
  --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
  --fuzz --wordlist payloads.txt --delay_ms 50

Example output, single write:

$ iottack ble write \
    --address DD:EE:FF:44:55:66 \
    --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
    --value R

Plugin name:    ble/write
Execution time: 1.42 s
Status:         pass

[INFO] Write successful to 19b10001-e8f2-537e-4f6c-d104768a1214
  Device:         DD:EE:FF:44:55:66
  Characteristic: 19b10001-e8f2-537e-4f6c-d104768a1214
  Method:         write-with-response
  Bytes written:  1
  Payload (hex):  52

IoTTack Target Bluetooth

The IoTTack Target Bluetooth board advertises a custom LED control service. Use iottack ble scan to find the board’s address, then iottack ble device to confirm the characteristic UUID, then use ble write to control the LED or fuzz the characteristic.

PropertyValue
Device nameIoTTack Target Bluetooth
Service UUID19b10000-e8f2-537e-4f6c-d104768a1214
Characteristic UUID19b10001-e8f2-537e-4f6c-d104768a1214
Propertiesread, write, write-no-rsp

Accepted commands:

ValueEffect
RSet NeoPixel to red
GSet NeoPixel to green
BSet NeoPixel to blue
OTurn NeoPixel off

Turn the LED red:

iottack ble write \
  --address <ADDR> \
  --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
  --value R

Cycle through all colors in sequence:

for cmd in R G B O; do
  iottack ble write \
    --address <ADDR> \
    --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
    --value "$cmd"
done

Write the same commands using raw HEX bytes (R=52, G=47, B=42, O=4f):

iottack ble write \
  --address <ADDR> \
  --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
  --value 52 --hex

Multi-byte hex payloads are also accepted using space, colon, or no separator:

iottack ble write \
  --address <ADDR> \
  --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
  --value "52 00 00" --hex

Fuzz the characteristic to check how the firmware handles unexpected input:

iottack ble write \
  --address <ADDR> \
  --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
  --fuzz --delay-ms 100

The target prints every received write command to its serial output, so connect a serial monitor to observe how each payload is handled at the firmware level.

Example output, single write to the target:

$ iottack ble write \
    --address AA:BB:CC:DD:EE:FF \
    --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
    --value G

Plugin name:    ble/write
Execution time: 1.38 s
Status:         pass

[INFO] Write successful to 19b10001-e8f2-537e-4f6c-d104768a1214
  Device:         AA:BB:CC:DD:EE:FF
  Characteristic: 19b10001-e8f2-537e-4f6c-d104768a1214
  Method:         write-with-response
  Bytes written:  1
  Payload (hex):  47

Serial output on the target board after receiving the write:

[BLE Write] Raw: 'G'  Parsed: 'G'
[Action Executed] Onboard LED configured to GREEN.

Example output, fuzz mode:

$ iottack ble write \
    --address DD:EE:FF:44:55:66 \
    --characteristic 19b10001-e8f2-537e-4f6c-d104768a1214 \
    --fuzz

Plugin name:    ble/write
Execution time: 38.7 s
Status:         pass

[INFO] No interesting responses
  All payloads x 1 iteration(s) produced no interesting response
  from DD:EE:FF:44:55:66/19b10001-e8f2-537e-4f6c-d104768a1214.

I2C plugins

I2C (Inter-Integrated Circuit) is a two-wire serial bus widely used to connect sensors, EEPROMs, displays and other peripherals on embedded systems. A single bus master can address up to 112 devices using 7-bit addresses.

The protocol has no authentication or access control. Any device that can reach the bus can read sensor values, configuration registers, and stored data, and write to actuator outputs or configuration registers.

Hardware requirement

All I2C plugins require an FTDI MPSSE adapter (FT232H, FT2232H, or FT4232H) connected to the target bus. See FTDI adapter wiring for pin connections and the required udev rule.

Plugins

PluginCommandPurpose
scaniottack i2c scanProbe all 112 valid I2C addresses and report responding devices
readiottack i2c readRead bytes from a specific device register

Severity model

Discovered devices are reported at Medium severity. Their presence on the bus is the finding. Register reads are reported at Info since reading a known address and register is an intentional action rather than a discovery.

i2c scan

Probe all 112 valid 7-bit I2C addresses and report every device that responds with an ACK.

Requirements

An FTDI MPSSE adapter (FT232H, FT2232H or FT4232H) or a Microchip MCP2221/MCP2221A USB-to-I2C adapter connected to the I2C bus.

Usage

iottack i2c scan [OPTIONS]

Description

For each address in the range 0x08-0x77 the plugin sends a zero-byte I2C write (START + address + W + STOP) and checks for ACK. Reserved address ranges (0x00-0x07 general call/high-speed codes, 0x78-0x7F 10-bit addressing) are skipped.

Addresses that respond are reported at Medium severity together with a hint about common devices that use that address range.

Select the hardware backend with --adapter:

BackendHardwareNotes
ftdi (default)FT232H / FT2232H / FT4232HConfigurable channel and clock speed
mcp2221MCP2221 / MCP2221AUses the device’s configured I2C speed

Options

FlagShortDefaultDescription
--adapter <TYPE>-AftdiHardware backend: ftdi or mcp2221
--channel <CHANNEL>-cAFTDI channel to use, must be A or B (ftdi only)
--vid <HEX>-0403USB vendor ID in hex (ftdi only)
--pid <HEX>-auto-detectUSB product ID in hex (ftdi only)
--clock-hz <HZ>-100000I2C clock frequency in Hz (ftdi only)
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Address hint table

Address rangeTypical devices
0x18-0x19LIS3DH/LIS2DH accelerometer
0x1C-0x1DMMA8452/FXOS8700 accelerometer
0x1E-0x1FHMC5883L/MAG3110 magnetometer
0x20-0x27PCF8574/MCP23017 GPIO expander
0x28-0x29BNO055 IMU
0x38-0x3BPCF8574A GPIO expander/AHT10 humidity
0x3C-0x3DSSD1306/SH1106 OLED display
0x40-0x41INA219 power monitor
0x44-0x45SHT30/SHT31/SHT35 humidity & temperature
0x48-0x4FADS1115 ADC/LM75/TMP102 temperature
0x50-0x5724Cxx I2C EEPROM
0x60-0x67PCA9685 PWM driver
0x68-0x69MPU-6050/9250 IMU/DS3231/DS1307 RTC
0x70-0x75TCA9548A/PCA9548 I2C mux
0x76-0x77BMP280/BME280/BMP388 pressure sensor

Examples

FTDI adapter

$ iottack i2c scan --channel A --clock-hz 400000

Plugin name:    i2c/scan
Execution time: 312 ms
Status:         pass

[INFO] 3 I2C device(s) found
  Scanned addresses 0x08-0x77 at 400000 Hz via FTDI 0403:6011 channel A.

[MEDIUM] I2C device at 0x3c
  Address 0x3c (decimal 60) responded with ACK.
  Likely: SSD1306/SH1106 OLED display
  Evidence: "addr=0x3c hint=\"SSD1306/SH1106 OLED display\""

[MEDIUM] I2C device at 0x68
  Address 0x68 (decimal 104) responded with ACK.
  Likely: MPU-6050/9250 IMU / DS3231/DS1307 RTC
  Evidence: "addr=0x68 hint=\"MPU-6050/9250 IMU / DS3231/DS1307 RTC\""

[MEDIUM] I2C device at 0x76
  Address 0x76 (decimal 118) responded with ACK.
  Likely: BMP280/BME280/BMP388 pressure sensor
  Evidence: "addr=0x76 hint=\"BMP280/BME280/BMP388 pressure sensor\""

MCP2221 adapter

$ iottack i2c scan --adapter mcp2221

Plugin name:    i2c/scan
Execution time: 420 ms
Status:         pass

[INFO] 1 I2C device(s) found
  Scanned addresses 0x08-0x77 at 100000 Hz via MCP2221 (04d8:00dd).

[MEDIUM] I2C device at 0x76
  Address 0x76 (decimal 118) responded with ACK.
  Likely: BMP280/BME280/BMP388 pressure sensor
  Evidence: "addr=0x76 hint=\"BMP280/BME280/BMP388 pressure sensor\""

Troubleshooting

No devices found despite wiring being correct

  • Confirm pull-up resistors (4.7 kOhm) are present on SCL and SDA.
  • Try a lower clock frequency (--clock-hz 100000, ftdi only).
  • Verify target power is on.

FTDI device not found

  • Check lsusb shows the adapter (0403:6011 or similar).
  • Apply the udev rule and reconnect.

MCP2221 not found

  • Check lsusb shows 04d8:00dd.
  • Apply the udev rule and reconnect.

MPSSE initialization failed

  • Channels C and D on the FT4232H do not support MPSSE. Use --channel A or --channel B.

All or nearly all addresses respond (FTDI - ACK sensing broken)

If the scan reports a large number of devices (e.g., all 112 addresses), the ACK bit cannot be read and every probe falsely appears as ACK. The most common cause is that ADBUS2 (DI/TDO) is not connected to SDA.

The FT232H needs two pins shorted to the SDA line:

FTDI pinSignalNotes
ADBUS0 (SK/TCK)SCL4.7 kOhm pull-up to VCC
ADBUS1 (DO/TDI)SDA4.7 kOhm pull-up to VCC
ADBUS2 (DI/TDO)SDASame net, shorted to ADBUS1

ADBUS1 drives SDA low (open-drain). ADBUS2 reads SDA back to detect ACK/NACK. Without ADBUS2 on SDA the read pin floats low and every address appears to ACK.

i2c read

Read one or more bytes from a specific I2C device register via an FTDI MPSSE adapter.

Requirements

An FTDI MPSSE adapter (FT232H, FT2232H or FT4232H) connected to the I2C bus. See FTDI adapter wiring for the exact pin connections and the required udev rule.

Usage

iottack i2c read --address <HEX> [OPTIONS]

Description

Performs a single I2C transaction to the target address:

  • Plain read (--address only): issues a raw read of --length bytes.
  • Write-then-read (--address + --register): writes the register byte first (repeated-START), then reads back --length bytes. This is the standard way to read a sensor register.

Raw bytes are reported as hex, decimal, and printable ASCII.

Options

FlagShortDefaultDescription
--address <HEX>-a(required)7-bit I2C target address in hex, e.g., 68 or 0x68
--register <HEX>-r(none)Register/command byte to write before reading, e.g., 00 or 0x00
--length <N>-n1Number of bytes to read
--channel <CHANNEL>-cAFTDI channel to use, must be A or B (MPSSE-capable)
--vid <HEX>-0403USB vendor ID in hex
--pid <HEX>-6011USB product ID in hex (6001=FT232R, 6010=FT2232H, 6011=FT4232H, 6014=FT232H)
--clock-hz <HZ>-100000I2C clock frequency in Hz
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Examples

Read 1 byte from the WHO_AM_I register (0x75) of an MPU-6050 at address 0x68:

$ iottack i2c read --address 68 --register 75

Plugin name:    i2c/read
Execution time: 18 ms
Status:         pass

[INFO] 1 byte(s) from I2C 0x68 reg 0x75
  Device 0x68 reg 0x75 on channel A at 100000 Hz
  HEX:     68
  Decimal: 104
  ASCII:   h
  Evidence: addr=0x68 reg=0x75 bytes=[68]

Read 6 raw bytes (accelerometer X/Y/Z) from register 0x3b:

$ iottack i2c read --address 68 --register 3b --length 6

[INFO] 6 byte(s) from I2C 0x68 reg 0x3b
  Device 0x68 reg 0x3b on channel A at 100000 Hz
  HEX:     01 2c ff e4 00 08
  Decimal: 1 44 255 228 0 8
  ASCII:   ....

Troubleshooting

NACK/read failed

  • Confirm the address is correct (use iottack i2c scan to discover devices).
  • Check the register byte is valid for the target device.
  • Verify pull-up resistors (4.7 kOhm) are on SCL and SDA.

FTDI device not found

  • Check lsusb shows the adapter (0403:6011 or similar).
  • Apply the udev rule and reconnect.

MPSSE initialization failed

  • Channels C and D on the FT4232H do not support MPSSE. Use --channel A or --channel B.

1-Wire plugins

1-Wire (Dallas/Maxim) is a single-wire serial bus used for temperature sensors, iButton authentication tokens, EEPROMs and other low-speed peripherals. Each device carries a unique 64-bit ROM code (8-bit family & 48-bit serial & 8-bit CRC) that serves as its address. Multiple devices share a single data line using a master-slave open-drain protocol.

The protocol has no authentication or encryption. Any master that can reach the bus can enumerate all ROM codes, read sensor data and in some cases write to configuration or EEPROM storage. iButton tokens (DS1990A, DS2401) are used as physical access credentials in many industrial and building-automation systems. Their 48-bit serial numbers can be read in milliseconds and are trivially cloneable.

Hardware requirement

All 1-Wire plugins use the FTDI UART TX/RX loopback method. This works on any FTDI chip (FT232R, FT232H, FT2232H, FT4232H) and requires no special adapter beyond the chip itself.

Wiring generic

Connect TX and RX together to the 1-Wire DQ line and add a 4.7 kOhm pull-up resistor from DQ to VCC (3.3 V or 5 V depending on target):

FTDI TX ──┬──── DQ (1-Wire bus)
FTDI RX ──┘        │
                  4.7 kOhm
                   │
                  VCC (3.3 V or 5 V)

The TX line drives the bus low. Because TX and RX are shorted, RX reads back the actual bus level (open-drain pull-up for 1, TX-driven low for 0), giving exact timing via the FTDI hardware UART engine.

FT4232H

The FT4232H has four independent UART channels (A-D). Each channel exposes a TX and RX pin on its xDBUS header. Use any channel. The example below uses channel A.

  • FT4232H channel pin names
ChannelTX pinRX pin
AADBUS0 (TXD)ADBUS1 (RXD)
BBDBUS0 (TXD)BDBUS1 (RXD)
CCDBUS0 (TXD)CDBUS1 (RXD)
DDDBUS0 (TXD)DDBUS1 (RXD)
  • DS18B20 pin-out (TO-92, flat side facing you)
  DS18B20
  ┌───────┐
  │ 1 2 3 │
  └───────┘
    │ │ └── VDD  -> 3.3 V or 5 V
    │ └──── DQ   -> data line
    └────── GND  -> ground
  • Full connection diagram (channel A, 3.3 V)
FT4232H                        DS18B20
─────────                      ───────
ADBUS0 (TXD) ──┬────────────── DQ  (pin 2)
ADBUS1 (RXD) ──┘     │
                   4.7 kOhm
                     │
3.3 V ───────────────┴──────── VDD (pin 3)
GND  ───────────────────────── GND (pin 1)

The 4.7 kOhm resistor is mandatory. Without it the open-drain bus cannot return to logic high between slots and every bit reads back as 0.

DS18B20 is 5 V tolerant. If the target system runs at 5 V, replace the 3.3 V rail with 5 V. The FT4232H I/O is 3.3 V logic. The DS18B20 input threshold is well below that, so a 5 V pull-up with 3.3 V-driven TX still works correctly.

Run the scan on channel A:

iottack onewire scan --channel A --temp

Linux UDEV rule

Add the following rule so the FTDI device is accessible without root:

SUBSYSTEM=="usb", ATTR{idVendor}=="0403", MODE="0666"

Place it in /etc/udev/rules.d/99-ftdi.rules and run udevadm control --reload-rules.

Plugins

PluginCommandPurpose
scaniottack onewire scanEnumerate all 1-Wire device ROM codes on the bus and report family type and security relevance

Severity model

FindingSeverityRationale
DS2401 iButton (or DS1990A)LowUsed as physical-access credential; trivially cloneable
DS2431/DS28EC20 EEPROMMediumMay store configuration or key material
DS18B20/DS1822 temperatureInfoPresence noted; temperature data is not sensitive
Other known familyInfoDevice enumerated; assess per deployment
Unknown familyLowUnrecognized family byte warrants manual inspection

onewire scan

Enumerate all 1-Wire devices on the bus using the standard Maxim ROM Search algorithm and report each device’s ROM code, family name and security relevance.

Requirements

An FTDI adapter (FT232R, FT232H, FT2232H, or FT4232H) wired to the 1-Wire DQ line. See 1-Wire plugin intro for the TX and RX loopback circuit and the required UDEV rule.

Usage

iottack onewire scan [OPTIONS]

Description

The plugin opens the FTDI UART at 9600 baud to issue a 1-Wire reset pulse (sends 0xF0, reads echo. A device pulls the echo low to signal presence). It then switches to 115200 baud for bit-level communication:

  • writing 0xFF clocks a 1 (and reads the bus level back)
  • writing 0x00 clocks a 0

ROM Search runs the standard Maxim algorithm to discover all devices simultaneously. Each iteration resolves one bit-conflict until all 64-bit ROM codes have been read. Up to 20 devices per bus are reported. The 8-bit Dallas/Maxim CRC (polynomial 0x8C) is validated for every ROM code. Codes failing CRC are discarded.

For each device the plugin reports:

  • 64-bit ROM code in XX:XX:XX:XX:XX:XX:XX:XX format
  • Family name decoded from the first byte
  • Security-relevant severity if applicable

With --temp, any DS18B20 or DS1822 sensors are additionally queried:

  • the plugin sends MATCH ROM + CONVERT T
  • waits 750 ms for conversion
  • reads the 9-byte scratchpad and converts the raw value to degrees Celsius

Options

FlagShortDefaultDescription
--vid <HEX>-0403USB vendor ID in hex
--pid <HEX>-auto-detectUSB product ID in HEX (6001=FT232R, 6010=FT2232H, 6011=FT4232H, 6014=FT232H). Omit to probe all known PIDs
--channel <CHANNEL>-cAFTDI channel to use: A, B, C or D
--temp-offAlso read temperature from DS18B20/DS1822 sensors
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Device family table

Family byteDeviceNotes
0x01DS2401/DS1990A iButtonPhysical-access credential. Cloneable
0x10DS18S20High-precision thermometer
0x14DS2430A256-bit EEPROM
0x1DDS2423Dual counter/EEPROM
0x22DS1822Thermometer (+/-2 °C, cheaper DS18B20)
0x23DS24334 kbit EEPROM
0x28DS18B20Ubiquitous programmable thermometer
0x2DDS24311 kbit EEPROM
0x36DS2740Current accumulator
0x3ADS2413Dual-channel GPIO
0x42DS28EA00Thermometer & 2 GPIO
0x43DS28EC2020 kbit EEPROM

Example

$ iottack onewire scan --channel A --temp

Plugin name:    onewire/scan
Execution time: 1842 ms
Status:         pass

[INFO] 3 device(s) found on 1-Wire bus (channel A)
  ROM search complete. 3 device(s) enumerated, 0 CRC error(s).

[INFO] 1-Wire device: DS18B20 (28:FF:3A:91:7C:04:00:7E)
  Family 0x28 (DS18B20 Programmable Resolution Thermometer).
  Temperature: 23.44 °C
  Evidence: "rom=28:FF:3A:91:7C:04:00:7E family=0x28 (DS18B20) temp=23.44C"

[LOW] 1-Wire device: DS2401 iButton (01:A3:7E:12:00:00:00:4F)
  Family 0x01 (DS2401/DS1990A). Used as physical-access credential.
  The 48-bit serial number is trivially readable and cloneable.
  Evidence: "rom=01:A3:7E:12:00:00:00:4F family=0x01 (DS2401 iButton)"

[MEDIUM] 1-Wire device: DS2431 EEPROM (2D:08:C1:3F:00:00:00:12)
  Family 0x2D (DS2431 1 kbit EEPROM). May store configuration or key material.
  Evidence: "rom=2D:08:C1:3F:00:00:00:12 family=0x2D (DS2431 EEPROM)"

Troubleshooting

No devices found / no presence pulse

  • Confirm the 4.7 kOhm pull-up resistor is present between DQ and VCC.
  • Verify target power is on.
  • Check that TX and RX are both shorted to DQ (not just TX).
  • Try --channel B if channel A produces no result.

CRC errors

  • Check for marginal connections or long wire runs (increase pull-up strength or shorten bus).
  • A single bus with more than ~20 devices may need bus-master hardware instead of UART loopback.

FTDI device not found

  • Run lsusb and confirm the adapter appears (0403:6001, 0403:6014, etc.).
  • Apply the udev rule and reconnect.

Wrong temperature readings from DS18B20

  • The 750 ms conversion wait is mandatory at 12-bit resolution; do not reduce it.
  • Confirm VCC wiring (DS18B20 in parasite-power mode may require an external strong pull-up during conversion).

Plugins that require hardware

Some tests depends on dedicated hardware connected to the host/platform that is used.

PluginDescription
ftdiFTDI MPSSE adapter for I2C, SPI, JTAG, SWD and UART bridge
ftdi deviceEnumerate connected FTDI adapters and report chip details
ghostespGhostESP for BLE-related tasks
logic-analyser deviceList connected sigrok-supported logic analyzers with full details
logic-analyser captureCapture digital samples and analyze signal activity
mcp2221 deviceEnumerate connected MCP2221/MCP2221A adapters and report USB identity and capabilities
nrf52840Nordic nRF52840 dongle for IEEE 802.15.4 / Zigbee passive capture

FTDI MPSSE Adapter

FTDI USB-to-serial chips are used throughout iottack as a generic hardware bridge between the host and embedded targets. The FT232H, FT2232H and FT4232H all expose the MPSSE (Multi-Protocol Synchronous Serial Engine), which allows a single USB device to speak I2C, SPI, JTAG, SWD or plain UART depending on configuration.

Supported chips

ChipChannelsMPSSE channelsUSB PID
FT232R1-0x6001
FT232H11 (A)0x6014
FT2232H22 (A, B)0x6010
FT4232H42 (A, B)0x6011

All chips share vendor ID 0x0403. Only channels A and B have an MPSSE engine. Channels C and D on the FT4232H are UART/bit-bang only.

Test your FTDI device with Python:

nix-shell -p python3Packages.pyftdi
python
Python 3.14.7 (main, Aug  5 2026, 10:29:49) [GCC 16.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from pyftdi.ftdi import Ftdi
>>> Ftdi.show_devices()
Available interfaces:
  ftdi://ftdi:232h:1:1e/1  (Single RS232-HS)

Wiring

I2C

Adapter        Target
AD0      ->    SCL (plus 4.7 kOhm pull-up to VCC)
AD1+AD2  <->   SDA (AD1 and AD2 shorted. Plus 4.7 kOhm pull-up to VCC)
GND      <->   GND

AD1 is the write path and AD2 is the read path for SDA. Both pins must be shorted together because the FT4232H has no open-drain output mode.

SPI

Adapter       Target
AD0     ->    SCLK
AD1     ->    MOSI
AD2     <-    MISO
AD3     ->    CS# (active low)
GND     <->   GND

JTAG

Adapter       Target
AD0     ->    TCK
AD1     ->    TDI
AD2     <-    TDO
AD3     ->    TMS
AD7     ->    nSRST (optional)
GND     <->   GND

SWD

Adapter        Target
AD0      ->    SWCLK
AD1+AD2  <->   SWDIO (220-470 Ohm on AD1 -> SWDIO prevents contention)
AD4      ->    nRESET (optional)
GND      <->   GND

Linux setup (udev)

Without a udev rule the kernel will not grant regular users access to the USB device. Add the following rule once:

echo 'SUBSYSTEM=="usb", ATTR{idVendor}=="0403", MODE="0666"' \
  | sudo tee /etc/udev/rules.d/99-ftdi.rules
sudo udevadm control --reload
sudo udevadm trigger

Reconnect the adapter after reloading.

Clock frequencies

ModeTypicalMaximum
I2C standard100 kHz100 kHz
I2C fast400 kHz400 kHz
SPI1 MHz30 MHz
JTAG1-10 MHz30 MHz

ftdi device

Enumerate all FTDI USB adapters connected to this host and report their chip type, chip ID, EEPROM strings and MPSSE capability.

Usage

iottack ftdi device

Description

Probes the five most common FTDI USB product IDs (0x6001, 0x6010, 0x6011, 0x6014, 0x6015) and for each adapter found reports:

FieldDescription
USBVendor ID and product ID
ChipChip family name
Chip IDUnique 32-bit identifier burned into the chip (hex)
ManufacturerEEPROM manufacturer string
ProductEEPROM product string
SerialEEPROM serial number string
MPSSEChannels with MPSSE engines and their maximum clock

If no adapter is detected the plugin reports an info finding with udev setup instructions.

Options

This plugin has no plugin-specific options.

FlagShortDescription
--output <FILE>-oSave result to a file
--format <FORMAT>-ftext or json
--verbose-vIncrease log verbosity

Example

$ iottack ftdi device

Plugin name:    ftdi/device
Execution time: 45 ms
Status:         pass

[INFO] 1 FTDI adapter(s) detected
  Use 'iottack i2c scan' or 'iottack i2c read' for I2C operations.

[INFO] FT4232H — USB-COM485 Plus4
  USB:          0403:6011
  Chip:         FT4232H
  Chip ID:      0a1b2c3d
  Manufacturer: FTDI
  Product:      USB-COM485 Plus4
  Serial:       FT12345
  MPSSE:        A, B (30 MHz Hi-Speed); C, D UART only

Linux setup (udev)

Without a UDEV rule normal users cannot open the USB device. See the FTDI adapter setup page for instructions.

ghostesp device

GhostESP is an ESP32-based wireless security tool capable of Bluetooth and Wi-Fi scanning, deauthentication and credential harvesting. Its presence on a network or in a facility is itself a security finding.

Requirements

An ESP32 that runs GhostESP. Keep an eye the type of ESP32 that you are going to use, not all variants have support for Bluetooth.

Plugin description

Opens a serial connection to a GhostESP device, sends a newline to wake the interactive shell and waits for the ghost> prompt. Once the prompt is confirmed, the plugin runs two commands:

  • chipinfo: retrieves ESP32 chip identity, revision, and flash size.
  • devices: lists enabled hardware peripherals (GPS, RGB LED, SD card, etc.) and their configuration.

Findings are classified as follows:

FindingSeverityCondition
GhostESP device detectedHighghost> prompt found on port
GhostESP chip informationInfochipinfo returned output
Enabled peripheralsInfodevices returned peripheral list
Prompt not found / port errorInfoDevice absent or wrong firmware

Usage

iottack ghostesp device --port <PORT> [OPTIONS]

Options

FlagShortDefaultDescription
--port <PORT>-p(required)Serial port, e.g., /dev/ttyACM0
--baud-rate <BAUD>-b115200Serial baud rate
--timeout-ms <MS>-t5000Per-command response timeout in ms
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack ghostesp device --port /dev/ttyACM1

Plugin name:    ghostesp/device
Execution time: 1.23 s
Status:         pass

[INFO] GhostESP chip information
  ESP32-D0WD-V3 rev 3, 4 MB flash, single core

[INFO] 3 enabled peripheral(s) on GhostESP device
  Enabled devices:
    GPS: default pin [idle]
    RGB: data GPIO0, 0 LEDs
    SD Card: SPI (CS GPIO4) [not mounted]

ghostesp bledetect

Detects BLE trackers, skimmers and beacons near a GhostESP device by matching advertisement signatures against a built-in database. Each discovered device is reported as a finding with severity scaled by type.

Requirements

An ESP32 that runs GhostESP. Not all ESP32 variants support Bluetooth — check your board’s specifications before use.

Plugin description

Opens a serial connection to a GhostESP device, waits for the ghost> prompt, then starts bledetect to scan for known device signatures in the background. After the configured duration the plugin queries:

  • bledetect -l: structured list of discovered devices (type, name/MAC, RSSI)
  • bledetect -i: scan state and device count

The scan is then stopped with bledetect -s and findings are reported.

Findings are classified as follows:

FindingSeverityCondition
Skimmer detectedHighDevice type contains “skimmer”
Tracker / AirTag detectedMediumDevice type contains “tracker”, “airtag” or “tile”
Beacon detectedLowDevice type contains “beacon”
Other BLE deviceInfoAny other signature match
No devices detectedInfoScan returned empty list
BLE detect scan stateInfoOutput of bledetect -i
Prompt not found / port errorInfoDevice absent or wrong firmware

Usage

iottack ghostesp bledetect --port <PORT> [OPTIONS]

Options

FlagShortDefaultDescription
--port <PORT>-p(required)Serial port, e.g. /dev/ttyACM0
--duration <SECS>-d15Scan duration in seconds before querying results
--baud-rate <BAUD>-b115200Serial baud rate
--timeout-ms <MS>-t5000Prompt wait timeout in ms
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity

Example

$ iottack ghostesp bledetect --port /dev/ttyACM1 --duration 30

Plugin name:    ghostesp/bledetect
Execution time: 30.58 s
Status:         pass

[INFO] BLE detect scan state
  Scan: running | Devices found: 3 | Tracking: none

[HIGH] Suspicious BLE device detected: [1] Skimmer AA:BB:CC:11:22:33 RSSI: -68 dBm
  [1] Skimmer AA:BB:CC:11:22:33 RSSI: -68 dBm

[MEDIUM] Suspicious BLE device detected: [2] AirTag "John's bag" DD:EE:FF:44:55:66 RSSI: -72 dBm
  [2] AirTag "John's bag" DD:EE:FF:44:55:66 RSSI: -72 dBm

[LOW] BLE device detected: [3] Beacon 11:22:33:AA:BB:CC RSSI: -80 dBm
  [3] Beacon 11:22:33:AA:BB:CC RSSI: -80 dBm

ghostesp blescan

Starts a BLE scan on a GhostESP device in one of eight modes, collects observations for a configurable duration, stops the scan and reports everything as structured findings.

Requirements

An ESP32 that runs GhostESP. Not all ESP32 variants support Bluetooth — check your board’s specifications before use.

Scan modes

ModeGhostESP flagDescription
flipper-fDetect Flipper Zero devices nearby
spam-detector-dsDetect active BLE advertisement spam
airtag-aScan for Apple AirTags
advertiser-advParsed BLE advertiser scan (default)
oui-oui <prefix>Filter advertisers by OUI prefix
vendor-vendor <name>Filter advertisers by vendor name
gatt-gScan connectable GATT devices
raw-rRaw BLE packet capture

Plugin description

Opens a serial connection to a GhostESP device, waits for the ghost> prompt, then starts a BLE scan in the chosen mode. After the configured duration the scan is stopped with blescan -s and all observed output is reported as findings.

Findings are classified as follows:

FindingSeverityCondition
N BLE observationsInfoOne or more devices detected
No BLE devices detectedInfoScan returned no output
Prompt not found / port errorInfoDevice absent or wrong firmware

Usage

iottack ghostesp blescan --port <PORT> [OPTIONS]

Options

FlagShortDefaultDescription
--port <PORT>-p(required)Serial port, e.g. /dev/ttyACM0
--mode <MODE>-madvertiserScan mode (see table above)
--filter <VALUE>--OUI prefix or vendor name (required for oui/vendor modes)
--duration <SECS>-d10Scan duration in seconds
--baud-rate <BAUD>-b115200Serial baud rate
--timeout-ms <MS>-t5000Prompt wait timeout in ms
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity

Examples

$ iottack ghostesp blescan --port /dev/ttyACM1 --mode advertiser --duration 15

Plugin name:    ghostesp/blescan
Execution time: 15.42 s
Status:         pass

[INFO] 4 BLE observation(s) — advertiser mode
  [ADV] AA:BB:CC:11:22:33 (Apple, Inc.) RSSI: -62 dBm
  [ADV] DD:EE:FF:44:55:66 (Samsung Electronics) RSSI: -74 dBm
  [ADV] 11:22:33:AA:BB:CC (Unknown) RSSI: -81 dBm
  [ADV] 44:55:66:DD:EE:FF (Google) RSSI: -69 dBm
$ iottack ghostesp blescan --port /dev/ttyACM1 --mode flipper --duration 10

Plugin name:    ghostesp/blescan
Execution time: 10.38 s
Status:         pass

[INFO] 1 BLE observation(s) — flipper mode
  [FLIPPER] AA:BB:CC:DD:EE:FF "xXx_FlipperZero_xXx" RSSI: -55 dBm
$ iottack ghostesp blescan --port /dev/ttyACM1 --mode vendor --filter Apple --duration 20

Plugin name:    ghostesp/blescan
Execution time: 20.15 s
Status:         pass

[INFO] 2 BLE observation(s) — vendor mode
  [ADV] AA:BB:CC:11:22:33 (Apple, Inc.) RSSI: -62 dBm
  [ADV] 44:55:66:DD:EE:FF (Apple, Inc.) RSSI: -70 dBm

logic-analyser device

List all sigrok-supported logic analyzers currently connected to the host, together with their full details: vendor, model, firmware version, serial number, connection ID, driver name, and the complete channel list.

Requirements

Same as logic-analyser capture. The libsigrok system library must be installed and the user must have access to USB/serial devices.

Plugin description

The plugin initialises a libsigrok context, iterates every registered driver, and returns one Info finding per discovered device. Each finding includes:

  • Vendor, model, firmware version
  • Serial number and connection ID
  • Driver short name and long name
  • Number of channels and their names (disabled channels are marked)

No hardware interaction beyond device scanning takes place. The device is not opened and no samples are captured.

Usage

iottack logic-analyser device

Example output

One device found

$ iottack logic-analyser device

Plugin name:    logic-analyser/device
Execution time: 284 ms
Status:         pass

[INFO] 1 logic analyzer(s) detected
  Use 'iottack logic-analyser capture --driver <DRIVER>' to start a capture.

[INFO] ACME Logic Pro (driver: fx2lafw)
  Driver:     fx2lafw (Cypress FX2 USB hardware logic analyzer)
  Vendor:     ACME
  Model:      Logic Pro
  Version:    1.02
  Serial:     00A1B2C3
  Connection: 1.7
  Channels:   8 — D0, D1, D2, D3, D4, D5, D6, D7

No devices found

$ iottack logic-analyser device

Plugin name:    logic-analyser/device
Execution time: 112 ms
Status:         pass

[INFO] No sigrok-supported logic analyzers found
  No devices were detected. Connect a supported logic analyzer and retry,
  or use 'iottack logic-analyser capture --driver demo' to test with a
  simulated device.

Notes

  • The demo driver always appears because it requires no hardware. Use iottack logic-analyser capture --driver demo to test the capture plugin without a physical device.
  • Disabled channels are listed with a (disabled) suffix. A channel may be disabled if the device was previously configured and the driver preserved that state.
  • To capture samples from a listed device pass its driver name to iottack logic-analyser capture --driver <DRIVER>.

logic-analyser capture

A logic analyzer passively samples digital signals at a configurable rate and reports which channels carry active traffic. This is useful for detecting live debug interfaces (JTAG, SWD, SPI, I2C) on a target device that should have been disabled before shipping.

Requirements

A sigrok-supported logic analyzer connected to the host.

Common supported devices include:

  • Demo driver (demo): simulated device, no hardware needed; useful for testing the plugin itself.
  • FX2-based analyzers (fx2lafw): cheap 8-channel USB analyzers based on the Cypress FX2 chip (clone Salae Logic, USBee, etc.).
  • Saleae Logic (saleae-logic, saleae-logic16)
  • Rigol DS1000Z (rigol-ds)
  • Any other device supported by libsigrok. Run the plugin without --driver to discover what is attached.

The libsigrok and libsigrokdecode system libraries must be installed. On NixOS the flake.nix already pulls them in; on Debian/Ubuntu:

sudo apt install libsigrok-dev libsigrokdecode-dev

It might be required that UDEV rules are present. E.g, for NixOS:

{
  services.udev = {
    enable = true;
    packages = [ pkgs.libsigrok ];
  };
}

Plugin description

Without --driver the plugin initializes a libsigrok context, iterates every registered driver, and returns one Info finding per discovered device listing its vendor, model, firmware version, serial number, and driver name.

With --driver the plugin opens a capture session, sets the requested sample rate, acquires the requested number of samples, then analyses the raw byte buffer:

  • Each byte represents one sample unit. For ≤ 8 active channels sigrok packs one channel per bit, so a non-zero byte means at least one channel was high during that sample period.
  • The plugin reports one aggregate finding covering all monitored channels, then one individual finding per active channel showing its exact activity percentage and sample counts. When --channels is supplied only those channels appear in the per-channel findings; all other bits are ignored.
  • Severity scales with the percentage of active samples:
Active samplesSeverity
< 10 %Low
10 -49 %Medium
≥ 50 %High

An additional Medium finding is raised whenever ≥ 5 % of samples are active, flagging the possibility of a live debug bus.

Usage

# Scan for connected devices
iottack logic-analyser capture

# Capture 1000 samples from the demo driver at 1 MHz (all channels)
iottack logic-analyser capture --driver demo

# Monitor a single channel
iottack logic-analyser capture --driver fx2lafw --channels D0

# Monitor a comma-separated list
iottack logic-analyser capture --driver fx2lafw --channels D0,D2,D4

# Monitor a range (D0 through D3 inclusive)
iottack logic-analyser capture --driver fx2lafw --channels D0-D3

# Mix ranges and individual channels
iottack logic-analyser capture --driver fx2lafw --channels D0-D2,D7

# Capture from an FX2-based analyzer at 4 MHz and save a raw binary dump
iottack logic-analyser capture --driver fx2lafw --samplerate 4000000 --dump-file capture.bin

# Capture 5000 samples, increase verbosity
iottack logic-analyser capture --driver fx2lafw --samples 5000 -v

Options

FlagShortDefaultDescription
--driver <DRIVER>-d(empty -> scan)sigrok driver name (e.g. demo, fx2lafw). Omit to list connected devices.
--samples <COUNT>-n1000Number of samples to capture
--samplerate <HZ>-r1000000Sample rate in Hz (1 MHz)
--channels <CHANNELS>-c(all)Channels to monitor: D0, D0,D2,D4, D0-D3 or mixed D0-D2,D7. Omit for all channels.
--dump-file <FILE>-w(none)Save a raw binary capture dump to this path
--output <FILE>-o-Save plugin result (findings) to a file
--format <FORMAT>-ftextOutput format: text or json
--verbose-v-Increase log verbosity

Examples

Scan for devices

$ iottack logic-analyser capture

Plugin name:    logic-analyser/capture
Execution time: 342 ms
Status:         pass

[INFO] 1 logic analyzer(s) detected
  Pass --driver <DRIVER> with one of the driver names below to start a capture.

[INFO] VENDOR Model (driver: fx2lafw)
  Version: 1.0  Serial: 0001  Connection: 1.42
  Evidence: "vendor=VENDOR, model=Model, version=1.0, serial=0001, connection=1.42, driver=fx2lafw"

Capture with demo driver (no hardware required)

$ iottack logic-analyser capture --driver demo --samples 200

Plugin name:    logic-analyser/capture
Execution time: 1.21 s
Status:         pass

[HIGH] Signal activity on 8 channel(s): D0, D1, D2, D3, D4, D5, D6, D7
  Monitored: all channels. 200 of 200 samples (100%) showed at least one
  high channel over a 200 µs window at 1000000 Hz. Idle samples: 0.
  Active channels: D0, D1, D2, D3, D4, D5, D6, D7.

[HIGH] D0: 100% active (200/200 samples)
  Channel D0 was high in 200 of 200 samples (100%) over 200 µs at 1000000 Hz.
  Idle samples: 0.

[HIGH] D1: 100% active (200/200 samples)
  Channel D1 was high in 200 of 200 samples (100%) over 200 µs at 1000000 Hz.
  Idle samples: 0.

... (one finding per active channel) ...

[MEDIUM] Sustained bus activity — possible debug interface
  100% of samples were active. Sustained traffic on D0, D1, D2, D3, D4,
  D5, D6, D7 may indicate a live JTAG, SWD, SPI or I2C interface. Confirm
  that debug ports are intentionally exposed and access is properly controlled.

Capture with a channel filter

Only the requested channels appear in the per-channel findings.

$ iottack logic-analyser capture --driver fx2lafw --channels D0,D2 --samples 500

Plugin name:    logic-analyser/capture
Execution time: 512 ms
Status:         pass

[LOW] Signal activity on 2 channel(s): D0, D2
  Monitored: D0, D2. 45 of 500 samples (9%) showed at least one high
  channel over a 500 µs window at 1000000 Hz. Idle samples: 455.
  Active channels: D0, D2.

[LOW] D0: 8% active (40/500 samples)
  Channel D0 was high in 40 of 500 samples (8%) over 500 µs at 1000000 Hz.
  Idle samples: 460.

[LOW] D2: 1% active (5/500 samples)
  Channel D2 was high in 5 of 500 samples (1%) over 500 µs at 1000000 Hz.
  Idle samples: 495.

All channels idle

$ iottack logic-analyser capture --driver fx2lafw --samples 1000

Plugin name:    logic-analyser/capture
Execution time: 1.05 s
Status:         pass

[INFO] All channels idle during capture
  Captured 1000 samples (1000 µs at 1000000 Hz) - all monitored channel
  bits were low for the entire window. Monitored: all channels.

Notes

  • The libsigrok-sys crate and the linked libsigrok C library are both licensed GPL-3.0-or-later. Review license compatibility if you redistribute a build that includes this plugin.
  • USB access to logic analyzers typically requires the user to be in the plugdev group or a matching udev rule to be in place. On most Linux distributions, install the sigrok package to get the udev rules automatically.
  • The demo driver generates a repeating test pattern across all 8 channels. All channels will appear active, which is expected.
  • For protocol-level decoding (SPI, I2C, JTAG) use the --dump-file flag to save a capture and then process it with sigrok-cli --protocol-decoder.

MCP2221 / MCP2221A

The Microchip MCP2221/MCP2221A is a USB Full Speed to I2C and UART protocol converter. It enumerates as a USB HID device (no kernel driver required on Linux, macOS or Windows) and exposes an I2C master, a UART bridge, four GPIO pins, three ADC channels and one DAC channel over a single USB connection.

The MCP2221A is the current production variant. It is electrically identical to the original MCP2221 and uses the same USB VID/PID.

USB identifiers

FieldValue
Vendor ID0x04D8 (Microchip Technology)
Product ID0x00DD
USB classHID (03h)
SpeedFull Speed (12 Mbps)

Pin functions

The MCP2221A has four general-purpose pins, GP0-GP3, each configurable as GPIO or as a dedicated peripheral function:

PinGPIOAlternate function
GP0GP0SSPND (USB suspend indicator)/LED UART RX
GP1GP1Clock output/ADC1/Interrupt (edge)/LED UART TX
GP2GP2ADC2/DAC1/USB configured indicator
GP3GP3ADC3/DAC2/LED I2C traffic

SCL and SDA are dedicated I2C pins and are not shared with the GP pins.

Wiring

I2C

MCP2221A      Target
SCL    ->     SCL  (4.7 kOhm pull-up to VCC)
SDA    <->    SDA  (4.7 kOhm pull-up to VCC)
GND    <->    GND
VCC    ->     VCC  (3.3 V or 5 V depending on target)

The MCP2221A I2C pins are open-drain. External pull-up resistors are required. Use 4.7 kOhm for 100 kHz (standard mode) and 2.2 kOhm for 400 kHz (fast mode).

UART

MCP2221A      Target
TX     ->     RX
RX     <-     TX
GND    <->    GND

The UART bridge appears as a standard CDC-ACM serial port (/dev/ttyACM* on Linux). No additional kernel module is needed.

Electrical characteristics

ParameterValue
Supply voltage3.0 V - 5.5 V
I/O voltage3.0 V - 5.5 V (not 5V-tolerant on 3.3 V boards)
I2C speed (standard)100 kHz
I2C speed (fast)400 kHz
UART baud rateUp to 115200 baud (USB Full Speed limited)
ADC resolution10-bit (0-VDD or 0-1024 V/2048 V/4096 V ref)
DAC resolution5-bit (0-VDD or 0-1024 V/2048 V/4096 V ref)
GPIO current+/-25 mA per pin, 100 mA total

Linux setup (udev)

The MCP2221A enumerates as a USB HID device. Access to both the raw USB interface and the HID node requires a udev rule.

Standard Linux

echo 'SUBSYSTEM=="usb", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="00dd", MODE="0666"
SUBSYSTEM=="hidraw", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="00dd", MODE="0666"' \
  | sudo tee /etc/udev/rules.d/99-mcp2221.rules
sudo udevadm control --reload-rules
sudo udevadm trigger

Reconnect the adapter after reloading.

NixOS

Add to your NixOS configuration and rebuild:

services.udev.extraRules = ''
  SUBSYSTEM=="usb", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="00dd", MODE="0666", GROUP="plugdev"
  SUBSYSTEM=="hidraw", ATTRS{idVendor}=="04d8", ATTRS{idProduct}=="00dd", MODE="0666", GROUP="plugdev"
'';

The USB rule covers raw USB enumeration; the HID rule covers /dev/hidrawN access needed for I2C, GPIO, ADC, and DAC operations.

Verifying the setup

# Confirm the kernel sees the device
lsusb | grep 04d8:00dd

# Check HID node permissions (should show crw-rw-rw-)
ls -la /dev/hidraw*

# Enumerate with iottack
iottack mcp2221 device

Plugins

PluginCommandPurpose
mcp2221 deviceiottack mcp2221 deviceEnumerate connected MCP2221/MCP2221A adapters and report USB identity and capabilities
i2c scaniottack i2c scan --adapter mcp2221Scan all 112 valid 7-bit I2C addresses (0x08–0x77) and report responding devices

mcp2221 device

Enumerate all MCP2221/MCP2221A adapters connected to this host and report their USB identity and capabilities.

Usage

iottack mcp2221 device

Description

Scans for USB devices with Microchip VID 0x04D8 and PID 0x00DD and for each adapter found reports:

FieldDescription
USBVendor ID and product ID
ManufacturerUSB manufacturer string
ProductUSB product string
SerialUSB serial number string
InterfacesFixed capability summary (I2C, UART, GPIO, ADC, DAC)

If no adapter is detected the plugin reports an info finding with udev setup instructions.

Options

This plugin has no plugin-specific options.

FlagShortDescription
--output <FILE>-oSave result to a file
--format <FORMAT>-ftext or json
--verbose-vIncrease log verbosity

Example

$ iottack mcp2221 device

Plugin name:    mcp2221/device
Execution time: 3 ms
Status:         pass

[INFO] 1 MCP2221/MCP2221A adapter(s) detected
  The MCP2221A provides a USB-to-I2C bridge (up to 400 kHz), a USB-to-UART bridge,
  4x GPIO, 3x 10-bit ADC and 1x 5-bit DAC.

[INFO] MCP2221 USB-I2C/UART Combo — 0001234567
  USB:          04d8:00dd
  Manufacturer: Microchip Technology Inc.
  Product:      MCP2221 USB-I2C/UART Combo
  Serial:       0001234567
  Interfaces:   USB-I2C (up to 400 kHz), USB-UART, 4x GPIO, 3x ADC, 1x DAC

Linux setup (udev)

Without a udev rule normal users cannot access the HID device. See the MCP2221 adapter setup page for instructions.

nRF52840 Dongle

The Nordic Semiconductor nRF52840 USB dongle, running the nRF Sniffer for 802.15.4 firmware, is used by the zigbee sniffer and zigbee capture plugins as a passive IEEE 802.15.4 receiver.

USB identifiers

All variants share vendor ID 0x1915 (Nordic Semiconductor ASA). iottack auto-detects the dongle by VID/PID via Linux sysfs. Use --port to override when multiple dongles are connected.

PIDMode
0x520FApplication (sniffer) mode
0xCA37DFU bootloader mode
0x154AnRF52 USB Product (generic)
0x154BnRF Sniffer for 802.15.4 official firmware

Flashing the firmware

Download the pre-built firmware package from the nRF Sniffer for 802.15.4 releases page and follow Nordic’s flashing guide. The dongle ships in bootloader mode (PID 0xCA37). After flashing it switches to application mode (PID 0x520F or 0x154B).

Linux setup

The dongle uses USB CDC-ACM and appears as /dev/ttyACM* without additional drivers. Grant unprivileged access by adding the user to the dialout group:

sudo usermod -aG dialout $USER

Log out and back in for the change to take effect. Alternatively, install a udev rule so any user can open the device:

echo 'SUBSYSTEM=="tty", ATTRS{idVendor}=="1915", MODE="0666"' \
  | sudo tee /etc/udev/rules.d/99-nrf52840.rules
sudo udevadm control --reload
sudo udevadm trigger

Plugins

PluginCommandPurpose
zigbee snifferiottack zigbee snifferPassive 802.15.4 frame capture with MAC-layer security analysis
zigbee captureiottack zigbee captureCapture raw 802.15.4 frames to a PCAP file for Wireshark

Zigbee plugins

Zigbee is an IEEE 802.15.4-based wireless mesh protocol widely used in smart home, building automation and industrial IoT devices. It operates in the 2.4 GHz ISM band across 16 channels (11-26) and is defined by the Zigbee Alliance (now CSA).

Hardware

Both Zigbee plugins require a Nordic Semiconductor nRF52840 USB dongle running the nRF Sniffer for 802.15.4 firmware.

Recognized USB VID/PIDs (VID 0x1915, Nordic Semiconductor ASA):

PIDMode
0x520FnRF52840 Dongle - application (sniffer) mode
0xCA37nRF52840 Dongle - DFU bootloader mode
0x154AnRF52 USB Product (generic)
0x154BnRF Sniffer for 802.15.4 official firmware

The dongle is detected automatically by USB VID/PID via Linux sysfs. Use --port to override auto-detection when multiple dongles are present.

Plugins

PluginCommandPurpose
snifferiottack zigbee snifferPassive 802.15.4 frame capture with MAC-layer security analysis
captureiottack zigbee captureCapture raw 802.15.4 frames to a PCAP file for Wireshark

zigbee sniffer

Passively capture IEEE 802.15.4/Zigbee frames via an nRF52840 sniffer dongle and report MAC-layer security weaknesses.

Usage

iottack zigbee sniffer [OPTIONS]

Description

Uses a Nordic Semiconductor nRF52840 USB dongle running the nRF Sniffer for 802.15.4 firmware to passively capture IEEE 802.15.4 MAC frames. The dongle is auto-detected by USB VID/PID (VID 0x1915) via Linux sysfs. The firmware exposes a simple line-oriented shell over USB CDC-ACM; the plugin sends channel N and receive commands and parses the received: HEX power: RSSI lqi: LQI time: TS output lines.

Captured frames are parsed and analyzed for the following weaknesses:

CheckFindingSeverity
Data frames without MAC Security Enabled bitUnencrypted trafficHigh
MAC association requests observedDevice join in progressMedium
PAN ID is 0x1234Factory-default PAN IDHigh
PAN ID is 0xFFFFBroadcast PAN ID in useMedium

Frame statistics are reported per channel: frame count, beacons, encrypted and plaintext data frames, association events and unique PAN IDs observed.

Note: This plugin captures at the MAC layer only. Zigbee NWK-layer encryption (AES-128 CCM*) is not decrypted. The absence of MAC-layer security (the Security Enabled bit in the Frame Control Word) is flagged, but NWK-layer encrypted frames still appear as secure here even if the network key is weak.

Options

FlagShortDefaultDescription
--port <PORT>-p(auto-detect)Serial port of the nRF52840 dongle (e.g., /dev/ttyACM0)
--channel <CH>-c15IEEE 802.15.4 channel to sniff (11-26). Ignored when --scan-all is set
--scan-all-a-Sniff all 16 Zigbee channels (11-26) sequentially, spending duration-ms/16 on each
--duration-ms <MS>-d5000Total capture duration in milliseconds
--timeout-ms <MS>-t200Per-read serial timeout. Controls how quickly the loop reacts between frames
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json

Examples

Auto-detect dongle and sniff channel 15 for 5 seconds:

iottack zigbee sniffer

Sniff all 16 channels for 30 seconds (about 1.9 s per channel):

iottack zigbee sniffer --scan-all --duration-ms 30000

Target a specific port and channel:

iottack zigbee sniffer --port /dev/ttyACM0 --channel 20 --duration-ms 10000

zigbee capture

Capture raw IEEE 802.15.4/Zigbee frames to a PCAP file for analysis in Wireshark or as summary to the CLI.

Usage

iottack zigbee capture [OPTIONS]

Description

The captured file can be opened in Wireshark during or after the capture. Wireshark refreshes automatically on new packets. Full 802.15.4 and Zigbee dissection is available out of the box. Network keys for decryption can be added under Edit -> Preferences -> Protocols -> IEEE 802.15.4 -> Decryption Keys.

Timestamps use the sniffer’s own microsecond clock (the time: field in each output line), anchored to the host wall clock on the first received frame.

The 2-byte FCS appended by the firmware is stripped before writing, producing clean DLT_IEEE802_15_4_NOFCS records that Wireshark expects.

Options

FlagShortDefaultDescription
--port <PORT>-p(auto-detect)Serial port of the nRF52840 dongle (e.g., /dev/ttyACM0)
--channel <CH>-c15IEEE 802.15.4 channel to capture (11-26). Ignored when --scan-all is set
--scan-all-a-Capture on all 16 Zigbee channels (11-26) sequentially, spending duration-ms/16 on each
--duration-ms <MS>-d30000Total capture duration in milliseconds
--timeout-ms <MS>-t200Per-read serial timeout (ms)
--pcap <FILE>-Pzigbee_capture.pcapOutput PCAP file path
--table-T-Show all captured frames as an ASCII table instead of one finding per frame
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json

Examples

Capture channel 15 for 30 seconds to the default file:

iottack zigbee capture

Open Wireshark on the output file immediately so it follows the live capture:

iottack zigbee capture &
wireshark zigbee_capture.pcap

Scan all 16 channels for 60 seconds and save to a named file:

iottack zigbee capture --scan-all --duration-ms 60000 --pcap network.pcap

Show a summary table of all captured frames:

iottack zigbee capture --channel 11 --duration-ms 10000 --table

Wireshark decryption

To decrypt Zigbee NWK-layer traffic in Wireshark:

  1. Open Edit -> Preferences -> Protocols -> IEEE 802.15.4
  2. Under Decryption Keys, click Edit and add the network key
  3. Wireshark will automatically decrypt frames that match the key

The network key can often be recovered by capturing a device join with iottack zigbee sniffer --scan-all and looking for the Network Key Transport frame during the Trust Centre join procedure.

CAN bus plugins

CAN (Controller Area Network) is a robust serial bus protocol developed by Bosch in 1986. It is the dominant communication standard in automotive electronics and is widely deployed in industrial automation, medical devices, aerospace systems and building controls.

The protocol was designed for reliability in electrically noisy environments. It has no built-in authentication, encryption, or access control. Any node connected to the bus can read all traffic and inject arbitrary frames without restriction.

Frame formats

CAN supports two frame formats distinguished by the identifier length:

FormatID bitsRangeCommon use
SFF (Standard Frame Format)11 bits0x000-0x7FFCANopen, OBD-II
EFF (Extended Frame Format)29 bits0x00000000-0x1FFFFFFFJ1939, proprietary

Common higher-layer protocols

ProtocolID rangeDomain
CANopen0x001-0x77F (SFF)Industrial automation, medical
OBD-II (ISO 15765-4)0x7DF, 0x7E0-0x7EF (SFF)Automotive diagnostics
J1939EFF, PGN-encodedHeavy vehicles (trucks, buses)
CANaerospaceSFFAvionics

Setup

All CAN plugins require a Linux SocketCAN interface. Bring one up before running any plugin. Make can-utils available on your system.

USB CAN adapters using the gs_usb kernel module (CANable, CANtact, PEAK PCAN-USB in GS-USB mode):

sudo ip link set can0 up type can bitrate 500000

SLCAN-based adapters (older USB-to-CAN bridges):

sudo slcand -o -c -s6 /dev/ttyACM0 can0
sudo ip link set can0 up

Virtual CAN (for local testing or replay):

sudo modprobe vcan
sudo ip link add dev vcan0 type vcan
sudo ip link set vcan0 up

To verify the interface is up:

ip link show type can
18: can0: <NOARP,UP,LOWER_UP> mtu 16 qdisc pfifo_fast state UP mode DEFAULT group default qlen 10
    link/can

Plugins

PluginCommandMode
dumpiottack can dumpPassive capture and traffic analysis
scaniottack can scanPassive ID enumeration
sendiottack can sendActive: transmit arbitrary frames
enumerateiottack can enumerateActive device discovery (OBD-II & CANopen)

Severity model

SeverityCondition
HighOBD-II diagnostic IDs observed or responding (0x7DF, 0x7E0-0x7EF)
HighCANopen node found and device type identified via SDO
MediumCANopen node found (heartbeat or node guarding)
MediumCANopen SDO, PDO, or NMT management IDs observed
LowCAN error frames detected
InfoGeneral traffic statistics, no active traffic, or interface error

can dump

Passively captures CAN frames from a SocketCAN interface and reports traffic statistics, the most active IDs, and any security-relevant IDs.

Status

ResultMeaning
passCapture completed (even if no frames were received)
failInterface could not be opened

Severity classification

SeverityCondition
HighOBD-II diagnostic IDs present (0x7DF, 0x7E0-0x7EF)
MediumCANopen SDO/NMT/PDO IDs present
LowCAN error frames detected
InfoTraffic summary, top IDs, no traffic, or read error

Usage

iottack can dump [OPTIONS]

Options

FlagShortDefaultDescription
--iface <IFACE>-ican0SocketCAN interface name
--duration <SECS>-d10Capture duration in seconds
--max-frames <N>-10000Stop early after capturing this many frames
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Description

The plugin opens the specified SocketCAN interface in read-only mode (no frames are transmitted) and collects frames for the configured duration or until --max-frames is reached.

After capture it reports:

  • Traffic summary: total frame count, unique ID count, frame rate, error frame count.
  • Top 10 IDs by volume: the most active IDs with their frame count, DLC and last observed payload.
  • Notable IDs: any ID matching a known protocol range (CANopen, OBD-II) is reported as a separate finding at an elevated severity.

Error frames (bus-off, bit errors, CRC errors) are counted separately and reported at Low severity because they may indicate a bit-rate mismatch, wiring fault or active fault injection.

ID classification

ID rangeProtocolSeverity
0x000CANopen NMT masterMedium
0x001 - 0x07FCANopen SYNC/timestampMedium
0x080 - 0x0FFCANopen EMCY (emergency)Medium
0x100 - 0x4FFCANopen PDOMedium
0x580 - 0x5FFCANopen SDO server responseMedium
0x600 - 0x67FCANopen SDO client requestMedium
0x700 - 0x77FCANopen NMT heartbeatMedium
0x7DFOBD-II functional broadcastHigh
0x7E0 - 0x7E7OBD-II physical request to ECUHigh
0x7E8 - 0x7EFOBD-II response from ECUHigh

Examples

Default 10-second capture on can0:

iottack can dump

Longer capture on a custom interface:

iottack can dump --iface vcan0 --duration 60

Save to JSON for further processing:

iottack can dump --duration 30 --format json --output can-dump.json

Example output

Plugin name:    can/dump
Execution time: 10.01 s
Status:         pass

[INFO] can0: 4823 frame(s), 7 unique ID(s) in 10.0s (482.1 fps)
  Data frames: 4823
  Frame rate: 482.1/s
  Unique IDs: 7
  Error frames: 0

[INFO] Top 7 CAN ID(s) by volume on can0
  181h  count=1621   dlc=8  last=[00 00 00 00 E8 03 00 00]
  280h  count=1203   dlc=8  last=[7F 00 00 00 FF 1F 00 00]
  380h  count=802    dlc=8  last=[00 00 00 00 00 00 00 00]
  701h  count=401    dlc=1  last=[05]
  702h  count=401    dlc=1  last=[05]
  7DFh  count=200    dlc=3  last=[02 01 00]
  7E8h  count=195    dlc=6  last=[06 41 00 BE 1F A8 13]

[MEDIUM] Notable CAN ID 701h: CANopen: NMT heartbeat/node guarding
  ID 701h seen 401 time(s). Last frame: dlc=1 data=[05]

[MEDIUM] Notable CAN ID 702h: CANopen: NMT heartbeat/node guarding
  ID 702h seen 401 time(s). Last frame: dlc=1 data=[05]

[HIGH] Notable CAN ID 7DFh: OBD-II: diagnostic broadcast - exposes vehicle diagnostics (ISO 15765-4)
  ID 7DFh seen 200 time(s). Last frame: dlc=3 data=[02 01 00]

[HIGH] Notable CAN ID 7E8h: OBD-II: diagnostic response from ECU (ISO 15765-4)
  ID 7E8h seen 195 time(s). Last frame: dlc=6 data=[06 41 00 BE 1F A8 13]

Troubleshooting

Cannot open interface

Verify the interface exists and is up:

ip link show type can
sudo ip link set can0 up type can bitrate 500000

No frames received

  • Confirm the target bus is powered and has active traffic.
  • Check the bit rate matches the bus: a mismatch causes all frames to be discarded at the hardware level with no error returned to userspace.
  • Run ip -details link show can0 to view the current bitrate and bus state.

Error frames

If error frames appear, the interface bit rate may not match the bus or there is a wiring issue (missing termination resistors, ground loop). CAN buses typically require 120 Ohm termination at each end.

can scan

Passively listens on a SocketCAN interface and enumerates every unique CAN ID that transmits a data frame during the capture window. Each ID is reported as a separate finding.

Status

ResultMeaning
passScan completed (even if no IDs were observed)
failInterface could not be opened

Severity classification

SeverityCondition
HighOBD-II diagnostic ID observed (0x7DF, 0x7E0-0x7EF)
MediumCANopen protocol ID observed (SDO, PDO, NMT ranges)
InfoGeneral ID, extended (EFF) frame or no traffic

Usage

iottack can scan [OPTIONS]

Options

FlagShortDefaultDescription
--iface <IFACE>-ican0SocketCAN interface name
--duration <SECS>-d5Scan duration in seconds
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Description

For each unique CAN ID observed the plugin reports:

  • ID in HEX with the frame format (SFF or EFF)
  • Frame count and rate (frames per second) over the scan window
  • DLC (data length code, 0-8 bytes)
  • Last payload as a HEX byte string
  • A protocol hint when the ID falls in a known range

Extended 29-bit (EFF) frames are listed at Info severity without protocol classification. J1939 PGN decoding is not performed.

IDs are reported in ascending order for consistent output across runs.

Examples

Default 5-second scan on can0:

iottack can scan

Longer scan on a custom interface:

iottack can scan --iface vcan0 --duration 30

Example output

Plugin name:    can/scan
Execution time: 5.01 s
Status:         pass

[INFO] 5 unique CAN ID(s) active on can0 over 5.0s
  Discovered 5 unique CAN IDs transmitting data frames.

[INFO] CAN ID 181h
  Frames: 500   Rate: 100.0/s  DLC: 8  Last: [00 00 00 00 E8 03 00 00]

[INFO] CAN ID 280h
  Frames: 500   Rate: 100.0/s  DLC: 8  Last: [7F 00 00 00 FF 1F 00 00]

[MEDIUM] CAN ID 701h [CANopen: NMT heartbeat/node guarding]
  Frames: 50    Rate: 10.0/s   DLC: 1  Last: [05]

[HIGH] CAN ID 7DFh [OBD-II: diagnostic broadcast - exposes vehicle diagnostics (ISO 15765-4)]
  Frames: 25    Rate: 5.0/s    DLC: 3  Last: [02 01 00]

[HIGH] CAN ID 7E8h [OBD-II: diagnostic response from ECU (ISO 15765-4)]
  Frames: 24    Rate: 4.8/s    DLC: 6  Last: [06 41 00 BE 1F A8 13]

Comparison with can dump

Both can scan and can dump are passive. The difference is in output focus:

PluginFocus
can dumpTraffic statistics: total rate, top IDs, error frames
can scanPer-ID enumeration: one finding per unique ID with rate and payload

Use can scan when building an inventory of active nodes. Use can dump when diagnosing traffic patterns or looking for anomalies.

can send

Constructs and transmits one or more CAN data frames via a SocketCAN interface.

Status

ResultMeaning
passAt least one frame was sent successfully
failInterface could not be opened, or all writes failed

Usage

iottack can send --id <HEX> [OPTIONS]

Options

FlagShortDefaultDescription
--id <HEX>-(required)CAN ID in HEX without 0x prefix (e.g., 7DF). IDs greater than 0x7FF are automatically treated as 29-bit EFF
--data <HEX>-(empty)Payload bytes in HEX, any separator accepted (e.g., "02 01 00", "020100", "02:01:00"). Maximum 8 bytes
--iface <IFACE>-ican0SocketCAN interface name
--extended-eoffForce 29-bit extended frame format (EFF) even for IDs <= 0x7FF
--count <N>-n1Number of frames to send
--interval-ms <MS>-0Delay between consecutive frames in milliseconds
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Frame format selection

The ID determines the frame format automatically:

ConditionFormat
--id <= 0x7FFSFF (11-bit), unless --extended is set
--id > 0x7FFEFF (29-bit) always
--extended flagEFF (29-bit) regardless of ID value

Data encoding

The --data argument accepts HEX bytes in any common notation. All non-HEX characters (spaces, colons, commas) are stripped before parsing, so the following are equivalent:

--data "02 01 00"
--data "020100"
--data "02:01:00"
--data "02,01,00"

A data length of zero (no --data) sends a zero-length data frame (DLC=0), which is valid on CAN and commonly used as a keep-alive or ping.

Examples

OBD-II functional broadcast. Query supported PIDs:

iottack can send --id 7DF --data "02 01 00"

CANopen NMT command. Reset all nodes (use with caution):

iottack can send --id 000 --data "81 00"

Send a J1939 extended frame:

iottack can send --id 18DB33F1 --data "02 01 00"

Repeat a frame 10 times with 100 ms between sends:

iottack can send --id 123 --data "DEADBEEF" --count 10 --interval-ms 100

Send a zero-length frame on a virtual interface:

iottack can send --iface vcan0 --id 7FF

Example output

Plugin name:    can/send
Execution time: 0 ms
Status:         pass

[INFO] Sent 1/1 frame(s): 7DFh [02 01 00]
  Interface : can0
  ID        : 7DFh (SFF/11-bit)
  Payload   : [02 01 00] (3 byte(s))
  Sent      : 1  Errors: 0
  Evidence: "iface=can0 id=7DFh fmt=SFF/11-bit data=[02 01 00] sent=1 errors=0"

Notes

  • CAN classic frames carry a maximum of 8 bytes. CAN FD (Flexible Data-rate) is not currently supported.
  • Sending frames to a live CAN bus can disrupt operation. Take care when testing on production systems.
  • NMT reset commands (ID 0x000, data 0x81 0x00) will restart all CANopen nodes on the bus.

can enumerate

Active and passive device discovery across three sequential phases: passive traffic observation, OBD-II ECU discovery and CANopen node guarding with device type identification.

Status

ResultMeaning
passAll configured phases completed
failInterface could not be opened

Severity classification

SeverityCondition
HighOBD-II ECU responded with supported PID list
HighCANopen node found and device type identified via SDO
MediumCANopen node found (heartbeat or node guarding) but no SDO response
InfoNo devices found in a phase, or phase skipped

Usage

iottack can enumerate [OPTIONS]

Options

FlagShortDefaultDescription
--iface <IFACE>-ican0SocketCAN interface name
--passive-ms <MS>-1000Duration of the passive listening phase in ms
--probe-ms <MS>-500Response collection window after each active probe phase
--no-canopen-offSkip the CANopen node guarding and SDO phase
--no-obdii-offSkip the OBD-II ECU discovery phase
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Discovery phases

Phase 1 - Passive (default 1 s)

Listens for spontaneous traffic without transmitting anything. CANopen nodes periodically broadcast heartbeat frames on 0x700 + NodeID. Nodes found this way require no probe and cause no bus disruption.

Phase 2 - OBD-II ECU discovery

Transmits a single Service 01 PID 00 functional broadcast to 0x7DF:

ID: 0x7DF  data: [02 01 00]
  02 = 2 additional bytes
  01 = Service 01 (current powertrain data)
  00 = PID 00 (supported PIDs 01–20 bitmask)

Any ECU that supports OBD-II responds on 0x7E8-0x7EF with a bitmask of the PIDs it supports. Each responding address is reported as a separate High severity finding. The ECU index is response_id - 0x7E8.

Phase 3 - CANopen node guarding

Transmits RTR (Remote Transmission Request) frames simultaneously to 0x700 + N for N = 1 through 127. A node that supports node guarding responds with a data frame containing its current NMT state.

All 127 probes are sent before the response window opens, so the total active probe time is one --probe-ms window rather than 127 individual timeouts.

After collecting node guard responses, an SDO upload initiate request is sent to each found node to read object 0x1000 sub-index 0 (Device Type):

ID: 0x600 + NodeID  data: [40 00 10 00 00 00 00 00]
  40 = initiate upload
  00 10 = object index 0x1000
  00 = sub-index 0

The 32-bit response value encodes the CANopen device profile in the lower 16 bits. Nodes that respond are reported at High severity with the decoded profile. Nodes that do not support SDO or do not respond within --probe-ms are reported at Medium.

CANopen NMT states

State byteMeaning
0x00Boot-up / Initialising
0x04Stopped
0x05Operational
0x7FPre-Operational

CANopen device profiles (object 0x1000)

Profile (lower 16 bits)Device type
0x0191Encoder
0x0192Stepper motor
0x0401AC drive (IEC 61800-7-201)
0x0402Stepper motor drive
0x0403AC servo drive
0x0404Digital I/O module
0x0405Analog I/O module
0x0406Encoder interface
0x0407Safety controller
0xFFFFGeneric CANopen device

Examples

Full scan with all phases:

iottack can enumerate

OBD-II only with a longer response window:

iottack can enumerate --no-canopen --probe-ms 1000

CANopen only on a custom interface:

iottack can enumerate --no-obdii --iface vcan0

Extend the passive window for slow heartbeat cycles (e.g., 1 Hz nodes):

iottack can enumerate --passive-ms 3000

Example output

Plugin name:    can/enumerate
Execution time: 2.01 s
Status:         pass

[MEDIUM] 2 CANopen node(s) discovered via passive heartbeat on can0
    Node   1  ID=701h  state=Operational
    Node   2  ID=702h  state=Operational

[HIGH] OBD-II ECU 0 at 0x7E8h: 13 supported PID(s)
  ECU index 0 (request 0x7E0h → response 0x7E8h)
  Supported PIDs (01-20): 0x01, 0x03, 0x04, 0x05, 0x06, 0x07, 0x0C,
                           0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x13
  Raw response: [06 41 00 BE 1F A8 13]

[HIGH] CANopen node 1 at 701h: Operational
  Node ID  : 1
  Heartbeat: 701h
  State    : Operational (0x05)
  Device   : profile=0x0404 (Digital I/O module)  raw=0x00000404

[HIGH] CANopen node 2 at 702h: Operational
  Node ID  : 2
  Heartbeat: 702h
  State    : Operational (0x05)
  Device   : device type unknown (SDO timeout or not supported)

Notes

  • Node guarding is a legacy CANopen mechanism. Modern deployments often use heartbeat messages instead. If RTR probes produce no response, nodes may still be detectable via the passive heartbeat phase.
  • Sending the OBD-II functional broadcast (0x7DF) is a standard diagnostic operation and is safe on any compliant OBD-II bus.
  • The CANopen NMT reset command (0x000, data 0x81 0x00) is not sent by this plugin. Discovery is non-destructive.

Modbus plugins

Modbus is a serial communication protocol originally developed for industrial programmable logic controllers (PLCs). It has become the de-facto standard for industrial automation and is widely deployed in PLCs, HMIs, energy meters, building management systems and other OT/ICS equipment.

The protocol has no built-in authentication or encryption. Any device that can reach TCP port 502 or the correct serial bus, can read sensor values, setpoints, and configuration data and write directly to outputs or actuators.

Transport modes

All plugins support two transport modes selected by exclusive flags:

ModeFlagDefault port/baud
TCP--host <IP>502
RTU serial--serial <DEVICE>9600 baud

Exactly one of --host or --serial must be supplied. TCP is tried when --host is set. RTU is used when --serial is set.

Plugins

PluginCommandFunction code(s)
device-infomodbus device-infoFC03 (probe) & FC43 MEI
enumeratemodbus enumerateFC01, FC02, FC03, FC04
read-registersmodbus read-registersFC03/FC04
write-registermodbus write-registerFC06/FC16
read-coilsmodbus read-coilsFC01/FC02
write-coilmodbus write-coilFC05

Severity model

Successful unauthenticated reads are reported as High. The absence of any access control is the finding, regardless of the data values returned.

Successful unauthenticated writes are reported as Critical — they demonstrate the ability to modify process state, setpoints or actuator outputs without any authentication.

Connection failures and unsupported function codes are reported as Info.

modbus device-info

Connects to a Modbus device and performs two checks:

  1. Connectivity probe: reads holding registers 0–3 via FC03 to confirm the device accepts unauthenticated connections and returns data.
  2. FC43 MEI identification: sends a Read Device Identification request (function code 43, MEI type 14) to retrieve vendor name, product code, firmware revision and other identification strings.

Both checks run over a single connection. If FC43 is not supported or returns no objects, the connectivity finding is still reported.

Status

ResultMeaning
passConnection accepted (device is reachable and responded)
failCould not connect

Severity classification

SeverityCondition
HighUnauthenticated connection accepted
HighFC43 MEI identification objects returned
InfoFC43 not supported or returned no objects
InfoConnection failed

Usage

iottack modbus device-info --host <HOST> [OPTIONS]
iottack modbus device-info --serial <DEVICE> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required or –serial)Target hostname or IP for Modbus/TCP
--tcp-port <PORT>-502Modbus/TCP port
--serial <DEVICE>-s(required or –host)Serial device for Modbus RTU (e.g., /dev/ttyUSB0)
--baud <BAUD>-9600Baud rate for RTU serial
--unit <ID>-u1Modbus unit/slave ID (1–247)
--timeout-ms <MS>-t3000Timeout in milliseconds
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

MEI identification objects

FC43 MEI type 14 defines the following object IDs:

IDLabel
0x00VendorName
0x01ProductCode
0x02MajorMinorRevision
0x03VendorUrl
0x04ProductName
0x05ModelName
0x06UserApplicationName
0x07–0x7FReserved
0x80–0xFFDeviceSpecific

The plugin tries all three conformity levels (basic 0x01, regular 0x02 and extended 0x03) and returns the first non-empty response.

Examples

Identify a device over TCP:

iottack modbus device-info --host 192.168.1.100

Non-standard port:

iottack modbus device-info --host 192.168.1.100 --tcp-port 5020

Identify over RTU serial, unit ID 3:

iottack modbus device-info --serial /dev/ttyUSB0 --baud 19200 --unit 3

Save result as JSON:

iottack modbus device-info --host 192.168.1.100 \
  --format json --output device-info.json

Example output

Plugin name:    modbus/device-info
Execution time: 0.42 s
Status:         pass

[HIGH] Modbus/TCP: unauthenticated connection accepted (unit 1)
  Device at 192.168.1.100:502 accepted a Modbus connection without
  authentication. Holding registers 0-3: [0x0000, 0x0001, 0x0000, 0x0042]
  Evidence: "Holding registers 0-3: [0x0000, 0x0001, 0x0000, 0x0042]"

[HIGH] Modbus/TCP: device identification retrieved via FC43 MEI (unit 1)
  Device exposes identification strings without authentication:
  VendorName: Acme Corp; ProductCode: PLC-4000; MajorMinorRevision: 2.1.0
  Evidence:
    0x00 VendorName: Acme Corp
    0x01 ProductCode: PLC-4000
    0x02 MajorMinorRevision: 2.1.0
    0x04 ProductName: Industrial Controller

modbus enumerate

Scans a configurable address range across all four Modbus data types to discover which addresses a device will serve without error:

Data typeFunction codeDefault scan
Holding registersFC03yes
Input registersFC04yes
CoilsFC01yes
Discrete inputsFC02yes

Addresses are read in blocks of 125 (the Modbus maximum per request). The scan reports each contiguous accessible range and the total number of readable locations. This reveals the full attack surface available to an unauthenticated attacker.

Status

ResultMeaning
passAt least one accessible address found
failNo accessible addresses, or connection failed

Severity classification

SeverityCondition
HighMore than 100 accessible addresses of a given type
HighSummary finding when any data is found
Medium1-100 accessible addresses of a given type
InfoNo accessible addresses for a data type
InfoNo data found at all, or connection failed

Usage

iottack modbus enumerate --host <HOST> [OPTIONS]
iottack modbus enumerate --serial <DEVICE> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required or –serial)Target hostname or IP for Modbus/TCP
--tcp-port <PORT>-502Modbus/TCP port
--serial <DEVICE>-s(required or –host)Serial device for Modbus RTU (e.g., /dev/ttyUSB0)
--baud <BAUD>-9600Baud rate for RTU serial
--unit <ID>-u1Modbus unit/slave ID (1-247)
--timeout-ms <MS>-t3000Per-block timeout (lower values speed up the scan)
--start-addr <ADDR>-S0First address to scan
--end-addr <ADDR>-E999Last address to scan (inclusive)
--no-holding-offSkip holding register scan (FC03)
--no-input-offSkip input register scan (FC04)
--no-coils-offSkip coil scan (FC01)
--no-discrete-offSkip discrete input scan (FC02)
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Performance notes

Each block read is one round-trip. For the default range (0-999) with all four data types, the scan issues approximately 36 requests (⌈1000/125⌉ * 4 = 32-36). Reduce --timeout-ms (e.g., 500) for faster scans when the network is reliable.

Examples

Full default scan over TCP:

iottack modbus enumerate --host 192.168.1.100

Scan a wider range with a shorter timeout:

iottack modbus enumerate --host 192.168.1.100 \
  --start-addr 0 --end-addr 9999 --timeout-ms 500

Only scan holding registers and coils:

iottack modbus enumerate --host 192.168.1.100 \
  --no-input --no-discrete

RTU serial, unit 5:

iottack modbus enumerate --serial /dev/ttyUSB0 --unit 5

Example output

Plugin name:    modbus/enumerate
Execution time: 3.21 s
Status:         pass

[HIGH] Modbus/TCP: 875 accessible Holding Registers (FC03) in range 0-999
  Unit 1: 875 addresses in 2 contiguous block(s) are readable without
  authentication.
  Evidence:
    Accessible ranges: 0-874, 900-999
    Total accessible: 875

[MEDIUM] Modbus/TCP: 16 accessible Coils (FC01) in range 0-999
  Unit 1: 16 addresses in 1 contiguous block(s) are readable without
  authentication.
  Evidence:
    Accessible ranges: 0-15
    Total accessible: 16

[INFO] Modbus/TCP: no accessible Input Registers (FC04) in range 0-999
[INFO] Modbus/TCP: no accessible Discrete Inputs (FC02) in range 0-999

[HIGH] Modbus/TCP: 891 total accessible data points on unit 1
  Enumeration of addresses 0-999 found 891 readable locations across all
  scanned data types.
    Holding Registers (FC03): 875 accessible (2 range(s): 0-874, 900-999)
    Input Registers    (FC04): no accessible addresses
    Coils              (FC01): 16 accessible (1 range(s): 0-15)
    Discrete Inputs    (FC02): no accessible addresses

modbus read-registers

Reads a contiguous block of 16-bit registers from a Modbus device. Supports both holding registers (FC03) and input registers (FC04).

Holding registers are general-purpose read/write 16-bit values typically used for setpoints, configuration, and counters. Input registers are read-only 16-bit values typically representing analog measurements and sensor readings.

The finding reports all register values in hex and decimal and counts how many hold non-zero values.

Status

ResultMeaning
passRegisters read successfully
failRead failed or connection error

Severity classification

SeverityCondition
HighRegisters returned (unauthenticated read succeeded)
InfoRead failed or connection failed

Usage

iottack modbus read-registers --host <HOST> [OPTIONS]
iottack modbus read-registers --serial <DEVICE> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required or –serial)Target hostname or IP for Modbus/TCP
--tcp-port <PORT>-502Modbus/TCP port
--serial <DEVICE>-s(required or –host)Serial device for Modbus RTU (e.g., /dev/ttyUSB0)
--baud <BAUD>-9600Baud rate for RTU serial
--unit <ID>-u1Modbus unit/slave ID (1-247)
--timeout-ms <MS>-t3000Timeout in milliseconds
--address <ADDR>-a0Starting register address (0-65535)
--count <N>-c10Number of registers to read (max. 125)
--register-type <TYPE>-Tholdingholding (FC03) or input (FC04)
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

--count is capped at 125, the Modbus protocol maximum per request.

Examples

Read the first 10 holding registers:

iottack modbus read-registers --host 192.168.1.100

Read 20 input registers starting at address 100:

iottack modbus read-registers --host 192.168.1.100 \
  --register-type input --address 100 --count 20

Read over RTU serial, unit ID 3:

iottack modbus read-registers --serial /dev/ttyUSB0 --baud 19200 \
  --unit 3 --address 0 --count 10

Example output

Plugin name:    modbus/read-registers
Execution time: 0.08 s
Status:         pass

[HIGH] Modbus/TCP: unauthenticated read of Holding registers 0-9
  FC03: unit 1, 10 Holding registers at address 0.
  7/10 registers hold non-zero values.
  Evidence:
    [    0] 0x0064 =    100
    [    1] 0x01F4 =    500
    [    2] 0x0000 =      0
    [    3] 0x03E8 =   1000
    [    4] 0x0000 =      0
    [    5] 0x000A =     10
    [    6] 0x0032 =     50
    [    7] 0x0000 =      0
    [    8] 0x00C8 =    200
    [    9] 0x0001 =      1

modbus write-register

Writes one or more 16-bit values to Modbus holding registers without authentication. Two write modes are available:

ModeFunction codeFlag
Single registerFC06 — Write Single Register--value
Multiple registersFC16 — Write Multiple Registers--values

Values may be specified in decimal or 0x-prefixed hexadecimal.

Warning: Writing to holding registers can directly modify setpoints, configuration parameters or device state on industrial equipment.

Status

ResultMeaning
passWrite accepted by the device
failWrite rejected, parse error or connection failed

Severity classification

SeverityCondition
CriticalWrite succeeded (unauthenticated modification of device state)
InfoWrite failed, invalid value or connection failed

Usage

iottack modbus write-register --host <HOST> --value <VALUE> [OPTIONS]
iottack modbus write-register --host <HOST> --values <V1,V2,...> [OPTIONS]
iottack modbus write-register --serial <DEVICE> --value <VALUE> [OPTIONS]

Either --value or --values must be supplied.

Options

FlagShortDefaultDescription
--host <HOST>-H(required or –serial)Target hostname or IP for Modbus/TCP
--tcp-port <PORT>-502Modbus/TCP port
--serial <DEVICE>-s(required or –host)Serial device for Modbus RTU (e.g., /dev/ttyUSB0)
--baud <BAUD>-9600Baud rate for RTU serial
--unit <ID>-u1Modbus unit/slave ID (1-247)
--timeout-ms <MS>-t3000Timeout in milliseconds
--address <ADDR>-a0Target register address (0-65535)
--value <VALUE>-v-Single 16-bit value (decimal or 0xHEX) for FC06
--values <V1,V2,...>-V-Comma-separated values for FC16 multi-register write
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

When both --value and --values are supplied, --values (FC16) takes precedence.

Examples

Write decimal value 100 to register 40:

iottack modbus write-register --host 192.168.1.100 \
  --address 40 --value 100

Write a hex value:

iottack modbus write-register --host 192.168.1.100 \
  --address 40 --value 0x0064

Write multiple registers starting at address 10:

iottack modbus write-register --host 192.168.1.100 \
  --address 10 --values 100,200,300,0xFF

Write over RTU serial, unit 2:

iottack modbus write-register --serial /dev/ttyUSB0 --unit 2 \
  --address 0 --value 1

Example output

Single register write (FC06):

Plugin name:    modbus/write-register
Execution time: 0.07 s
Status:         pass

[CRITICAL] Modbus/TCP: wrote register 40 = 0x0064 without authentication (FC06)
  Unit 1: register 40 written with value 100 (0x0064) without authentication.
  Evidence: "address=40 value=100 (0x0064)"

Multi-register write (FC16):

Plugin name:    modbus/write-register
Execution time: 0.09 s
Status:         pass

[CRITICAL] Modbus/TCP: wrote 4 registers at address 10 without authentication (FC16)
  Unit 1: 4 consecutive registers written starting at 10.
  Evidence:
    [   10] 0x0064 = 100
    [   11] 0x00C8 = 200
    [   12] 0x012C = 300
    [   13] 0x00FF = 255

modbus read-coils

Reads a block of single-bit values from a Modbus device. Supports both coils (FC01) and discrete inputs (FC02).

Coils are read/write single-bit values typically representing digital output states such as relay on/off, valve open/closed or motor running. Discrete inputs are read-only single-bit values representing digital input states such as limit switches, door sensors or push buttons.

The finding reports each bit as ON or OFF and counts how many are active.

Status

ResultMeaning
passBits read successfully
failRead failed or connection error

Severity classification

SeverityCondition
HighBits returned (unauthenticated read succeeded)
InfoRead failed or connection failed

Usage

iottack modbus read-coils --host <HOST> [OPTIONS]
iottack modbus read-coils --serial <DEVICE> [OPTIONS]

Options

FlagShortDefaultDescription
--host <HOST>-H(required or –serial)Target hostname or IP for Modbus/TCP
--tcp-port <PORT>-502Modbus/TCP port
--serial <DEVICE>-s(required or –host)Serial device for Modbus RTU (e.g., /dev/ttyUSB0)
--baud <BAUD>-9600Baud rate for RTU serial
--unit <ID>-u1Modbus unit/slave ID (1-247)
--timeout-ms <MS>-t3000Timeout in milliseconds
--address <ADDR>-a0Starting coil address (0-65535)
--count <N>-c16Number of bits to read (max. 2000)
--coil-type <TYPE>-Tcoilcoil (FC01) or discrete (FC02)
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

--count is capped at 2000, the Modbus protocol maximum per request.

Examples

Read the first 16 coils:

iottack modbus read-coils --host 192.168.1.100

Read 32 discrete inputs starting at address 0:

iottack modbus read-coils --host 192.168.1.100 \
  --coil-type discrete --count 32

Read over RTU serial:

iottack modbus read-coils --serial /dev/ttyUSB0 --baud 9600 \
  --address 0 --count 8

Example output

Plugin name:    modbus/read-coils
Execution time: 0.07 s
Status:         pass

[HIGH] Modbus/TCP: unauthenticated read of Coils 0-15
  FC01: unit 1, 16 Coils at address 0. 5/16 bits are ON.
  Evidence:
    [    0] ON
    [    1] OFF
    [    2] ON
    [    3] OFF
    [    4] ON
    [    5] OFF
    [    6] OFF
    [    7] ON
    [    8] OFF
    [    9] OFF
    [   10] ON
    [   11] OFF
    [   12] OFF
    [   13] OFF
    [   14] OFF
    [   15] OFF

modbus write-coil

Writes a boolean value to a single Modbus coil using function code 05 (Write Single Coil).

Coils typically control digital outputs : relays, solenoid valves, motor starters, indicator lights and similar actuators. Unauthenticated coil writes can directly affect physical processes.

Warning: Writing to coils can immediately actuate physical devices!

Status

ResultMeaning
passWrite accepted by the device
failWrite rejected, invalid value, or connection failed

Severity classification

SeverityCondition
CriticalWrite succeeded (unauthenticated control of a digital output)
InfoWrite failed, invalid value, or connection failed

Usage

iottack modbus write-coil --host <HOST> --value <VALUE> [OPTIONS]
iottack modbus write-coil --serial <DEVICE> --value <VALUE> [OPTIONS]

--value is required.

Options

FlagShortDefaultDescription
--host <HOST>-H(required or –serial)Target hostname or IP for Modbus/TCP
--tcp-port <PORT>-502Modbus/TCP port
--serial <DEVICE>-s(required or –host)Serial device for Modbus RTU (e.g., /dev/ttyUSB0)
--baud <BAUD>-9600Baud rate for RTU serial
--unit <ID>-u1Modbus unit/slave ID (1-247)
--timeout-ms <MS>-t3000Timeout in milliseconds
--address <ADDR>-a0Coil address (0-65535)
--value <VALUE>-v(required)Coil state: on/off, 1/0 or true/false
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Accepted values for --value

InputMeaning
on, 1, true, yesCoil ON (0xFF00 on the wire)
off, 0, false, noCoil OFF (0x0000 on the wire)

Examples

Turn coil 5 on:

iottack modbus write-coil --host 192.168.1.100 --address 5 --value on

Turn coil 5 off:

iottack modbus write-coil --host 192.168.1.100 --address 5 --value off

Write over RTU serial, unit 2:

iottack modbus write-coil --serial /dev/ttyUSB0 --unit 2 \
  --address 0 --value 1

Example output

Plugin name:    modbus/write-coil
Execution time: 0.06 s
Status:         pass

[CRITICAL] Modbus/TCP: coil 5 set to ON without authentication (FC05)
  Unit 1: coil at address 5 written to ON.
  This may directly affect a physical actuator or digital output.
  Evidence: "address=5 value=ON"

BACnet plugins

BACnet (Building Automation and Control Networks) is an ASHRAE/ISO/ANSI standard protocol for building automation systems. It is widely deployed in HVAC controllers, fire alarm panels, lighting systems, energy meters and access control equipment in commercial buildings and industrial facilities.

BACnet/IP carries the protocol over UDP port 47808 (0xBAC0) and requires no authentication by default. Any host that can reach the UDP port can enumerate devices, read sensor values and setpoints and write to outputs or actuators. BACnet/SC (Secure Connect) adds TLS mutual authentication but is not yet widely deployed.

Device model

A BACnet network is composed of devices, each of which exposes a set of objects. Every object has a type (e.g., Analog-Input, Binary-Output, Device) and an instance number, identified together as an Object Identifier. Objects carry properties (present value, description, units, limits, etc.) read and written via the ReadProperty/WriteProperty confirmed services.

Discovery

Devices announce themselves via the Who-Is/I-Am exchange. A client broadcasts a Who-Is request. Every device in range responds with an I-Am containing its device instance number, vendor ID and maximum APDU size.

When the iottack client and the target device share a host, the simulator already holds port 47808 so I-Am broadcasts cannot be received. Use --device-id to bypass discovery and specify the device instance directly.

Plugins

PluginCommandPurpose
find-devicesiottack bacnet find-devicesDiscover all reachable BACnet/IP devices via Who-Is broadcast
scaniottack bacnet scanEnumerate devices and read key Device-object properties
infoiottack bacnet infoRead identification and status properties of a single device
network-infoiottack bacnet network-infoRead BACnet network configuration of a device
servicesiottack bacnet servicesRead supported BACnet services and object types
device-propertiesiottack bacnet device-propertiesRead all standard Device-object properties
object-listiottack bacnet object-listEnumerate all objects and read their present values
object-propertiesiottack bacnet object-propertiesRead all standard properties of a specific object
event-infoiottack bacnet event-infoRead event and alarm state of a device
fuzziottack bacnet fuzzSend malformed BACnet PDUs and report anomalous responses

Severity model

FindingSeverity
Device found; all property reads rejectedHigh
Identification/status properties readable unauthenticatedCritical
Process data (present values) readable unauthenticatedCritical
Writes accepted unauthenticatedCritical
No devices found or connection failedInfo

bacnet - find-devices

Enumerate all BACnet devices and routers reachable from the current host.

Usage

iottack bacnet find-devices [OPTIONS]

Description

Sends a BACnet Who-Is broadcast (or unicast to --host) and a Who-Is-Router broadcast to discover all BACnet devices and routers on the reachable network segment. Unlike bacnet/scan, no property reads are performed, making this a fast enumeration sweep.

Equivalent to BACteria find_devices().

Two discovery mechanisms run in sequence:

  1. Who-Is/I-Am: discovers BACnet devices; each I-Am response yields device ID, vendor, segmentation and max APDU size.
  2. Who-Is-Router/I-Am-Router-To-Network: discovers BACnet routers and the network numbers they route to, enabling lateral discovery of downstream segments.

Use --network to restrict the Who-Is to a specific BACnet network number routed via the target host.

Severity mapping

FindingSeverity
No devices or routers foundInfo
Devices discoveredHigh
Routers discoveredHigh

Options

FlagShortDefaultDescription
--host <HOST>-H(broadcast)Unicast target address; omit to broadcast
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-3000Discovery window in ms
--network <NET>-n-BACnet network number to query via router
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet find-devices

Plugin name:    bacnet/find-devices
Execution time: 3.01 s
Status:         pass
Date:           2025-11-08 00:00:00 UTC

3 BACnet devices found
  192.168.1.50:47808  ID=1001  vendor=Siemens (16)  max-apdu=1476
  192.168.1.51:47808  ID=2002  vendor=Schneider Electric (11)  max-apdu=1476
  192.168.1.52:47808  ID=3003  vendor=Johnson Controls (5)  max-apdu=480

1 BACnet router found
  192.168.1.1:47808  networks=[200, 201, 202]

bacnet scan

Discover BACnet/IP devices and read device properties unauthenticated.

Usage

iottack bacnet scan [OPTIONS]

Description

Implements the reconnaissance approach of BACteria as an iottack plugin.

  1. Who-Is broadcast / unicast: sends a BACnet Who-Is datagram on UDP 47808. Without --host the packet is sent as a global broadcast so every BACnet/IP device on the local network is queried at once. With --host a unicast Who-Is targets a single device.
  2. I-Am collection: the plugin listens for I-Am responses for the full --timeout-ms window. Each unique responder is recorded with its device instance number and vendor ID.
  3. ReadProperty enumeration: for every discovered device the plugin sends unauthenticated ReadProperty confirmed requests for eight Device-object properties: Vendor Name, Vendor ID, Object Name, Model Name, Firmware Revision, App Software Version, Description and Location.

BACnet provides no authentication by default (BACnet/SC adds TLS but is not yet widely deployed). Any device that responds is a potential attack target.

Severity mapping

FindingSeverity
No BACnet devices foundInfo
Device responds to Who-Is; ReadProperty rejectedHigh
Device allows unauthenticated ReadPropertyCritical

Options

FlagShortDefaultDescription
--host <HOST>-H(broadcast)Target host for unicast scan
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-3000Who-Is discovery window in ms
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet scan --host 192.168.1.50

Plugin name:    bacnet/scan
Execution time: 4.83 s
Status:         pass
Date:           2025-11-01 00:00:00 UTC

BACnet/IP device at 192.168.1.50:47808 exposes 6 properties unauthenticated
  Device accepted ReadProperty requests for 6 Device-object properties
  without any credentials: Vendor Name, Vendor ID, Object Name, Model Name,
  Firmware Revision, Description.
  Evidence:
    Address:         192.168.1.50:47808
    Device instance: 1234
    Vendor ID (IAm): 8
    Vendor Name: Siemens
    Vendor ID: 8
    Object Name: Field Panel
    Model Name: PXC001-E.D
    Firmware Revision: 2.3.1
    Description: HVAC controller lobby

bacnet - info

Show basic identification and status properties of a BACnet/IP device.

Usage

iottack bacnet info --host <HOST> [OPTIONS]

Description

Connects to the target BACnet/IP device and reads a curated set of Device-object properties that identify and characterize the device:

  • vendor
  • model
  • firmware version
  • application software version
  • location
  • protocol version
  • APDU transport settings
  • system status
  • local clock
  • backup/restore state

All reads are unauthenticated ReadProperty requests on the Device object. Any identifying property returned without credentials is flagged Critical.

Properties read

PropertyDescription
Object IdentifierDevice object ID (type=8, instance=N)
Object NameHuman-readable device name
System StatusOperational status (operational, load-expected, etc.)
Vendor NameManufacturer string
Vendor IdentifierNumeric vendor ID
Model NameDevice model
Firmware RevisionFirmware version string
Application Software VersionApplication layer software version
DescriptionFree-text description
LocationPhysical or logical location
Protocol VersionBACnet protocol version
Protocol RevisionBACnet protocol revision
Max APDU Length AcceptedMaximum APDU size in bytes
Segmentation SupportedSegmentation capability
APDU TimeoutPer-request timeout in milliseconds
APDU RetriesNumber of APDU retries
Database RevisionConfiguration database revision counter
Last Restart ReasonReason for last device restart
Backup and Restore StateBackup/restore operational state
Local DateDevice local date
Local TimeDevice local time
UTC OffsetUTC offset in minutes
Daylight SavingsDaylight savings status
Profile NameBACnet interoperability profile

Severity mapping

FindingSeverity
Device responds but no properties readableHigh
Identifying properties readable unauthenticatedCritical

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target BACnet/IP device
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-5000Per-request timeout in ms
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet info --host 192.168.1.50

Plugin name:    bacnet/info
Execution time: 2.31 s
Status:         pass
Date:           2025-11-05 00:00:00 UTC

18 device properties readable unauthenticated at 192.168.1.50:47808
  Address:    192.168.1.50:47808
  Device ID:  1001
  Vendor ID:  16 (Siemens)
  Max APDU:   1476
  Object Identifier: Device:1001
  Object Name: HVAC-Controller-01
  System Status: 0
  Vendor Name: Siemens
  Model Name: PXC100.D
  Firmware Revision: 2.4.1
  Application Software Version: 3.1.0
  Description: Building 7, HVAC Zone A
  Location: Level 3, Plant Room
  Protocol Version: 1
  Protocol Revision: 14
  Local Date: 2025-11-05
  Local Time: 09:42:15.00
  UTC Offset (min): -300

bacnet - network-info

Show BACnet network link details, addressing, and router topology.

Usage

iottack bacnet network-info --host <HOST> [OPTIONS]

Description

Reads network-related information from a BACnet/IP device in three steps:

  1. Device addressing: reads addressing and transport parameters from the I-Am response: UDP address, device ID, vendor identity, max APDU, segmentation and routing information.
  2. Network Port objects: enumerates Network Port objects (ASHRAE 135 clause 12.56) and reads their IP address, subnet mask, default gateway, UDP port, DHCP configuration, MAC address and link speed.
  3. Router discovery: sends Who-Is-Router to the target to discover any BACnet routers it knows about, including the network numbers they route to.

Equivalent to BACteria network_info(). Exposed network topology is flagged High severity.

Network Port properties read

PropertyDescription
Object NamePort name
DescriptionPort description
Network TypeIP, MS/TP, Ethernet, etc.
Network NumberBACnet network number
MAC AddressMAC address
IP AddressIPv4 address
IP Subnet MaskSubnet mask
IP Default GatewayDefault gateway
IP DNS ServerDNS server addresses
BACnet IP UDP PortBACnet/IP UDP port
IP DHCP EnableWhether DHCP is active
Link SpeedLink speed

Severity mapping

FindingSeverity
Device addressing exposedHigh
Network Port properties readableHigh
Routers discoveredHigh

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target BACnet/IP device
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-5000Per-request timeout in milliseconds
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet network-info --host 192.168.1.50

Plugin name:    bacnet/network-info
Execution time: 5.82 s
Status:         pass
Date:           2026-10-18 00:00:00 UTC

BACnet device addressing exposed at 192.168.1.50:47808
  UDP address:   192.168.1.50:47808
  Device ID:     1001
  Vendor:        Siemens (ID 16)
  Max APDU:      1476
  Segmentation:  NoSegmentation

Network Port NetworkPort:0 exposes 8 network properties at 192.168.1.50:47808
  Object Name: ETH1
  Network Type: 5
  IP Address: 192.168.1.50
  IP Subnet Mask: 255.255.255.0
  IP Default Gateway: 192.168.1.1
  BACnet IP UDP Port: 47808
  IP DHCP Enable: false
  Link Speed: 100000000

1 BACnet router discovered from 192.168.1.50:47808
  192.168.1.1:47808 → networks [200, 201]

bacnet - services

Read BACnet services-supported and object-types-supported unauthenticated.

Usage

iottack bacnet services --host <HOST> [OPTIONS]

Description

Implements the get_service_supported and object_types_supported recon operations from BACteria.

  1. Services supported: reads property 97 (services-supported), a BitString that indicates every BACnet service the device supports. Dangerous services such as write-property, device-communication-control, and reinitialize-device are flagged separately when enabled.
  2. Object types supported: reads property 96 (object-types-supported), a BitString that reveals the device’s complete object model (sensors, actuators, programs, trend logs, etc.).

Both properties require no authentication in standard BACnet/IP, making this a zero-credential capability fingerprint of the target.

Dangerous services

ServiceRisk
write-propertyModify device properties and control outputs
write-property-multipleModify multiple properties in one request
device-communication-controlDisable device communications (DoS)
reinitialize-deviceRestart or factory-reset the device
create-objectCreate new BACnet objects on the device
delete-objectDelete BACnet objects from the device

Severity mapping

FindingSeverity
Services/types not readableInfo
Services-supported readableMedium
One or more dangerous services enabledHigh
Object types supported readableInfo

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target BACnet/IP device
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-5000Per-request timeout in ms
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet services --host 192.168.1.50

Plugin name:    bacnet/services
Execution time: 3.12 s
Status:         pass
Date:           2026-10-18 00:00:00 UTC

34 BACnet services readable unauthenticated at 192.168.1.50:47808
  read-property, read-property-multiple, write-property, ...

4 dangerous services enabled at 192.168.1.50:47808
  write-property          - can modify device properties and control outputs
  write-property-multiple - can modify multiple properties in a single request
  device-communication-control - can disable device communications (DoS)
  reinitialize-device     - can restart or factory-reset the device

12 BACnet object types supported at 192.168.1.50:47808
  Analog-Input, Analog-Output, Analog-Value, Binary-Input,
  Binary-Output, Binary-Value, Device, File, Schedule, ...

bacnet - device-properties

Enumerate all standard properties of the BACnet Device object.

Usage

iottack bacnet device-properties --host <HOST> [OPTIONS]

Description

Reads every standard ASHRAE 135 property of the Device object on the target via unauthenticated ReadProperty requests. Properties that the device does not support or restricts are shown as <not readable>.

The Device object is the root of a BACnet device’s information model. Its properties expose configuration, capability and operational state. Readable properties are reported as Critical findings.

Properties attempted

Required Device object properties, optional common properties, and operational flags:

  • Object Identifier, Object Name, Object Type
  • System Status, Vendor Name, Vendor Identifier, Model Name
  • Firmware Revision, Application Software Version
  • Protocol Version, Protocol Revision
  • Protocol Services Supported, Protocol Object Types Supported
  • Object List, Max APDU Length Accepted, Segmentation Supported
  • APDU Timeout, Number of APDU Retries, Database Revision
  • Description, Location, Local Date, Local Time, UTC Offset
  • Daylight Savings Status, Profile Name
  • Last Restart Reason, Backup and Restore State
  • Out of Service, Event State, Status Flags

Severity mapping

FindingSeverity
No Device properties readableInfo
Device properties readable unauthenticatedCritical

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target BACnet/IP device
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-5000Per-request timeout in ms
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet device-properties --host 192.168.1.50

Plugin name:    bacnet/device-properties
Execution time: 8.74 s
Status:         pass
Date:           2025-10-06 00:00:00 UTC

24 of 31 Device properties readable unauthenticated at 192.168.1.50:47808
  Object Identifier: Device:1001
  Object Name: HVAC-Controller-01
  Object Type: 8
  System Status: 0
  Vendor Name: Siemens
  Vendor Identifier: 16
  Model Name: PXC100.D
  Firmware Revision: 2.4.1
  Application Software Version: 3.1.0
  Protocol Version: 1
  Protocol Revision: 14
  Protocol Services Supported: <binary/complex>
  Protocol Object Types Supported: <binary/complex>
  Max APDU Length Accepted: 1476
  Segmentation Supported: 3
  APDU Timeout (ms): 6000
  Number of APDU Retries: 3
  Database Revision: 42
  Description: Building 7, HVAC Zone A
  Location: Level 3, Plant Room
  Local Date: 2025-11-06
  Local Time: 09:42:15.00
  UTC Offset (min): -300
  Out of Service: false
  ...
  Profile Name: <not readable>
  Event State: <not readable>

bacnet - object-list

Enumerate all BACnet objects on a device and read their present values unauthenticated.

Usage

iottack bacnet object-list --host <HOST> [OPTIONS]

Description

Implements the list_objects and list_objects_info recon operations from BACteria.

  1. Object list: reads the object-list property (prop 76) from the Device object to obtain every BACnet object instantiated on the device.
  2. Object names: reads the object-name property (prop 77) for each object.
  3. Present values: for data-point types (Analog-Input/Output/Value, Binary-Input/Output/Value, Multi-State-Input/Output/Value) the present-value property (prop 85) is read, exposing live sensor and actuator readings.

Note: Very large object lists (> ~200 objects) may exceed the 1024-byte APDU limit. Use --max-objects to cap enumeration and a dedicated BACnet client for exhaustive scans.

Severity mapping

FindingSeverity
Object list not readableInfo
Object list accessible unauthenticatedHigh
Data-point present values readableCritical

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target BACnet/IP device
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-5000Per-request timeout in MS
--max-objects <N>-64Maximum number of objects to enumerate
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet object-list --host 192.168.1.50

Plugin name:    bacnet/object-list
Execution time: 12.40 s
Status:         pass
Date:           2026-10-18 00:00:00 UTC

BACnet object list readable at 192.168.1.50:47808: 18 objects
  Device:0  name=HVAC-Controller
  Analog-Input:0  name=Supply-Air-Temp  present-value=22.1500
  Analog-Input:1  name=Return-Air-Temp  present-value=19.3200
  Binary-Output:0  name=Fan-Enable  present-value=1
  ...

3 process data-points readable unauthenticated at 192.168.1.50:47808
  Analog-Input:0 = 22.1500 (Supply-Air-Temp)
  Analog-Input:1 = 19.3200 (Return-Air-Temp)
  Binary-Output:0 = 1 (Fan-Enable)

bacnet - object-properties

Show all readable properties of a specific BACnet object.

Usage

iottack bacnet object-properties --host <HOST> --object <TYPE:INSTANCE> [OPTIONS]

Description

Reads all standard properties of the named BACnet object on the target device. The object is specified as TYPE:INSTANCE where TYPE is the BACnet object type and INSTANCE is the object instance number.

Common abbreviations are accepted for object types. The plugin tries every standard property that may apply to the object and reports what is readable without credentials.

Object type abbreviations

Full nameAbbreviation
analogInputai
analogOutputao
analogValueav
binaryInputbi
binaryOutputbo
binaryValuebv
multiStateInputmsi
multiStateOutputmso
multiStateValuemsv
devicedev
eventEnrollmentee
notificationClassnc
trendLogtl
trendLogMultipletlm
eventLogel
lifeSafetyPointlsp
lifeSafetyZonelsz
pulseConverterpc
loadControllc
structuredViewsv
accessDoorad
accessZoneaz
accessUserau
accessRightsar
accessCredentialac
accessPointap
networkPortnp

Hyphens, underscores, and spaces in type names are ignored. Types without an abbreviation (calendar, command, file, group, loop, program, schedule, averaging, accumulator) must be spelled out.

Properties attempted

Object Identifier, Object Name, Object Type, Description, Present Value, Status Flags, Event State, Out of Service, Reliability, Units, Min/Max Present Value, Resolution, COV Increment, High/Low Limit, Deadband, Limit Enable, Event Enable, Acked Transitions, Notify Type, Number of States, State Text, Active Text, Inactive Text, Polarity, Priority Array, Relinquish Default, Profile Name, Property List.

Severity mapping

FindingSeverity
No properties readableInfo
Properties readable unauthenticatedHigh

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target BACnet/IP device
--object <OBJ>-O(required)Object to inspect, e.g., analogInput:1 or ai:1
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-5000Per-request timeout in ms
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet object-properties --host 192.168.1.50 --object analogInput:1

Plugin name:    bacnet/object-properties
Execution time: 4.12 s
Status:         pass
Date:           2026-10-18 00:00:00 UTC

9 properties readable for AnalogInput:1 at 192.168.1.50:47808
  Object Identifier: AnalogInput:1
  Object Name: Supply-Air-Temp
  Description: Supply air temperature sensor, AHU-01
  Present Value: 22.1500
  Status Flags: false
  Event State: 0
  Out of Service: false
  Units: 62
  High Limit: 35.0000
  Low Limit: 0.0000

bacnet - event-info

List currently active (non-normal) event states on a BACnet device.

Usage

iottack bacnet event-info --host <HOST> [OPTIONS]

Description

Retrieves the object list from the target device and checks the event-state property (property ID 36) on each object. Any object in a non-Normal state is reported with its object identifier, name, and state.

Equivalent to BACteria event_info().

Objects in Normal state or that do not support the event-state property are silently skipped. The plugin reports:

  1. Whether event states were readable at all (always a High finding. Live alarm state is exposed without credentials).
  2. Any objects with non-Normal states (flagged High or Critical depending on severity).

Event state values

ValueNameDescription
0NormalNo active event
1FaultReliability problem detected
2OffnormalValue outside normal range
3High-LimitValue above high limit
4Low-LimitValue below low limit
5Life-Safety-AlarmLife safety alarm condition

Severity mapping

FindingSeverity
Event states not readableInfo
Event states readable unauthenticatedHigh
Active Fault or Life-Safety-Alarm eventsCritical
Other active events (Offnormal, High/Low-Limit)High

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target BACnet/IP device
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-5000Per-request timeout in milliseconds
--max-objects <N>-128Maximum objects to scan for event states
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet event-info --host 192.168.1.50

Plugin name:    bacnet/event-info
Execution time: 18.40 s
Status:         pass
Date:           2025-10-06 00:00:00 UTC

Event state readable on 12 objects at 192.168.1.50:47808 (10 normal, 2 active)

2 active events on 192.168.1.50:47808
  Analog-Input:3  state=High-Limit  (Chilled-Water-Return-Temp)
  Binary-Input:1  state=Offnormal  (Smoke-Detector-Zone-A)

bacnet - fuzz

Send malformed BACnet/IP payloads to a device and report anomalous responses.

Usage

iottack bacnet fuzz --host <HOST> [OPTIONS]

Description

Sends a suite of crafted malformed BACnet/IP packets to the target device and classifies each response as a normal Error/Reject/Abort PDU, an anomalous PDU type or a potential crash indicator. A liveness check runs before and after the payload set. if the device stops responding, a Critical DoS finding is raised.

Based on the mutation strategy from BACteria fuzzer.py.

Payload categories

CategoryDescription
Truncated APDUEmpty, 1-byte, 2-byte Confirmed-Request frames
ReadProperty mutationsMax instance (0x3FFFFF), invalid object type (1023), property ID 0xFFFF, invoke-id 0xFF
Segmentation flagsSEG bit set without segmentation headers, MOR bit set
WritePropertyAttempts to overwrite Device Object Name and AnalogInput:0 Present Value
DeviceCommunicationControlTries to permanently disable device communications
ReinitializeDeviceAttempts cold-start and warm-start restarts
ReadPropertyMultiple ALLRequests all properties in one APDU
Who-Is extremesUnrestricted Who-Is broadcast
BVLC anomaliesWrong function code, length mismatch, broadcast function to unicast, garbage prefix
Boundary APDUs64/256/1024/1025 zero-bytes, all 0xFF

Response classification

Each response is decoded into a descriptive string before pattern matching:

Response typeDescription shown
Simple-ACKbacnet-simple-ack
Complex-ACKbacnet-complex-ack
Error PDUbacnet-error class=N code=N
Reject PDUbacnet-reject reason=N (label)
Abort PDUbacnet-abort reason=N (label)
Malformed BVLCinvalid-bvlc-response
No APDU foundno-apdu-in-response

Patterns flagged as interesting: bacnet-reject, bacnet-abort, overflow (buffer-overflow abort reason), bacnet-unknown, invalid-bvlc, no-apdu, plus any --pattern overrides.

Severity mapping

FindingSeverity
No anomalous responsesInfo
Reject/Abort PDU receivedMedium
Buffer-overflow abort reasonCritical
Device unresponsive after fuzzing (DoS)Critical

Options

FlagShortDefaultDescription
--host <HOST>-H(required)Target BACnet/IP device
--port <PORT>-p47808BACnet/IP UDP port
--timeout-ms <MS>-1000Per-packet response timeout
--iterations <N>-1Times to repeat the full payload set
--delay-ms <MS>-d50Inter-packet delay in ms
--wordlist <PATH>-w-File of additional APDU payloads (one hex or binary line each)
--pattern <STR>--Extra response pattern to flag as interesting
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json
--verbose-v-Increase log verbosity

Example

$ iottack bacnet fuzz --host 192.168.1.50 --delay-ms 100

Plugin name:    bacnet/fuzz
Execution time: 42.10 s
Status:         fail
Date:           2025-10-14 00:00:00 UTC

Interesting response to 'reinitialize-coldstart' payload
  192.168.1.50:47808 responded with patterns [bacnet-reject] after receiving the 'reinitialize-coldstart' payload.
  bacnet-reject reason=9 (unrecognized-service)

Interesting response to 'device-comm-control-disable' payload
  192.168.1.50:47808 responded with patterns [bacnet-reject] after receiving the 'device-comm-control-disable' payload.
  bacnet-reject reason=9 (unrecognized-service)

Interesting response to 'apdu-1025-zeros' payload
  192.168.1.50:47808 responded with patterns [bacnet-abort, overflow] after receiving the 'apdu-1025-zeros' payload.
  bacnet-abort reason=1 (buffer-overflow overflow)

Notes

  • Rate limiting: use --delay-ms to avoid overwhelming devices with slow BACnet stacks.
  • DoS risk: reinitialize-coldstart and device-comm-control-disable payloads may disrupt live devices.
  • Wordlist format: each line is treated as raw APDU bytes if the line starts with 0x81 (full packet), otherwise wrapped in a valid BVLC/NPDU unicast frame.

Thread

thread sniffer

Vulnerability plugins

Plugins in this category test for known published CVEs and vendor-specific vulnerabilities in IoT firmware and protocols. Each plugin targets a specific vulnerability, verifies exploitability conditions and reports findings with CVE references and concrete mitigation steps.

PluginDescription
blufiunauthenticated vendor-specific HCI commands CVE-2025-27840

vuln blueborne

Scans for nearby Bluetooth devices and assesses each one against the BlueBorne vulnerability set disclosed in September 2017.

BlueBorne is a collection of eight vulnerabilities affecting Bluetooth stacks across Linux, Android, Windows and iOS. Unlike most Bluetooth attacks, BlueBorne requires no pairing, no user interaction and no prior association with the target device. Any device with Bluetooth enabled and within radio range is potentially within the attack surface.

CVE coverage

CVEPlatformImpactCVSS
CVE-2017-0781AndroidRCE via BNEP heap overflow8.8
CVE-2017-0782AndroidRCE via AVDTP heap overflow8.8
CVE-2017-0783AndroidInformation disclosure via PAN6.5
CVE-2017-0785AndroidInformation disclosure via SDP6.5
CVE-2017-1000250Linux (BlueZ)Information disclosure via SDP6.5
CVE-2017-1000251Linux kernelRCE via L2CAP stack overflow8.0
CVE-2017-8628WindowsMitM attack via PAN/BNEP8.1

How detection works

The plugin cannot confirm patch status remotely. It uses observable Bluetooth properties to identify devices likely affected by each CVE:

SignalSourceInfers
Device name contains “Galaxy”, “Pixel”, “Huawei”, etc.Name propertyAndroid
Device name contains “ubuntu”, “raspberry”, “debian”, etc.Name propertyLinux
Bluetooth major class = Computer (0x01)Class propertyLinux
Bluetooth major class = Phone (0x02)Class propertyAndroid/mobile
Icon type = phoneIcon propertyAndroid/mobile
Advertises A2DP/AVDTP UUIDUUIDs propertyCVE-2017-0781/0782 target
Advertises BNEP/PAN UUIDUUIDs propertyCVE-2017-0783/0783/8628 target

All findings are advisory. A device that receives no specific CVE mapping is still reported as “in range” because BlueBorne can target any reachable device with Bluetooth Classic enabled.

Status

ResultMeaning
passScan completed (findings may still indicate exposure)
failBluetooth unavailable or no adapter found

Severity

SeverityCondition
HighPlatform identified (Android/Linux) and matching vulnerable profile present
MediumPlatform identified or vulnerable profile present
LowGeneric Bluetooth device with no specific indicators
InfoDevice discovered but no BlueBorne indicators found

Requirements

  • BlueZ daemon (bluetoothd) must be running.
  • The D-Bus system bus must be accessible.
  • Devices must be advertising and within radio range.

Usage

iottack vuln blueborne [OPTIONS]

Options

FlagShortDefaultDescription
--timeout <SECS>-t15Scan duration in seconds
--adapter <NAME>-afirst availableBluetooth adapter to use, e.g. hci0
--output <FILE>-o-Save result to a file
--format <FORMAT>-texttext or json
--verbose-v-Increase log verbosity

Examples

Scan with the default 15 second window:

iottack vuln blueborne

Extended scan with a specific adapter and JSON output:

iottack vuln blueborne --timeout 30 --adapter hci1 --format json --output report.json

Mitigation

Apply all Bluetooth security patches from September 2017 or later. Where possible, disable Bluetooth when not in use.

PlatformAction
AndroidApply the September 2017 Android Security Bulletin
LinuxUpdate kernel ≥ 4.14 and BlueZ ≥ 5.47
WindowsApply MS17-013 / KB4038788
iOSUpgrade to iOS 10 or later

vulns bluefi

CVE-2025-27840 affects ESP32 Bluetooth firmware. When an ESP32 is connected via USB in HCI (Host Controller Interface) mode, the full HCI command set is exposed with no authentication. This includes undocumented Espressif vendor-specific commands (OGF 0x3F) that provide:

  • Arbitrary memory read: extract RAM, ROM, or flash content including cryptographic keys, Wi-Fi credentials, and NVS secrets.
  • Arbitrary memory write: overwrite runtime state, disable security checks, or inject code.

The plugin:

  1. Opens the ESP32 serial port and sends HCI_Reset to confirm HCI mode.
  2. Probes the two known-dangerous OCFs (0x001 read, 0x002 write) and flags any that respond with a non-“unknown command” status.
  3. Sweeps vendor OCF 0x000 through --ocf-end (default 15) to enumerate the broader attack surface.

HCI command structure:

[0x01][opcode_lo][opcode_hi][param_len][params...]

For vendor commands (OGF 0x3F): opcode = 0xFC00 | OCF

Checks performed

CheckFindingSeverity
Device responds to HCI_ResetHCI interface reachableMedium
OCF 0x001 responsiveArbitrary memory readCritical
OCF 0x002 responsiveArbitrary memory writeCritical
Any OCF in sweep responsiveAdditional attack surfaceHigh
No responsive commands foundNot vulnerable / patchedInfo

Usage

iottack vulns bluefi --port /dev/ttyUSB1 [OPTIONS]

Options

FlagShortDefaultDescription
--port <PORT>-p(required)Serial port of the ESP32 in HCI mode
--baud-rate <BAUD>-b115200Serial baud rate
--timeout-ms <MS>-t200Per-command response timeout
--ocf-end <N>-e15Last OCF to sweep (max 1023 for full scan)
--output <FILE>-o-Save result to a file
--format <FORMAT>-ftexttext or json

Examples

Quick targeted probe (known dangerous OCFs only, ~3 s):

iottack vulns bluefi --port /dev/ttyUSB1

Full vendor command enumeration (~200 s):

iottack vulns bluefi --port /dev/ttyUSB1 --ocf-end 1023

Save as JSON:

iottack vulns bluefi --port /dev/ttyUSB1 --output bluefi.json --format json

Mitigation

  • In production firmware, disable the HCI UART interface: set CONFIG_BT_HCI_UART=n in sdkconfig.
  • Apply the Espressif patch that restricts vendor command access to authenticated channels (available in ESP-IDF ≥ 5.x with the security fix).
  • Reference: https://nvd.nist.gov/vuln/detail/CVE-2025-27840

Target devices

iottack is meant to run against real IoT hardware or services. These boards or services are used as targets or dummy devices throughout the documentation to demonstrate how the plugins behave against an actual piece of hardware or an actual service.

DeviceFirmwareNotes
Bluetooth deviceCircuitPythonBluetooth device with a LED
Generic IoT deviceESPHomeWi-Fi target for the network plugins
UART deviceCircuitPythonSerial target for the UART plugins
AMQP server-Local RabbitMQ server
TCP simulatorPython 3.13+Software-only target for all tcp plugins
Modbus simulatorPython / pymodbusSoftware-only target for all modbus plugins
BACnet/IP simulatorPython / bacpypes3Software-only target for BACnet plugins

Generic IoT Test Target (ESPHome)

A WEMOS LOLIN S2 Mini is used as a target or dummy device to demonstrate how the iottack plugins behave against a real piece of IoT hardware. Any other ESP32-S2 based board can be substituted.

The device runs ESPHome as its firmware. ESPHome exposes a well-known set of network services (mDNS, the native API, a web server and OTA updates), which makes the board a convenient target for the network plugins.

Firmware

ESPHome is compiled for the esp32s2 platform and flashed onto the board. The configuration below enables the services that the iottack network plugins target:

  • mdns: announces the device on the local network (see mdns-scan)
  • web_server: serves an HTTP interface on port 80
  • api: the native ESPHome API on port 6053
  • ota: over-the-air updates via the ESPHome dashboard

ESPHome configuration

# Board: LOLIN S2 Mini (LOLIN/Wemos)
# Definition: definitions/boards/esp32-s2-mini/manifest.yaml

esphome:
  name: iottack-target-device
  friendly_name: iottack Target device (ESPHome)

esp32:
  variant: esp32s2
  flash_size: 4MB
  framework:
    type: esp-idf

logger:

api:
  encryption:
    key: "2EXXjaLyzz9n13NZcjuDALwwIli7wyK/mfvLKssxHoA="

ota:
  - platform: esphome

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  ap:
    ssid: iottack Target  Fallback Hotspot
    password: "12345678"

captive_portal:

async_tcp:

mdns:

web_server:

text_sensor:
  - platform: uptime
    name: Uptime Text Sensor
    id: text_sensor_uptime_1
  - platform: version
    name: Version Text Sensor
    id: text_sensor_version_1
  - platform: wifi_info
    ip_address:
      name: IP Address
      id: wifi_info_ip_address
      address_0:
        name: Address 0

Testing with iottack

Once flashed and connected to the network, the device can be discovered and enumerated:

# Discover the device via mDNS
iottack network mdns-scan

UART Test Target (CircuitPython)

Some example in the Plugin documentation are showing how an actual approach could be taken to exploit a device.

The hardware base for this “simulator”, target or dummy device is a Seeed Studio XIAO RP2040. Pretty much every other device based on the RP 2040 could be used.

For simplicity, ciruitpython act as the base firmware. For further details about the usage or how to get started with circuitpython, check their documentation.

Code for UART fuzz examples

This code simulates a IoT bulb which can be controlled over a serial connection. The code accepts a number of command to interact with the build-in LED.

Add this code to code.py and add neopixel.mpy to the libs folder. Then reboot the device with Ctrl-D.

import board
import digitalio
import neopixel
import supervisor
import sys
import time

# Turn ON the power to the onboard NeoPixel
pixel_power = digitalio.DigitalInOut(board.NEOPIXEL_POWER)
pixel_power.direction = digitalio.Direction.OUTPUT
pixel_power.value = True

# Initialize the NeoPixel (1 pixel built into the board, uses GRB color ordering
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.3, pixel_order=neopixel.GRB)

# Define some colors (Red, Green, Blue)
BLACK = (0, 0, 0)  # Off
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
    
# Helper function to generate rainbow colors (0-255)
def color_wheel(pos):
    if pos < 0 or pos > 255:
        return (0, 0, 0)
    if pos < 85:
        return (255 - pos * 3, pos * 3, 0)
    if pos < 170:
        pos -= 85
        return (0, 255 - pos * 3, pos * 3)
    pos -= 170
    return (pos * 3, 0, 255 - pos * 3)

# Shell and animation variables
input_buffer = ""
rainbow_active = False
rainbow_wheel_pos = 0
last_rainbow_update = 0

# Print instructions and the initial shell prompt
print("XIAO Shell: Type 'red', 'green', 'blue' or 'off'. Ctrl+C to exit.")
sys.stdout.write("xiao> ")

while True:
    # 1. Process standard keyboard inputs
    if supervisor.runtime.serial_bytes_available:
        char = sys.stdin.read(1)
        
        # Handle Enter key
        if char in ('\r', '\n'):
            sys.stdout.write("\n")
            command = input_buffer.strip().lower()
            
            if command == "green":
                rainbow_active = False
                pixel[0] = GREEN
                sys.stdout.write("Hit - Green\n")
            elif command == "red":
                rainbow_active = False
                pixel[0] = RED
                sys.stdout.write("Hit - Red\n")
            elif command == "blue":
                rainbow_active = False
                pixel[0] = BLUE
                sys.stdout.write("Hit - Blue\n")
            elif command == "abc":
                rainbow_active = True
                sys.stdout.write("Hit - Rainbow started!\n")
            elif command == "x":
                rainbow_active = False
                pixel[0] = YELLOW
                sys.stdout.write("Hit - x\n")
            elif command == "off":
                rainbow_active = False
                pixel[0] = BLACK
                sys.stdout.write("Hit - Off\n")
            elif command == "":
                pass
            else:
                sys.stdout.write(f"Unknown command: '{command}'\n")
                
            input_buffer = ""
            sys.stdout.write("xiao> ")
            
        # Handle Backspace key
        elif char in ('\x08', '\x7f'):
            if len(input_buffer) > 0:
                input_buffer = input_buffer[:-1]
                sys.stdout.write("\x08 \x08")
                
        # Handle printable text characters
        else:
            input_buffer += char
            sys.stdout.write(char)

    # Update the rainbow animation incrementally (non-blocking)
    if rainbow_active:
        current_time = time.monotonic()
        # Update the color roughly every 0.02 seconds (20ms) for a smooth cycle
        if current_time - last_rainbow_update > 0.02:
            pixel[0] = color_wheel(rainbow_wheel_pos)
            rainbow_wheel_pos = (rainbow_wheel_pos + 1) % 256
            last_rainbow_update = current_time

Once the code is uploaded to the device:

XIAO Shell: Type 'red', 'green', 'blue' or 'off'. Ctrl+C to exit.
xiao> green
Hit - Green
xiao> off
Hit - Off

AMQP server

To test and to get yourself familiar with AMQP, a local RabbitMQ server is useful.

On NixOS you can spin-up a AMQP server by enabling it in the configuration.nix file:

  services.rabbitmq = {
    enable = true;
    managementPlugin.enable = true;
  };

For more options, check the options.

After sudo nixos-rebuild switch, the server is available.

$ http http://localhost:15672
HTTP/1.1 200 OK
allow: HEAD, GET, OPTIONS
[...]
server: Cowboy
vary: origin, accept-encoding

TCP Test Target

The TCP test target is a Python script that simulates nine vulnerable IoT services on separate ports. It runs entirely in software with no physical hardware required, so every iottack tcp plugin can be exercised locally.

Source: test-targets/iottack-target-tcp/iottack-tcp.py

Requirements

Python 3.13 or later. No third-party packages/modules are needed.

Services

ServiceDefault portSimulated vulnerabilityExpected finding
SSH2222Version disclosure in bannerInfo
FTP2121vsftpd 2.3.4, any password acceptedHigh
Telnet2323Login prompt with weak credentialsHigh
HTTP8080Admin panel with firmware version disclosureLow
Redis6379No authentication requiredHigh
MQTT1883No authentication requiredHigh
Modbus/TCP5020PLC registers readable without authHigh
Shell4444Unauthenticated root shellCritical
Fuzz7777Buffer overflow and format string bugsHigh

Usage

Start all services on localhost:

python test-targets/iottack-target-tcp/iottack-tcp.py

Start only a subset:

python test-targets/iottack-target-tcp/iottack-tcp.py --services shell,telnet,fuzz

Expose on all interfaces (use with care):

python test-targets/iottack-target-tcp/iottack-tcp.py --host 0.0.0.0

Override individual ports:

python test-targets/iottack-target-tcp/iottack-tcp.py --shell-port 9999 --fuzz-port 9998

Enable debug logging:

python test-targets/iottack-target-tcp/iottack-tcp.py -v

Testing with iottack

Scan all simulated services in one pass:

iottack tcp banner --host 127.0.0.1 \
    --ports 2222,2121,2323,8080,6379,1883,5020

Shell detection

Unauthenticated root shell (Critical):

iottack tcp shell-detect --host 127.0.0.1 --port 4444

Telnet login prompt (High):

iottack tcp shell-detect --host 127.0.0.1 --port 2323

Fuzzing

iottack tcp fuzz --host 127.0.0.1 --port 7777

With reconnect per payload to catch crash behaviour:

iottack tcp fuzz --host 127.0.0.1 --port 7777 --reconnect

Telnet credentials

The Telnet service accepts any of these username/password combinations:

UsernamePassword
adminadmin
adminroot
rootroot
rootpassword
guest1234

Any other combination returns Login incorrect.

Code

#!/usr/bin/env python3
"""IoTtack TCP target is a multi-service test server for TCP attack scenarios.

Simulates twelve vulnerable IoT services on separate ports so that every
iottack TCP plugin (banner, shell-detect or fuzz) can be exercised locally
without real hardware.

Usage
-----
  python iottack-tcp.py                           # all services, 127.0.0.1
  python iottack-tcp.py --host 0.0.0.0            # expose on all interfaces
  python iottack-tcp.py --services ssh,ftp,redis  # start a subset
  python iottack-tcp.py --shell-port 9999 -v      # override a port

Services and expected plugin findings
--------------------------------------
  ssh    :2222 SSH-2.0 banner             -> banner Info
  ftp    :2121 vsftpd 2.3.4 (any pass)    -> banner High
  telnet :2323 IAC negotiation + login:   -> banner High / shell-detect High
  http   :8080 admin panel response       -> banner Low
  redis  :6379 no-auth Redis              -> banner High
  mqtt   :1883 MQTT broker (no auth)      -> banner High
  modbus :5020 Modbus/TCP PLC sim         -> banner High
  shell  :4444 unauthenticated root shell -> shell-detect Critical
  fuzz   :7777 buffer-overflow target     -> fuzz High
"""

import asyncio
import argparse
import logging
import struct
import sys
from dataclasses import dataclass
from typing import Callable

log = logging.getLogger("iottack-target")


async def handle_ssh(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Handle an incoming SSH connection."""
    log.info("SSH connect from %s", writer.get_extra_info("peername"))
    try:
        writer.write(b"SSH-2.0-OpenSSH_7.2p2 IoTtackOS-1.0\r\n")
        await writer.drain()
        await asyncio.wait_for(reader.read(256), timeout=5.0)
    except (asyncio.TimeoutError, ConnectionResetError, BrokenPipeError):
        pass
    finally:
        writer.close()


async def handle_ftp(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Handle an incoming FTP connection."""
    log.info("FTP connect from %s", writer.get_extra_info("peername"))
    try:
        writer.write(b"220 (vsftpd 2.3.4)\r\n")
        await writer.drain()
        while True:
            line = await asyncio.wait_for(reader.readline(), timeout=30.0)
            if not line:
                break
            cmd = line.strip().upper()
            if cmd.startswith(b"USER"):
                writer.write(b"331 Please specify the password.\r\n")
            elif cmd.startswith(b"PASS"):
                writer.write(b"230 Login successful.\r\n")  # accept any password
            elif cmd.startswith(b"SYST"):
                writer.write(b"215 UNIX Type: L8\r\n")
            elif cmd.startswith(b"FEAT"):
                writer.write(b"211-Features:\r\n EPRT\r\n EPSV\r\n211 End\r\n")
            elif cmd.startswith(b"PWD"):
                writer.write(b'257 "/" is current directory.\r\n')
            elif cmd.startswith(b"LIST") or cmd.startswith(b"NLST"):
                writer.write(b"150 Here comes the directory listing.\r\n226 Directory send OK.\r\n")
            elif cmd.startswith(b"QUIT"):
                writer.write(b"221 Goodbye.\r\n")
                break
            else:
                writer.write(b"500 Unknown command.\r\n")
            await writer.drain()
    except (asyncio.TimeoutError, ConnectionResetError, BrokenPipeError):
        pass
    finally:
        writer.close()


def _strip_iac(data: bytes) -> bytes:
    """Remove Telnet IAC command sequences from raw client data."""
    result = bytearray()
    i = 0
    while i < len(data):
        if data[i] == 0xFF and i + 1 < len(data):
            cmd = data[i + 1]
            if cmd in (0xFB, 0xFC, 0xFD, 0xFE) and i + 2 < len(data):
                i += 3  # WILL/WONT/DO/DONT & option byte
            elif cmd == 0xFF:
                result.append(0xFF)
                i += 2
            else:
                i += 2
        else:
            result.append(data[i])
            i += 1
    return bytes(result)


async def handle_telnet(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Handle an incoming Telnet connection."""
    log.info("Telnet connect from %s", writer.get_extra_info("peername"))
    try:
        # IAC DO SUPPRESS-GO-AHEAD + IAC WILL ECHO, then banner and login prompt
        writer.write(b"\xff\xfd\x03\xff\xfb\x01\r\nIoTtack Test Device v1.0\r\n\r\nlogin: ")
        await writer.drain()

        username = _strip_iac(await asyncio.wait_for(reader.read(64), timeout=15.0)).strip().lower()
        writer.write(b"\r\nPassword: ")
        await writer.drain()
        password = _strip_iac(await asyncio.wait_for(reader.read(64), timeout=15.0)).strip().lower()

        weak_users = (b"admin", b"root", b"user", b"guest")
        weak_passes = (b"admin", b"root", b"password", b"1234", b"12345", b"")
        if username in weak_users and password in weak_passes:
            writer.write(b"\r\n# ")
            await writer.drain()
            while True:
                cmd = (await asyncio.wait_for(reader.readline(), timeout=60.0)).strip()
                if not cmd or cmd in (b"exit", b"logout"):
                    break
                if cmd == b"id":
                    reply = b"uid=0(root) gid=0(root) groups=0(root)\r\n# "
                elif cmd == b"whoami":
                    reply = b"root\r\n# "
                elif cmd == b"uname -a":
                    reply = b"Linux iottack-device 4.14.0 #1 SMP PREEMPT armv7l GNU/Linux\r\n# "
                elif cmd == b"cat /etc/passwd":
                    reply = b"root:x:0:0:root:/root:/bin/sh\r\nadmin:x:1000:1000::/home/admin:/bin/sh\r\n# "
                elif cmd.startswith(b"ls"):
                    reply = b"bin  dev  etc  lib  proc  root  sys  tmp  usr  var\r\n# "
                elif cmd == b"":
                    reply = b"# "
                else:
                    reply = cmd + b": not found\r\n# "
                writer.write(reply)
                await writer.drain()
        else:
            writer.write(b"\r\nLogin incorrect\r\n\r\nlogin: ")
            await writer.drain()
    except (asyncio.TimeoutError, ConnectionResetError, BrokenPipeError):
        pass
    finally:
        writer.close()


async def handle_http(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Handle an incoming HTTP connection."""
    log.info("HTTP   connect from %s", writer.get_extra_info("peername"))
    try:
        await asyncio.wait_for(reader.read(4096), timeout=10.0)
        body = (
            b"<html><head><title>IoTtack Device Admin</title></head>"
            b"<body><h1>IoTtack Device Admin Panel</h1>"
            b"<p>Firmware: 1.0.0 | Model: IoTtack-T1</p>"
            b"</body></html>"
        )
        writer.write(
            b"HTTP/1.1 200 OK\r\n"
            b"Server: IoT-HTTPD/1.0\r\n"
            b"Content-Type: text/html\r\n"
            b"Content-Length: " + str(len(body)).encode() + b"\r\n"
            b"\r\n" + body
        )
        await writer.drain()
    except (asyncio.TimeoutError, ConnectionResetError, BrokenPipeError):
        pass
    finally:
        writer.close()


async def handle_redis(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Handle an incoming Redis connection."""
    log.info("Redis connect from %s", writer.get_extra_info("peername"))
    try:
        while True:
            data = await asyncio.wait_for(reader.read(256), timeout=10.0)
            if not data:
                break
            upper = data.decode(errors="replace").upper()
            if "PING" in upper:
                writer.write(b"+PONG\r\n")
            elif "INFO" in upper:
                info = (
                    b"# Server\r\nredis_version:2.8.17\r\nredis_mode:standalone\r\n"
                    b"os:Linux 4.14.0 armv7l\r\nconfig_file:/etc/redis/redis.conf\r\n"
                )
                writer.write(b"$" + str(len(info)).encode() + b"\r\n" + info + b"\r\n")
            elif "CONFIG" in upper:
                writer.write(b"*2\r\n$4\r\nbind\r\n$9\r\n0.0.0.0\r\n")
            elif "QUIT" in upper:
                writer.write(b"+OK\r\n")
                break
            else:
                writer.write(b"-ERR unknown command\r\n")
            await writer.drain()
    except (asyncio.TimeoutError, ConnectionResetError, BrokenPipeError):
        pass
    finally:
        writer.close()


async def handle_mqtt(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Handle an incoming MQTT connection."""
    log.info("MQTT connect from %s", writer.get_extra_info("peername"))
    try:
        data = await asyncio.wait_for(reader.read(256), timeout=10.0)
        if not data or data[0] != 0x10:  # CONNECT packet type
            return
        # CONNACK: accepted, no session present
        writer.write(b"\x20\x02\x00\x00")
        await writer.drain()
        while True:
            pkt = await asyncio.wait_for(reader.read(256), timeout=30.0)
            if not pkt:
                break
            pkt_type = (pkt[0] & 0xF0) >> 4
            if pkt_type == 14:    # DISCONNECT
                break
            elif pkt_type == 12:  # PINGREQ -> PINGRESP
                writer.write(b"\xd0\x00")
                await writer.drain()
            elif pkt_type == 8 and len(pkt) >= 4:  # SUBSCRIBE -> SUBACK
                writer.write(b"\x90\x03" + pkt[2:4] + b"\x00")
                await writer.drain()
    except (asyncio.TimeoutError, ConnectionResetError, BrokenPipeError):
        pass
    finally:
        writer.close()


async def handle_modbus(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Handle an incoming Modbus connection."""
    log.info("Modbus connect from %s", writer.get_extra_info("peername"))
    try:
        while True:
            header = await asyncio.wait_for(reader.readexactly(6), timeout=10.0)
            trans_id = header[0:2]
            length = struct.unpack(">H", header[4:6])[0]
            pdu = await asyncio.wait_for(reader.readexactly(length), timeout=5.0)
            if not pdu:
                break
            unit_id = pdu[0]
            func_code = pdu[1] if len(pdu) > 1 else 0x00

            if func_code == 0x03:  # Read Holding Registers
                reg_data = b"\x00\x01\x00\x02"
                body = bytes([unit_id, func_code, len(reg_data)]) + reg_data
            elif func_code == 0x01:  # Read Coils
                body = bytes([unit_id, func_code, 1, 0x01])
            elif func_code == 0x2B:  # Read Device Identification
                vendor = b"IoT Corp"
                body = bytes([unit_id, func_code, 0x0E, 0x01, 0x01, 0x00, 0x00, 0x01, len(vendor)]) + vendor
            else:
                body = bytes([unit_id, func_code | 0x80, 0x01])  # illegal function exception

            writer.write(trans_id + b"\x00\x00" + struct.pack(">H", len(body)) + body)
            await writer.drain()
    except (asyncio.TimeoutError, asyncio.IncompleteReadError, ConnectionResetError, BrokenPipeError):
        pass
    finally:
        writer.close()


async def handle_shell(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Unauthenticated root shell. No credentials required (Critical finding)."""
    log.info("Shell connect from %s (unauthenticated)", writer.get_extra_info("peername"))
    try:
        writer.write(b"root@iottack:~# ")
        await writer.drain()
        while True:
            cmd = (await asyncio.wait_for(reader.readline(), timeout=60.0)).strip()
            if not cmd or cmd in (b"exit", b"logout"):
                break
            if cmd == b"id":
                reply = b"uid=0(root) gid=0(root) groups=0(root)\r\nroot@iottack:~# "
            elif cmd == b"whoami":
                reply = b"root\r\nroot@iottack:~# "
            elif cmd == b"uname -a":
                reply = b"Linux iottack 4.14.0 #1 SMP PREEMPT armv7l GNU/Linux\r\nroot@iottack:~# "
            elif cmd == b"cat /etc/passwd":
                reply = b"root:x:0:0:root:/root:/bin/sh\r\nadmin::1000:1000::/home/admin:/bin/sh\r\nroot@iottack:~# "
            elif cmd == b"cat /etc/shadow":
                reply = b"root:$1$IoTtarget$abc123:0:0:99999:7:::\r\nadmin::0:0:99999:7:::\r\nroot@iottack:~# "
            elif cmd.startswith(b"ls"):
                reply = b"bin  dev  etc  lib  proc  root  sys  tmp  usr  var\r\nroot@iottack:~# "
            elif cmd == b"":
                reply = b"root@iottack:~# "
            else:
                reply = cmd + b": command not found\r\nroot@iottack:~# "
            writer.write(reply)
            await writer.drain()
    except (asyncio.TimeoutError, ConnectionResetError, BrokenPipeError):
        pass
    finally:
        writer.close()


async def handle_fuzz(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    """Fuzz target: simulates buffer overflow, format-string and path-traversal bugs."""
    log.info("Fuzz connect from %s", writer.get_extra_info("peername"))
    try:
        writer.write(b"READY\r\n")
        await writer.drain()
        while True:
            data = await asyncio.wait_for(reader.read(4096), timeout=10.0)
            if not data:
                break
            if len(data) > 512:
                writer.write(b"ERROR: input too long -- buffer overflow\r\n")
                break
            if b"\x00" in data:
                writer.write(b"ERROR: null byte in input\r\n")
                break
            if b"%s" in data or b"%n" in data or b"%x" in data:
                writer.write(b"ERROR: format string in input\r\n")
            elif b"/../" in data or b"../" in data:
                writer.write(b"ERROR: path traversal attempt\r\n")
            elif data.strip().upper() in (b"ADMIN", b"ROOT"):
                writer.write(b"ACCESS GRANTED\r\n")
            else:
                writer.write(b"OK: " + data[:256])
            await writer.drain()
    except (asyncio.TimeoutError, ConnectionResetError, BrokenPipeError):
        pass
    finally:
        writer.close()


@dataclass
class ServiceDef:
    name: str
    handler: Callable
    default_port: int
    description: str


SERVICES: list[ServiceDef] = [
    ServiceDef("ssh", handle_ssh, 2222, "SSH-2.0 banner (Info)"),
    ServiceDef("ftp", handle_ftp, 2121, "vsftpd 2.3.4, any password accepted (High)"),
    ServiceDef("telnet", handle_telnet, 2323, "Telnet login prompt, weak creds succeed (High)"),
    ServiceDef("http", handle_http, 8080, "HTTP admin panel with info disclosure (Low)"),
    ServiceDef("redis", handle_redis, 6379, "Redis with no authentication (High)"),
    ServiceDef("mqtt", handle_mqtt, 1883, "MQTT broker with no authentication (High)"),
    ServiceDef("modbus", handle_modbus, 5020, "Modbus/TCP PLC simulation (High)"),
    ServiceDef("shell", handle_shell, 4444, "Unauthenticated root shell (Critical)"),
    ServiceDef("fuzz", handle_fuzz, 7777, "Buffer-overflow/format-string target (High)"),
]


async def _amain(args: argparse.Namespace) -> None:
    """Main entry point for the TCP service target."""
    if args.services == "all":
        enabled = {s.name for s in SERVICES}
    else:
        enabled = {x.strip().lower() for x in args.services.split(",")}

    servers = []
    for svc in SERVICES:
        if svc.name not in enabled:
            continue
        port: int = getattr(args, f"{svc.name}_port")
        try:
            srv = await asyncio.start_server(svc.handler, args.host, port)
            servers.append((svc.name, port, srv))
            log.info("%-8s  %s:%d - %s", svc.name.upper(), args.host, port, svc.description)
        except OSError as exc:
            log.error("%-8s  cannot bind on %s:%d - %s", svc.name, args.host, port, exc)

    if not servers:
        log.error("No services started, exiting")
        sys.exit(1)

    log.info("%d service(s) running. Ctrl-C to stop.", len(servers))
    tasks = [asyncio.create_task(srv.serve_forever()) for _, _, srv in servers]
    try:
        await asyncio.gather(*tasks)
    except (KeyboardInterrupt, asyncio.CancelledError):
        pass
    finally:
        for task in tasks:
            task.cancel()
        for _, _, srv in servers:
            srv.close()
            await srv.wait_closed()
        log.info("All services stopped.")


def main() -> None:
    """IoTtack TCP test target."""
    svc_names = ", ".join(s.name for s in SERVICES)
    parser = argparse.ArgumentParser(
        description="IoTtack TCP test target to simulate vulnerable IoT services.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "Default ports:\n"
            + "\n".join(f"  {s.name:<8} :{s.default_port:<5}  {s.description}" for s in SERVICES)
            + "\n\nExamples:\n"
            "  python iottack-tcp.py\n"
            "  python iottack-tcp.py --host 0.0.0.0 -v\n"
            "  python iottack-tcp.py --services shell,fuzz,telnet\n"
            "  python iottack-tcp.py --shell-port 9999 --fuzz-port 9998\n"
            "\n"
            "Test with iottack banner plugin:\n"
            f"  iottack tcp banner --host 127.0.0.1 --ports 2222,2121,2323,2525,1100,1430,5900,8080,6379,1883,5020\n"
            "\n"
            "Test shell-detect:\n"
            "  iottack tcp shell-detect --host 127.0.0.1 --port 4444   # Critical\n"
            "  iottack tcp shell-detect --host 127.0.0.1 --port 2323   # High\n"
            "\n"
            "Test fuzz:\n"
            "  iottack tcp fuzz --host 127.0.0.1 --port 7777\n"
        ),
    )
    parser.add_argument(
        "--host", default="127.0.0.1",
        help="Bind address (default: 127.0.0.1, use 0.0.0.0 to expose on all interfaces)",
    )
    parser.add_argument(
        "--services", default="all", metavar="LIST",
        help=f"Comma-separated services to start or 'all'. Available: {svc_names}",
    )
    parser.add_argument("-v", "--verbose", action="store_true", help="Enable debug logging")
    for svc in SERVICES:
        parser.add_argument(
            f"--{svc.name}-port", type=int, default=svc.default_port,
            metavar="PORT", dest=f"{svc.name}_port",
            help=f"{svc.name} port (default: {svc.default_port})",
        )

    args = parser.parse_args()
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.INFO,
        format="%(asctime)s  %(levelname)-8s  %(message)s",
    )
    try:
        asyncio.run(_amain(args))
    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()

Modbus/TCP Simulator

The Modbus/TCP simulator is a standalone Python server that emulates a realistic PLC with pre-populated data across all four Modbus data types. It runs entirely in software — no physical hardware required. So every iottack modbus plugin can be exercised locally.

Source: test-targets/iottack-modbus/simulator.py

Requirements

pymodbus 3.x. The Nix flake in test-targets/iottack-modbus/ provides a reproducible environment with the correct version pinned.

Data layout

Data typeFunction codeAddress rangeCountNotes
Holding registersFC030-9991000Status, setpoints, counters, config, alarm thresholds
Input registersFC040-99100Temperature, pressure, voltage, current, uptime
CoilsFC010-3132Alternating ON/OFF pattern
Discrete inputsFC020-3132Fixed sensor bits (door open, motor running, …)

FC43 MEI device identification (Read Device Identification) is also enabled with vendor strings: iottack Labs / SIMBUS-1000 / 1.0.0.

Usage

# Start on 0.0.0.0:5020, unit 1
nix run ./test-targets/iottack-modbus

# Loopback only
nix run ./test-targets/iottack-modbus -- --host 127.0.0.1

# Custom port and unit ID
nix run ./test-targets/iottack-modbus -- --port 502 --unit 3

Without Nix

pip install pymodbus
python test-targets/iottack-modbus/simulator.py
python test-targets/iottack-modbus/simulator.py --host 127.0.0.1 --port 5020 --unit 1

Testing with iottack

Start the simulator first, then run any of the commands below against it.

Device identification

iottack modbus device-info --host 127.0.0.1 --tcp-port 5020

Read holding registers

iottack modbus read-registers --host 127.0.0.1 --tcp-port 5020 --address 0 --count 10

Read input registers (FC04):

iottack modbus read-registers --host 127.0.0.1 --tcp-port 5020 \
    --register-type input --address 0 --count 10

Read coils

iottack modbus read-coils --host 127.0.0.1 --tcp-port 5020 --address 0 --count 32

Read discrete inputs (FC02):

iottack modbus read-coils --host 127.0.0.1 --tcp-port 5020 \
    --coil-type discrete --address 0 --count 32

Write a coil

iottack modbus write-coil --host 127.0.0.1 --tcp-port 5020 --address 0 --value on

Write a register

Single register (FC06):

iottack modbus write-register --host 127.0.0.1 --tcp-port 5020 --address 1 --value 0x00FF

Multiple registers (FC16):

iottack modbus write-register --host 127.0.0.1 --tcp-port 5020 \
    --address 200 --values 0x0001,0x09C4,0x0003

CLI options

OptionDefaultDescription
--host0.0.0.0Bind address
--port5020TCP port
--unit1Modbus unit/slave ID

Code

#!/usr/bin/env python3
"""Modbus TCP test server for IoTtack.

Starts a persistent Modbus/TCP simulator on port 5020 (configurable) with
pre-populated data across all four data types so every IoTtack Modbus plugin
can be exercised locally.

Default data layout
-------------------
  Holding registers (FC03)  0-999    : mix of fixed, counter, and sensor values
  Input registers   (FC04)  0-99     : read-only analog sensor readings
  Coils             (FC01)  0-31     : alternating ON/OFF pattern
  Discrete inputs   (FC02)  0-31     : fixed sensor bits

Device identification (FC43 MEI) is enabled with realistic vendor strings.

Usage
-----
  python simulator.py                  # listen on 0.0.0.0:5020, unit 1
  python simulator.py --port 502       # standard Modbus port (needs root)
  python simulator.py --host 127.0.0.1 # loopback only
  python simulator.py --unit 3         # respond as unit ID 3
"""

import argparse
import asyncio
import logging

from pymodbus import ModbusDeviceIdentification
from pymodbus.server import StartAsyncTcpServer
from pymodbus.simulator import DataType, SimData, SimDevice

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s  %(levelname)-8s  %(message)s",
    datefmt="%H:%M:%S",
)
log = logging.getLogger("modbus-simulator")


def build_holding_registers() -> list[int]:
    """Return 1000 holding registers with a realistic mix of values."""
    regs = [0] * 1000
    # System status word
    regs[0] = 0x0001   # run mode
    regs[1] = 0x0064   # setpoint 100
    regs[2] = 0x01F4   # setpoint 500
    regs[3] = 0x0042   # firmware build
    # Temperature setpoints (addresses 10-19)
    for index, value in enumerate([200, 350, 400, 250, 300, 180, 220, 270, 310, 290]):
        regs[10 + index] = value
    # Process counters (addresses 100-109)
    for index in range(10):
        regs[100 + index] = index * 137 + 42
    # Config block (addresses 200-209)
    regs[200] = 0x0001  # enabled
    regs[201] = 0x09C4  # timeout 2500 ms
    regs[202] = 0x0003  # retries
    regs[203] = 0x0001  # protocol version
    # Alarm thresholds (addresses 500-509)
    for index in range(10):
        regs[500 + index] = 1000 + index * 50
    return regs


def build_input_registers() -> list[int]:
    """Return 100 input registers simulating analog sensor readings."""
    regs = [0] * 100
    # Temperature readings (0.1 °C units)
    regs[0] = 234    # 23.4 °C
    regs[1] = 251    # 25.1 °C
    regs[2] = 187    # 18.7 °C
    # Pressure (mbar)
    regs[10] = 1013
    regs[11] = 987
    # Voltage (0.01 V units)
    regs[20] = 2400  # 24.00 V
    regs[21] = 1199  # 11.99 V
    # Current (mA)
    regs[30] = 420
    regs[31] = 850
    # Uptime (seconds, low word then high word)
    regs[50] = 0xAB12
    regs[51] = 0x0002
    return regs


def build_coils() -> list[bool]:
    """Return 32 coils in an alternating ON/OFF pattern."""
    return [bool(i % 2) for i in range(32)]


def build_discrete_inputs() -> list[bool]:
    """Return 32 discrete inputs representing sensor states."""
    bits = [False] * 32
    bits[0] = True   # door open
    bits[2] = True
    bits[8] = True   # motor running
    bits[9] = True
    return bits


def build_sim_device(unit_id: int) -> SimDevice:  # noqa: ARG001
    """Build and return a simulated Modbus device with pre-populated data."""
    # id=0 is the pymodbus catch-all device: SimCore.__get_device falls back to
    # self.devices[0] when the requested unit ID is not an exact match.
    return SimDevice(
        id=0,
        simdata=(
            [SimData(address=0, values=build_coils(), datatype=DataType.BITS)],
            [SimData(address=0, values=build_discrete_inputs(), datatype=DataType.BITS)],
            [SimData(address=0, values=build_holding_registers(), datatype=DataType.REGISTERS)],
            [SimData(address=0, values=build_input_registers(), datatype=DataType.REGISTERS)],
        ),
    )


def build_identity() -> ModbusDeviceIdentification:
    """Build and return the Modbus device identity information."""
    ident = ModbusDeviceIdentification()
    ident.VendorName = "iottack Labs"
    ident.ProductCode = "SIMBUS-1000"
    ident.MajorMinorRevision = "1.0.0"
    ident.VendorUrl = "https://github.com/your-org/iottack"
    ident.ProductName = "Modbus Test Target"
    ident.ModelName = "SimBus"
    ident.UserApplicationName = "iottack modbus test"
    return ident


async def run_server(host: str, port: int, unit_id: int) -> None:
    """Run the Modbus/TCP simulator server on the specified host, port, and unit ID."""
    device = build_sim_device(unit_id)
    identity = build_identity()

    log.info("Modbus/TCP simulator starting on %s:%d  unit=%d", host, port, unit_id)
    log.info("Data layout:")
    log.info("  Holding registers (FC03)  0-999  (1000 regs)")
    log.info("  Input registers   (FC04)  0-99   (100 regs)")
    log.info("  Coils             (FC01)  0-31   (32 coils)")
    log.info("  Discrete inputs   (FC02)  0-31   (32 bits)")
    log.info("  FC43 MEI device identification: enabled")
    log.info("Press Ctrl-C to stop.")

    await StartAsyncTcpServer(
        context=device,
        identity=identity,
        address=(host, port),
    )


def main() -> None:
    """Parse command-line arguments and start the Modbus/TCP simulator."""
    parser = argparse.ArgumentParser(description="iottack Modbus/TCP test simulator")
    parser.add_argument("--host", default="0.0.0.0", help="Bind address (default: 0.0.0.0)")
    parser.add_argument("--port", type=int, default=5020, help="TCP port (default: 5020)")
    parser.add_argument("--unit", type=int, default=1, help="Modbus unit/slave ID (default: 1)")
    args = parser.parse_args()

    asyncio.run(run_server(args.host, args.port, args.unit))


if __name__ == "__main__":
    main()

BACnet/IP Simulator

The BACnet/IP simulator is a standalone Python server that emulates a realistic building automation controller with two virtual stations pre-populated with sensor and actuator objects. It runs entirely in software. No physical hardware required. So every iottack bacnet plugin can be exercised locally.

Source: test-targets/iottack-target-bacnet/simulator.py

Requirements

bacpypes3. The Nix flake in test-targets/iottack-target-bacnet/ provides a reproducible environment with the correct version pinned.

Device layout

Device instance:: 100 (configurable via --device) Device name:: SimBAS Protocol:: BACnet/IP, UDP port 47808 (configurable via --port)

Station 1 - Boiler Room Controller

Object typeInstanceNameValueUnits
analogInput1boiler-temp75.3°C
analogInput2water-pressure2.1bar
analogInput3flue-gas-temp185.0°C
analogOutput1burner-power65.0%
analogOutput2pump-speed80.0%
binaryInput1high-temp-alarminactive-
binaryInput2low-pressure-alarminactive-
binaryOutput1pump-enableactive-
binaryOutput2burner-enableactive-

Station 2 - HVAC Unit

Object typeInstanceNameValueUnits
analogInput11supply-air-temp18.5°C
analogInput12return-air-temp24.2°C
analogInput13outdoor-air-temp9.8°C
analogOutput11cooling-setpoint21.0°C
analogOutput12heating-setpoint19.0°C
analogOutput13fan-speed75.0%
binaryInput11fan-runningactive-
binaryInput12filter-dirtyinactive-
binaryOutput11chilled-water-valveactive-
binaryOutput12hot-water-valveinactive-

Usage

# Start on 0.0.0.0:47808, device instance 100
nix run ./test-targets/iottack-target-bacnet

# Loopback only
nix run ./test-targets/iottack-target-bacnet -- --host 127.0.0.1

# Custom port and device instance
nix run ./test-targets/iottack-target-bacnet -- --port 47809 --device 200

Without Nix

pip install bacpypes3
python test-targets/iottack-target-bacnet/simulator.py
python test-targets/iottack-target-bacnet/simulator.py --host 127.0.0.1 --port 47808 --device 100

CLI options

OptionDefaultDescription
--host0.0.0.0Bind address
--port47808UDP port
--device100BACnet device instance number

Code

#!/usr/bin/env python3
"""BACnet/IP test server for IoTtack.

Exposes two virtual BACnet stations inside a single device so that BACnet
discovery and read/write tools can be exercised locally without real hardware.

Device layout
-------------
  Device instance  : 100  (configurable)
  Device name      : SimBAS
  Protocol         : BACnet/IP, UDP port 47808 (configurable)

  Station 1 - Boiler Room Controller
    analogInput  1   boiler-temp          75.3 °C
    analogInput  2   water-pressure        2.1 bar
    analogInput  3   flue-gas-temp       185.0 °C
    analogOutput 1   burner-power         65.0 %
    analogOutput 2   pump-speed           80.0 %
    binaryInput  1   high-temp-alarm      False
    binaryInput  2   low-pressure-alarm   False
    binaryOutput 1   pump-enable          True
    binaryOutput 2   burner-enable        True

  Station 2 - HVAC Unit
    analogInput  11  supply-air-temp      18.5 °C
    analogInput  12  return-air-temp      24.2 °C
    analogInput  13  outdoor-air-temp      9.8 °C
    analogOutput 11  cooling-setpoint     21.0 °C
    analogOutput 12  heating-setpoint     19.0 °C
    analogOutput 13  fan-speed            75.0 %
    binaryInput  11  fan-running          True
    binaryInput  12  filter-dirty         False
    binaryOutput 11  chilled-water-valve  True
    binaryOutput 12  hot-water-valve      False

Usage
-----
  python simulator.py                    # 0.0.0.0:47808, device 100
  python simulator.py --port 47809       # alternate port
  python simulator.py --host 127.0.0.1   # loopback only
  python simulator.py --device 200       # custom device instance
"""

import argparse
import asyncio
import logging

from bacpypes3.app import Application
from bacpypes3.apdu import WhoIsRequest
from bacpypes3.local.analog import AnalogInputObject, AnalogOutputObject
from bacpypes3.local.binary import BinaryInputObject, BinaryOutputObject
from bacpypes3.local.device import DeviceObject
from bacpypes3.local.networkport import NetworkPortObject

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s  %(levelname)-8s  %(message)s",
    datefmt="%H:%M:%S",
)
log = logging.getLogger("bacnet-simulator")


class SimBASApplication(Application):
    """Application with unicast I-Am so loopback clients receive the response.

    The standard bacpypes3 Application broadcasts I-Am to 255.255.255.255:47808.
    When client and simulator share a host the simulator holds port 47808 and
    the client's random-port socket never sees that broadcast.  Sending a
    unicast I-Am back to apdu.pduSource (the client's actual IP:port) fixes
    this for all loopback and same-host testing scenarios.
    """

    async def do_WhoIsRequest(self, apdu: WhoIsRequest) -> None:
        device_id = self.device_object.objectIdentifier[1]

        low = apdu.deviceInstanceRangeLowLimit
        high = apdu.deviceInstanceRangeHighLimit
        if low is not None and device_id < low:
            return
        if high is not None and device_id > high:
            return

        log.info("Who-Is from %s → unicast I-Am (device %d)", apdu.pduSource, device_id)
        await self.i_am(address=apdu.pduSource)


def ai(instance, name, value, units="degreesCelsius", description=""):
    """Create an AnalogInputObject."""
    return AnalogInputObject(
        objectIdentifier=("analog-input", instance),
        objectName=name,
        presentValue=float(value),
        units=units,
        description=description,
        outOfService=False,
    )


def ao(instance, name, value, units="percent", description=""):
    """Create an AnalogOutputObject."""
    return AnalogOutputObject(
        objectIdentifier=("analog-output", instance),
        objectName=name,
        presentValue=float(value),
        units=units,
        description=description,
        outOfService=False,
    )


def bi(instance, name, active, description=""):
    """Create a BinaryInputObject."""
    return BinaryInputObject(
        objectIdentifier=("binary-input", instance),
        objectName=name,
        presentValue="active" if active else "inactive",
        description=description,
        outOfService=False,
    )


def bo(instance, name, active, description=""):
    """Create a BinaryOutputObject."""
    return BinaryOutputObject(
        objectIdentifier=("binary-output", instance),
        objectName=name,
        presentValue="active" if active else "inactive",
        description=description,
        outOfService=False,
    )


async def main() -> None:
    """Main entry point for the BACnet/IP simulator."""
    parser = argparse.ArgumentParser(description="IoTtack BACnet/IP test simulator")
    parser.add_argument(
        "--host", default="0.0.0.0", help="Bind address (default: 0.0.0.0)"
    )
    parser.add_argument(
        "--port", type=int, default=47808, help="UDP port (default: 47808)"
    )
    parser.add_argument(
        "--device", type=int, default=100, help="BACnet device instance (default: 100)"
    )
    args = parser.parse_args()

    station_1_objects = [
        ai(1, "boiler-temp", 75.3, "degreesCelsius", "Boiler water temperature"),
        ai(2, "water-pressure", 2.1, "bars", "System water pressure"),
        ai(3, "flue-gas-temp", 185.0, "degreesCelsius", "Flue gas exit temperature"),
        ao(1, "burner-power", 65.0, "percent", "Burner modulation output"),
        ao(2, "pump-speed", 80.0, "percent", "Circulation pump speed"),
        bi(1, "high-temp-alarm", False, "Boiler over-temperature alarm"),
        bi(2, "low-pressure-alarm", False, "Low water pressure alarm"),
        bo(1, "pump-enable", True, "Circulation pump on/off"),
        bo(2, "burner-enable", True, "Main burner on/off"),
    ]

    station_2_objects = [
        ai(11, "supply-air-temp", 18.5, "degreesCelsius", "Supply air temperature"),
        ai(12, "return-air-temp", 24.2, "degreesCelsius", "Return air temperature"),
        ai(13, "outdoor-air-temp", 9.8, "degreesCelsius", "Outdoor air temperature"),
        ao(11, "cooling-setpoint", 21.0, "degreesCelsius", "Zone cooling setpoint"),
        ao(12, "heating-setpoint", 19.0, "degreesCelsius", "Zone heating setpoint"),
        ao(13, "fan-speed", 75.0, "percent", "Supply fan speed command"),
        bi(11, "fan-running", True, "Supply fan status"),
        bi(12, "filter-dirty", False, "Air filter pressure differential alarm"),
        bo(11, "chilled-water-valve", True, "Chilled water coil valve"),
        bo(12, "hot-water-valve", False, "Heating coil valve"),
    ]

    device = DeviceObject(
        objectIdentifier=("device", args.device),
        objectName="SimBAS",
        maxApduLengthAccepted=1024,
        segmentationSupported="noSegmentation",
        vendorIdentifier=15,
        vendorName="iottack Labs",
        modelName="SimBAS-1000",
        firmwareRevision="1.0",
        applicationSoftwareVersion="1.0",
        description="iottack BACnet/IP building automation simulator",
    )

    address = f"{args.host}:{args.port}"
    network_port = NetworkPortObject(
        objectIdentifier=("network-port", 1),
        objectName="NetworkPort-1",
        networkNumberQuality="unknown",
        bacnetIPUDPPort=args.port,
    )

    all_objects = [device, network_port] + station_1_objects + station_2_objects
    SimBASApplication.from_object_list(all_objects, address)

    log.info(
        "BACnet/IP simulator starting on %s  device-instance=%d", address, args.device
    )
    log.info(
        "Station 1 (Boiler Room): analogInput 1-3, analogOutput 1-2, binaryInput 1-2, binaryOutput 1-2"
    )
    log.info(
        "Station 2 (HVAC Unit):   analogInput 11-13, analogOutput 11-13, binaryInput 11-12, binaryOutput 11-12"
    )
    log.info(
        "Total objects: %d  (plus device object)",
        len(station_1_objects) + len(station_2_objects),
    )
    log.info("Press Ctrl-C to stop.")

    await asyncio.Future()


if __name__ == "__main__":
    asyncio.run(main())

CAN Bus Simulator

The CAN bus simulator is a standalone Rust binary that emulates a mixed industrial/automotive CAN network. It transmits a continuous stream of realistic frames over a Linux SocketCAN interface so that every iottack can plugin can be exercised locally without physical hardware.

Source: test-targets/iottack-target-can/src/main.rs

Requirements

  • Linux with the vcan kernel module (modprobe vcan)
  • Rust toolchain (provided by the Nix flake in test-targets/iottack-target-can/)

Node layout

The simulator brings up 14 virtual nodes across three higher-layer protocols.

CANopen master

NodeCAN IDFormatPeriodNotes
canopen-sync0x080SFF100 msSYNC object
canopen-emcy-node10x081SFF5 sEMCY from node 1 (generic error / fault cleared)

CANopen node 1 — temperature/pressure sensor

NodeCAN IDFormatPeriodNotes
canopen-node1-tpdo10x181SFF100 msTemperature + pressure (PDO)
canopen-node1-tpdo20x281SFF200 msDigital I/O status (PDO)
canopen-node1-sdo-resp0x581SFF2 sSDO server response (device type, vendor ID)
canopen-node1-sdo-req0x601SFF2 sSDO client request — includes unauthenticated write to digital outputs
canopen-node1-heartbeat0x701SFF1 sNMT heartbeat (operational / pre-operational)

CANopen node 2 — motor controller

NodeCAN IDFormatPeriodNotes
canopen-node2-tpdo10x182SFF200 msMotor RPM (PDO)
canopen-node2-heartbeat0x702SFF1 sNMT heartbeat

CANopen node 3 — valve controller

NodeCAN IDFormatPeriodNotes
canopen-node3-tpdo10x183SFF500 msValve setpoint + actual position (PDO)
canopen-node3-heartbeat0x703SFF1 sNMT heartbeat

OBD-II / ISO 15765-4

NodeCAN IDFormatPeriodNotes
obd2-broadcast0x7DFSFF1 sDiagnostic broadcast — HIGH severity
obd2-ecu1-response0x7E8SFF1 sECU 1 response (RPM, speed, coolant temp, intake air) — HIGH severity

J1939 (extended 29-bit)

NodeCAN IDFormatPeriodNotes
j1939-eec10x0CF00400EFF100 msPGN 0xF004 EEC1 — torque demand + engine speed

CLI options

OptionDefaultDescription
-i, --ifacevcan0SocketCAN interface to transmit on
-d, --duration0Stop after N seconds; 0 runs until Ctrl-C
--stats-interval5Print frame rate statistics every N seconds

Setup

A virtual CAN interface must be up before starting the simulator:

sudo modprobe vcan
sudo ip link add dev vcan0 type vcan
sudo ip link set vcan0 up

Usage

# Start on vcan0, run indefinitely
nix run ./test-targets/iottack-target-can

# Custom interface
nix run ./test-targets/iottack-target-can -- --iface vcan1

# Stop after 30 seconds
nix run ./test-targets/iottack-target-can -- --duration 30

Without Nix

cd test-targets/iottack-target-can
cargo run -- --iface vcan0
cargo run -- --iface vcan0 --duration 30

Testing with iottack

With the simulator running, open a second terminal and run any CAN plugin:

iottack can scan     --iface vcan0
iottack can dump     --iface vcan0 --duration 5
iottack can enumerate --iface vcan0

Expected findings from can scan and can enumerate:

  • High: OBD-II diagnostic IDs observed (0x7DF, 0x7E8)
  • High: CANopen nodes identified via SDO (node 1 device type)
  • Medium: CANopen heartbeat nodes (nodes 1-3)
  • Medium: CANopen SDO, PDO, NMT IDs observed

Code

//! Virtual CAN bus simulator for IoTtack testing.
//!
//! Simulates a mixed industrial/automotive CAN network with CANopen nodes,
//! OBD-II diagnostics and a J1939 engine controller. Exercises all
//! security-relevant IDs that the iottack `can scan`, `can dump` and
//! `can enumerate` plugins flag.
//!
//! # Quick start
//!
//!   # Set up virtual CAN interface
//!   modprobe vcan
//!   ip link add dev vcan0 type vcan
//!   ip link set vcan0 up
//!
//!   # Run the simulator
//!   cargo run -- --iface vcan0
//!
//!   # In another terminal, test with iottack
//!   iottack can scan  --iface vcan0
//!   iottack can dump  --iface vcan0 --duration 5
//!
//! # Node layout
//!
//!   CANopen master
//!     0x080  SYNC               100 ms
//!     0x081  EMCY from node 1   5 s
//!
//!   CANopen node 1 - temperature/pressure sensor
//!     0x181  TPDO1              100 ms
//!     0x281  TPDO2              200 ms
//!     0x581  SDO response         2 s
//!     0x601  SDO request (write)  2 s   <- unauthenticated register access
//!     0x701  NMT heartbeat        1 s
//!
//!   CANopen node 2 - motor controller
//!     0x182  TPDO1              200 ms
//!     0x702  NMT heartbeat        1 s
//!
//!   CANopen node 3 - valve controller
//!     0x183  TPDO1              500 ms
//!     0x703  NMT heartbeat        1 s
//!
//!   OBD-II/ISO 15765-4
//!     0x7DF  diagnostic broadcast  1 s  <- HIGH severity
//!     0x7E8  ECU 1 response        1 s  <- HIGH severity
//!
//!   J1939 (extended 29-bit)
//!     0x0CFEEF00  EEC1 engine data  100 ms

use anyhow::{Context, Result};
use clap::Parser;
use socketcan::{CanDataFrame, CanFrame, CanSocket, EmbeddedFrame, ExtendedId, Id, Socket, StandardId};
use std::io;
use std::time::{Duration, Instant};

#[derive(Parser)]
#[command(
    name = "can-simulator",
    about = "Virtual CAN bus simulator for IoTtack testing"
)]
struct Cli {
    /// SocketCAN interface to send on
    #[arg(short, long, default_value = "vcan0")]
    iface: String,

    /// Stop after this many seconds (0 = run until Ctrl-C)
    #[arg(short, long, default_value = "0")]
    duration: u64,

    /// Print statistics every N seconds
    #[arg(long, default_value = "5")]
    stats_interval: u64,
}

/// Representation of a CAN node, including its transmit schedule and payload generation function.
struct Node {
    name: &'static str,
    id: u32,
    extended: bool,
    period_ms: u64,
    next_tx: Instant,
    tick: u64,
    total_sent: u64,
    payload_fn: fn(u64) -> Vec<u8>,
}

/// Representation of a CAN node, including its transmit schedule and payload generation function.
impl Node {
    fn new(
        name: &'static str,
        id: u32,
        extended: bool,
        period_ms: u64,
        payload_fn: fn(u64) -> Vec<u8>,
    ) -> Self {
        Self {
            name,
            id,
            extended,
            period_ms,
            next_tx: Instant::now(),
            tick: 0,
            total_sent: 0,
            payload_fn,
        }
    }

    fn is_due(&self) -> bool {
        Instant::now() >= self.next_tx
    }

    /// Build a CAN data frame for the current tick, using the node's payload function.
    fn build_frame(&self) -> Result<CanDataFrame> {
        let payload = (self.payload_fn)(self.tick);
        if self.extended {
            let eid = ExtendedId::new(self.id)
                .ok_or_else(|| anyhow::anyhow!("invalid EFF ID 0x{:08X}", self.id))?;
            CanDataFrame::new(eid, &payload)
                .ok_or_else(|| anyhow::anyhow!("frame build failed for {}", self.name))
        } else {
            let sid = StandardId::new(self.id as u16)
                .ok_or_else(|| anyhow::anyhow!("invalid SFF ID 0x{:03X}", self.id))?;
            CanDataFrame::new(sid, &payload)
                .ok_or_else(|| anyhow::anyhow!("frame build failed for {}", self.name))
        }
    }

    /// Advance the node's internal state, updating the next transmit time and tick counter.
    fn advance(&mut self) {
        self.tick += 1;
        self.total_sent += 1;
        self.next_tx += Duration::from_millis(self.period_ms);
        // Clamp: drop missed slots instead of sending a burst after a stall
        let now = Instant::now();
        if self.next_tx < now {
            self.next_tx = now + Duration::from_millis(self.period_ms);
        }
    }
}

/// Entry point for the CAN traffic generator. Initializes the CAN socket, sets up nodes, and runs the main transmit loop.
fn main() -> Result<()> {
    let cli = Cli::parse();

    let socket = CanSocket::open(&cli.iface).with_context(|| {
        format!(
            "Cannot open '{}'. Set up a virtual CAN interface with:\n  \
             modprobe vcan\n  \
             ip link add dev vcan0 type vcan\n  \
             ip link set vcan0 up",
            cli.iface
        )
    })?;
    // Short timeout so read_frame() acts non-blocking in the drain loop.
    // SO_RECV_OWN_MSGS is off by default, so we only see frames from other
    // sockets (iottack can send, etc.) Never our own TX.
    socket
        .set_read_timeout(Duration::from_millis(1))
        .context("set_read_timeout")?;

    let mut nodes = build_nodes();

    // Spread initial transmit times so all nodes don't fire simultaneously
    let stagger = Duration::from_millis(5);
    for (i, node) in nodes.iter_mut().enumerate() {
        node.next_tx += stagger * (i as u32);
    }

    print_header(&cli.iface, cli.duration, &nodes);

    let deadline = (cli.duration > 0)
        .then(|| Instant::now() + Duration::from_secs(cli.duration));
    let stats_interval = Duration::from_secs(cli.stats_interval.max(1));

    let mut total_sent: u64 = 0;
    let mut total_errors: u64 = 0;
    let mut total_recv: u64 = 0;
    let mut interval_sent: u64 = 0;
    let mut last_stats = Instant::now();

    loop {
        if deadline.is_some_and(|d| Instant::now() >= d) {
            break;
        }

        for node in nodes.iter_mut() {
            if !node.is_due() {
                continue;
            }
            match node.build_frame() {
                Ok(frame) => match socket.write_frame(&frame) {
                    Ok(()) => {
                        total_sent += 1;
                        interval_sent += 1;
                    }
                    Err(e) => {
                        total_errors += 1;
                        eprintln!("[error] write {} (id={:03X}h): {e}", node.name, node.id);
                    }
                },
                Err(e) => eprintln!("[error] build {}: {e}", node.name),
            }
            node.advance();
        }

        // Drain any frames written by external tools (iottack can send, etc.).
        // The socket does not echo its own TX frames, so everything here came
        // from another process.
        drain_rx(&socket, &mut total_recv);

        // Sleep until the next node is due (but no longer than 10 ms)
        if let Some(next) = nodes.iter().map(|n| n.next_tx).min() {
            let now = Instant::now();
            if next > now {
                std::thread::sleep((next - now).min(Duration::from_millis(10)));
            }
        }

        // Periodic stats
        let elapsed = last_stats.elapsed();
        if elapsed >= stats_interval {
            let rate = interval_sent as f64 / elapsed.as_secs_f64();
            println!(
                "  sent={total_sent:<8}  recv={total_recv:<6}  errors={total_errors}  rate={rate:.1} frames/s"
            );
            interval_sent = 0;
            last_stats = Instant::now();
        }
    }

    println!("\nSimulator stopped.  total_sent={total_sent}  errors={total_errors}");
    Ok(())
}

fn build_nodes() -> Vec<Node> {
    vec![
        // --- CANopen master
        // SYNC (0x080): 10 Hz - triggers "CANopen: SYNC/timestamp"
        Node::new("canopen-sync", 0x080, false, 100, |tick| {
            vec![(tick & 0xFF) as u8]
        }),
        // EMCY from node 1 (0x081): 0.2 Hz - triggers "CANopen: EMCY"
        Node::new("canopen-emcy-node1", 0x081, false, 5000, |tick| {
            if tick % 3 == 0 {
                // Generic error 0x1000
                vec![0x00, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00]
            } else {
                // Fault cleared
                vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
            }
        }),
        // --- CANopen node 1: temperature/pressure sensor
        // TPDO1 (0x181): 10 Hz - triggers "CANopen: PDO"
        Node::new("canopen-node1-tpdo1", 0x181, false, 100, |tick| {
            // Temperature 65–75 °C ×10 (int16 big-endian)
            let temp = 650u16 + ((tick * 7 % 100) as u16);
            // Pressure 20–35 (×10 bar, i.e. 2.0–3.5 bar)
            let pres = 20u16 + ((tick * 3 % 15) as u16);
            vec![
                (temp >> 8) as u8, (temp & 0xFF) as u8,
                (pres >> 8) as u8, (pres & 0xFF) as u8,
                0x00, 0x00, 0x00, 0x00,
            ]
        }),
        // TPDO2 (0x281): 5 Hz - digital I/O status
        Node::new("canopen-node1-tpdo2", 0x281, false, 200, |tick| {
            let io = if tick % 10 < 7 { 0x01u8 } else { 0x03u8 };
            vec![io, 0x00]
        }),
        // SDO server response (0x581): 0.5 Hz - triggers "CANopen: SDO server response"
        Node::new("canopen-node1-sdo-resp", 0x581, false, 2000, |tick| {
            match tick % 3 {
                0 => vec![0x43, 0x00, 0x10, 0x00, 0x91, 0x01, 0x02, 0x00], // device type
                1 => vec![0x4B, 0x18, 0x10, 0x01, 0x34, 0x12, 0x00, 0x00], // vendor ID
                _ => vec![0x4B, 0x18, 0x10, 0x02, 0x01, 0x00, 0x00, 0x00], // product code
            }
        }),
        // SDO client request (0x601): 0.5 Hz - triggers "CANopen: SDO client request
        //   (unauthenticated register access)"
        Node::new("canopen-node1-sdo-req", 0x601, false, 2000, |tick| {
            match tick % 4 {
                0 => vec![0x40, 0x18, 0x10, 0x01, 0x00, 0x00, 0x00, 0x00], // read vendor ID
                1 => vec![0x40, 0x18, 0x10, 0x02, 0x00, 0x00, 0x00, 0x00], // read product code
                2 => vec![0x40, 0x00, 0x60, 0x01, 0x00, 0x00, 0x00, 0x00], // read digital inputs
                // Unauthenticated write to digital outputs - high-value security finding
                _ => vec![0x2F, 0x00, 0x62, 0x01, 0x01, 0x00, 0x00, 0x00],
            }
        }),
        // NMT heartbeat (0x701): 1 Hz - triggers "CANopen: NMT heartbeat/node guarding"
        Node::new("canopen-node1-heartbeat", 0x701, false, 1000, |tick| {
            // Mostly operational (0x05), briefly pre-operational (0x7F)
            let state = if tick % 20 < 18 { 0x05u8 } else { 0x7Fu8 };
            vec![state]
        }),
        // --- CANopen node 2: motor controller
        // TPDO1 (0x182): 5 Hz
        Node::new("canopen-node2-tpdo1", 0x182, false, 200, |tick| {
            let rpm = 1500u16 + ((tick * 13 % 500) as u16);
            vec![
                (rpm >> 8) as u8, (rpm & 0xFF) as u8,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            ]
        }),
        // NMT heartbeat (0x702): 1 Hz
        Node::new("canopen-node2-heartbeat", 0x702, false, 1000, |_| vec![0x05]),
        // --- CANopen node 3: valve controller
        // TPDO1 (0x183): 2 Hz
        Node::new("canopen-node3-tpdo1", 0x183, false, 500, |tick| {
            let setpoint = (tick % 100) as u8;
            let actual = ((tick + 2) % 100) as u8;
            vec![setpoint, actual, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
        }),
        // NMT heartbeat (0x703): 1 Hz
        Node::new("canopen-node3-heartbeat", 0x703, false, 1000, |_| vec![0x05]),
        // --- OBD-II / ISO 15765-4
        // Diagnostic broadcast (0x7DF): 1 Hz - HIGH severity in iottack
        Node::new("obd2-broadcast", 0x7DF, false, 1000, |tick| {
            let pid = [0x0Cu8, 0x0D, 0x05, 0x0F][(tick % 4) as usize];
            vec![0x02, 0x01, pid, 0x00, 0x00, 0x00, 0x00, 0x00]
        }),
        // ECU 1 diagnostic response (0x7E8): 1 Hz - HIGH severity in iottack
        Node::new("obd2-ecu1-response", 0x7E8, false, 1000, |tick| {
            match tick % 4 {
                0 => { // PID 0x0C: RPM = 2500 rpm  (A*256+B)/4
                    let raw = 2500u16 * 4;
                    vec![0x04, 0x41, 0x0C, (raw >> 8) as u8, (raw & 0xFF) as u8, 0x00, 0x00, 0x00]
                }
                1 => { // PID 0x0D: speed = 80 km/h
                    vec![0x03, 0x41, 0x0D, 80, 0x00, 0x00, 0x00, 0x00]
                }
                2 => { // PID 0x05: coolant temp = 92 °C  (A-40)
                    vec![0x03, 0x41, 0x05, 92 + 40, 0x00, 0x00, 0x00, 0x00]
                }
                _ => { // PID 0x0F: intake air = 25 °C  (A-40)
                    vec![0x03, 0x41, 0x0F, 25 + 40, 0x00, 0x00, 0x00, 0x00]
                }
            }
        }),
        // --- J1939 (extended 29-bit EFF)
        // EEC1 (Electronic Engine Controller 1), PGN 0xF004, SA=0x00: 10 Hz
        // 29-bit ID = Priority(3)=0b011 | DP=0 | PF=0xF0 | PS=0x04 | SA=0x00
        //           = 0x0CF00400
        Node::new("j1939-eec1", 0x0CF00400, true, 100, |tick| {
            // Byte 0: torque demand (0–100%)
            // Bytes 2-3: engine speed (0.125 rpm/bit, range 0–8031.875)
            let torque = ((tick * 3) % 100) as u8;
            let rpm_raw = (2500.0_f64 / 0.125) as u16; // 2500 rpm
            vec![
                torque,
                0xFF, // driver torque demand
                (rpm_raw & 0xFF) as u8,
                (rpm_raw >> 8) as u8,
                0xFF, 0xFF, 0xFF, 0xFF,
            ]
        }),
    ]
}

// --- RX support

/// Drain all frames currently queued on the socket and log them.
///
/// Because SO_RECV_OWN_MSGS is off by default, every frame returned here was
/// sent by a different socket.
fn drain_rx(socket: &CanSocket, total_recv: &mut u64) {
    loop {
        match socket.read_frame() {
            Ok(CanFrame::Data(f)) => {
                *total_recv += 1;
                let (id, ext) = raw_id(&f);
                let id_str = fmt_id(id, ext);
                let data = f.data();
                let hex = hex_bytes(data);
                println!("[recv]  id={id_str:<14}  dlc={}  data=[{hex}]", f.dlc());
                if let Some(detail) = decode_frame(id, ext, data) {
                    println!("        {detail}");
                }
            }
            Ok(CanFrame::Remote(f)) => {
                *total_recv += 1;
                let (id, ext) = raw_id(&f);
                println!("[recv]  id={:<14}  RTR  dlc={}", fmt_id(id, ext), f.dlc());
            }
            Ok(CanFrame::Error(_)) => {
                eprintln!("[recv]  error frame");
            }
            Err(e)
                if e.kind() == io::ErrorKind::WouldBlock
                    || e.kind() == io::ErrorKind::TimedOut =>
            {
                break;
            }
            Err(e) => {
                eprintln!("[rx-error]  {e}");
                break;
            }
        }
    }
}

/// Extract the raw CAN ID and whether it is an extended frame from a CAN frame.
fn raw_id(f: &impl EmbeddedFrame) -> (u32, bool) {
    match f.id() {
        Id::Standard(s) => (s.as_raw() as u32, false),
        Id::Extended(e) => (e.as_raw(), true),
    }
}

/// Format a CAN ID as a human-readable string, indicating whether it is standard or extended.
fn fmt_id(id: u32, ext: bool) -> String {
    if ext {
        format!("{id:08X}h(EFF)")
    } else {
        format!("{id:03X}h(SFF)")
    }
}

fn hex_bytes(data: &[u8]) -> String {
    data.iter()
        .map(|b| format!("{b:02X}"))
        .collect::<Vec<_>>()
        .join(" ")
}

/// Decode a received frame into a human-readable description of the operation
/// and any state change it implies.  Returns None for unrecognized frames.
fn decode_frame(id: u32, ext: bool, data: &[u8]) -> Option<String> {
    if ext || data.is_empty() {
        return None;
    }
    match id {
        // NMT command (0x000)
        0x000 if data.len() >= 2 => {
            let cmd_name = match data[0] {
                0x01 => "Start node (→ Operational)",
                0x02 => "Stop node",
                0x80 => "Enter Pre-Operational",
                0x81 => "Reset node",
                0x82 => "Reset communication",
                _ => "Unknown NMT command",
            };
            let target = if data[1] == 0 {
                "all nodes".to_string()
            } else {
                format!("node {}", data[1])
            };
            Some(format!("CANopen NMT  cmd={cmd_name}  target={target}"))
        }

        // SDO client request to node N at base address 0x600+N
        0x600..=0x67F if data.len() >= 4 => {
            let node_id = id - 0x600;
            let cmd = data[0];
            let index = u16::from_le_bytes([data[1], data[2]]);
            let subidx = data[3];

            match cmd >> 5 {
                // Upload initiate (read request)
                0b010 => Some(format!(
                    "CANopen SDO read-request  node={node_id}  obj={index:#06X}:{subidx:02X}"
                )),
                // Download initiate (write command) — implies a state change
                0b001 => {
                    let expedited = (cmd >> 1) & 1 == 1;
                    let size_indicated = cmd & 1 == 1;
                    if expedited && size_indicated {
                        let n = ((cmd >> 2) & 0x03) as usize;
                        let byte_count = 4usize.saturating_sub(n);
                        let raw = &data[4..data.len().min(4 + byte_count)];
                        let value = raw
                            .iter()
                            .enumerate()
                            .fold(0u32, |acc, (i, &b)| acc | ((b as u32) << (i * 8)));
                        let obj_hint = sdo_object_hint(index, subidx);
                        Some(format!(
                            "CANopen SDO write  node={node_id}  obj={index:#06X}:{subidx:02X}\
                             {obj_hint}  value={value:#010X}  [{byte_count} byte(s)]  \
                             -> state change"
                        ))
                    } else {
                        Some(format!(
                            "CANopen SDO write (segmented)  node={node_id}  \
                             obj={index:#06X}:{subidx:02X}"
                        ))
                    }
                }
                _ => None,
            }
        }

        // OBD-II diagnostic broadcast / targeted request
        0x7DF | 0x7E0..=0x7E7 if data.len() >= 3 => {
            let svc = data[1];
            let pid = data[2];
            let pid_label = obd2_pid_label(svc, pid);
            let target = if id == 0x7DF {
                "all ECUs (broadcast)".to_string()
            } else {
                format!("ECU {} ({id:#05X}h)", id - 0x7E0)
            };
            let resp_id = if id == 0x7DF { 0x7E8u32 } else { id + 8 };
            Some(format!(
                "OBD-II request  target={target}  svc={svc:#04X}  pid={pid:#04X}  \
                 ({pid_label})  → response expected on {resp_id:#05X}h"
            ))
        }

        _ => None,
    }
}

/// Return a human-readable hint for a given SDO object index and subindex.
fn sdo_object_hint(index: u16, subidx: u8) -> &'static str {
    match (index, subidx) {
        (0x1000, 0) => " (device-type)",
        (0x1001, 0) => " (error-register)",
        (0x1017, 0) => " (heartbeat-period)",
        (0x1018, 1) => " (vendor-ID)",
        (0x1018, 2) => " (product-code)",
        (0x1018, 3) => " (revision-number)",
        (0x6000, _) => " (digital-inputs)",
        (0x6200, _) => " (digital-outputs)",
        (0x6401, _) => " (analog-inputs)",
        (0x6411, _) => " (analog-outputs)",
        _ => "",
    }
}

/// Return a human-readable label for a given OBD-II service and PID.
fn obd2_pid_label(svc: u8, pid: u8) -> &'static str {
    if svc == 0x01 {
        match pid {
            0x00 => "supported PIDs 01-20",
            0x03 => "fuel system status",
            0x04 => "calculated engine load",
            0x05 => "coolant temperature",
            0x0C => "engine RPM",
            0x0D => "vehicle speed",
            0x0F => "intake air temperature",
            0x11 => "throttle position",
            0x1C => "OBD standards",
            0x2F => "fuel tank level",
            0x33 => "barometric pressure",
            _ => "unknown PID",
        }
    } else {
        match svc {
            0x02 => "freeze frame data",
            0x03 => "emission fault codes",
            0x04 => "clear fault codes",
            0x07 => "pending fault codes",
            0x09 => "vehicle information",
            _ => "unknown service",
        }
    }
}

/// Print the header for the CAN bus simulator output
fn print_header(iface: &str, duration: u64, nodes: &[Node]) {
    println!("IoTtack CAN bus simulator");
    println!("Interface : {iface}");
    if duration > 0 {
        println!("Duration  : {duration}s");
    } else {
        println!("Duration  : unlimited  (Ctrl-C to stop)");
    }
    println!();
    println!(
        "  {:<30}  {:<20}  {}",
        "node", "id", "period"
    );
    println!("  {}", "-".repeat(60));
    for node in nodes {
        let id_str = if node.extended {
            format!("{:08X}h (EFF/29-bit)", node.id)
        } else {
            format!("{:03X}h (SFF/11-bit)", node.id)
        };
        println!(
            "  {:<30}  {:<20}  {}ms",
            node.name, id_str, node.period_ms
        );
    }
    println!();
    println!("Sending ...");
}

Development

Adding a new plugin

Plugins are the unit of work in iottack. Each plugin performs one focused test and reports zero or more findings with a severity level and optional evidence string. Adding a plugin requires no changes to main.rs or any central registry. The framework discovers plugins automatically at startup.

A complete working reference lives at src/protocols/example/example.rs. The walkthrough below follows that file step by step.

1. Create the module files

Plugins are grouped by under src/protocols/, src/hardware (if it’s a physical device like a Logic analyzer) or src/vulns. Create a directory for the plugin if one does not exist yet, then add the plugin source file and the module declaration:

The example here is for a plugin that belongs to “the protocol” group.

src/protocols/<protocol>/
├── mod.rs          ← declares pub mod <plugin>;
└── <plugin>.rs     ← the plugin implementation

Expose the new protocol module from src/protocols/mod.rs:

#![allow(unused)]
fn main() {
pub mod <protocol>;
}

2. Define the plugin struct

The struct holds every parameter the plugin needs between initialize and execute. Fields should mirror the CLI arguments declared in meta().

#![allow(unused)]
fn main() {
pub struct ExamplePlugin {
    message: String,
    fail: bool,
}

impl ExamplePlugin {
    pub fn new() -> Self {
        Self { message: String::new(), fail: false }
    }
}

impl Default for ExamplePlugin {
    fn default() -> Self { Self::new() }
}
}

3. Implement Plugin::meta

meta() returns a PluginMeta built with the plugin_meta! macro. The macro derives the plugin name and category from the Rust module path automatically.

Module pathDerived name
iottack::protocols::http::bannerhttp/banner
iottack::protocols::network::tcp_bannernetwork/tcp-banner
iottack::protocols::example::exampleexample/example

The args slice describes every CLI flag. main.rs reads this slice to build the clap subcommand dynamically.

#![allow(unused)]
fn main() {
fn meta(&self) -> PluginMeta {
    plugin_meta!(
        summary: "Example plugin, shows the full plugin authoring pattern",
        description: "A reference plugin that exercises every part of the Plugin \
                      API: initialize, execute, teardown, CLI arguments, findings \
                      at multiple severity levels, and the inventory registration \
                      macro.",
        needs_root: false,
        args: &[
            CliArg {
                name: "message",        // config key; becomes --message on the CLI
                short: Some('m'),
                help: "Text to include in the Info finding",
                value_name: "TEXT",
                default: Some("hello from example plugin"),
                is_flag: false,
            },
            CliArg {
                name: "fail",
                short: Some('x'),
                help: "Emit a High finding and exit with status Fail",
                value_name: "",
                default: None,
                is_flag: true,          // presence sets config key to "true"
            },
        ],
    )
}
}

4. Implement Plugin::initialize

initialize is called once before execute. Read every CLI argument from config and store the values on self.

MethodWhen to use
config.get_or(key, default)String value with a fallback
config.parse_or(key, default)Typed value (u16, u64, …) with a fallback
config.require(key)Value that must be present. Returns Err if missing
#![allow(unused)]
fn main() {
fn initialize(&mut self, config: &PluginConfig) -> Result<()> {
    self.message = config.get_or("message", "hello from example plugin");
    self.fail    = config.get("fail") == Some("true");
    Ok(())
}
}

5. Implement Plugin::execute

execute contains the core test logic. Create a PluginResult, add PluginFinding values, and call result.finish(status) before returning.

Severity levels (lowest to highest): Info -> Low -> Medium -> High -> Critical

Use PluginFinding::with_evidence to attach the raw data that triggered a finding: a banner, a header value, a captured packet and so on. Evidence is shown in the text output and preserved in JSON results.

#![allow(unused)]
fn main() {
fn execute(&mut self) -> Result<PluginResult> {
    let mut result = PluginResult::new(self.meta().name);

    // Neutral observation — always emitted.
    result.add(PluginFinding::new(
        Severity::Info,
        format!("Example plugin executed: {}", self.message),
        "Informational finding describing an observed property of the target.",
    ));

    // Conditional finding with evidence.
    if self.fail {
        result.add(
            PluginFinding::new(
                Severity::High,
                "Simulated failure",
                "The --fail flag was set.",
            )
            .with_evidence("flag: --fail was present"),
        );
        result.finish(PluginStatus::Fail);
        return Ok(result);
    }

    result.finish(PluginStatus::Pass);
    Ok(result)
}
}

Early-return with PluginStatus::Fail for expected failure conditions such as a refused connection or a missing required argument. Reserve Err(...) / ? for truly unexpected failures.

6. Implement Plugin::teardown (optional)

teardown is always called after execute, even when execute returned an error. Use it to close sockets, file handles or serial ports. The default implementation is a no-op. Please omit this method if there is nothing to release.

#![allow(unused)]
fn main() {
fn teardown(&mut self) -> Result<()> {
    Ok(())
}
}

7. Register the plugin

Add a single line at the bottom of the file. The framework collects all registered factories at startup via the inventory crate. Thus, no changes to main.rs or any registry file are needed.

#![allow(unused)]
fn main() {
inventory::submit! {
    crate::PluginFactory(|| Box::new(ExamplePlugin::new()) as Box<dyn crate::Plugin>)
}
}

8. Add documentation

Create a Markdown file at documentation/src/plugins/<protocol>/<plugin-name>.md and add it to documentation/src/SUMMARY.md. See http - banner for an example of the expected structure: one-liner, usage block, description, checks table with severities, options table and example commands.

Running the example plugin

# Pass status with default message
iottack example example

# Custom message
iottack example example --message "testing 1 2 3"

# Trigger the High finding and Fail status
iottack example example --fail

# Save JSON output
iottack example example --fail --output result.json --format json

Running the tests

cargo test

The test suite covers the core types (PluginConfig, PluginFinding, PluginResult, Severity, Category, PluginRegistry) and the output-formatting helpers in main.rs. Doc-tests embedded in the public API are run as part of the same cargo test invocation.