Metadata-Version: 2.5
Name: hwntools
Version: 0.1.0
Summary: pwntools for hardware: a scripting toolkit for authorized hardware security assessments (UART, U-Boot, JTAG/OpenOCD, SPI flash, firmware).
Project-URL: Homepage, https://github.com/reflex-hs/hwntools
Project-URL: Issues, https://github.com/reflex-hs/hwntools/issues
Project-URL: Changelog, https://github.com/reflex-hs/hwntools/blob/main/CHANGELOG.md
Author: Reflex Hardware Security
License-Expression: MIT
License-File: LICENSE
Keywords: embedded,firmware,flashrom,hardware-security,iot,jtag,openocd,pentest,pwntools,u-boot,uart
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Embedded Systems
Classifier: Topic :: System :: Hardware
Classifier: Typing :: Typed
Requires-Python: >=3.10
Provides-Extra: all
Requires-Dist: pyserial>=3.5; extra == 'all'
Provides-Extra: chipwhisperer
Requires-Dist: chipwhisperer>=5.6; extra == 'chipwhisperer'
Provides-Extra: dev
Requires-Dist: build; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pyserial>=3.5; extra == 'dev'
Requires-Dist: pytest-cov>=5; extra == 'dev'
Requires-Dist: pytest-timeout>=2.3; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Requires-Dist: twine; extra == 'dev'
Requires-Dist: types-pyserial; extra == 'dev'
Provides-Extra: serial
Requires-Dist: pyserial>=3.5; extra == 'serial'
Description-Content-Type: text/markdown

# hwntools

**pwntools for hardware.** A Python scripting toolkit for *authorized* hardware security
assessments of IoT, embedded Linux and edge-AI devices: UART consoles, U-Boot, Linux shells
over serial, JTAG via OpenOCD, SPI flash via flashrom, firmware extraction and triage, and
fault-injection parameter sweeps.

```python
from hwntools import *

io = serial("/dev/ttyUSB0", 115200)
ub = UBoot(io)
ub.interrupt()                         # now power-cycle the target
print(ub.printenv()["bootcmd"])
ub.run("sf probe; sf read 0x82000000 0x0 0x1000000")
ub.dump(0x82000000, 0x1000000, out="flash.bin")   # resumable md.b dump
```

```console
$ hwn fw analyze firmware.bin
```

> **Authorized use only.** hwntools is meant for testing devices you own or are explicitly
> permitted to assess. Glitching, flash writes and environment changes can permanently damage
> hardware. Read the [Safety](#safety) section before connecting anything.

## Install

```console
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` |
| `chipwhisperer` | `chipwhisperer` | `glitch.ChipWhispererGlitcher` |
| `all` | `pyserial` | everything that is pip-installable and light |
| `dev` | pytest, ruff, mypy, build, twine, ... | development |

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

```python
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):

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

The same from the command line:

```console
$ 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
```

### Read memory over OpenOCD (JTAG/SWD)

```python
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

```python
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

```python
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())
```

```console
$ 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 or on a
real pseudo-terminal, so scripts can be developed before the board arrives:

```python
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

| 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` | `autobaud()` on a live port (pure-Python scoring), `autobaud_from_capture()` via baudhound |
| `hwntools.openocd` | 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` | `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.glitch` | `GlitchSweep`: randomized parameter grid, outcome classification, CSV/JSONL logging, stop-on-success; optional ChipWhisperer adapter |
| `hwntools.tools` | 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` |

## Firmware extraction backends

`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:

```console
cargo install fwsift bootlint baudhound mcpwarden
```

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

```python
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()`, `OpenOCD.flash_write_image()` and `GlitchSweep.run()` 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.
- Fault injection (voltage, clock or EM glitching) can permanently damage chips and corrupt
  flash.

## 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

```console
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`).

## License

MIT. Copyright (c) 2026 Reflex Hardware Security.
