Tag: logic analyzer

  • Hardware hacking, part 6: decoding I2C and SPI with sigrok and a 24 MHz logic analyzer

    Hardware hacking, part 6: decoding I2C and SPI with sigrok and a 24 MHz logic analyzer

    Part 6 of 7 in the Hardware hacking series. Part 1: updating the firmware on a Pinecil V2. Part 2: the bench I work on. Part 3: using my 5V FTDI cable on 3.3V UARTs. Part 4: finding the UART console on a router I own. Part 5: reading SPI flash without wrecking it.

    Much of the interesting traffic inside a device never touches a network. A sensor talks to a microcontroller over I2C, a microcontroller talks to its flash over SPI, and a security chip hands out keys over one or the other. A logic analyzer is the cheapest way to listen. Mine is the HiLetgo 24 MHz, 8-channel clone that works with sigrok and PulseView through the fx2lafw firmware.

    Everything here is for boards I own. I only clip onto boards that run from a low-voltage adapter or a battery, never anything with mains-voltage circuitry (a low-voltage output from a mains supply doesn’t make the board safe to touch while it is plugged in), and never while it is plugged into the wall. The analyzer is input only. I never connect any adapter, programmer or other output to a bus the board is already driving. I touch an earthed metal object before handling a board (a wrist strap is better), I move leads only with the board powered down, and I connect the analyzer’s ground first. Small clips can short neighbouring pins, so I check them before powering up. I measure the bus voltage with a multimeter on the powered low-voltage board before attaching any signal lead, and I only clip onto a line if that level is within what my analyzer is rated for. I haven’t verified that rating for my clone, so I treat anything above 3.3V as off limits. Plenty of hobby boards still run at 5V.

    The captures below are synthetic. I generated the signals with a short Python script and decoded them with sigrok-cli 0.7.2 in a throwaway container, so I control exactly what is on the wire. They are not recordings of real hardware.

    What the analyzer does and doesn’t do

    It samples eight inputs at a fixed rate and records high or low for each. Everything else, the bytes and addresses and ACK bits, is the decoder reconstructing meaning afterwards. When the decode is garbage the tool won’t say so. It prints confident nonsense, so the sample rate and decoder options matter more than anything else.

    I2C: two wires, open drain

    I2C uses a clock line (SCL) and a data line (SDA). Devices only pull the lines low. Pull-up resistors bring them back high, which is why the spec says the output stages must be open-drain or open-collector (NXP UM10204 rev 7, section 3.1.1). Standard-mode runs up to 100 kHz, Fast-mode to 400 kHz and Fast-mode Plus to 1 MHz (Table 11). The maximum input low level (VIL) is 0.3 x VDD and the minimum input high level (VIH) is 0.7 x VDD (Table 10), which on a 3.3V bus is 0.99V and 2.31V. They are limits a device has to meet, not a single switching point.

    The pull-ups matter for what you see, not just whether the bus works. The line rises with an RC curve, and the spec caps the rise time at 1000 ns in Standard-mode, 300 ns in Fast-mode and 120 ns in Fast-mode Plus (Table 11). The time to go from 30% to 70% of VDD is 0.8473 x R x C (section 7.1). A 10 kohm pull-up on 50 pF of wiring and probe capacitance gives about 424 ns: fine for a 100 kHz bus, too slow for a 400 kHz one. The 50 pF is my assumption for the example, not a measurement. Slow edges like that break the spec, and no decoder setting will fix them.

    Here is a decode of a synthetic 100 kHz transaction, the kind of thing a 24C02-style EEPROM does: write a memory address of 0x00 to device 0x50, restart, read four bytes. The generator sampled at 2 MHz, so 20 samples per bit.

    $ sigrok-cli -I binary:numchannels=8:samplerate=2000000 -i i2c_100k.bin \
        -P i2c:scl=0:sda=1 \
        -A i2c=address-write:address-read:data-write:data-read:nack
    i2c-1: Write
    i2c-1: Address write: 50
    i2c-1: Data write: 00
    i2c-1: Read
    i2c-1: Address read: 50
    i2c-1: Data read: 41
    i2c-1: Data read: 42
    i2c-1: Data read: 43
    i2c-1: Data read: 44
    i2c-1: NACK

    The 0x50 is the 7-bit address. On the wire it is the byte 0xA0 for a write and 0xA1 for a read, because the lowest bit is the direction, and tools disagree on which form they show. The trailing NACK is correct: a controller NACKs the last byte it reads to tell the device to stop sending.

    Sample rate: the setting that quietly ruins everything

    Now the same synthetic signal, decimated so it was sampled at 200 kHz. That is two samples per bit. The decoder still runs.

    $ sigrok-cli -I binary:numchannels=8:samplerate=200000 -i i2c_100k_at200k.bin \
        -P i2c:scl=0:sda=1 \
        -A i2c=address-write:address-read:data-write:data-read:nack
    i2c-1: Write
    i2c-1: Address write: 50
    i2c-1: Data write: 00
    i2c-1: Data write: 50
    i2c-1: NACK
    i2c-1: Data write: 20
    i2c-1: NACK
    i2c-1: Data write: 21
    i2c-1: Data write: 21
    i2c-1: NACK
    i2c-1: Data write: 22

    The first two bytes survive by luck. After that it invents data bytes and NACKs that never happened, and it never reports the read at all. Nothing in the output says the sample rate was too low.

    Terminal screenshot of sigrok-cli decoding a synthetic I2C capture: a correct decode at 2 MHz sampling and a garbage decode of the same signal at 200 kHz sampling

    Terminal output I captured from sigrok-cli 0.7.2 decoding my synthetic I2C signal: the correct 2 MHz decode first, then the same signal sampled at only 200 kHz producing invented bytes and NACKs.

    My rule of thumb (it isn’t from any standard) is at least four samples per bit, and ten if I can afford it. With a 24 MHz maximum that gives me:

    • 100 kHz I2C: 240 samples per bit at 24 MS/s, so there is plenty of room.
    • 400 kHz I2C: 60 samples per bit at 24 MS/s, still comfortable.
    • 1 MHz I2C: 24 samples per bit.
    • SPI at 8 MHz: 3 samples per clock period, which is already below my four-sample minimum.
    • SPI at 24 MHz: 1 sample per clock period. Useless.
    Bar chart of samples per bit at 24 MS/s for I2C and SPI bus speeds, with a dashed line at four samples per bit

    Bar chart I drew (not a measurement): samples per bit at 24 MS/s for I2C at 100 kHz, 400 kHz and 1 MHz and SPI at 4, 8 and 24 MHz, with my four-sample minimum as a dashed line.

    A lot of SPI flash runs well above 8 MHz, so this analyzer cannot capture a full-speed flash read at all. For a part like that I either slow the controller down, if the firmware lets me, or I accept that I will only see the command phase of a slow operation. Higher rates also mean more data: 24 MS/s on eight channels is roughly 24 MB per second, so half a minute is hundreds of megabytes. I keep the rate as low as the bus allows.

    SPI: four wires and a mode you have to guess

    SPI has a clock, MOSI, MISO and a chip select, but no formal addressing and no ACK. The decoder needs to know the clock polarity (CPOL) and phase (CPHA): which level the clock idles at, and whether data is sampled on the first or second edge. Get it wrong and the bytes come out shifted, not obviously broken.

    Here is a synthetic 500 kHz SPI mode 0 read: command 0x03, a 24-bit address of 0x000100, then four data bytes. I put the bytes 7F 45 4C 46 on MISO, the start of an ELF header, because that is what a lot of firmware starts with. First the correct mode, looking at each data line separately:

    $ sigrok-cli -I binary:numchannels=8:samplerate=2000000 -i spi_500k.bin \
        -P spi:clk=0:mosi=1:miso=2:cs=3:cpol=0:cpha=0 -A spi=mosi-data | sed 's/spi-1: //' | paste -sd' '
    03 00 01 00 00 00 00 00
    
    $ ... -A spi=miso-data | sed 's/spi-1: //' | paste -sd' '
    00 00 00 00 7F 45 4C 46

    The four zero bytes on MISO are the chip not driving anything meaningful while it receives the command and address, and the last four are the payload. Now the same file decoded with CPHA=1:

    $ ... cpol=0:cpha=1 -A spi=miso-data | sed 's/spi-1: //' | paste -sd' '
    00 00 00 00 FE 8A 98 8C

    7F 45 4C 46 has become FE 8A 98 8C, which is the same bits shifted left by one position. If you are expecting a magic number and don’t see it, try the other mode before you conclude the data is encrypted. The Winbond W25Q128JV I read in part 5 supports modes 0 and 3 (datasheet revision F), so for that chip those are the two I try first.

    Terminal screenshot of sigrok-cli decoding a synthetic SPI capture: correct MOSI and MISO bytes in mode 0 and shifted bytes FE 8A 98 8C with the wrong clock phase

    Terminal output I captured from sigrok-cli 0.7.2 decoding my synthetic SPI signal: MOSI and MISO in the right mode, then MISO with CPHA wrong, where 7F 45 4C 46 comes out as FE 8A 98 8C.

    What I check before I trust a decode

    I look for a known value: a magic number, a device ID, a repeated command. If I can’t find one, I don’t believe the decode. I also decode the same capture at two sample rates and check that chip select frames the transactions the way I expect. Same discipline as reading a flash chip twice and comparing hashes.

    Next is part 7, on JTAG and SWD, the debug ports that vendors are supposed to lock before a product ships.

    Other parts of the Hardware hacking series: 1, updating the firmware on a Pinecil V2; 2, the bench I work on; 3, using my 5V FTDI cable on 3.3V UARTs; 4, finding the UART console on a router I own; 5, reading SPI flash without wrecking it; 6, decoding I2C and SPI with sigrok; 7, JTAG and SWD basics.

  • Hardware hacking, part 4: finding the UART console on a router I own

    Hardware hacking, part 4: finding the UART console on a router I own

    Part 4 of 7 in the Hardware hacking series. Part 1: updating the firmware on a Pinecil V2. Part 2: the bench I work on. Part 3: using my 5V FTDI cable on 3.3V UARTs.

    The first thing I check on a router I own is whether it has a serial console, and whether that console hands a root shell to anyone who clips a cable on. Plenty of consumer gear does. That takes physical access, so it isn’t a remote bug. Still, routers get stolen, resold and left in shared closets, and a free root prompt turns a lost box into an open one.

    Everything here is for hardware I own. If a router is ISP supplied or rented, I check my terms first. I only open routers that run from a low-voltage external DC adapter, and the board stays unplugged while I open it and do the continuity checks. If a device has mains-voltage circuitry inside, or I can’t tell what powers it, I don’t open it, and I never connect anything to a board that has mains on it. A cheap transformerless adapter is not isolated, so I use the one that shipped with the router. After unplugging I wait a minute, then touch an earthed metal object (or wear a wrist strap) before handling the board.

    Finding the pads

    Flowchart I drew: unpowered board, find pads, measure idle voltage, listen with the logic analyzer, find baud rate, then wire the cable per part 3, with warnings never to connect the 5 V wire or a mains-powered board

    I drew the flowchart above. It’s the order I work in, and the two red warnings apply at every step.

    A router UART is usually four pads or an unpopulated header near the SoC: ground, TX, RX and a supply pin, often 3.3V. Some are labelled and many aren’t. With the board unpowered I use the multimeter’s continuity mode. Ground beeps to the metal shield cans and to the ground of the power jack. The pad that beeps to the 3.3V regulator output is the supply pin, and I never connect that one to anything.

    Then I power the board from its own adapter and measure the other pads against ground, with insulated probe tips and a hand that stays still, because a slipped probe shorting two fine pads is how boards die. TX usually idles high and flickers during boot. RX usually idles high and doesn’t move, though a floating pad can read anything. I measure at idle after boot, since a meter averages a toggling line into a meaningless number.

    About 3.3V is what I expect. If a pad reads 1.8V, 2.5V or anything well above 3.6V, I stop. The divider from part 3 is wrong for that board and I need a proper level shifter.

    Finding the baud rate

    A UART has no clock, so the receiver has to know the bit time in advance. Consoles almost always use 8N1: eight data bits, no parity, one stop bit. The line idles high and a frame starts with a low start bit, which is how the sigrok UART decoder documentation puts it. So the shortest pulse on the line is one bit, and one over its width is the baud rate. 115200 baud is 8.68 µs per bit, 57600 is 17.36 µs and 9600 is 104.17 µs.

    With the board unpowered, analyzer ground goes to board ground first. Then one channel goes on the router’s TX pad and I power the board. I only listen, though I still touch only pads I have measured, because some SoC pins double as boot straps. I haven’t found a datasheet for the clone analyzer’s input limits, so I only clip it onto a line I have measured at 3.3V or lower.

    Sample rate matters. At 1 MHz a 115200 baud bit is 8.7 samples wide, which is fine. At 921600 baud it is 1.09 samples and you can’t measure anything. When hunting for an unknown rate I use the highest rate the analyzer gives me for the channels I enable, power cycle the router and capture the boot.

    In PulseView I put two cursors across the narrowest pulse. The same estimate in code is a few lines, and I snap the result to the nearest standard rate because one sample of error moves the raw number by several percent. The capture below is synthetic: I generated a 57600 baud signal with Python so I could show the decoding without publishing a real device’s boot log.

    Terminal output from a synthetic 57600 baud capture generated with Python: a pulse-width baud estimate, sigrok-cli decoding garbage at the wrong rate 115200, and readable text at 57600

    The screenshot is real output from sigrok-cli 0.7.2 and my small Python script, run on the synthetic file in a throwaway container.

    The first command measures the pulse: 17 samples at 1 MHz, 58824 raw, snapped to 57600. The second decodes the same file with a wrong guess of 115200 and gives bytes like 0x80 and 0x98 instead of text. At 57600 the text appears. The pulse method needs a bit that sits alone between two opposite levels, which boot messages almost always have. If the estimate is ambiguous I try the usual rates in turn, starting with 115200, the most common and U-Boot’s CONFIG_BAUDRATE default (boards override it). A capture of a real boot log is sensitive, since it can hold Wi-Fi keys, tokens and serial numbers.

    Talking to it

    Once I can read the boot text I know the rate. I still haven’t connected a transmitter, and that’s deliberate: the second wire goes in only after I can see the whole boot log.

    The wiring is part 3: cable ground to board ground first, board TX straight to the cable’s RX, and the cable’s TX through the 1 kΩ and 2 kΩ divider to the board’s RX. The cable’s red 5V wire stays insulated and unconnected. The board’s only power source is its own adapter. I plug the cable into USB last, and I never power cycle the board with the cable still plugged in, because the cable’s TX idling high into an unpowered board can feed it through the pin’s protection diodes. To finish I unplug USB, power the board off, remove the signal wires and take ground off last. Then I open the port:

    picocom -b 57600 /dev/ttyUSB0

    Use the rate you measured in place of 57600. picocom defaults to 8N1 with no flow control, and Ctrl-A then Ctrl-X exits. On Debian-family systems the account needs to be in the dialout group, and without it you get a permission error, not garbage. Garbage usually means the wrong rate, but I also check ground, voltage level and framing. Boot text with no response to typing can be a wiring fault, but it can also be the vendor’s doing: input disabled in the bootloader, or no login process on the port. I go back to the meter before I guess.

    What I check on my own boards

    Does the bootloader stop at a prompt if I press a key during the countdown? Does the kernel boot into a shell with no login? Does the boot log print secrets? Does root have a password? Any yes goes in my notes for that device. If the problem is the design and not just my unit, I tell the vendor. I don’t change a bootloader environment on a router I depend on until I have a verified flash backup. That is part 5.

    Closing the console

    The U-Boot documentation lists the knobs. The bootdelay variable set to -2 boots with no delay and doesn’t check for a keypress. Set to -1 it disables autoboot and leaves you at a prompt, the worst choice for hardening. CONFIG_AUTOBOOT_KEYED requires a specific stop string, so a stray character doesn’t halt the boot, though a string compiled into the image is not a password. silent_linux boots the kernel with console= empty, which hides output and removes no shell. These are environment settings, and the environment is often writable from the prompt or from flash, so they are only as strong as access to those. A build-time CONFIG_BOOTDELAY is stronger.

    On the OS side the fix is boring: no auto-login root shell on the serial port, a real login prompt, and a root password that isn’t shared across a product line. Leaving the header unpopulated costs a vendor nothing and stops casual attempts. It won’t stop someone who desolders the flash chip, and that’s what the next parts are about.

    Other parts of the Hardware hacking series: 1, updating the firmware on a Pinecil V2; 2, the bench I work on; 3, using my 5V FTDI cable on 3.3V UARTs; 4, finding the UART console on a router I own; 5, reading SPI flash without wrecking it; 6, decoding I2C and SPI with sigrok; 7, JTAG and SWD basics.

  • Hardware hacking, part 2: the bench I work on and what each tool is for

    Hardware hacking, part 2: the bench I work on and what each tool is for

    Part 2 of 7 in the Hardware hacking series. Part 1: updating the firmware on a Pinecil V2.

    Nothing on my bench is expensive. I bought it one problem at a time, and that matters for this series. I’m not trying to show off lab gear. The point is how little it takes to look inside a device, and how little an attacker needs for the same job. If a cheap logic analyzer and a serial cable can show what a router prints at boot, then “nobody will ever open it” is not a security control.

    The rules before the tools

    Diagram: five device interfaces, the bench tool used to reach each, and the matching defender control

    I drew the diagram above. It links each interface a device exposes to the bench tool that reaches it and the control that closes it.

    Everything here happens on hardware I own and am allowed to take apart. No work devices, no borrowed ones, nothing that belongs to a neighbour or a client.

    I do not open, probe or connect anything that is plugged into mains. Many small devices, such as smart plugs, bulbs and some power bricks, have supplies that are not isolated from mains, so a board’s ground can sit at mains potential. I work on boards powered from a proper low-voltage adapter, a battery or USB, and if I am unsure what powers a board, I do not connect anything.

    Then the boring habits. Power down and unplug before soldering, swapping a chip or moving a probe onto a chip. For UART and logic captures I make the connections with the target off and power it up afterwards, from its own supply only, never from the serial cable as well. Ground goes on first and comes off last. I touch an earthed metal object, such as an unpowered PC case, before handling a board, and I hold boards by the edges, because static discharge can damage chips without any visible sign. If you use a wrist strap, use one with a built-in series resistor and never wear it near anything that could be connected to mains. Wear safety glasses when cutting leads or soldering, and keep some ventilation going.

    The iron: Pinecil V2

    I covered the firmware in part 1. It is a small USB-C powered iron running IronOS, and I use it for tinning wires, pin headers and joint rework. A hot tip burns skin and scorches a desk, so it sits in its stand while it is on, and I let it cool before putting it away.

    The logic analyzer: HiLetgo 24 MHz, 8 channels

    This is a cheap Saleae-style clone that works with the open source sigrok and PulseView software through the fx2lafw driver. It records when each of up to eight digital lines goes high or low. It does not measure voltage and it does not replace a multimeter. It gives you timing.

    Two things matter in practice. The sample rate tops out at 24 MHz, but a UART at 115200 baud has bits about 8.68 microseconds long, so at 24 MHz you get roughly 208 samples per bit, far more than needed. The other is voltage. I have not found a datasheet for mine, so I treat its inputs as unprotected with a threshold I cannot adjust. I measure the target’s logic level with a multimeter first, with the target powered from its own supply and nothing else connected, I connect the analyzer’s ground before any signal lead, and I do not expect it to read a 1.8V signal reliably.

    In part 6 I decode I2C and SPI with it. Here is PulseView with a capture loaded. This is a synthetic signal I generated with a Python script (8N1 at 115200 baud, written as a raw binary file and opened in PulseView), not a capture from a device.

    PulseView window with a synthetic 115200 baud UART signal on channel 0 and a millisecond time scale

    The trace is synthetic UART data on channel 0, with milliseconds along the top.

    The serial cable: FTDI FT232RL, 5V

    A USB-to-serial cable with an FTDI chip and a 6-pin 0.1 inch female header. It lets a PC talk to the UART console that many routers and embedded boards expose on a few unpopulated pads. A UART needs a transmit line, a receive line and a ground. The line idles high, and each byte is framed by a low start bit and a high stop bit. There is no clock, so both sides have to agree on the baud rate in advance.

    Mine is sold as a 5V cable, and I expect its data lines to be 5V too, not only the red power wire. I will confirm that by measuring the idle level of its TX line with the USB end plugged in. Many boards run their UART at 3.3V, and a 5V transmit line into a 3.3V receiver is the real risk, which leaving the red wire unconnected does not fix. I never connect the cable’s 5V wire to a target, I connect only ground, TX and RX (cable TX to target RX, target TX to cable RX), and I measure the target’s logic level first. Part 3 makes this cable safe on 3.3V targets, with the numbers worked out.

    The programmer: XGecu T48

    A universal programmer with a ZIF socket and a set of adapters (mine came with 19) for SPI and I2C EEPROM, NOR and NAND flash, microcontrollers and BIOS chips. Its software, Xgpro, is Windows only, so I won’t show screenshots of it here and I only download it from the vendor. Chips go in the socket once they’re off the board, which means desoldering, heat and a steady hand. Orientation and supply voltage have to be right before I start a read, because a chip in backwards or at the wrong voltage can be destroyed.

    The probe frame

    A small frame with four probe pens that holds against a board and touches the pads or pins of a chip without desoldering it. It is sold as a BDM frame, though it is just a probe holder and has nothing to do with Motorola’s debug interface. I use it when I can’t or won’t desolder something, and it is where most of my failed reads come from. The rest of the board is still attached to the chip, so other devices on the same bus can interfere. Back-powering can also damage the board or the programmer, so for in-circuit reads the board stays unpowered except for whatever the programmer supplies, at the voltage the chip expects. Part 5 covers reading in circuit, and why I read every chip twice and compare hashes before I trust a dump.

    The small stuff

    DOWELL micro flush cutters for trimming leads, always cutting away from my face because clipped leads fly. A pack of 120 Dupont jumper wires for temporary connections. A sheet of PTM7950 phase-change thermal pad for putting a device with a heatsink back together properly. A pad that has been removed gets replaced rather than reused, and old residue is cleaned off with isopropyl alcohol first.

    What is not on the bench

    No JTAG or SWD probe. Part 7 on debug ports is therefore about concepts, pinouts and how vendors lock those ports, not a walkthrough on my own hardware.

    Why a defender should care

    Every tool above is cheap and easy to buy, which is the whole argument. If your product ships with an open UART console, an unprotected SPI flash holding secrets in plain text, or a debug port that never got locked, assume someone with this bench will find it. The fixes are in the design: authenticate or close the console, encrypt and sign what is in flash, and fuse the debug port before shipping. The later parts show each of these on boards I own.

    Other parts of the Hardware hacking series: 1, updating the firmware on a Pinecil V2; 2, the bench I work on; 3, using my 5V FTDI cable on 3.3V UARTs; 4, finding the UART console on a router I own; 5, reading SPI flash without wrecking it; 6, decoding I2C and SPI with sigrok; 7, JTAG and SWD basics.