Embedded HandbookApps
All sections › III. Peripherals
STM32F405, STM32F407 · level intermediate · 17 min read
Open in the interactive handbook

43г. A do-it-yourself secure channel between a device and a computer: key exchange, frame encryption, replay protection

Section 43в covers the primitives one by one: cipher, MAC, signature, key exchange, HKDF — and what each costs on a Cortex-M4F. In 43б the device's private key lives in a secure element, in 37а — what a ready-made TLS costs. Here the primitives are put together into a working channel: a device on a serial port, a host computer, a three-message handshake, encrypted frames with a counter and a replay window.

The channel is checked by a run. The device is C firmware in QEMU (netduinoplus2, Cortex-M4F), its USART1 is exposed as a TCP port. The host is a Python program with pyca/cryptography 49.0.0 on the computer. Five experiments: a normal session, a substituted byte, a replayed frame, a substituted device, a repeated nonce after a counter fault. The cost of each step is in QEMU instructions, as in 43в.

Sources: X25519 — RFC 7748, HKDF — RFC 5869, ECDSA on P-256 and test vectors — as in 43в, AES-CCM — NIST SP 800-38C; the replay window — as in Mbed TLS 3.6 (ssl_msg.c, MBEDTLS_SSL_DTLS_ANTI_REPLAY); EDHOC and OSCORE — RFC 9528 and RFC 8613 from the uOSCORE/uEDHOC description in the Zephyr modules. Libraries — only from the disk: TinyCrypt 0.2.8 and fiat-crypto from the MCUboot package, as in 43в.

What it is called in the documentation

Original Meaning
secure channel, session protected link, session
handshake, transcript hash handshake, hash of the exchange so far
ephemeral key, long-term key one-time key, permanent key
key confirmation, Finished key confirmation, control message
man-in-the-middle attacker in the middle
key pinning key stored in advance
record, frame, header record, frame, header
associated data (AAD) plaintext data under the tag
sequence number frame number
anti-replay window replay protection window
rekeying key change

43г.1 The setting: device, host and what the attacker can do

The device is connected to a computer over UART, USB or radio. The host reads readings and sends commands: "open the door", "write a setting". The line is visible to an outsider: the wire runs through someone else's room, the radio is received outside, a "sniffing" adapter is plugged into USB. The attacker can do four things — and the protection is built around them:

Threat What the attacker does What closes it Experiment
eavesdropping reads everything on the line AES-128-CCM, a key per session 43г.4
tampering changes frame bytes an 8-byte CCM tag over header and data 43г.5, experiment 2
replay records a frame and sends it again frame number under the tag and a 32-frame window 43г.5, experiment 3
device substitution puts in its own device or sits in the middle the device's ECDSA signature over the handshake, key stored at the host 43г.5, experiment 4

What the channel does not do: it does not hide frame length and timing, does not prove to the device who the host is (that is a separate step: a password or a host key under the channel's protection), does not help if the device's private key leaks from flash (against that — 43б and 48б).

No primitive of 43в gives this alone: AEAD without a number lets a replay through, key exchange without a signature hands the channel to an attacker in the middle, a signature without a one-time key gives no forward secrecy. All of it together is the protocol.


43г.2 Handshake: three messages and two direction keys

The scheme is the same as TLS 1.3 with a server certificate, only without certificates: the device has a long-term P-256 key pair, the host got the public key at the factory and keeps it. The signature is ECDSA P-256, because the MCUboot package has no Ed25519 signing, only verification (43в).

Handshake diagram and frame format. On the left the host — a computer with pyca/cryptography and the device key stored in advance, on the right the device — a Cortex-M4F with TinyCrypt and fiat and a P-256 private key. The first message M1 from the host: 01 01 and the host's one-time X25519 public key, 34 bytes. The second M2 from the device: 02, the device's one-time key and the signature, 97 bytes; the device computes X25519 twice, the hash th1 — SHA-256 of the string 43g-v1, M1, byte 02 and the device key, signs th1 with the ECDSA P-256 key and derives keys with HKDF — 13.46 million instructions, of them the signature 11.07 million. The third M3 from the host: 03 and fin, 33 bytes; the host has checked the signature against the stored key, derived with HKDF the keys k_h2d, k_d2h and k_fin, fin — HMAC-SHA-256 of SHA-256 of messages M1 and M2. Then the device's first frame READY, 19 bytes — the device knows the keys, the whole handshake with it is 183 bytes. Then data frames both ways. At the bottom the frame format: type 10, length, frame number 4 bytes, AES-128-CCM ciphertext, tag 8 bytes; 64 bytes of data — 78 on the line, overhead 14 bytes; the 6-byte header goes under the tag as associated data, the 13-byte nonce — direction letter H or D, 8 zeros and the number; on receive first the tag, then the 32-frame window

Step by step:

  1. M1, host → device: type 01, version 01, the host's one-time X25519 public key eph_h — 34 bytes.
  2. The device takes its own one-time X25519 key, computes the shared secret X25519(eph_d, eph_h) and the transcript hash th1 = SHA-256("43g-v1" ‖ M1 ‖ 02 ‖ eph_d). It signs th1 with the long-term key. M2 — type 02, eph_d, signature r ‖ s — 97 bytes.
  3. The host checks the signature against the stored key. No match — abort, no keys are derived. Match — the same shared secret and HKDF-SHA-256(salt = th1, ikm = secret, info = "43g keys") → 64 bytes: k_h2d (16), k_d2h (16), k_fin (32).
  4. M3, host → device: fin = HMAC-SHA-256(k_fin, SHA-256(M1 ‖ M2)) — 33 bytes. The device compares fin in constant time. Match — the channel is open, and the device sends the first encrypted frame READY: the host sees that the device has the same keys.

Why each part is there:

Device code, start of M1 handling (dev43e.c):

    default_CSPRNG(eph_priv, 32);
    X25519(m2 + 1, eph_priv, BASE9);
    t = ticks();
    cost("hs_x25519_keygen", t - t0);
    X25519(ss, eph_priv, m1 + 2);
    cost("hs_x25519_shared", ticks() - t);
    t = ticks();
    tc_sha256_init(&sh);
    tc_sha256_update(&sh, (const uint8_t *)"43g-v1", 6);
    tc_sha256_update(&sh, S.m12, 34 + 33);
    tc_sha256_final(th1, &sh);

default_CSPRNG here is a predictable xorshift, so that the run repeats byte for byte. In a product — the RNG and the checks from 43а: with a predictable generator both the one-time key and the ECDSA signature's k are predictable, and through k — the private key (43в.7).


43г.3 The frame and the replay window

A data frame is the same in both directions:

Bytes Field Under the tag Encrypted
0 type 10 yes no
1 data length, up to 96 yes no
2–5 frame number, big-endian yes no
6 … 6 + len − 1 data yes yes
last 8 CCM tag — —

The header goes into CCM as associated data: the length or number cannot be changed without the key, the tag will not match (experiment 2). The nonce is 13 bytes: the direction letter, 8 zeros, the number. Each side has its own number, it starts at 1 and only grows; number 0 is not accepted. Overhead — 6 bytes of header and 8 bytes of tag, 14 bytes: 64 bytes of data go over the line as 78 bytes, plus 21.9 %.

An 8-byte tag is a choice for a slow line: the attacker can guess it only by brute force through the device itself, one frame per attempt. For radio with frequent tampering 16 is used.

Receiving takes two steps, and the order matters: first the tag, then the window. The window changes only on an authentic frame; otherwise the attacker would shift it with a forged number 1000000 and the device would reject all honest frames.

    nonce_of(n, 'H', c);
    tc_ccm_config(&cc, &S.rx.ks, n, 13, 8);
    int good = tc_ccm_decryption_verification(pt, len, f, 6, f + 6, len + 8, &cc) == TC_CRYPTO_SUCCESS;
    uint32_t t_dec = ticks() - t0;
    if (!good) {
        send_err(1);
        put("dev rx ctr=");
        putu(c);
        put(" tag bad -> err 1");
        flush();
        return;
    }
    if (!replay_ok(&S.rx, c)) {

The window is the highest accepted number top and 32 bits of map below it: bit n — frame top − n has already been seen. UART neither loses nor reorders frames, and the rule "number greater than the previous one" would be enough. The window is needed where frames get lost and overtake each other: radio, UDP. Mbed TLS 3.6 keeps the same kind of window of 64 frames in DTLS (in_window, ssl_msg.c).

static int replay_ok(struct dir *d, uint32_t ctr)
{
    if (ctr == 0)
        return 0;
    if (ctr > d->top) {
        uint32_t sh_ = ctr - d->top;
        d->seen = sh_ >= 32 ? 0 : d->seen << sh_;
        d->seen |= 1u;
        d->top = ctr;
        return 1;
    }
    uint32_t back = d->top - ctr;
    if (back >= 32 || (d->seen >> back) & 1u)
        return 0;
    d->seen |= 1u << back;
    return 1;
}

The number is 32-bit: after 2³² frames the channel must do the handshake again, otherwise a number repeats. Error messages (7F and a code) go in the clear — they must not change state, only be answered.


43г.4 The test bench: device in QEMU, host on the computer

The device is dev43e.c, built with arm-none-eabi-gcc 12.2.1 with TinyCrypt and fiat from the MCUboot package and run in QEMU 7.2 netduinoplus2 (STM32F405, Cortex-M4F) with -icount shift=0. QEMU exposes the device's USART1 as TCP port 5555 of the container (-serial tcp:0.0.0.0:5555,server=on,wait=on), the device log goes through semihosting. The host is host43e.py on the computer: it starts the container itself, connects to the port and runs five experiments in a row over one line.

python _verify/cry43e/host43e.py        # docker run stm-arm:1 sh /v/run43e.sh qemu + хозяин
sh /v/run43e.sh size                     # в stm-arm:1: размер прошивки

The device sends the first byte after enabling the receiver itself — A5, "ready". Without it the first bytes of M1 arrived before the firmware enabled the USART, and QEMU lost them: the handshake hung (43г.7).

A normal session — the host log:

== 1 good session
host hs ok: m1=34 m2=97 m3=33 bytes, sig ok, eph_d=86c92d3960ada907..
host first frame: ('ok', 1, b'READY')
host hs_result True
host tx ctr=1 len=5 wire=19 -> ok ctr=2 len=34
host tx ctr=2 len=13 wire=27 -> ok ctr=3 len=13
host tx ctr=3 len=64 wire=78 -> ok ctr=4 len=64
host overhead per frame: header=6 tag=8 total=14; 64-byte payload -> 78 on wire (21.9%)
host handshake bytes incl READY frame: 183

Device and host are different libraries: X25519 — fiat against OpenSSL 4.0.1 inside pyca, AES-CCM and HMAC — TinyCrypt against OpenSSL, the signature — TinyCrypt against pyca's verification. The session worked — so both sides compute the same. The handshake with the READY frame is 183 bytes on the line.


43г.5 Attacks on the channel: four experiments

Experiment 2 — a substituted byte. The host corrupts three frames in different ways: a ciphertext byte, a number byte in the header, a tag byte. Then it sends an intact frame:

host flipped ciphertext byte 4 -> ('err', 1)
host flipped header ctr byte -> ('err', 1)
host flipped tag byte -> ('err', 1)
host intact frame after three bad ones -> ok 2 b'SET DOOR=OPEN'

All three substitutions — "tag mismatch". The corrupted number (2 → 3) is also caught: the header is under the tag. The intact frame after three bad ones is accepted — the bad frames did not shift the window.

Experiment 3 — replay. Recorded frame 2 is sent again, then frames out of order and far back:

host replay of recorded ctr=2 -> ('err', 2)
host ctr=6 (5 skipped) -> ok 5
host ctr=5 late, inside window -> ok 6
host ctr=5 again -> ('err', 2)
host ctr=40 -> ok 7
host ctr=8 (32 behind top=40) -> ('err', 2)
host ctr=9 (31 behind top=40, never seen) -> ok 8

The replay has a valid tag — only the window catches it. The late frame 5 inside the window is accepted once, the second time — not. Frame 8, 32 behind the highest 40, is beyond the window's edge and rejected, although it was never seen; frame 9, 31 behind, is accepted.

Experiment 4 — device substitution. The attacker sits in the middle and changes M2 in three ways:

host mitm: attacker eph + attacker signature
host m2 signature BAD (pinned key) -> abort, no keys derived
host hs_result False
host mitm: attacker eph + device signature
host m2 signature BAD (pinned key) -> abort, no keys derived
host hs_result False
host mitm: recorded m2 of session 1
host m2 signature BAD (pinned key) -> abort, no keys derived
host hs_result False
host frame after aborted handshakes -> ('err', 4)

Its own one-time key with its own signature — the wrong signing key. Its own one-time key with the device's signature — a signature over a different th1. The recorded M2 of the first session — an honest signature, but over a different M1. The host aborts the handshake before deriving keys, and the device does not open the channel without M3: a frame after three aborted handshakes gets error 4, "no session". Without the signature — with plain X25519 — all three substitutions would have passed: the attacker would hold two channels, with the host and with the device, and read everything.

Experiment 5 — a repeated nonce after a counter fault. The keys are alive, but the device's transmit counter is reset to 1 — this happens if the session keys are saved in backup memory and the counter in RAM. The fault is triggered by the command DBG RESET_TX:

host GET T        -> ok dev_ctr=2 len=34
host DBG RESET_TX -> ok dev_ctr=3 len=2
host GET CFG      -> replay dev_ctr=1 len=37
host GET CFG      -> replay dev_ctr=2 len=37
eve ctr=2 reused: xor_c==xor_p True over 34 bytes
eve ctr=2 known first plaintext -> recovered second: WIFI=garage-7;PSK=k9Qx2Lm4vT;PIN=4

The host's window did its job: frames with numbers 1 and 2 came a second time and were rejected. But the eavesdropper already has everything: under one key and number 2 went both the reply to GET T and the reply to GET CFG, the XOR of the ciphertexts equals the XOR of the texts in all 34 bytes. The reply to GET T is guessable (these are readings), and from it 34 bytes of settings are recovered — the network name, the password and the start of the code. Replay protection on receive does not protect against a repeated nonce on transmit: the transmit counter is saved together with the keys, or after a fault the handshake is done again.


43г.6 Cost, and when to take a ready-made protocol

Device instructions are counted by SysTick under -icount, calibrated by a loop of 2 million instructions, as in 43в. The handshake ran 7 times — once in experiments 1, 2, 3 and 5 and three in experiment 4, — the average is over them; the ECDSA signature varies from 11.05 to 11.08 million because of the one-time k.

Step on the device Instructions
X25519: one-time key 1.16 million
X25519: shared secret 1.16 million
SHA-256 of the transcript, 73 bytes 8.5 thousand
ECDSA P-256 signature 11.07 million
HKDF, 64 bytes, and two AES key schedules 68.3 thousand
reply to M1, total 13.46 million
checking fin: SHA-256 of 131 bytes and HMAC 35.0 thousand
receiving a 64-byte frame: CCM and tag 65.7 thousand
sending a 64-byte frame: CCM and writing to USART 66.1 thousand

The handshake on the device is 13.50 million instructions, on an F407 at 168 MHz no less than 80 ms; the signature is 82 % of it. A 64-byte frame is about 1026 instructions per byte, no less than 0.39 ms. The whole firmware is 22516 bytes of flash, of which 5094 is our own code (protocol, log, USART), the rest is TinyCrypt and fiat.

Comparison with ready-made protocols.

Own channel (43г) TLS 1.2 / 1.3 on Mbed TLS (37а) EDHOC + OSCORE
device role responder with a signature server with a certificate any
device instructions per handshake 13.50 million 42.62 million (TLS 1.2 server), 42.66 million (TLS 1.3) not measured
bytes from the device per handshake 116 732 (TLS 1.2), 788 (TLS 1.3) not measured
flash 22516 bytes whole firmware 59176 bytes minimal client not measured
analysis, checks, review only yours years of other people's fixes IETF, RFC 9528 and 8613
on disk this section modules/crypto/mbedtls-3.6 modules/lib/uoscore-uedhoc

The own handshake is 3 times cheaper than a TLS server — by dropping certificates and using X25519 instead of P-256 for the exchange; the comparison is rough, the libraries differ. Bytes from the device — 116 (M2 and READY) against 732.

When to build your own:

When to take a ready-made one:

The rule: your own — only when a ready-made one does not fit in memory or does not suit the transport, and then — no inventions in the primitives themselves, following a known protocol.


43г.7 Pitfalls

The handshake hangs on the very first message. The host connected and immediately sent M1, but the firmware had not yet enabled the USART receiver: QEMU loses such bytes. The device signals readiness itself — byte A5 — and the host waits for it.

The window shifted before the tag was checked. A forged frame with number 1000000 shifts the window, and all honest frames after it are "replays". First the tag, then the window (43г.3).

One key for both directions. Both sides start at number 1, and the first frames go under the same nonce — experiment 5 without any fault. Two keys from HKDF, or at least the direction letter in the nonce.

The transmit counter is lost, the keys are not. The keys are saved in backup memory, the counter in RAM: after a reset the numbers start again under the old key (experiment 5, 34 bytes of settings recovered). Save them together, or after a fault — a new handshake.

Signature over the one-time key alone. The attacker records M2 and slips it to the host in another session. Sign the hash of the whole exchange, including the host's one-time key (experiment 4).

The device key comes from the same message. A host that takes the public key from M2 and checks the signature with it is checking the attacker. The key is stored at the host in advance or signed by someone the host trusts (43в.7).

An error message changes state. The error code goes in the clear: the attacker can send an "error" on behalf of the device. It may only be reported to the host, not reset the session or shift the window.

The tag is checked with memcmp. The comparison time depends on the first mismatching byte. fin is compared in constant time (ct_equal), TinyCrypt checks the CCM tag the same way (_compare in utils.c).


43г.8 Summary

Next: section 43д "Common cryptography mistakes in firmware: how to spot them in review and how to write it right" — constant-time tag comparison, keys not from rand() and not in the image, secret wiping the optimizer cannot remove, a signature check that actually stops, and a review checklist with an analyzer run.

Open in the interactive handbook