hwntools 0.1.0__py3-none-any.whl
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.
- hwntools/__about__.py +1 -0
- hwntools/__init__.py +66 -0
- hwntools/__main__.py +5 -0
- hwntools/_backend.py +36 -0
- hwntools/cli.py +295 -0
- hwntools/context.py +149 -0
- hwntools/exceptions.py +31 -0
- hwntools/firmware/__init__.py +91 -0
- hwntools/firmware/_analyze.py +187 -0
- hwntools/firmware/_fallback.py +358 -0
- hwntools/firmware/_safe.py +55 -0
- hwntools/firmware/_unpack.py +487 -0
- hwntools/firmware/analysis.py +251 -0
- hwntools/glitch.py +253 -0
- hwntools/linux_shell.py +354 -0
- hwntools/log.py +177 -0
- hwntools/openocd.py +251 -0
- hwntools/parsing.py +75 -0
- hwntools/py.typed +0 -0
- hwntools/sim.py +524 -0
- hwntools/spiflash.py +184 -0
- hwntools/tools/__init__.py +30 -0
- hwntools/tools/_common.py +192 -0
- hwntools/tools/baudhound.py +192 -0
- hwntools/tools/bootlint.py +122 -0
- hwntools/tools/fwsift.py +127 -0
- hwntools/tools/mcpwarden.py +100 -0
- hwntools/tubes/__init__.py +10 -0
- hwntools/tubes/process.py +142 -0
- hwntools/tubes/remote.py +109 -0
- hwntools/tubes/serialtube.py +119 -0
- hwntools/tubes/tube.py +383 -0
- hwntools/uart/__init__.py +7 -0
- hwntools/uart/autobaud.py +164 -0
- hwntools/uboot.py +341 -0
- hwntools/util/__init__.py +40 -0
- hwntools/util/crc.py +106 -0
- hwntools/util/cyclic.py +74 -0
- hwntools/util/misc.py +121 -0
- hwntools/util/packing.py +152 -0
- hwntools-0.1.0.dist-info/METADATA +322 -0
- hwntools-0.1.0.dist-info/RECORD +45 -0
- hwntools-0.1.0.dist-info/WHEEL +4 -0
- hwntools-0.1.0.dist-info/entry_points.txt +2 -0
- hwntools-0.1.0.dist-info/licenses/LICENSE +21 -0
hwntools/__about__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
hwntools/__init__.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""hwntools: pwntools for hardware.
|
|
2
|
+
|
|
3
|
+
A scripting toolkit for authorized hardware security assessments: UART consoles, U-Boot,
|
|
4
|
+
Linux shells over serial, OpenOCD/JTAG, SPI flash via flashrom, firmware triage and glitch
|
|
5
|
+
parameter sweeps.
|
|
6
|
+
|
|
7
|
+
``from hwntools import *`` brings the common names into scope, like ``from pwn import *``::
|
|
8
|
+
|
|
9
|
+
from hwntools import *
|
|
10
|
+
|
|
11
|
+
io = serial("/dev/ttyUSB0", 115200)
|
|
12
|
+
ub = UBoot(io)
|
|
13
|
+
ub.interrupt()
|
|
14
|
+
ub.dump(0x82000000, 0x100000, out="kernel.bin")
|
|
15
|
+
|
|
16
|
+
The core has no third-party dependencies; serial support needs ``hwntools[serial]``.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from . import firmware, glitch, linux_shell, openocd, sim, spiflash, uart, uboot, util
|
|
22
|
+
from .__about__ import __version__
|
|
23
|
+
from .context import context
|
|
24
|
+
from .exceptions import HwnError, HwnTimeoutError, ParseError, SafetyError, ToolNotFoundError
|
|
25
|
+
from .glitch import GlitchSweep
|
|
26
|
+
from .linux_shell import LinuxShell
|
|
27
|
+
from .log import log
|
|
28
|
+
from .openocd import OpenOCD
|
|
29
|
+
from .spiflash import Flashrom
|
|
30
|
+
from .tubes import Tube, process, remote, serial, serialtube
|
|
31
|
+
from .uart import autobaud
|
|
32
|
+
from .uboot import UBoot
|
|
33
|
+
from .util import *
|
|
34
|
+
from .util import __all__ as _util_all
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"Flashrom",
|
|
38
|
+
"GlitchSweep",
|
|
39
|
+
"HwnError",
|
|
40
|
+
"HwnTimeoutError",
|
|
41
|
+
"LinuxShell",
|
|
42
|
+
"OpenOCD",
|
|
43
|
+
"ParseError",
|
|
44
|
+
"SafetyError",
|
|
45
|
+
"ToolNotFoundError",
|
|
46
|
+
"Tube",
|
|
47
|
+
"UBoot",
|
|
48
|
+
"__version__",
|
|
49
|
+
"autobaud",
|
|
50
|
+
"context",
|
|
51
|
+
"firmware",
|
|
52
|
+
"glitch",
|
|
53
|
+
"linux_shell",
|
|
54
|
+
"log",
|
|
55
|
+
"openocd",
|
|
56
|
+
"process",
|
|
57
|
+
"remote",
|
|
58
|
+
"serial",
|
|
59
|
+
"serialtube",
|
|
60
|
+
"sim",
|
|
61
|
+
"spiflash",
|
|
62
|
+
"uart",
|
|
63
|
+
"uboot",
|
|
64
|
+
"util",
|
|
65
|
+
*_util_all,
|
|
66
|
+
]
|
hwntools/__main__.py
ADDED
hwntools/_backend.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Optional accelerated backend hook.
|
|
2
|
+
|
|
3
|
+
Pure-Python implementations of heavy, side-effect-free functions (entropy, signature scans,
|
|
4
|
+
console parsers) look up a same-named function in an optional compiled ``hwntools._native``
|
|
5
|
+
extension and use it when present. No such extension ships yet; the hook keeps the public
|
|
6
|
+
signatures stable so one can be added later without changing callers.
|
|
7
|
+
|
|
8
|
+
Set ``HWNTOOLS_NO_NATIVE=1`` to force the pure-Python code paths.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import importlib
|
|
14
|
+
import os
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from functools import cache
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
__all__ = ["native"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@cache
|
|
23
|
+
def _module() -> Any:
|
|
24
|
+
if os.environ.get("HWNTOOLS_NO_NATIVE"):
|
|
25
|
+
return None
|
|
26
|
+
try:
|
|
27
|
+
return importlib.import_module("hwntools._native")
|
|
28
|
+
except ImportError:
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def native(name: str) -> Callable[..., Any] | None:
|
|
33
|
+
"""Return the accelerated implementation of *name*, or ``None``."""
|
|
34
|
+
mod = _module()
|
|
35
|
+
fn = getattr(mod, name, None) if mod is not None else None
|
|
36
|
+
return fn if callable(fn) else None
|
hwntools/cli.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""``hwn`` command line interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Sequence
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from .__about__ import __version__
|
|
12
|
+
from .context import context
|
|
13
|
+
from .exceptions import HwnError
|
|
14
|
+
from .log import log
|
|
15
|
+
from .tubes.tube import Tube
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _int(text: str) -> int:
|
|
19
|
+
return int(text, 0)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _open_tube(args: argparse.Namespace) -> Tube:
|
|
23
|
+
if args.port.startswith("tcp:"):
|
|
24
|
+
from .tubes.remote import remote
|
|
25
|
+
|
|
26
|
+
host, _, port = args.port[4:].rpartition(":")
|
|
27
|
+
return remote(host, int(port))
|
|
28
|
+
from .tubes.serialtube import serialtube
|
|
29
|
+
|
|
30
|
+
return serialtube(args.port, baudrate=args.baud)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _add_port(p: argparse.ArgumentParser) -> None:
|
|
34
|
+
p.add_argument(
|
|
35
|
+
"--port",
|
|
36
|
+
"-p",
|
|
37
|
+
required=True,
|
|
38
|
+
help="serial device, pyserial URL, or tcp:HOST:PORT (ser2net)",
|
|
39
|
+
)
|
|
40
|
+
p.add_argument("--baud", "-b", type=int, default=115200)
|
|
41
|
+
p.add_argument("--prompt", default=None, help="U-Boot prompt (auto-detected by default)")
|
|
42
|
+
p.add_argument(
|
|
43
|
+
"--interrupt",
|
|
44
|
+
action="store_true",
|
|
45
|
+
help="spam the stop key until a prompt appears (power-cycle the target)",
|
|
46
|
+
)
|
|
47
|
+
p.add_argument("--key", default="\x03", help="autoboot stop key or string (default Ctrl-C)")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _uboot(args: argparse.Namespace): # type: ignore[no-untyped-def]
|
|
51
|
+
from .uboot import UBoot
|
|
52
|
+
|
|
53
|
+
tube = _open_tube(args)
|
|
54
|
+
ub = UBoot(tube, prompt=args.prompt)
|
|
55
|
+
if args.interrupt:
|
|
56
|
+
ub.interrupt(key=args.key, timeout=args.interrupt_timeout)
|
|
57
|
+
return ub
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cmd_uboot_dump(args: argparse.Namespace) -> int:
|
|
61
|
+
ub = _uboot(args)
|
|
62
|
+
try:
|
|
63
|
+
ub.dump(args.addr, args.size, out=args.out, chunk=args.chunk, resume=not args.no_resume)
|
|
64
|
+
finally:
|
|
65
|
+
ub.tube.close()
|
|
66
|
+
log.success("Saved to %s", args.out)
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def cmd_uboot_env(args: argparse.Namespace) -> int:
|
|
71
|
+
ub = _uboot(args)
|
|
72
|
+
try:
|
|
73
|
+
env = ub.printenv()
|
|
74
|
+
finally:
|
|
75
|
+
ub.tube.close()
|
|
76
|
+
if args.json:
|
|
77
|
+
print(json.dumps(env, indent=2, sort_keys=True))
|
|
78
|
+
else:
|
|
79
|
+
for k in sorted(env):
|
|
80
|
+
print(f"{k}={env[k]}")
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def cmd_autobaud(args: argparse.Namespace) -> int:
|
|
85
|
+
from .uart.autobaud import COMMON_BAUDS, autobaud
|
|
86
|
+
|
|
87
|
+
bauds = [int(b) for b in args.bauds.split(",")] if args.bauds else list(COMMON_BAUDS)
|
|
88
|
+
results = autobaud(
|
|
89
|
+
args.port, bauds=bauds, sample_time=args.time, probe=None if args.listen else b"\r\n"
|
|
90
|
+
)
|
|
91
|
+
for r in results[: args.top]:
|
|
92
|
+
print(f"{r.baud:>8} score {r.score:.3f} {r.sample[:60]!r}")
|
|
93
|
+
return 0 if results and results[0].score > 0 else 1
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _read_input(path: str) -> bytes:
|
|
97
|
+
if path == "-":
|
|
98
|
+
return sys.stdin.buffer.read()
|
|
99
|
+
return Path(path).read_bytes()
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def cmd_hexdump(args: argparse.Namespace) -> int:
|
|
103
|
+
from .util.misc import hexdump
|
|
104
|
+
|
|
105
|
+
data = _read_input(args.file)
|
|
106
|
+
data = data[args.offset :]
|
|
107
|
+
if args.length is not None:
|
|
108
|
+
data = data[: args.length]
|
|
109
|
+
print(hexdump(data, base=args.offset, width=args.width, skip_repeats=not args.all))
|
|
110
|
+
return 0
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def cmd_entropy(args: argparse.Namespace) -> int:
|
|
114
|
+
from .firmware import entropy_map, entropy_plot
|
|
115
|
+
|
|
116
|
+
data = _read_input(args.file)
|
|
117
|
+
if args.plot:
|
|
118
|
+
print(entropy_plot(data, args.block, args.width))
|
|
119
|
+
return 0
|
|
120
|
+
for b in entropy_map(data, args.block):
|
|
121
|
+
flag = " high" if b.entropy > 7.5 else (" low" if b.entropy < 1.0 else "")
|
|
122
|
+
print(f"{b.offset:#010x} {b.entropy:5.3f}{flag}")
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def cmd_sigs(args: argparse.Namespace) -> int:
|
|
127
|
+
from .firmware import find_signatures
|
|
128
|
+
|
|
129
|
+
data = _read_input(args.file)
|
|
130
|
+
matches = find_signatures(data, alignment=args.align)
|
|
131
|
+
if args.json:
|
|
132
|
+
print(
|
|
133
|
+
json.dumps(
|
|
134
|
+
[
|
|
135
|
+
{
|
|
136
|
+
"offset": m.offset,
|
|
137
|
+
"name": m.name,
|
|
138
|
+
"description": m.description,
|
|
139
|
+
"size": m.size,
|
|
140
|
+
}
|
|
141
|
+
for m in matches
|
|
142
|
+
],
|
|
143
|
+
indent=2,
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
else:
|
|
147
|
+
for m in matches:
|
|
148
|
+
print(f"{m.offset:#010x} {m.name:<10} {m.description}")
|
|
149
|
+
return 0
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def cmd_fw_unpack(args: argparse.Namespace) -> int:
|
|
153
|
+
from .firmware import unpack
|
|
154
|
+
|
|
155
|
+
res = unpack(args.image, args.outdir, backend=args.backend)
|
|
156
|
+
if args.json:
|
|
157
|
+
print(json.dumps(res.to_dict(), indent=2))
|
|
158
|
+
return 0
|
|
159
|
+
print(f"backend: {res.backend} outdir: {res.outdir} files: {len(res.files)}")
|
|
160
|
+
for label, items in (
|
|
161
|
+
("rootfs", res.rootfs),
|
|
162
|
+
("kernel", res.kernels),
|
|
163
|
+
("dtb", res.dtbs),
|
|
164
|
+
("env", res.env_candidates),
|
|
165
|
+
("kconfig", res.kconfigs),
|
|
166
|
+
):
|
|
167
|
+
for p in items:
|
|
168
|
+
print(f" {label:<8} {p.relative_to(res.outdir)}")
|
|
169
|
+
for w in res.warnings:
|
|
170
|
+
print(f"warning: {w}")
|
|
171
|
+
if args.tree:
|
|
172
|
+
print(res.tree())
|
|
173
|
+
return 0
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def cmd_fw_analyze(args: argparse.Namespace) -> int:
|
|
177
|
+
from .firmware import analyze
|
|
178
|
+
from .tools._common import severity_rank
|
|
179
|
+
|
|
180
|
+
res = analyze(args.image, args.outdir, backend=args.backend, osv=args.osv)
|
|
181
|
+
if args.json:
|
|
182
|
+
print(json.dumps(res.to_dict(), indent=2))
|
|
183
|
+
else:
|
|
184
|
+
print(res.report(limit=args.limit))
|
|
185
|
+
if args.fail_on:
|
|
186
|
+
floor = severity_rank(args.fail_on)
|
|
187
|
+
if any(severity_rank(f.severity) >= floor for f in res.findings):
|
|
188
|
+
return 1
|
|
189
|
+
return 0
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
193
|
+
parser = argparse.ArgumentParser(
|
|
194
|
+
prog="hwn",
|
|
195
|
+
description="hwntools: scripting toolkit for authorized hardware security assessments",
|
|
196
|
+
)
|
|
197
|
+
parser.add_argument("--version", action="version", version=f"hwntools {__version__}")
|
|
198
|
+
parser.add_argument("-v", "--verbose", action="store_true", help="debug logging")
|
|
199
|
+
parser.add_argument("-q", "--quiet", action="store_true", help="only warnings and errors")
|
|
200
|
+
parser.add_argument("--timeout", type=float, default=None, help="default I/O timeout (s)")
|
|
201
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
202
|
+
|
|
203
|
+
ub = sub.add_parser("uboot", help="U-Boot console helpers")
|
|
204
|
+
ubsub = ub.add_subparsers(dest="uboot_command", required=True)
|
|
205
|
+
dump = ubsub.add_parser("dump", help="dump memory with md.b (resumable)")
|
|
206
|
+
_add_port(dump)
|
|
207
|
+
dump.add_argument("--addr", type=_int, required=True)
|
|
208
|
+
dump.add_argument("--size", type=_int, required=True)
|
|
209
|
+
dump.add_argument("--out", "-o", required=True)
|
|
210
|
+
dump.add_argument("--chunk", type=_int, default=0x1000)
|
|
211
|
+
dump.add_argument("--no-resume", action="store_true")
|
|
212
|
+
dump.add_argument("--interrupt-timeout", type=float, default=60.0)
|
|
213
|
+
dump.set_defaults(func=cmd_uboot_dump)
|
|
214
|
+
env = ubsub.add_parser("env", help="print the U-Boot environment")
|
|
215
|
+
_add_port(env)
|
|
216
|
+
env.add_argument("--json", action="store_true")
|
|
217
|
+
env.add_argument("--interrupt-timeout", type=float, default=60.0)
|
|
218
|
+
env.set_defaults(func=cmd_uboot_env)
|
|
219
|
+
|
|
220
|
+
ab = sub.add_parser("autobaud", help="guess the baud rate of a live UART")
|
|
221
|
+
ab.add_argument("--port", "-p", required=True)
|
|
222
|
+
ab.add_argument("--bauds", help="comma separated list (default: common rates)")
|
|
223
|
+
ab.add_argument("--time", type=float, default=1.5, help="seconds to sample per rate")
|
|
224
|
+
ab.add_argument("--listen", action="store_true", help="do not send a probe CRLF")
|
|
225
|
+
ab.add_argument("--top", type=int, default=5)
|
|
226
|
+
ab.set_defaults(func=cmd_autobaud)
|
|
227
|
+
|
|
228
|
+
hd = sub.add_parser("hexdump", help="hexdump a file ('-' for stdin)")
|
|
229
|
+
hd.add_argument("file")
|
|
230
|
+
hd.add_argument("--offset", "-s", type=_int, default=0)
|
|
231
|
+
hd.add_argument("--length", "-n", type=_int, default=None)
|
|
232
|
+
hd.add_argument("--width", "-w", type=int, default=16)
|
|
233
|
+
hd.add_argument("--all", "-a", action="store_true", help="do not collapse repeated lines")
|
|
234
|
+
hd.set_defaults(func=cmd_hexdump)
|
|
235
|
+
|
|
236
|
+
en = sub.add_parser("entropy", help="entropy map of a firmware image")
|
|
237
|
+
en.add_argument("file")
|
|
238
|
+
en.add_argument("--block", type=_int, default=4096)
|
|
239
|
+
en.add_argument("--plot", action="store_true", help="one-line sparkline")
|
|
240
|
+
en.add_argument("--width", type=int, default=64)
|
|
241
|
+
en.set_defaults(func=cmd_entropy)
|
|
242
|
+
|
|
243
|
+
sg = sub.add_parser("sigs", help="scan a firmware image for known signatures")
|
|
244
|
+
sg.add_argument("file")
|
|
245
|
+
sg.add_argument("--align", type=_int, default=1)
|
|
246
|
+
sg.add_argument("--json", action="store_true")
|
|
247
|
+
sg.set_defaults(func=cmd_sigs)
|
|
248
|
+
|
|
249
|
+
fw = sub.add_parser("fw", help="firmware extraction and analysis")
|
|
250
|
+
fwsub = fw.add_subparsers(dest="fw_command", required=True)
|
|
251
|
+
backends = ["auto", "unblob", "docker", "binwalk", "python"]
|
|
252
|
+
fu = fwsub.add_parser("unpack", help="extract a firmware image")
|
|
253
|
+
fu.add_argument("image")
|
|
254
|
+
fu.add_argument("--outdir", "-o", default=None, help="default: <image>.extracted")
|
|
255
|
+
fu.add_argument("--backend", choices=backends, default="auto")
|
|
256
|
+
fu.add_argument("--tree", action="store_true", help="print the extracted tree")
|
|
257
|
+
fu.add_argument("--json", action="store_true")
|
|
258
|
+
fu.set_defaults(func=cmd_fw_unpack)
|
|
259
|
+
fa = fwsub.add_parser("analyze", help="unpack, then run fwsift and bootlint")
|
|
260
|
+
fa.add_argument("image")
|
|
261
|
+
fa.add_argument("--outdir", "-o", default=None, help="default: <image>.extracted")
|
|
262
|
+
fa.add_argument("--backend", choices=backends, default="auto")
|
|
263
|
+
fa.add_argument("--osv", action="store_true", help="query OSV for known CVEs (network)")
|
|
264
|
+
fa.add_argument("--json", action="store_true")
|
|
265
|
+
fa.add_argument("--limit", type=int, default=40, help="findings shown in the text report")
|
|
266
|
+
fa.add_argument(
|
|
267
|
+
"--fail-on",
|
|
268
|
+
choices=["info", "low", "medium", "high", "critical"],
|
|
269
|
+
help="exit 1 if a finding at or above this severity exists",
|
|
270
|
+
)
|
|
271
|
+
fa.set_defaults(func=cmd_fw_analyze)
|
|
272
|
+
return parser
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
276
|
+
parser = build_parser()
|
|
277
|
+
args = parser.parse_args(argv)
|
|
278
|
+
if args.verbose:
|
|
279
|
+
context.log_level = "debug"
|
|
280
|
+
elif args.quiet:
|
|
281
|
+
context.log_level = "warn"
|
|
282
|
+
if args.timeout is not None:
|
|
283
|
+
context.timeout = args.timeout
|
|
284
|
+
try:
|
|
285
|
+
return int(args.func(args))
|
|
286
|
+
except (HwnError, OSError, ValueError) as exc:
|
|
287
|
+
log.failure(str(exc))
|
|
288
|
+
return 2
|
|
289
|
+
except KeyboardInterrupt:
|
|
290
|
+
log.failure("Interrupted")
|
|
291
|
+
return 130
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
if __name__ == "__main__": # pragma: no cover
|
|
295
|
+
sys.exit(main())
|
hwntools/context.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
"""Global, thread-local-free configuration object, modelled after pwntools' ``context``.
|
|
2
|
+
|
|
3
|
+
Example::
|
|
4
|
+
|
|
5
|
+
from hwntools import context
|
|
6
|
+
context.log_level = "debug"
|
|
7
|
+
context.timeout = 5
|
|
8
|
+
with context.local(endian="big"):
|
|
9
|
+
...
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import contextlib
|
|
15
|
+
import logging
|
|
16
|
+
from collections.abc import Iterator
|
|
17
|
+
from dataclasses import dataclass, field, fields, replace
|
|
18
|
+
from typing import Any, Literal
|
|
19
|
+
|
|
20
|
+
__all__ = ["Context", "SerialDefaults", "context"]
|
|
21
|
+
|
|
22
|
+
Endian = Literal["little", "big"]
|
|
23
|
+
|
|
24
|
+
_LEVELS: dict[str, int] = {
|
|
25
|
+
"debug": logging.DEBUG,
|
|
26
|
+
"info": logging.INFO,
|
|
27
|
+
"warn": logging.WARNING,
|
|
28
|
+
"warning": logging.WARNING,
|
|
29
|
+
"error": logging.ERROR,
|
|
30
|
+
"critical": logging.CRITICAL,
|
|
31
|
+
"silent": logging.CRITICAL + 10,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
_ARCHES: dict[str, tuple[int, Endian]] = {
|
|
35
|
+
"arm": (32, "little"),
|
|
36
|
+
"thumb": (32, "little"),
|
|
37
|
+
"aarch64": (64, "little"),
|
|
38
|
+
"arm64": (64, "little"),
|
|
39
|
+
"mips": (32, "big"),
|
|
40
|
+
"mipsel": (32, "little"),
|
|
41
|
+
"mips64": (64, "big"),
|
|
42
|
+
"mips64el": (64, "little"),
|
|
43
|
+
"riscv32": (32, "little"),
|
|
44
|
+
"riscv64": (64, "little"),
|
|
45
|
+
"i386": (32, "little"),
|
|
46
|
+
"amd64": (64, "little"),
|
|
47
|
+
"x86_64": (64, "little"),
|
|
48
|
+
"powerpc": (32, "big"),
|
|
49
|
+
"xtensa": (32, "little"),
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class SerialDefaults:
|
|
55
|
+
"""Default line settings used by :func:`hwntools.serial` when not given explicitly."""
|
|
56
|
+
|
|
57
|
+
baudrate: int = 115200
|
|
58
|
+
bytesize: int = 8
|
|
59
|
+
parity: str = "N"
|
|
60
|
+
stopbits: float = 1
|
|
61
|
+
xonxoff: bool = False
|
|
62
|
+
rtscts: bool = False
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class Context:
|
|
67
|
+
"""Process-wide settings. Use the module level :data:`context` instance."""
|
|
68
|
+
|
|
69
|
+
timeout: float = 10.0
|
|
70
|
+
tool_timeout: float = 600.0
|
|
71
|
+
newline: bytes = b"\n"
|
|
72
|
+
arch: str = "arm"
|
|
73
|
+
bits: int = 32
|
|
74
|
+
endian: Endian = "little"
|
|
75
|
+
serial: SerialDefaults = field(default_factory=SerialDefaults)
|
|
76
|
+
_log_level: int = logging.INFO
|
|
77
|
+
|
|
78
|
+
# ----------------------------------------------------------------- log level
|
|
79
|
+
@property
|
|
80
|
+
def log_level(self) -> int:
|
|
81
|
+
"""Current log level as an int (``logging.INFO`` etc.).
|
|
82
|
+
|
|
83
|
+
Assign either an int or one of ``debug``, ``info``, ``warn``, ``error``, ``silent``.
|
|
84
|
+
"""
|
|
85
|
+
return self._log_level
|
|
86
|
+
|
|
87
|
+
@log_level.setter
|
|
88
|
+
def log_level(self, value: int | str) -> None:
|
|
89
|
+
if isinstance(value, str):
|
|
90
|
+
try:
|
|
91
|
+
value = _LEVELS[value.lower()]
|
|
92
|
+
except KeyError:
|
|
93
|
+
raise ValueError(f"unknown log level {value!r}") from None
|
|
94
|
+
self._log_level = int(value)
|
|
95
|
+
|
|
96
|
+
# ----------------------------------------------------------------- arch
|
|
97
|
+
def set_arch(self, arch: str) -> None:
|
|
98
|
+
"""Set ``arch`` and derive ``bits``/``endian`` from it."""
|
|
99
|
+
try:
|
|
100
|
+
bits, endian = _ARCHES[arch.lower()]
|
|
101
|
+
except KeyError:
|
|
102
|
+
raise ValueError(
|
|
103
|
+
f"unknown arch {arch!r}; known: {', '.join(sorted(_ARCHES))}"
|
|
104
|
+
) from None
|
|
105
|
+
self.arch = arch.lower()
|
|
106
|
+
self.bits = bits
|
|
107
|
+
self.endian = endian
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def word_size(self) -> int:
|
|
111
|
+
"""Word size in bytes (``bits // 8``)."""
|
|
112
|
+
return self.bits // 8
|
|
113
|
+
|
|
114
|
+
# ----------------------------------------------------------------- updates
|
|
115
|
+
def update(self, **kwargs: Any) -> None:
|
|
116
|
+
"""Set several attributes at once. ``arch`` also updates ``bits``/``endian``."""
|
|
117
|
+
if "arch" in kwargs:
|
|
118
|
+
self.set_arch(kwargs.pop("arch"))
|
|
119
|
+
for key, value in kwargs.items():
|
|
120
|
+
if key == "log_level":
|
|
121
|
+
self.log_level = value
|
|
122
|
+
continue
|
|
123
|
+
if key.startswith("_") or not hasattr(self, key):
|
|
124
|
+
raise AttributeError(f"context has no setting {key!r}")
|
|
125
|
+
if key == "endian" and value not in ("little", "big"):
|
|
126
|
+
raise ValueError("endian must be 'little' or 'big'")
|
|
127
|
+
setattr(self, key, value)
|
|
128
|
+
|
|
129
|
+
@contextlib.contextmanager
|
|
130
|
+
def local(self, **kwargs: Any) -> Iterator[Context]:
|
|
131
|
+
"""Temporarily override settings inside a ``with`` block."""
|
|
132
|
+
saved = {f.name: getattr(self, f.name) for f in fields(self)}
|
|
133
|
+
saved["serial"] = replace(self.serial)
|
|
134
|
+
try:
|
|
135
|
+
self.update(**kwargs)
|
|
136
|
+
yield self
|
|
137
|
+
finally:
|
|
138
|
+
for key, value in saved.items():
|
|
139
|
+
setattr(self, key, value)
|
|
140
|
+
|
|
141
|
+
def reset(self) -> None:
|
|
142
|
+
"""Restore every setting to its default value."""
|
|
143
|
+
fresh = Context()
|
|
144
|
+
for f in fields(self):
|
|
145
|
+
setattr(self, f.name, getattr(fresh, f.name))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
context = Context()
|
|
149
|
+
"""The global :class:`Context` instance."""
|
hwntools/exceptions.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Exception hierarchy used across hwntools."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"HwnError",
|
|
7
|
+
"HwnTimeoutError",
|
|
8
|
+
"ParseError",
|
|
9
|
+
"SafetyError",
|
|
10
|
+
"ToolNotFoundError",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class HwnError(Exception):
|
|
15
|
+
"""Base class for every error raised by hwntools."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class HwnTimeoutError(HwnError, TimeoutError):
|
|
19
|
+
"""An expected response did not arrive in time."""
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ParseError(HwnError, ValueError):
|
|
23
|
+
"""Device output could not be parsed."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SafetyError(HwnError):
|
|
27
|
+
"""A destructive operation was requested without ``force=True``."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ToolNotFoundError(HwnError, FileNotFoundError):
|
|
31
|
+
"""A required external program (flashrom, binwalk, ...) is not on PATH."""
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""Firmware helpers: entropy, signature scanning, carving and unpacking.
|
|
2
|
+
|
|
3
|
+
Example::
|
|
4
|
+
|
|
5
|
+
from hwntools import firmware
|
|
6
|
+
result = firmware.analyze("flash.bin") # unpack + fwsift + bootlint
|
|
7
|
+
print(result.report())
|
|
8
|
+
|
|
9
|
+
for m in firmware.find_signatures(open("flash.bin", "rb").read()):
|
|
10
|
+
print(hex(m.offset), m.description)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import TYPE_CHECKING
|
|
18
|
+
|
|
19
|
+
from ..log import log
|
|
20
|
+
from ._analyze import AnalysisResult, analyze
|
|
21
|
+
from ._unpack import DOCKER_IMAGE, UnpackResult, classify_tree, docker_available, unpack
|
|
22
|
+
from .analysis import (
|
|
23
|
+
SIGNATURES,
|
|
24
|
+
EntropyBlock,
|
|
25
|
+
Signature,
|
|
26
|
+
SignatureMatch,
|
|
27
|
+
entropy,
|
|
28
|
+
entropy_map,
|
|
29
|
+
find_signatures,
|
|
30
|
+
shannon_entropy,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
if TYPE_CHECKING:
|
|
34
|
+
from ..tools.fwsift import FwsiftReport
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"DOCKER_IMAGE",
|
|
38
|
+
"SIGNATURES",
|
|
39
|
+
"AnalysisResult",
|
|
40
|
+
"EntropyBlock",
|
|
41
|
+
"Signature",
|
|
42
|
+
"SignatureMatch",
|
|
43
|
+
"UnpackResult",
|
|
44
|
+
"analyze",
|
|
45
|
+
"carve",
|
|
46
|
+
"classify_tree",
|
|
47
|
+
"docker_available",
|
|
48
|
+
"entropy",
|
|
49
|
+
"entropy_map",
|
|
50
|
+
"entropy_plot",
|
|
51
|
+
"find_signatures",
|
|
52
|
+
"scan",
|
|
53
|
+
"shannon_entropy",
|
|
54
|
+
"unpack",
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
_BARS = " ▁▂▃▄▅▆▇█"
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def entropy_plot(data: bytes, block_size: int = 4096, width: int = 64) -> str:
|
|
61
|
+
"""Return a compact text sparkline of the entropy map (one char per bucket)."""
|
|
62
|
+
values = entropy(data, block_size)
|
|
63
|
+
if not values:
|
|
64
|
+
return ""
|
|
65
|
+
per = max(1, -(-len(values) // width))
|
|
66
|
+
buckets = [max(values[i : i + per]) for i in range(0, len(values), per)]
|
|
67
|
+
return "".join(_BARS[min(8, int(v / 8 * 8 + 0.5))] for v in buckets)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def carve(
|
|
71
|
+
data: bytes,
|
|
72
|
+
offset: int,
|
|
73
|
+
size: int | None = None,
|
|
74
|
+
out: str | os.PathLike[str] | None = None,
|
|
75
|
+
) -> bytes:
|
|
76
|
+
"""Return ``data[offset:offset+size]`` (to the end if *size* is None); optionally save it."""
|
|
77
|
+
if offset < 0 or offset > len(data):
|
|
78
|
+
raise ValueError(f"offset {offset:#x} outside data of size {len(data):#x}")
|
|
79
|
+
piece = data[offset:] if size is None else data[offset : offset + size]
|
|
80
|
+
if size is not None and len(piece) < size:
|
|
81
|
+
log.warn("carve: only %d of %d bytes available at %#x", len(piece), size, offset)
|
|
82
|
+
if out is not None:
|
|
83
|
+
Path(out).write_bytes(piece)
|
|
84
|
+
return piece
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def scan(target: str | os.PathLike[str], osv: bool = False) -> FwsiftReport:
|
|
88
|
+
"""Run ``fwsift`` on an extracted rootfs or a raw image (see :mod:`hwntools.tools`)."""
|
|
89
|
+
from ..tools import fwsift
|
|
90
|
+
|
|
91
|
+
return fwsift.scan(target, osv=osv)
|