hwntools 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. hwntools-0.1.0/.gitignore +14 -0
  2. hwntools-0.1.0/CHANGELOG.md +27 -0
  3. hwntools-0.1.0/LICENSE +21 -0
  4. hwntools-0.1.0/PKG-INFO +322 -0
  5. hwntools-0.1.0/README.md +277 -0
  6. hwntools-0.1.0/examples/dry_run_simulator.py +14 -0
  7. hwntools-0.1.0/examples/firmware_triage.py +11 -0
  8. hwntools-0.1.0/examples/glitch_sweep.py +38 -0
  9. hwntools-0.1.0/examples/openocd_read_memory.py +16 -0
  10. hwntools-0.1.0/examples/root_shell_exfil.py +19 -0
  11. hwntools-0.1.0/examples/uboot_dump_flash.py +26 -0
  12. hwntools-0.1.0/pyproject.toml +122 -0
  13. hwntools-0.1.0/src/hwntools/__about__.py +1 -0
  14. hwntools-0.1.0/src/hwntools/__init__.py +66 -0
  15. hwntools-0.1.0/src/hwntools/__main__.py +5 -0
  16. hwntools-0.1.0/src/hwntools/_backend.py +36 -0
  17. hwntools-0.1.0/src/hwntools/cli.py +295 -0
  18. hwntools-0.1.0/src/hwntools/context.py +149 -0
  19. hwntools-0.1.0/src/hwntools/exceptions.py +31 -0
  20. hwntools-0.1.0/src/hwntools/firmware/__init__.py +91 -0
  21. hwntools-0.1.0/src/hwntools/firmware/_analyze.py +187 -0
  22. hwntools-0.1.0/src/hwntools/firmware/_fallback.py +358 -0
  23. hwntools-0.1.0/src/hwntools/firmware/_safe.py +55 -0
  24. hwntools-0.1.0/src/hwntools/firmware/_unpack.py +487 -0
  25. hwntools-0.1.0/src/hwntools/firmware/analysis.py +251 -0
  26. hwntools-0.1.0/src/hwntools/glitch.py +253 -0
  27. hwntools-0.1.0/src/hwntools/linux_shell.py +354 -0
  28. hwntools-0.1.0/src/hwntools/log.py +177 -0
  29. hwntools-0.1.0/src/hwntools/openocd.py +251 -0
  30. hwntools-0.1.0/src/hwntools/parsing.py +75 -0
  31. hwntools-0.1.0/src/hwntools/py.typed +0 -0
  32. hwntools-0.1.0/src/hwntools/sim.py +524 -0
  33. hwntools-0.1.0/src/hwntools/spiflash.py +184 -0
  34. hwntools-0.1.0/src/hwntools/tools/__init__.py +30 -0
  35. hwntools-0.1.0/src/hwntools/tools/_common.py +192 -0
  36. hwntools-0.1.0/src/hwntools/tools/baudhound.py +192 -0
  37. hwntools-0.1.0/src/hwntools/tools/bootlint.py +122 -0
  38. hwntools-0.1.0/src/hwntools/tools/fwsift.py +127 -0
  39. hwntools-0.1.0/src/hwntools/tools/mcpwarden.py +100 -0
  40. hwntools-0.1.0/src/hwntools/tubes/__init__.py +10 -0
  41. hwntools-0.1.0/src/hwntools/tubes/process.py +142 -0
  42. hwntools-0.1.0/src/hwntools/tubes/remote.py +109 -0
  43. hwntools-0.1.0/src/hwntools/tubes/serialtube.py +119 -0
  44. hwntools-0.1.0/src/hwntools/tubes/tube.py +383 -0
  45. hwntools-0.1.0/src/hwntools/uart/__init__.py +7 -0
  46. hwntools-0.1.0/src/hwntools/uart/autobaud.py +164 -0
  47. hwntools-0.1.0/src/hwntools/uboot.py +341 -0
  48. hwntools-0.1.0/src/hwntools/util/__init__.py +40 -0
  49. hwntools-0.1.0/src/hwntools/util/crc.py +106 -0
  50. hwntools-0.1.0/src/hwntools/util/cyclic.py +74 -0
  51. hwntools-0.1.0/src/hwntools/util/misc.py +121 -0
  52. hwntools-0.1.0/src/hwntools/util/packing.py +152 -0
  53. hwntools-0.1.0/tests/__init__.py +0 -0
  54. hwntools-0.1.0/tests/conftest.py +23 -0
  55. hwntools-0.1.0/tests/data/tools/baudhound_bootlog.json +110 -0
  56. hwntools-0.1.0/tests/data/tools/baudhound_bootlog.meta +5 -0
  57. hwntools-0.1.0/tests/data/tools/baudhound_clean.json +84 -0
  58. hwntools-0.1.0/tests/data/tools/baudhound_clean.meta +5 -0
  59. hwntools-0.1.0/tests/data/tools/baudhound_findings.json +173 -0
  60. hwntools-0.1.0/tests/data/tools/baudhound_findings.meta +5 -0
  61. hwntools-0.1.0/tests/data/tools/bootlint_clean.json +26 -0
  62. hwntools-0.1.0/tests/data/tools/bootlint_clean.meta +5 -0
  63. hwntools-0.1.0/tests/data/tools/bootlint_error.json +20 -0
  64. hwntools-0.1.0/tests/data/tools/bootlint_error.meta +5 -0
  65. hwntools-0.1.0/tests/data/tools/bootlint_findings.json +129 -0
  66. hwntools-0.1.0/tests/data/tools/bootlint_findings.meta +5 -0
  67. hwntools-0.1.0/tests/data/tools/bootlint_multi.json +281 -0
  68. hwntools-0.1.0/tests/data/tools/bootlint_multi.meta +5 -0
  69. hwntools-0.1.0/tests/data/tools/fwsift_clean.json +38 -0
  70. hwntools-0.1.0/tests/data/tools/fwsift_clean.meta +5 -0
  71. hwntools-0.1.0/tests/data/tools/fwsift_findings.json +139 -0
  72. hwntools-0.1.0/tests/data/tools/fwsift_findings.meta +5 -0
  73. hwntools-0.1.0/tests/data/tools/fwsift_image.json +53 -0
  74. hwntools-0.1.0/tests/data/tools/fwsift_image.meta +5 -0
  75. hwntools-0.1.0/tests/data/tools/mcpwarden_clean.json +31 -0
  76. hwntools-0.1.0/tests/data/tools/mcpwarden_clean.meta +5 -0
  77. hwntools-0.1.0/tests/data/tools/mcpwarden_config_tools.json +143 -0
  78. hwntools-0.1.0/tests/data/tools/mcpwarden_config_tools.meta +5 -0
  79. hwntools-0.1.0/tests/data/tools/mcpwarden_rules.json +146 -0
  80. hwntools-0.1.0/tests/data/tools/mcpwarden_rules.meta +4 -0
  81. hwntools-0.1.0/tests/data/tools/mcpwarden_source.json +162 -0
  82. hwntools-0.1.0/tests/data/tools/mcpwarden_source.meta +5 -0
  83. hwntools-0.1.0/tests/data/tools/mcpwarden_tools_only.json +161 -0
  84. hwntools-0.1.0/tests/data/tools/mcpwarden_tools_only.meta +5 -0
  85. hwntools-0.1.0/tests/data/tools/mcpwarden_warnings.json +42 -0
  86. hwntools-0.1.0/tests/data/tools/mcpwarden_warnings.meta +5 -0
  87. hwntools-0.1.0/tests/fake_openocd.py +124 -0
  88. hwntools-0.1.0/tests/fake_tools.py +122 -0
  89. hwntools-0.1.0/tests/fwimages.py +169 -0
  90. hwntools-0.1.0/tests/test_autobaud_glitch.py +224 -0
  91. hwntools-0.1.0/tests/test_cli.py +243 -0
  92. hwntools-0.1.0/tests/test_context_log.py +119 -0
  93. hwntools-0.1.0/tests/test_firmware.py +590 -0
  94. hwntools-0.1.0/tests/test_linux_shell.py +194 -0
  95. hwntools-0.1.0/tests/test_openocd.py +118 -0
  96. hwntools-0.1.0/tests/test_spiflash.py +111 -0
  97. hwntools-0.1.0/tests/test_tools.py +397 -0
  98. hwntools-0.1.0/tests/test_tubes.py +280 -0
  99. hwntools-0.1.0/tests/test_uboot.py +231 -0
  100. hwntools-0.1.0/tests/test_util.py +188 -0
@@ -0,0 +1,14 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .coverage
8
+ .coverage.*
9
+ htmlcov/
10
+ coverage.xml
11
+ .pytest_cache/
12
+ .mypy_cache/
13
+ .ruff_cache/
14
+ .DS_Store
@@ -0,0 +1,27 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.1.0] - 2026-12-03
8
+
9
+ ### Added
10
+ - `context` (log level, timeouts, arch/endianness, serial defaults) and pwntools-style `log`
11
+ with progress lines.
12
+ - Tubes with a common API: `serial` (pyserial, optional extra), `remote` (TCP, optional telnet
13
+ IAC stripping) and `process`.
14
+ - `UBoot`: autoboot interrupt, prompt detection, commands, env read/write, `saveenv(force=True)`,
15
+ resumable `md.b` dumps with retries, bootargs injection, `audit_env()` via bootlint.
16
+ - `LinuxShell`: prompt classification, login, explicit default-credential check, marker-framed
17
+ commands, file exfiltration (base64/hexdump/od) and upload (base64/printf).
18
+ - `uart.autobaud` for live ports and `autobaud_from_capture` via baudhound.
19
+ - `OpenOCD` TCL RPC client and `Flashrom` wrapper with double-read verification.
20
+ - `firmware`: entropy, signature scanning, carving, multi-backend `unpack()` (native unblob,
21
+ unblob in Docker, binwalk v2/v3, pure-Python fallback with path-traversal and
22
+ decompression-bomb guards) and `analyze()` (fwsift + bootlint).
23
+ - `tools`: wrappers for the fwsift, bootlint, baudhound and mcpwarden CLIs.
24
+ - `glitch.GlitchSweep` with CSV/JSONL logging and an optional ChipWhisperer adapter.
25
+ - `sim`: fake U-Boot and Linux shell devices, in-process or on a pseudo-terminal.
26
+ - `util`: packing, `flat`, `hexdump`, `xor`, `cyclic`, CRC helpers.
27
+ - `hwn` CLI: `uboot dump|env`, `autobaud`, `hexdump`, `entropy`, `sigs`, `fw unpack|analyze`.
hwntools-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Reflex Hardware Security
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,322 @@
1
+ Metadata-Version: 2.5
2
+ Name: hwntools
3
+ Version: 0.1.0
4
+ Summary: pwntools for hardware: a scripting toolkit for authorized hardware security assessments (UART, U-Boot, JTAG/OpenOCD, SPI flash, firmware).
5
+ Project-URL: Homepage, https://github.com/reflex-hs/hwntools
6
+ Project-URL: Issues, https://github.com/reflex-hs/hwntools/issues
7
+ Project-URL: Changelog, https://github.com/reflex-hs/hwntools/blob/main/CHANGELOG.md
8
+ Author: Reflex Hardware Security
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: embedded,firmware,flashrom,hardware-security,iot,jtag,openocd,pentest,pwntools,u-boot,uart
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Information Technology
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Security
24
+ Classifier: Topic :: Software Development :: Embedded Systems
25
+ Classifier: Topic :: System :: Hardware
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.10
28
+ Provides-Extra: all
29
+ Requires-Dist: pyserial>=3.5; extra == 'all'
30
+ Provides-Extra: chipwhisperer
31
+ Requires-Dist: chipwhisperer>=5.6; extra == 'chipwhisperer'
32
+ Provides-Extra: dev
33
+ Requires-Dist: build; extra == 'dev'
34
+ Requires-Dist: mypy>=1.10; extra == 'dev'
35
+ Requires-Dist: pyserial>=3.5; extra == 'dev'
36
+ Requires-Dist: pytest-cov>=5; extra == 'dev'
37
+ Requires-Dist: pytest-timeout>=2.3; extra == 'dev'
38
+ Requires-Dist: pytest>=8; extra == 'dev'
39
+ Requires-Dist: ruff>=0.6; extra == 'dev'
40
+ Requires-Dist: twine; extra == 'dev'
41
+ Requires-Dist: types-pyserial; extra == 'dev'
42
+ Provides-Extra: serial
43
+ Requires-Dist: pyserial>=3.5; extra == 'serial'
44
+ Description-Content-Type: text/markdown
45
+
46
+ # hwntools
47
+
48
+ **pwntools for hardware.** A Python scripting toolkit for *authorized* hardware security
49
+ assessments of IoT, embedded Linux and edge-AI devices: UART consoles, U-Boot, Linux shells
50
+ over serial, JTAG via OpenOCD, SPI flash via flashrom, firmware extraction and triage, and
51
+ fault-injection parameter sweeps.
52
+
53
+ ```python
54
+ from hwntools import *
55
+
56
+ io = serial("/dev/ttyUSB0", 115200)
57
+ ub = UBoot(io)
58
+ ub.interrupt() # now power-cycle the target
59
+ print(ub.printenv()["bootcmd"])
60
+ ub.run("sf probe; sf read 0x82000000 0x0 0x1000000")
61
+ ub.dump(0x82000000, 0x1000000, out="flash.bin") # resumable md.b dump
62
+ ```
63
+
64
+ ```console
65
+ $ hwn fw analyze firmware.bin
66
+ ```
67
+
68
+ > **Authorized use only.** hwntools is meant for testing devices you own or are explicitly
69
+ > permitted to assess. Glitching, flash writes and environment changes can permanently damage
70
+ > hardware. Read the [Safety](#safety) section before connecting anything.
71
+
72
+ ## Install
73
+
74
+ ```console
75
+ pip install hwntools # core: zero third-party dependencies
76
+ pip install "hwntools[serial]" # + pyserial for real serial ports
77
+ ```
78
+
79
+ Python 3.10 or newer. The core (tubes over TCP/processes, U-Boot/Linux helpers, OpenOCD,
80
+ firmware analysis, util) imports without any extra packages.
81
+
82
+ | Extra | Pulls in | Needed for |
83
+ |---|---|---|
84
+ | `serial` | `pyserial` | `serial()` / `serialtube`, `hwn uboot ...`, `hwn autobaud` |
85
+ | `chipwhisperer` | `chipwhisperer` | `glitch.ChipWhispererGlitcher` |
86
+ | `all` | `pyserial` | everything that is pip-installable and light |
87
+ | `dev` | pytest, ruff, mypy, build, twine, ... | development |
88
+
89
+ External programs are optional and used when present: `flashrom`, `openocd` (you run it),
90
+ `unblob` (native or Docker image), `binwalk`, `unsquashfs`, `ubireader_extract_files`,
91
+ `jefferson`, and the Reflex Rust tools (see below).
92
+
93
+ ## Quickstart
94
+
95
+ ### Interrupt U-Boot and dump flash over UART
96
+
97
+ ```python
98
+ from hwntools import *
99
+
100
+ io = serial("/dev/ttyUSB0", 115200) # or remote("ser2net-host", 3001)
101
+ ub = UBoot(io)
102
+ ub.interrupt(key=b"\x03", timeout=60) # spam Ctrl-C until "=> " (power-cycle now)
103
+ print(ub.version())
104
+
105
+ env = ub.printenv()
106
+ ub.run("sf probe 0")
107
+ ub.run("sf read 0x82000000 0x0 0x1000000", timeout=120)
108
+ ub.dump(0x82000000, 0x1000000, out="spi.bin", chunk=0x1000) # Ctrl-C and rerun to resume
109
+ ```
110
+
111
+ Get a root shell on the next boot (RAM only, nothing is saved):
112
+
113
+ ```python
114
+ ub.inject_bootargs("init=/bin/sh", boot=True)
115
+ ```
116
+
117
+ The same from the command line:
118
+
119
+ ```console
120
+ $ hwn uboot env --port /dev/ttyUSB0 --interrupt --json
121
+ $ hwn uboot dump --port /dev/ttyUSB0 --addr 0x82000000 --size 0x1000000 -o spi.bin
122
+ $ hwn uboot dump --port tcp:10.0.0.5:3001 --addr 0x82000000 --size 0x1000000 -o spi.bin
123
+ ```
124
+
125
+ ### Read memory over OpenOCD (JTAG/SWD)
126
+
127
+ ```python
128
+ from hwntools import OpenOCD
129
+
130
+ # openocd -f interface/ftdi/ft232h.cfg -f target/stm32f1x.cfg (TCL RPC on :6666)
131
+ with OpenOCD("127.0.0.1", 6666) as ocd:
132
+ ocd.halt()
133
+ print(hex(ocd.reg("pc")))
134
+ vectors = ocd.read_memory(0x08000000, 0x100, width=32)
135
+ ocd.dump(0x08000000, 0x10000, out="internal-flash.bin")
136
+ ocd.flash_read_bank(0, "/tmp/bank0.bin") # written on the OpenOCD host, fast
137
+ ```
138
+
139
+ ### Exfiltrate a file from a root shell
140
+
141
+ ```python
142
+ from hwntools import *
143
+
144
+ sh = LinuxShell(serial("/dev/ttyUSB0", 115200))
145
+ state = sh.detect() # "root", "user", "login", "password" or "unknown"
146
+ if state == "login":
147
+ sh.try_default_credentials() # only when you call it explicitly
148
+ print(sh.run("id")) # output framed by markers; .status = exit code
149
+ shadow = sh.read_file("/etc/shadow") # base64 -> hexdump -> od fallback, chunked, md5-checked
150
+ sh.upload(open("busybox-armv7l", "rb").read(), "/tmp/bb", mode="755")
151
+ ```
152
+
153
+ ### Firmware: one-line extraction and audit
154
+
155
+ ```python
156
+ from hwntools import firmware
157
+
158
+ res = firmware.unpack("firmware.bin") # unblob -> unblob in Docker -> binwalk -> built-in
159
+ print(res.rootfs, res.kernels, res.dtbs, res.env_candidates, res.kconfigs)
160
+
161
+ report = firmware.analyze("firmware.bin") # unpack + fwsift per rootfs + bootlint on env/DTB/config
162
+ print(report.report())
163
+ ```
164
+
165
+ ```console
166
+ $ hwn fw analyze firmware.bin
167
+ Image: /work/firmware.bin
168
+ Unpacked: /work/firmware.bin.extracted (backend unblob-docker, 11 files)
169
+ Found: 1 rootfs, 1 kernel(s), 1 DTB/FIT, 1 U-Boot env, 1 kernel config(s)
170
+ Findings: critical 2, high 2, medium 2, low 3
171
+ CRITICAL BL-CMD-002 init replaced with a shell .../00000040.uboot-env.bin [bootargs]
172
+ CRITICAL CRED-001 Account without password .../squashfs_v4_le_extract/etc/shadow:1
173
+ HIGH SVC-001 Telnet daemon started at boot .../etc/init.d/rcS:2
174
+ ...
175
+ $ hwn fw analyze firmware.bin --json --fail-on high # CI-friendly
176
+ $ hwn fw unpack firmware.bin --tree
177
+ $ hwn sigs firmware.bin ; hwn entropy firmware.bin --plot ; hwn hexdump firmware.bin -n 0x100
178
+ ```
179
+
180
+ ### Try everything without hardware
181
+
182
+ `hwntools.sim` ships a fake U-Boot console and a fake Linux shell. They run in-process or on a
183
+ real pseudo-terminal, so scripts can be developed before the board arrives:
184
+
185
+ ```python
186
+ from hwntools import serial, UBoot
187
+ from hwntools.sim import FakeUBoot, PtyBridge
188
+
189
+ with PtyBridge(FakeUBoot(memory=open("flash.bin", "rb").read())) as bridge:
190
+ ub = UBoot(serial(bridge.port))
191
+ ub.interrupt()
192
+ print(ub.md(0x80000000, 64).hex())
193
+ ```
194
+
195
+ ## Module overview
196
+
197
+ | Module | What it does |
198
+ |---|---|
199
+ | `hwntools.context` | log level, timeouts (`timeout`, `tool_timeout`), arch/bits/endianness, default serial settings; `with context.local(...)` |
200
+ | `hwntools.log` | pwntools-style `info`/`success`/`warn`/`failure`/`progress()` |
201
+ | `hwntools.tubes` | `Tube` API (`send`, `sendline`, `recv`, `recvn`, `recvuntil`, `recvline`, `recvregex`, `sendlineafter`, `clean`, `interactive`) with `serial`, `remote` (TCP, optional telnet IAC stripping) and `process` |
202
+ | `hwntools.uboot` | stop autoboot, prompt detection, `run`, `printenv`/`setenv`/`saveenv(force=True)`, `md.b` dump with retries and resume, `inject_bootargs`, `audit_env()` (bootlint) |
203
+ | `hwntools.linux_shell` | prompt classification, login, explicit default-credential check, marker-framed `run`, `read_file` (base64/hexdump/od), `upload` (base64/printf) |
204
+ | `hwntools.uart` | `autobaud()` on a live port (pure-Python scoring), `autobaud_from_capture()` via baudhound |
205
+ | `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)` |
206
+ | `hwntools.spiflash` | `Flashrom`: detect, read with double-read verification, `write(force=True)`, `erase(force=True)`, verify |
207
+ | `hwntools.firmware` | entropy map/plot, signature scan (uImage, FIT/DTB, SquashFS, gzip, xz, lzma, ELF, ...), `carve`, `unpack()`, `analyze()`, `scan()` (fwsift) |
208
+ | `hwntools.glitch` | `GlitchSweep`: randomized parameter grid, outcome classification, CSV/JSONL logging, stop-on-success; optional ChipWhisperer adapter |
209
+ | `hwntools.tools` | wrappers for the Reflex Rust CLIs (fwsift, bootlint, baudhound, mcpwarden) |
210
+ | `hwntools.sim` | fake U-Boot / Linux shell devices, `SimTube`, `PtyBridge` |
211
+ | `hwntools.util` | `p8..p64`, `u8..u64`, `flat`, `hexdump`, `xor`, `cyclic`/`cyclic_find`, `crc32`, `crc16_*`, `crc8`, `crc_generic`, `enhex`/`unhex`, `b64e`/`b64d` |
212
+
213
+ ## Firmware extraction backends
214
+
215
+ `firmware.unpack(image, outdir=None, backend="auto")` tries, in order:
216
+
217
+ 1. **native `unblob`** if it is on `PATH`. If it reports missing extractors or failed chunks
218
+ for filesystem formats (for example SquashFS without `sasquatch` on macOS), the Docker
219
+ image is tried next.
220
+ 2. **`unblob` in Docker** (`ghcr.io/onekey-sec/unblob:latest`, never pulled automatically):
221
+ `docker run --rm --network none -v <input dir>:/data/input:ro -v <outdir>:/data/output ...`.
222
+ Only the input's directory (read-only) and the output directory are mounted.
223
+ 3. **`binwalk`** (v2 and v3 flag sets are detected).
224
+ 4. **built-in pure-Python extractor**: uImage (header and data CRC check), gzip/xz/lzma/bzip2,
225
+ FIT/DTB carving, kernel `IKCFG` configs, CRC-verified U-Boot environments, tar and cpio,
226
+ and SquashFS/UBI/JFFS2 through `unsquashfs`/`ubireader_extract_files`/`jefferson` when
227
+ installed (otherwise it tells you what to install).
228
+
229
+ Use `backend="docker"` or `HWNTOOLS_UNBLOB_DOCKER=1` to start with Docker. After an external
230
+ extractor runs, hwntools post-scans the files it left unidentified to find U-Boot environments,
231
+ uImage kernels, DTBs and embedded kernel configs. The built-in extractor never writes outside
232
+ the output directory (no `..`, no absolute paths, no writing through symlinks) and bounds every
233
+ decompression (stream size, ratio, total size, file count, depth) against decompression bombs.
234
+
235
+ ## Using with the Reflex Rust tools
236
+
237
+ hwntools can drive four standalone Rust CLIs from Reflex Hardware Security. Each is its own
238
+ project; install the ones you need:
239
+
240
+ ```console
241
+ cargo install fwsift bootlint baudhound mcpwarden
242
+ ```
243
+
244
+ | Tool | Python | What it does |
245
+ |---|---|---|
246
+ | [fwsift](https://github.com/reflex-hs/fwsift) | `tools.fwsift.scan(rootfs_or_image, osv=False)` | rootfs triage: credentials, keys, services, components (SBOM), ELF hardening |
247
+ | [bootlint](https://github.com/reflex-hs/bootlint) | `tools.bootlint.audit(paths)` | U-Boot env, FIT/DTB/DTS and kernel config audit |
248
+ | [baudhound](https://github.com/reflex-hs/baudhound) | `tools.baudhound.analyze(capture)` | find the UART, baud rate and framing in a logic-analyzer capture |
249
+ | [mcpwarden](https://github.com/reflex-hs/mcpwarden) | `tools.mcpwarden.scan(paths=, tools=, source=)` | audit MCP server configs and tool metadata on edge-AI devices |
250
+
251
+ ```python
252
+ from hwntools import UBoot, serial
253
+ from hwntools.tools import fwsift, baudhound
254
+
255
+ rep = fwsift.scan("rootfs/")
256
+ for f in rep.at_least("high"):
257
+ print(f.severity, f.rule_id, f.path, f.line, f.message)
258
+
259
+ uart = baudhound.analyze("boot.sr").best.uart # .baudrate, .framing, .inverted
260
+ env_report = UBoot(serial("/dev/ttyUSB0")).audit_env() # live U-Boot env -> bootlint
261
+ ```
262
+
263
+ The binaries are located through `$HWNTOOLS_<NAME>` (path to the executable), then `PATH`,
264
+ then `~/.cargo/bin`. Every report exposes normalised `Finding` objects (`rule_id`, `severity`,
265
+ `title`, `message`, `path`, `line`, `location`, `evidence`, and `raw` for the original JSON);
266
+ the full tool output stays available as `report.raw`. "Findings above threshold" exit codes are
267
+ not treated as errors; real tool failures raise `ToolError`. Timeouts come from
268
+ `context.tool_timeout`. `mcpwarden.scan()` refuses to run without explicit inputs, so it never
269
+ scans your own workstation's MCP configs by accident (pass `discover=True` to allow that).
270
+
271
+ ## Safety
272
+
273
+ **Destructive operations need an explicit opt-in.** `UBoot.saveenv()`, `Flashrom.write()`,
274
+ `Flashrom.erase()`, `OpenOCD.flash_write_image()` and `GlitchSweep.run()` raise `SafetyError`
275
+ unless called with `force=True`. Always take and verify a full backup first (`Flashrom.read()`
276
+ reads twice and compares).
277
+
278
+ **Wiring and voltage levels.**
279
+
280
+ - Connect ground first, and keep a common ground between the target, your adapter and any
281
+ logic analyzer.
282
+ - Measure the UART/JTAG/SPI pins with a multimeter before connecting. Embedded boards use
283
+ **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
284
+ level shifter or an adapter that matches the target's I/O voltage.
285
+ - Connect the adapter's RX to the target's TX first and listen. Only connect TX after you have
286
+ confirmed the voltage level.
287
+ - Do not power the target from the adapter's VCC pin unless you know the board's power
288
+ requirements. Leave it disconnected.
289
+ - In-circuit SPI flash reads (clip on a powered-off board) can back-power the SoC through the
290
+ flash's VCC. If reads are unstable or the board heats up, stop: hold the SoC in reset or
291
+ desolder the chip.
292
+ - RS-232 ports swing to +/-12 V and must never be wired to logic-level UART pins.
293
+ - Fault injection (voltage, clock or EM glitching) can permanently damage chips and corrupt
294
+ flash.
295
+
296
+ ## Roadmap
297
+
298
+ - Optional accelerated backend: heavy, side-effect-free functions (entropy and signature
299
+ scanning, FDT/U-Boot env parsing, capture/UART decoding) are kept as pure functions with
300
+ plain types (`bytes` in, lists/dataclasses out) in their own modules (`firmware.analysis`,
301
+ `parsing`). `hwntools._backend` looks for an optional compiled `hwntools._native` module
302
+ (for example PyO3 bindings to the Reflex Rust libraries) and falls back to Python when it is
303
+ missing. No compiled code ships today.
304
+ - `md.l`/`md.q` dumps for faster U-Boot reads, `loady`/`loadb` uploads over the console.
305
+ - SWD/JTAG helpers beyond OpenOCD RPC; more U-Boot vendor prompt profiles.
306
+
307
+ ## Development
308
+
309
+ ```console
310
+ python -m venv .venv && . .venv/bin/activate
311
+ pip install -e ".[dev]"
312
+ pytest --cov # pty-based tests are skipped on Windows
313
+ ruff check src tests examples && ruff format --check src tests examples && mypy
314
+ python -m build && twine check dist/*
315
+ ```
316
+
317
+ Optional integration tests: `HWNTOOLS_TEST_BIN_DIRS=<dirs with the Rust binaries>` and
318
+ `HWNTOOLS_TEST_DOCKER=1` (needs the unblob Docker image and `mksquashfs`).
319
+
320
+ ## License
321
+
322
+ MIT. Copyright (c) 2026 Reflex Hardware Security.
@@ -0,0 +1,277 @@
1
+ # hwntools
2
+
3
+ **pwntools for hardware.** A Python scripting toolkit for *authorized* hardware security
4
+ assessments of IoT, embedded Linux and edge-AI devices: UART consoles, U-Boot, Linux shells
5
+ over serial, JTAG via OpenOCD, SPI flash via flashrom, firmware extraction and triage, and
6
+ fault-injection parameter sweeps.
7
+
8
+ ```python
9
+ from hwntools import *
10
+
11
+ io = serial("/dev/ttyUSB0", 115200)
12
+ ub = UBoot(io)
13
+ ub.interrupt() # now power-cycle the target
14
+ print(ub.printenv()["bootcmd"])
15
+ ub.run("sf probe; sf read 0x82000000 0x0 0x1000000")
16
+ ub.dump(0x82000000, 0x1000000, out="flash.bin") # resumable md.b dump
17
+ ```
18
+
19
+ ```console
20
+ $ hwn fw analyze firmware.bin
21
+ ```
22
+
23
+ > **Authorized use only.** hwntools is meant for testing devices you own or are explicitly
24
+ > permitted to assess. Glitching, flash writes and environment changes can permanently damage
25
+ > hardware. Read the [Safety](#safety) section before connecting anything.
26
+
27
+ ## Install
28
+
29
+ ```console
30
+ pip install hwntools # core: zero third-party dependencies
31
+ pip install "hwntools[serial]" # + pyserial for real serial ports
32
+ ```
33
+
34
+ Python 3.10 or newer. The core (tubes over TCP/processes, U-Boot/Linux helpers, OpenOCD,
35
+ firmware analysis, util) imports without any extra packages.
36
+
37
+ | Extra | Pulls in | Needed for |
38
+ |---|---|---|
39
+ | `serial` | `pyserial` | `serial()` / `serialtube`, `hwn uboot ...`, `hwn autobaud` |
40
+ | `chipwhisperer` | `chipwhisperer` | `glitch.ChipWhispererGlitcher` |
41
+ | `all` | `pyserial` | everything that is pip-installable and light |
42
+ | `dev` | pytest, ruff, mypy, build, twine, ... | development |
43
+
44
+ External programs are optional and used when present: `flashrom`, `openocd` (you run it),
45
+ `unblob` (native or Docker image), `binwalk`, `unsquashfs`, `ubireader_extract_files`,
46
+ `jefferson`, and the Reflex Rust tools (see below).
47
+
48
+ ## Quickstart
49
+
50
+ ### Interrupt U-Boot and dump flash over UART
51
+
52
+ ```python
53
+ from hwntools import *
54
+
55
+ io = serial("/dev/ttyUSB0", 115200) # or remote("ser2net-host", 3001)
56
+ ub = UBoot(io)
57
+ ub.interrupt(key=b"\x03", timeout=60) # spam Ctrl-C until "=> " (power-cycle now)
58
+ print(ub.version())
59
+
60
+ env = ub.printenv()
61
+ ub.run("sf probe 0")
62
+ ub.run("sf read 0x82000000 0x0 0x1000000", timeout=120)
63
+ ub.dump(0x82000000, 0x1000000, out="spi.bin", chunk=0x1000) # Ctrl-C and rerun to resume
64
+ ```
65
+
66
+ Get a root shell on the next boot (RAM only, nothing is saved):
67
+
68
+ ```python
69
+ ub.inject_bootargs("init=/bin/sh", boot=True)
70
+ ```
71
+
72
+ The same from the command line:
73
+
74
+ ```console
75
+ $ hwn uboot env --port /dev/ttyUSB0 --interrupt --json
76
+ $ hwn uboot dump --port /dev/ttyUSB0 --addr 0x82000000 --size 0x1000000 -o spi.bin
77
+ $ hwn uboot dump --port tcp:10.0.0.5:3001 --addr 0x82000000 --size 0x1000000 -o spi.bin
78
+ ```
79
+
80
+ ### Read memory over OpenOCD (JTAG/SWD)
81
+
82
+ ```python
83
+ from hwntools import OpenOCD
84
+
85
+ # openocd -f interface/ftdi/ft232h.cfg -f target/stm32f1x.cfg (TCL RPC on :6666)
86
+ with OpenOCD("127.0.0.1", 6666) as ocd:
87
+ ocd.halt()
88
+ print(hex(ocd.reg("pc")))
89
+ vectors = ocd.read_memory(0x08000000, 0x100, width=32)
90
+ ocd.dump(0x08000000, 0x10000, out="internal-flash.bin")
91
+ ocd.flash_read_bank(0, "/tmp/bank0.bin") # written on the OpenOCD host, fast
92
+ ```
93
+
94
+ ### Exfiltrate a file from a root shell
95
+
96
+ ```python
97
+ from hwntools import *
98
+
99
+ sh = LinuxShell(serial("/dev/ttyUSB0", 115200))
100
+ state = sh.detect() # "root", "user", "login", "password" or "unknown"
101
+ if state == "login":
102
+ sh.try_default_credentials() # only when you call it explicitly
103
+ print(sh.run("id")) # output framed by markers; .status = exit code
104
+ shadow = sh.read_file("/etc/shadow") # base64 -> hexdump -> od fallback, chunked, md5-checked
105
+ sh.upload(open("busybox-armv7l", "rb").read(), "/tmp/bb", mode="755")
106
+ ```
107
+
108
+ ### Firmware: one-line extraction and audit
109
+
110
+ ```python
111
+ from hwntools import firmware
112
+
113
+ res = firmware.unpack("firmware.bin") # unblob -> unblob in Docker -> binwalk -> built-in
114
+ print(res.rootfs, res.kernels, res.dtbs, res.env_candidates, res.kconfigs)
115
+
116
+ report = firmware.analyze("firmware.bin") # unpack + fwsift per rootfs + bootlint on env/DTB/config
117
+ print(report.report())
118
+ ```
119
+
120
+ ```console
121
+ $ hwn fw analyze firmware.bin
122
+ Image: /work/firmware.bin
123
+ Unpacked: /work/firmware.bin.extracted (backend unblob-docker, 11 files)
124
+ Found: 1 rootfs, 1 kernel(s), 1 DTB/FIT, 1 U-Boot env, 1 kernel config(s)
125
+ Findings: critical 2, high 2, medium 2, low 3
126
+ CRITICAL BL-CMD-002 init replaced with a shell .../00000040.uboot-env.bin [bootargs]
127
+ CRITICAL CRED-001 Account without password .../squashfs_v4_le_extract/etc/shadow:1
128
+ HIGH SVC-001 Telnet daemon started at boot .../etc/init.d/rcS:2
129
+ ...
130
+ $ hwn fw analyze firmware.bin --json --fail-on high # CI-friendly
131
+ $ hwn fw unpack firmware.bin --tree
132
+ $ hwn sigs firmware.bin ; hwn entropy firmware.bin --plot ; hwn hexdump firmware.bin -n 0x100
133
+ ```
134
+
135
+ ### Try everything without hardware
136
+
137
+ `hwntools.sim` ships a fake U-Boot console and a fake Linux shell. They run in-process or on a
138
+ real pseudo-terminal, so scripts can be developed before the board arrives:
139
+
140
+ ```python
141
+ from hwntools import serial, UBoot
142
+ from hwntools.sim import FakeUBoot, PtyBridge
143
+
144
+ with PtyBridge(FakeUBoot(memory=open("flash.bin", "rb").read())) as bridge:
145
+ ub = UBoot(serial(bridge.port))
146
+ ub.interrupt()
147
+ print(ub.md(0x80000000, 64).hex())
148
+ ```
149
+
150
+ ## Module overview
151
+
152
+ | Module | What it does |
153
+ |---|---|
154
+ | `hwntools.context` | log level, timeouts (`timeout`, `tool_timeout`), arch/bits/endianness, default serial settings; `with context.local(...)` |
155
+ | `hwntools.log` | pwntools-style `info`/`success`/`warn`/`failure`/`progress()` |
156
+ | `hwntools.tubes` | `Tube` API (`send`, `sendline`, `recv`, `recvn`, `recvuntil`, `recvline`, `recvregex`, `sendlineafter`, `clean`, `interactive`) with `serial`, `remote` (TCP, optional telnet IAC stripping) and `process` |
157
+ | `hwntools.uboot` | stop autoboot, prompt detection, `run`, `printenv`/`setenv`/`saveenv(force=True)`, `md.b` dump with retries and resume, `inject_bootargs`, `audit_env()` (bootlint) |
158
+ | `hwntools.linux_shell` | prompt classification, login, explicit default-credential check, marker-framed `run`, `read_file` (base64/hexdump/od), `upload` (base64/printf) |
159
+ | `hwntools.uart` | `autobaud()` on a live port (pure-Python scoring), `autobaud_from_capture()` via baudhound |
160
+ | `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)` |
161
+ | `hwntools.spiflash` | `Flashrom`: detect, read with double-read verification, `write(force=True)`, `erase(force=True)`, verify |
162
+ | `hwntools.firmware` | entropy map/plot, signature scan (uImage, FIT/DTB, SquashFS, gzip, xz, lzma, ELF, ...), `carve`, `unpack()`, `analyze()`, `scan()` (fwsift) |
163
+ | `hwntools.glitch` | `GlitchSweep`: randomized parameter grid, outcome classification, CSV/JSONL logging, stop-on-success; optional ChipWhisperer adapter |
164
+ | `hwntools.tools` | wrappers for the Reflex Rust CLIs (fwsift, bootlint, baudhound, mcpwarden) |
165
+ | `hwntools.sim` | fake U-Boot / Linux shell devices, `SimTube`, `PtyBridge` |
166
+ | `hwntools.util` | `p8..p64`, `u8..u64`, `flat`, `hexdump`, `xor`, `cyclic`/`cyclic_find`, `crc32`, `crc16_*`, `crc8`, `crc_generic`, `enhex`/`unhex`, `b64e`/`b64d` |
167
+
168
+ ## Firmware extraction backends
169
+
170
+ `firmware.unpack(image, outdir=None, backend="auto")` tries, in order:
171
+
172
+ 1. **native `unblob`** if it is on `PATH`. If it reports missing extractors or failed chunks
173
+ for filesystem formats (for example SquashFS without `sasquatch` on macOS), the Docker
174
+ image is tried next.
175
+ 2. **`unblob` in Docker** (`ghcr.io/onekey-sec/unblob:latest`, never pulled automatically):
176
+ `docker run --rm --network none -v <input dir>:/data/input:ro -v <outdir>:/data/output ...`.
177
+ Only the input's directory (read-only) and the output directory are mounted.
178
+ 3. **`binwalk`** (v2 and v3 flag sets are detected).
179
+ 4. **built-in pure-Python extractor**: uImage (header and data CRC check), gzip/xz/lzma/bzip2,
180
+ FIT/DTB carving, kernel `IKCFG` configs, CRC-verified U-Boot environments, tar and cpio,
181
+ and SquashFS/UBI/JFFS2 through `unsquashfs`/`ubireader_extract_files`/`jefferson` when
182
+ installed (otherwise it tells you what to install).
183
+
184
+ Use `backend="docker"` or `HWNTOOLS_UNBLOB_DOCKER=1` to start with Docker. After an external
185
+ extractor runs, hwntools post-scans the files it left unidentified to find U-Boot environments,
186
+ uImage kernels, DTBs and embedded kernel configs. The built-in extractor never writes outside
187
+ the output directory (no `..`, no absolute paths, no writing through symlinks) and bounds every
188
+ decompression (stream size, ratio, total size, file count, depth) against decompression bombs.
189
+
190
+ ## Using with the Reflex Rust tools
191
+
192
+ hwntools can drive four standalone Rust CLIs from Reflex Hardware Security. Each is its own
193
+ project; install the ones you need:
194
+
195
+ ```console
196
+ cargo install fwsift bootlint baudhound mcpwarden
197
+ ```
198
+
199
+ | Tool | Python | What it does |
200
+ |---|---|---|
201
+ | [fwsift](https://github.com/reflex-hs/fwsift) | `tools.fwsift.scan(rootfs_or_image, osv=False)` | rootfs triage: credentials, keys, services, components (SBOM), ELF hardening |
202
+ | [bootlint](https://github.com/reflex-hs/bootlint) | `tools.bootlint.audit(paths)` | U-Boot env, FIT/DTB/DTS and kernel config audit |
203
+ | [baudhound](https://github.com/reflex-hs/baudhound) | `tools.baudhound.analyze(capture)` | find the UART, baud rate and framing in a logic-analyzer capture |
204
+ | [mcpwarden](https://github.com/reflex-hs/mcpwarden) | `tools.mcpwarden.scan(paths=, tools=, source=)` | audit MCP server configs and tool metadata on edge-AI devices |
205
+
206
+ ```python
207
+ from hwntools import UBoot, serial
208
+ from hwntools.tools import fwsift, baudhound
209
+
210
+ rep = fwsift.scan("rootfs/")
211
+ for f in rep.at_least("high"):
212
+ print(f.severity, f.rule_id, f.path, f.line, f.message)
213
+
214
+ uart = baudhound.analyze("boot.sr").best.uart # .baudrate, .framing, .inverted
215
+ env_report = UBoot(serial("/dev/ttyUSB0")).audit_env() # live U-Boot env -> bootlint
216
+ ```
217
+
218
+ The binaries are located through `$HWNTOOLS_<NAME>` (path to the executable), then `PATH`,
219
+ then `~/.cargo/bin`. Every report exposes normalised `Finding` objects (`rule_id`, `severity`,
220
+ `title`, `message`, `path`, `line`, `location`, `evidence`, and `raw` for the original JSON);
221
+ the full tool output stays available as `report.raw`. "Findings above threshold" exit codes are
222
+ not treated as errors; real tool failures raise `ToolError`. Timeouts come from
223
+ `context.tool_timeout`. `mcpwarden.scan()` refuses to run without explicit inputs, so it never
224
+ scans your own workstation's MCP configs by accident (pass `discover=True` to allow that).
225
+
226
+ ## Safety
227
+
228
+ **Destructive operations need an explicit opt-in.** `UBoot.saveenv()`, `Flashrom.write()`,
229
+ `Flashrom.erase()`, `OpenOCD.flash_write_image()` and `GlitchSweep.run()` raise `SafetyError`
230
+ unless called with `force=True`. Always take and verify a full backup first (`Flashrom.read()`
231
+ reads twice and compares).
232
+
233
+ **Wiring and voltage levels.**
234
+
235
+ - Connect ground first, and keep a common ground between the target, your adapter and any
236
+ logic analyzer.
237
+ - Measure the UART/JTAG/SPI pins with a multimeter before connecting. Embedded boards use
238
+ **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
239
+ level shifter or an adapter that matches the target's I/O voltage.
240
+ - Connect the adapter's RX to the target's TX first and listen. Only connect TX after you have
241
+ confirmed the voltage level.
242
+ - Do not power the target from the adapter's VCC pin unless you know the board's power
243
+ requirements. Leave it disconnected.
244
+ - In-circuit SPI flash reads (clip on a powered-off board) can back-power the SoC through the
245
+ flash's VCC. If reads are unstable or the board heats up, stop: hold the SoC in reset or
246
+ desolder the chip.
247
+ - RS-232 ports swing to +/-12 V and must never be wired to logic-level UART pins.
248
+ - Fault injection (voltage, clock or EM glitching) can permanently damage chips and corrupt
249
+ flash.
250
+
251
+ ## Roadmap
252
+
253
+ - Optional accelerated backend: heavy, side-effect-free functions (entropy and signature
254
+ scanning, FDT/U-Boot env parsing, capture/UART decoding) are kept as pure functions with
255
+ plain types (`bytes` in, lists/dataclasses out) in their own modules (`firmware.analysis`,
256
+ `parsing`). `hwntools._backend` looks for an optional compiled `hwntools._native` module
257
+ (for example PyO3 bindings to the Reflex Rust libraries) and falls back to Python when it is
258
+ missing. No compiled code ships today.
259
+ - `md.l`/`md.q` dumps for faster U-Boot reads, `loady`/`loadb` uploads over the console.
260
+ - SWD/JTAG helpers beyond OpenOCD RPC; more U-Boot vendor prompt profiles.
261
+
262
+ ## Development
263
+
264
+ ```console
265
+ python -m venv .venv && . .venv/bin/activate
266
+ pip install -e ".[dev]"
267
+ pytest --cov # pty-based tests are skipped on Windows
268
+ ruff check src tests examples && ruff format --check src tests examples && mypy
269
+ python -m build && twine check dist/*
270
+ ```
271
+
272
+ Optional integration tests: `HWNTOOLS_TEST_BIN_DIRS=<dirs with the Rust binaries>` and
273
+ `HWNTOOLS_TEST_DOCKER=1` (needs the unblob Docker image and `mksquashfs`).
274
+
275
+ ## License
276
+
277
+ MIT. Copyright (c) 2026 Reflex Hardware Security.