Skip to main content

A circuit board wired through a USB-UART adapter to a laptop

hwntools

pwntools for hardware.
UART, U-Boot, JTAG, SPI flash and firmware triage, scripted from one Python file.

PyPI Python versions CI Documentation MIT license Zero dependencies GitHub Discussions

Documentation · Install · Quickstart · Simulator · Learn · Safety · Reflex Hardware Security


Every hardware assessment starts the same way: find the UART, stop U-Boot, dump the flash by hand, unpack it, grep for passwords. hwntools turns that first day into a script, with the same recvuntil / sendline feel as pwntools, for IoT, embedded Linux and edge-AI devices.

Stop U-Boot and dump the SPI flash over the serial console, in three lines:

from hwntools import *

ub = UBoot(serial("/dev/ttyUSB0", 115200)); ub.interrupt()    # now power-cycle the target
ub.run("sf probe; sf read 0x82000000 0x0 0x1000000")          # flash -> RAM
ub.dump(0x82000000, 0x1000000, out="flash.bin")               # RAM -> file, resumable md.b dump

No board on your desk yet? The same calls run against the built-in simulator, in-process and without any extra packages:

from hwntools import UBoot
from hwntools.sim import FakeUBoot, SimTube

ub = UBoot(SimTube(FakeUBoot(memory=bytes(range(256)) * 16)))
ub.interrupt()
print(ub.printenv()["bootcmd"], ub.dump(0x80000000, 0x1000)[:16].hex())

hwn fw analyze unpacking a firmware image and listing findings

What it covers

Serial consoles
pwntools-style tubes over serial, TCP (ser2net) and processes. Auto-detect the baud rate.
U-Boot
Stop autoboot, read and audit the environment, resumable md.b flash dumps, one-shot init=/bin/sh.
Linux shells
Classify the prompt, log in, run commands with exit codes, pull files out and push tools in, all over UART.
JTAG / SWD and SPI flash
OpenOCD TCL RPC (halt, registers, memory, flash banks) and flashrom with double-read verification.
Firmware triage
hwn fw analyze: unpack with unblob / binwalk / a safe built-in extractor, then find credentials, open shells and weak boot settings.
Simulator
A fake U-Boot and Linux shell on a real pseudo-terminal, so you can write the script before the board arrives.

UART → U-Boot → flash dump → unpack → findings,  in one script or one hwn command.

Learn in your terminal

New to hardware hacking? hwn learn is an interactive tutorial in the spirit of rustlings and vimtutor: nine short lessons on a simulated router (read a UART, find the baud rate, stop U-Boot, dump the flash, analyze the firmware, get a shell, JTAG, and a final CTF). Each lesson creates an exercise file with TODOs, and hwn learn check grades it against the simulator. No hardware, no network.

pip install hwntools && hwn learn

hwn learn: the lesson list, lesson 1 and a passing check

The same lessons, with more detail, are on the Learn pages of the documentation.

Install

pip install hwntools            # core: zero third-party dependencies
pip install "hwntools[serial]"  # + pyserial for real serial ports

Python 3.10 or newer. The core (tubes over TCP/processes, U-Boot/Linux helpers, OpenOCD, firmware analysis, util) imports without any extra packages.

Extra Pulls in Needed for
serial pyserial serial() / serialtube, hwn uboot ..., hwn autobaud, hwn console on a port
all pyserial everything that is pip-installable and light
dev pytest, ruff, mypy, build, twine, ... development
docs MkDocs Material, mkdocstrings building the documentation site

External programs are optional and used when present: flashrom, openocd (you run it), unblob (native or Docker image), binwalk, unsquashfs, ubireader_extract_files, jefferson, and the Reflex Rust tools (see below).

Quickstart

Interrupt U-Boot and dump flash over UART

from hwntools import *

io = serial("/dev/ttyUSB0", 115200)        # or remote("ser2net-host", 3001)
ub = UBoot(io)
ub.interrupt(key=b"\x03", timeout=60)       # spam Ctrl-C until "=> " (power-cycle now)
print(ub.version())

env = ub.printenv()
ub.run("sf probe 0")
ub.run("sf read 0x82000000 0x0 0x1000000", timeout=120)
ub.dump(0x82000000, 0x1000000, out="spi.bin", chunk=0x1000)   # Ctrl-C and rerun to resume

Get a root shell on the next boot (RAM only, nothing is saved):

ub.inject_bootargs("init=/bin/sh", boot=True)

The same from the command line:

$ hwn uboot env  --port /dev/ttyUSB0 --interrupt --json
$ hwn uboot dump --port /dev/ttyUSB0 --addr 0x82000000 --size 0x1000000 -o spi.bin
$ hwn uboot dump --port tcp:10.0.0.5:3001 --addr 0x82000000 --size 0x1000000 -o spi.bin
$ hwn console /dev/ttyUSB0 -b 115200 --log session.log -t   # interactive, logged; Ctrl-] quits
$ hwn console --sim                                          # the same against a simulated U-Boot

Read memory over OpenOCD (JTAG/SWD)

from hwntools import OpenOCD

# openocd -f interface/ftdi/ft232h.cfg -f target/stm32f1x.cfg   (TCL RPC on :6666)
with OpenOCD("127.0.0.1", 6666) as ocd:
    ocd.halt()
    print(hex(ocd.reg("pc")))
    vectors = ocd.read_memory(0x08000000, 0x100, width=32)
    ocd.dump(0x08000000, 0x10000, out="internal-flash.bin")
    ocd.flash_read_bank(0, "/tmp/bank0.bin")      # written on the OpenOCD host, fast

Exfiltrate a file from a root shell

from hwntools import *

sh = LinuxShell(serial("/dev/ttyUSB0", 115200))
state = sh.detect()                       # "root", "user", "login", "password" or "unknown"
if state == "login":
    sh.try_default_credentials()          # only when you call it explicitly
print(sh.run("id"))                       # output framed by markers; .status = exit code
shadow = sh.read_file("/etc/shadow")      # base64 -> hexdump -> od fallback, chunked, md5-checked
sh.upload(open("busybox-armv7l", "rb").read(), "/tmp/bb", mode="755")

Firmware: one-line extraction and audit

from hwntools import firmware

res = firmware.unpack("firmware.bin")     # unblob -> unblob in Docker -> binwalk -> built-in
print(res.rootfs, res.kernels, res.dtbs, res.env_candidates, res.kconfigs)

report = firmware.analyze("firmware.bin") # unpack + fwsift per rootfs + bootlint on env/DTB/config
print(report.report())
$ hwn fw analyze firmware.bin
Image:    /work/firmware.bin
Unpacked: /work/firmware.bin.extracted (backend unblob-docker, 11 files)
Found:    1 rootfs, 1 kernel(s), 1 DTB/FIT, 1 U-Boot env, 1 kernel config(s)
Findings: critical 2, high 2, medium 2, low 3
  CRITICAL BL-CMD-002   init replaced with a shell  .../00000040.uboot-env.bin [bootargs]
  CRITICAL CRED-001     Account without password  .../squashfs_v4_le_extract/etc/shadow:1
  HIGH     SVC-001      Telnet daemon started at boot  .../etc/init.d/rcS:2
  ...
$ hwn fw analyze firmware.bin --json --fail-on high     # CI-friendly
$ hwn fw unpack firmware.bin --tree
$ hwn sigs firmware.bin ; hwn entropy firmware.bin --plot ; hwn hexdump firmware.bin -n 0x100

Try everything without hardware

hwntools.sim ships a fake U-Boot console and a fake Linux shell. They run in-process (SimTube, as in the example at the top) or on a real pseudo-terminal, so scripts written for a serial port can be developed before the board arrives. PtyBridge goes through serial(), so it needs the serial extra:

from hwntools import serial, UBoot
from hwntools.sim import FakeUBoot, PtyBridge

with PtyBridge(FakeUBoot(memory=open("flash.bin", "rb").read())) as bridge:
    ub = UBoot(serial(bridge.port))
    ub.interrupt()
    print(ub.md(0x80000000, 64).hex())

Module overview

Every module and what it does
Module What it does
hwntools.context log level, timeouts (timeout, tool_timeout), arch/bits/endianness, default serial settings; with context.local(...)
hwntools.log pwntools-style info/success/warn/failure/progress()
hwntools.tubes Tube API (send, sendline, recv, recvn, recvuntil, recvline, recvregex, sendlineafter, clean, interactive) with serial, remote (TCP, optional telnet IAC stripping) and process
hwntools.uboot stop autoboot, prompt detection, run, printenv/setenv/saveenv(force=True), md.b dump with retries and resume, inject_bootargs, audit_env() (bootlint)
hwntools.linux_shell prompt classification, login, explicit default-credential check, marker-framed run, read_file (base64/hexdump/od), upload (base64/printf)
hwntools.uart (experimental) autobaud() on a live port (pure-Python scoring), autobaud_from_capture() via baudhound
hwntools.openocd (experimental) TCL RPC client: halt/resume/reset/step, registers, read/write memory, chunked dumps, dump_image, load_image, flash bank read, flash_write_image(force=True)
hwntools.spiflash (experimental) Flashrom: detect, read with double-read verification, write(force=True), erase(force=True), verify
hwntools.firmware entropy map/plot, signature scan (uImage, FIT/DTB, SquashFS, gzip, xz, lzma, ELF, ...), carve, unpack(), analyze(), scan() (fwsift)
hwntools.tools (experimental) wrappers for the Reflex Rust CLIs (fwsift, bootlint, baudhound, mcpwarden)
hwntools.sim fake U-Boot / Linux shell devices, SimTube, PtyBridge
hwntools.util p8..p64, u8..u64, flat, hexdump, xor, cyclic/cyclic_find, crc32, crc16_*, crc8, crc_generic, enhex/unhex, b64e/b64d

Experimental modules. uart, openocd, spiflash and tools are tested only against simulated devices and recorded tool output so far, not real hardware. Their APIs may change in minor releases until they have been validated on real targets.

Firmware extraction backends

How firmware.unpack() picks an extractor, and how it stays safe

firmware.unpack(image, outdir=None, backend="auto") tries, in order:

  1. native unblob if it is on PATH. If it reports missing extractors or failed chunks for filesystem formats (for example SquashFS without sasquatch on macOS), the Docker image is tried next.
  2. unblob in Docker (ghcr.io/onekey-sec/unblob:latest, never pulled automatically): docker run --rm --network none -v <input dir>:/data/input:ro -v <outdir>:/data/output .... Only the input's directory (read-only) and the output directory are mounted.
  3. binwalk (v2 and v3 flag sets are detected).
  4. built-in pure-Python extractor: uImage (header and data CRC check), gzip/xz/lzma/bzip2, FIT/DTB carving, kernel IKCFG configs, CRC-verified U-Boot environments, tar and cpio, and SquashFS/UBI/JFFS2 through unsquashfs/ubireader_extract_files/jefferson when installed (otherwise it tells you what to install).

Use backend="docker" or HWNTOOLS_UNBLOB_DOCKER=1 to start with Docker. After an external extractor runs, hwntools post-scans the files it left unidentified to find U-Boot environments, uImage kernels, DTBs and embedded kernel configs. The built-in extractor never writes outside the output directory (no .., no absolute paths, no writing through symlinks) and bounds every decompression (stream size, ratio, total size, file count, depth) against decompression bombs.

Using with the Reflex Rust tools

hwntools can drive four standalone Rust CLIs from Reflex Hardware Security. Each is its own project; install the ones you need:

cargo install --git https://github.com/reflex-hs/fwsift      # not on crates.io yet
cargo install --git https://github.com/reflex-hs/bootlint
cargo install --git https://github.com/reflex-hs/baudhound
cargo install --git https://github.com/reflex-hs/mcpwarden
Tool Python What it does
fwsift tools.fwsift.scan(rootfs_or_image, osv=False) rootfs triage: credentials, keys, services, components (SBOM), ELF hardening
bootlint tools.bootlint.audit(paths) U-Boot env, FIT/DTB/DTS and kernel config audit
baudhound tools.baudhound.analyze(capture) find the UART, baud rate and framing in a logic-analyzer capture
mcpwarden tools.mcpwarden.scan(paths=, tools=, source=) audit MCP server configs and tool metadata on edge-AI devices
from hwntools import UBoot, serial
from hwntools.tools import fwsift, baudhound

rep = fwsift.scan("rootfs/")
for f in rep.at_least("high"):
    print(f.severity, f.rule_id, f.path, f.line, f.message)

uart = baudhound.analyze("boot.sr").best.uart      # .baudrate, .framing, .inverted
env_report = UBoot(serial("/dev/ttyUSB0")).audit_env()   # live U-Boot env -> bootlint

The binaries are located through $HWNTOOLS_<NAME> (path to the executable), then PATH, then ~/.cargo/bin. Every report exposes normalised Finding objects (rule_id, severity, title, message, path, line, location, evidence, and raw for the original JSON); the full tool output stays available as report.raw. "Findings above threshold" exit codes are not treated as errors; real tool failures raise ToolError. Timeouts come from context.tool_timeout. mcpwarden.scan() refuses to run without explicit inputs, so it never scans your own workstation's MCP configs by accident (pass discover=True to allow that).

Safety

Destructive operations need an explicit opt-in. UBoot.saveenv(), Flashrom.write(), Flashrom.erase() and OpenOCD.flash_write_image() raise SafetyError unless called with force=True. Always take and verify a full backup first (Flashrom.read() reads twice and compares).

Wiring and voltage levels.

  • Connect ground first, and keep a common ground between the target, your adapter and any logic analyzer.
  • Measure the UART/JTAG/SPI pins with a multimeter before connecting. Embedded boards use 1.8 V, 3.3 V or 5 V logic. A 5 V USB-UART adapter can destroy a 1.8 V or 3.3 V SoC. Use a level shifter or an adapter that matches the target's I/O voltage.
  • Connect the adapter's RX to the target's TX first and listen. Only connect TX after you have confirmed the voltage level.
  • Do not power the target from the adapter's VCC pin unless you know the board's power requirements. Leave it disconnected.
  • In-circuit SPI flash reads (clip on a powered-off board) can back-power the SoC through the flash's VCC. If reads are unstable or the board heats up, stop: hold the SoC in reset or desolder the chip.
  • RS-232 ports swing to +/-12 V and must never be wired to logic-level UART pins.

Roadmap

  • Optional accelerated backend: heavy, side-effect-free functions (entropy and signature scanning, FDT/U-Boot env parsing, capture/UART decoding) are kept as pure functions with plain types (bytes in, lists/dataclasses out) in their own modules (firmware.analysis, parsing). hwntools._backend looks for an optional compiled hwntools._native module (for example PyO3 bindings to the Reflex Rust libraries) and falls back to Python when it is missing. No compiled code ships today.
  • md.l/md.q dumps for faster U-Boot reads, loady/loadb uploads over the console.
  • SWD/JTAG helpers beyond OpenOCD RPC; more U-Boot vendor prompt profiles.

Development

Set up a dev environment and run the checks
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
pytest --cov            # pty-based tests are skipped on Windows
ruff check src tests examples && ruff format --check src tests examples && mypy
python -m build && twine check dist/*

Optional integration tests: HWNTOOLS_TEST_BIN_DIRS=<dirs with the Rust binaries> and HWNTOOLS_TEST_DOCKER=1 (needs the unblob Docker image and mksquashfs).

Community

License

The code is MIT licensed. Copyright (c) 2026 Reflex Hardware Security.

The illustrations in docs/art/ are not covered by the MIT license: they come from Reflex Design by Reflex Hardware Security and are licensed under CC BY 4.0. See docs/art/LICENSE-ART.md.

Built by Reflex Hardware Security
Hardware security assessments for robots, drones, edge AI and IoT devices. If hwntools saves you a day, a ⭐ helps others find it.

Metadata

Release files for hwntools 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hwntools 0.3.0
File Size Uploaded Provenance Actions
hwntools-0.3.0.tar.gz 149.9 kB With provenance Details for hwntools-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for hwntools 0.3.0
File Interpreter ABI Platform Actions
hwntools-0.3.0-py3-none-any.whl Python 3 none any Details for hwntools-0.3.0-py3-none-any.whl

Total release size: 278.8 kB

Release files / hwntools-0.3.0.tar.gz

Download URL hwntools-0.3.0.tar.gz
Size 149.9 kB
Tags Source
SHA-256 checksum
How to use checksums
bedc075f3501cf0aa407b9532195906e85bc801a02baf7e73f3493f567c00ca4
BLAKE2b-256 checksum
How to use checksums
f53e5da83e4b54573c9558972a88980ebb48f2e2c5c95c555895e97ba303fc74
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Release files / hwntools-0.3.0-py3-none-any.whl

Download URL hwntools-0.3.0-py3-none-any.whl
Size 129.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8e165904b847e05e1d863c198369396e1a28a8e7434e30914a3ed713365a23d6
BLAKE2b-256 checksum
How to use checksums
6982638c38926d8d3a3a0a7af3922d0fe76bb01347c4096c5f5f393a109fd883
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Security for hwntools 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for hwntools-0.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page