2. Find the baud rate¶
Garbage means the wrong speed¶
A UART has no clock wire. Both sides must agree on the speed (the baud rate) in advance.
If you guess wrong you still receive bytes, just the wrong ones: \xf8\x00~\xff... instead of
U-Boot. The common rates are few (115200 is by far the most common, then 57600, 38400,
9600...), so the practical fix is to try them all and keep the one whose output looks like
text.
autobaud() does exactly that: for each rate it opens the port, sends Enter, reads for a
moment and gives the result a score from 0 to about 1.2 (share of printable characters and
letters, line breaks, and boot-log words such as U-Boot, login or BusyBox).
On a real board you would run hwn autobaud --port /dev/ttyUSB0 or
autobaud("/dev/ttyUSB0"). Here, lab.uart_at(baud) opens the simulated port at a given
rate: at the right one the board answers with a login banner, at any other it sends noise.
from hwntools import autobaud
from hwntools.learn.lab import uart_at
results = autobaud(opener=uart_at, bauds=[9600, 57600, 115200, 230400], sample_time=0.3)
for r in results:
print(f"{r.baud:>7} score {r.score:.2f} {r.sample[:24]!r}")
[x] Autobaud
[+] Autobaud: best 115200 (score 0.96)
115200 score 0.96 b'\r\nRX-AP100 Linux 4.4.60 '
9600 score 0.23 b'~\xff~~\x80\x00x\xff~\x00~\xf8\x00\xf8\xf8\xe0\x80xx\xe0\xf8\x00\xff\xff'
57600 score 0.10 b'\x00\xf8\xfe\xff~\x80\xf8\x00\x00\xf8\xff\xe0\xe0\xfe\xf8\xff\xff\xfe\xe0\xf8\xf8\xff\xe0\x80'
What just happened¶
opener=uart_atreplaces the default "open this serial port at this speed" step. Any function that takes a baud rate and returns a tube works, which is how you would scan a network serial server too.- The scan stopped early at 115200, because the score reached
stop_score(0.95). 230400 was never tried. Passstop_score=Noneto try every rate. - The
[x]and[+]lines are hwntools' progress log. They go to stderr, so piping the script's output to a file keeps only yourprint()s.
On real hardware
- Power-cycle the board during the scan if it is idle and does not answer Enter (use
probe=Noneorhwn autobaud --listento only listen). - If you have a logic analyzer capture instead of a live port,
autobaud_from_capture()runs the separatebaudhoundtool, which measures the bit timing directly and also finds odd framings and inverted lines. It is not used here.
Try it¶
Try it
uart_at() takes a second argument, true_baud, the rate the simulated board really
uses. Simulate a board that runs at 57600 and find that rate with autobaud()
without changing the lab code. Hint: functools.partial.
Solution
from functools import partial
from hwntools import autobaud
from hwntools.learn.lab import uart_at
board = partial(uart_at, true_baud=57600)
best = autobaud(opener=board, sample_time=0.3)[0]
print(best.baud, best.score)
The default list tries 115200 first, gets noise, then finds 57600 and stops.