UART and serial consoles¶
Everything in hwntools that talks to a device does it through a tube: one byte-stream API
with pwntools-style helpers (recvuntil, sendline, sendlineafter, interactive, ...),
whatever is on the other end.
| Tube | Connects to | Notes |
|---|---|---|
serial(port, baud) / serialtube |
a serial port or any pyserial URL | needs hwntools[serial] |
remote(host, port) |
a TCP console (ser2net, telnet, network UART bridges) | standard library only |
process(argv) |
a local program's stdin/stdout (picocom, qemu-system ... -serial stdio) |
standard library only |
SimTube(device) |
a simulated device | in-process |
Check the voltage before you connect
Embedded boards use 1.8 V, 3.3 V or 5 V logic, and a mismatched USB-UART adapter can destroy the SoC. Connect ground first, then the adapter's RX to the target's TX, and only connect TX once the level is confirmed. See Safety.
Open a serial port¶
from hwntools import *
io = serial("/dev/ttyUSB0", 115200) # COM3 on Windows
io.sendline(b"")
print(io.recvline())
port may be a device path or any pyserial URL
such as rfc2217://host:port, socket://host:port or loop://. Line settings that you do
not pass (bytesize, parity, stopbits, xonxoff, rtscts, and the baud rate itself)
come from context.serial:
from hwntools import context, serial
context.serial.baudrate = 57600
io = serial("/dev/ttyUSB0") # 57600 8N1
io = serial("/dev/ttyUSB0", 115200, parity="E") # explicit settings win
Other options of serialtube:
convert_newlines=Trueturns every\nyou send into\r\n.newline=b"\r"changes whatsendline()appends (defaultcontext.newline,b"\n").io.set_baudrate(57600)changes the rate of an open port;io.send_break()sends a BREAK.
Consoles over TCP and local programs¶
from hwntools import remote, process
io = remote("10.0.0.5", 3001) # ser2net raw port
io = remote("10.0.0.5", 23, strip_telnet=True) # drop basic telnet IAC sequences
io = process(["picocom", "-b", "115200", "/dev/ttyUSB0"])
remote does not interpret telnet option negotiation; raw ser2net ports work as they are.
process merges stderr into stdout by default and reads with a background thread, so it
behaves the same on POSIX and Windows.
Receiving and sending¶
The receive helpers follow pwntools: on timeout they return b"" (or None for
recvregex) and keep partial data in the buffer, so nothing is lost. Pass strict=True,
or use expect(), to raise HwnTimeoutError instead.
io.recvuntil(b"login: ") # bytes up to and including the delimiter
io.recvuntil([b"=> ", b"# "], drop=True) # any of several delimiters, without it
io.recvline(keepends=False)
io.recvn(16) # exactly 16 bytes
m = io.recvregex(rb"U-Boot (\S+)") # a re.Match, or None
io.expect(b"Hit any key", timeout=30) # raises HwnTimeoutError if it never shows up
io.sendline("root") # str is encoded as latin-1
io.sendlineafter(b"Password: ", b"") # waits (strictly), then sends
io.clean(0.5) # drain until the line is quiet for 0.5 s
Timeouts are in seconds. Each tube has a default (timeout= when opening it, otherwise
context.timeout, 10 s); pass timeout=None to a helper to wait forever.
With context.log_level = "debug" every byte sent and received is logged as a hexdump.
Interactive mode¶
connects the tube to your terminal. Received bytes are printed raw, and your local lines are sent as you type them (the terminal stays in cooked mode, so line editing works). Press Ctrl-] then Enter to leave.
For a full terminal (keys sent one by one, Ctrl-C passed to the target, a session log, BREAK
and a hex view) use hwn console or hwntools.console.Console(io).run().
Find the baud rate¶
Experimental
hwntools.uart is tested against simulated devices only so far.
If the console prints garbage, let autobaud() try the common rates. It opens the port at
each rate, sends a CRLF to wake an idle console, reads for sample_time seconds and scores how
much the output looks like text (printable ratio, line breaks, typical boot-log words). It stops
early once a rate scores 0.95 or more, and returns the results best first:
from hwntools import autobaud
best = autobaud("/dev/ttyUSB0")[0]
print(best.baud, best.score, best.sample[:40])
Pass probe=None to stay listen-only and power-cycle the target during the scan instead. The
same is available as hwn autobaud:
For a logic-analyzer capture instead of a live port, autobaud_from_capture() runs the
external baudhound tool (see
Installation), which also finds
the framing and inverted lines:
from hwntools.uart import autobaud_from_capture
uart = autobaud_from_capture("boot.sr") # sigrok .sr or CSV export
if uart is not None:
print(uart.baudrate, uart.framing, uart.inverted)
Write your own tube¶
Subclass Tube and implement three primitives: _recv_raw(numb,
timeout) (return b"" on timeout, raise EOFError when the peer is gone), _send_raw(data)
and _close(). Every helper above is built on them.