courses

Building a Radio Link

Why this matters

Every other radio page in this course looks at a link somebody else built and asks where it is weak. Z-Wave bootstraps with an all-zeros key. Zigbee ships a default link key. LoRaWAN lets you replay when the frame counter resets. Those are satisfying findings, but they are findings about design decisions, and it is hard to judge a design decision you have never had to make.

So this page goes the other way. rflink is a complete radio link — framing, synchronisation, whitening, integrity, error correction, the lot — in one readable file, and it runs on the HackRFs in the class set. Every layer in it exists because leaving it out breaks something specific, and every layer has a direct counterpart in the protocols you will be attacking.

It is also a reminder that the hard parts of a radio are not the cryptography. The link below has no cryptography at all, and it still took three real bugs and a lot of gain-knob fiddling before a file arrived intact.

The tool

rflink sends a file from one SDR to another over a frequency you pick. It lives in rflink/ — the program is rflink.py and the operator’s manual is rflink/README.md. This page is about why it is built the way it is; the README is about running it.

It needs only NumPy. It drives hackrf_transfer to transmit and receive, and rtl_sdr to receive on a dongle.

Worked example: a file across the bench

Two HackRFs, one transmitting and one receiving, on the 915 MHz ISM band:

$ ./rflink.py devices
hackrf 0: 000000000000000087c867dc2d0e405f  HackRF One
hackrf 1: 0000000000000000977c64de2d3f4a13  HackRF Pro
rtl    0: Realtek, RTL2838UHIDIR, SN: 00000001  [Elonics E4000, gain -1.0-42.0 dB]  (receive only)

$ ./rflink.py loopback big.bin -o ./inbox --freq 915M \
      --tx-serial one --rx-serial pro --fec 20 --callsign AD7KM
[  ] tx 2d0e405f (HackRF One)  ->  rx 2d3f4a13 (HackRF Pro)
[tx] big.bin: 262198 bytes -> 639 frames x 1 (513 data + 126 parity,
     generations of 212+42, survives 20% loss), 28.56 s on the air
[  ] 2 Msps, 100 kbaud, +/-50 kHz dev, IF +300 kHz, 512 B/frame
[rx] locked: 513 data frames (256.5 KiB), +126 parity
[rx] station ID: DE AD7KM
[rx] OK   sha256 verified -- 262144 bytes -> ./inbox/big.bin
[rx] peak 71/127 (-5.1 dBFS), 0.00% clipped, 645 sync hits, 2 failed CRC

256 KiB, byte for byte. Without the --fec 20 the same file is 513 frames and 22.95 s on the air, which is a useful throughput of about 11.4 kB/s against a framing overhead of 6.9%.

There is also a selftest that runs the whole modem through a simulated channel with noise, a carrier offset, and a clock error, so you can work on it without touching a radio or a licence:

$ ./rflink.py selftest
[st] 20000 B, 40 frames x 1
[st] SNR 12.0 dB, CFO 18000 Hz, clock 20.0 ppm
[st] tx 2 Msps, 100 kbaud, +/-50 kHz dev, IF +300 kHz, 512 B/frame
[st] demodulated 1.82 s of signal in 0.27 s (6.7x realtime)
[st] PASS: 20000 bytes, name='rflink-st-juhq11fz.bin', sha256 matches

Anatomy of a frame

The transmission is a sequence of short, independent frames. Each one is laid out like this:

Part Length Job
Preamble 64 symbols Let the receiver find the signal and measure it
Sync word 63 symbols Say exactly where the frame starts
Header 16 bytes Sequence, totals, and the error-coding layout
Payload 512 bytes The file
CRC-32 4 bytes Decide whether to believe any of it
Guard 16 symbols Somewhere harmless for the amplitude ramp to land

That is 4,399 symbols, 44.0 ms on the air at the default 100 kbaud, followed by a 0.5 ms gap. Compare it against a CC1101 packet or a Zigbee PPDU and the shape is the same, because the problems are the same.

The preamble buys the receiver time

Sixty-four alternating symbols — 1010… — which on the air is a clean square wave at half the symbol rate. It carries no information. It exists so that by the time real data arrives, the receiver has seen enough signal to know the signal is there.

A real transceiver also uses it to settle its AGC and pull in its clock recovery loop. rflink does neither of those in hardware, but it still needs the preamble for a more mundane reason: the transmitter ramps its amplitude up over the first 64 samples to avoid splattering across the band, and that ramp has to land on symbols nobody cares about.

The sync word is a correlation target

The preamble tells the receiver that a frame is happening. It cannot say when it starts, because every bit of it looks like every other bit. That is what the sync word is for: 63 symbols that look like noise, chosen so that sliding them along the received signal gives one sharp peak and nothing else.

The sequence is a maximal-length sequence from the polynomial x6+x5+x2+x+1. M-sequences are the standard choice here because their autocorrelation is a spike and a flat floor, which is exactly the property you want. This one was picked by search over every degree-6 polynomial and every cyclic shift, scored on two things: how large its largest off-peak correlation is (0.11 of the peak), and how strongly it correlates against the alternating preamble that precedes it, which would otherwise cause a false lock a couple of symbols early.

Correlating over 63 symbols is also worth 18 dB of processing gain, which is why the receiver can find a frame well below the point where it could read one.

⚠️ A sync word is an address, not a credential. It is published, fixed, and the same for every frame. Anyone who knows it can find your traffic, and anyone who can transmit can produce frames that your receiver will happily parse. This is true of rflink, of CC1101-class radios, and of every protocol in this course. Treat “the receiver accepted the frame” as meaning nothing about who sent it.

Whitening keeps the clock alive

Before transmission, everything from the header to the CRC is XORed with a PN9 sequence — a 9-bit shift register with the polynomial x9+x5+1, seeded to all ones. This is the same scrambler CC1101-family radios use, described in TI’s design note DN509.

The reason is that real files contain long runs of identical bytes. A few thousand zero bits in a row is a constant tone: it gives a clock-recovery loop nothing to lock to, and it pushes a DC offset into anything that has to estimate one. Whitening makes the payload look statistically random, which keeps transitions frequent and the average balanced. rflink leans on this directly — its carrier-offset estimate is the mean of the frame, and that estimate is only correct because the payload is balanced.

Whitening is its own inverse: XOR with the same sequence again and the data comes back.

⚠️ Whitening is not encryption, and this is a trap people fall into. The sequence is fixed, published, and keyless. A capture that looks like structureless noise on a waterfall may be one XOR away from plaintext. When you are assessing a device, “the payload looks random” is not evidence of confidentiality — check whether it is a scrambler before you conclude anything.

The CRC turns errors into erasures

Each frame ends with a CRC-32 over its header and payload. A frame either passes or it is discarded whole; there is no partial credit.

That sounds wasteful, and it is the single most useful thing in the design. Because every surviving frame is known-good and every missing frame is known to be missing by sequence number, the receiver is not facing an error channel where bad data hides among good. It is facing an erasure channel, where it always knows exactly which pieces it lacks. Erasures are much cheaper to correct than errors — twice the correction for the same parity — and that is what makes the error correction below as effective as it is.

⚠️ A CRC is integrity against noise, not against an attacker. It has no key. Anyone modifying a frame simply recomputes it. If a device’s only integrity check is a CRC, it has no integrity check.

The modulation

Gaussian 2-FSK: a one is a tone 50 kHz above the carrier, a zero is a tone 50 kHz below, at 100,000 symbols per second.

The deviation is not arbitrary. The modulation index — twice the deviation divided by the symbol rate — is exactly 1, which puts the tone spacing equal to the symbol rate. That is the narrowest spacing at which two tones stay orthogonal to a receiver that ignores phase, so it is the least spectrum you can spend and still demodulate non-coherently. Most cheap sub-GHz radios sit near here for the same reason.

The “Gaussian” part is a filter applied to the frequency before it is transmitted, so the signal slews between tones instead of stepping. An abrupt step is a discontinuity, and discontinuities put energy a long way outside your channel, which is both rude and illegal. The cost is a little intersymbol interference, which is why the filter is gentle (BT = 1.0) rather than the BT = 0.5 that Bluetooth uses.

Everything is kept at constant amplitude, so the transmitter’s power amplifier never has to be linear — the same reason FSK is everywhere in low-power IoT and QAM is not.

Getting the signal back

The receiver mixes the signal down, low-pass filters it, and takes the angle between consecutive samples. That is an FM discriminator in one line, and it produces a value that is positive during a one and negative during a zero. Average it over a symbol period, slice it, and you have bits.

Two details in that path are worth stealing.

Carrier offset is free

Two radios never agree on frequency. A HackRF One’s crystal is good to about 20 ppm, which at 915 MHz is 18 kHz of error, and a cheap dongle can be worse. On a discriminator, a constant frequency offset shows up as a constant added to every sample — a DC term. So the receiver does not need a carrier recovery loop at all: it takes the mean of the frame and subtracts it.

This works precisely because the sync word is balanced and the payload is whitened. The two design decisions above are what make this one possible, which is a good illustration of why these layers are hard to reason about in isolation.

Measured tolerance: the link still decodes a whole file at ±72 kHz and fails by ±85 kHz — about 79 ppm at 915 MHz, or roughly four times the error of the crystals either end of it.

Clock drift by retry, not by loop

The two radios also disagree about time. Nothing re-synchronises the symbol clock inside a frame, so over 4,399 symbols a sampling-rate error accumulates into a visible timing drift.

The textbook answer is a timing recovery loop. rflink does something lazier and, for this job, better: if a frame fails CRC, the receiver re-slices the same samples at a ladder of trial clock rates — 0, then ±100, ±200, ±300, ±400, ±500 ppm — and keeps whichever one passes. Two HackRFs are normally within 20 ppm and never leave the first entry, so the ladder costs nothing until something goes wrong. Measured, it buys ±550 ppm: a file still arrives intact at ±550 ppm of sample-clock error and fails by ±600.

The general lesson: when you have a cheap, reliable way to check an answer, guessing is often a legitimate substitute for deriving.

Forward error correction

--fec PCT adds Reed-Solomon parity frames. The construction is the Cauchy form over GF(256): the generator matrix is [I ; C] with C a Cauchy matrix, every square submatrix of which is invertible. The consequence is the useful part — any k of the k+m frames in a generation rebuild it, and it does not matter which k arrive.

Frames are grouped into generations of at most 255, because that is as far as GF(256) reaches. A 256 KiB file at --fec 20 becomes three generations — 212, 212, and 89 data frames — each carrying 42 parity frames.

The percentage counts parity against the data, so the loss a transmission survives is PCT/(100+PCT): --fec 20 tolerates 17%, --fec 50 tolerates 33%. Within a single generation the bound is exact. A 64,000-byte file at --fec 100 is one generation of 126 data and 126 parity frames, and it recovers from losing 49% of them, recovers from losing exactly 50%, and fails at 51%.

Across several generations it is not that tidy, because protection is not shared between them. Each generation needs its own k frames, so a file whose last generation is short is the weak link: 65,536 bytes at --fec 100 splits into generations of 127 and 2 data frames, and a 49% loss spread over the whole transmission failed for us even though the overall code rate looked like it had room. Read the number the tool prints — it accounts for the real split — rather than the percentage you asked for.

The receiver needs no matching flag. Every frame header carries the generation layout, so the receiver works out the scheme from whichever frame it hears first.

Worked example: losing frames on purpose

--drop blanks whole frames where they sit in the waveform, which is what a burst of interference does to them:

$ ./rflink.py selftest --bytes 262144 --fec 20 --drop 15
[st] 262144 B, 639 frames x 1 (513 data + 126 parity, generations of 212+42, survives 20% loss)
[st] SNR 12.0 dB, CFO 18000 Hz, clock 20.0 ppm, blanking 96/639 frames (15.0%)
[st] tx 2 Msps, 100 kbaud, +/-50 kHz dev, IF +300 kHz, 512 B/frame
[st] demodulated 28.47 s of signal in 4.48 s (6.4x realtime)
[st] Reed-Solomon rebuilt 75 lost frame(s)
[st] PASS: 262144 bytes, sha256 matches

The same thing done to a real capture rather than a simulated one. A 32 KiB file was sent at --fec 30 and recorded off the air with rtl_sdr; fifteen frame-length holes were then blanked out of the recording, destroying thirteen data frames. All thirteen came back.

$ ./rflink.py demod rtlcap_holed.cu8 -o ./inbox --format u8 --sample-rate 2.4M --sps 24
[rx] locked: 65 data frames (32.5 KiB), +20 parity
[rx] OK   sha256 verified -- 32768 bytes -> ./inbox/small.bin
[rx] Reed-Solomon rebuilt 13 lost frame(s)
[rx] peak 57/127 (-7.0 dBFS), 0.00% clipped, 75 sync hits, 3 failed CRC

One practical wrinkle worth knowing if you try this: capture with rtl_sdr directly, not with rflink.py rtl --capture. The receiver stops as soon as it has every data frame, so its own recording ends before the parity frames are transmitted — and a capture with no parity in it cannot demonstrate parity.

It is worth seeing what this defends against in the wild rather than on purpose. Across the runs taken for this page, one 256 KiB transfer at --fec 20 arrived with 201 of its 513 data frames missing and 142 failed CRCs — at a healthy peak of 69/127 with nothing clipping, between two runs that were clean. 915 MHz is a shared band and something else transmitted. 20% parity was nowhere near enough to rebuild that, which is the honest argument for sizing --fec against the band you will actually be in rather than the bench you tested on.

Sending the file twice also works and needs no coding theory, but it is almost always the worse deal: two passes costs 100% overhead to survive 50% loss, where --fec 100 costs the same and survives the same, and --fec 20 costs 20% to survive 17%.

Receiving with an RTL-SDR

A dongle costs about a fortieth of a HackRF and cannot transmit at all, but it can receive this perfectly well. The rtl subcommand does that, using the same demodulator.

The thing that makes it work is worth stating plainly, because it surprises people: only the symbol rate has to match, not the sample rate. The transmitter runs at 2 Msps with 20 samples per symbol; the dongle runs at 2.4 Msps with 24. Both land on 100 kbaud, and 100 kbaud is the only number the two ends share. This matters in the field too — when you are reverse engineering somebody else’s link, the symbol rate is the parameter you must recover, and your own sample rate is yours to choose.

The dongle’s crystal error, which can be tens of ppm, needs no correction either: the per-frame carrier estimate and the clock ladder absorb it.

Worked example: a dongle reading a HackRF

$ ./rflink.py rtl -o ./inbox --freq 915M
[rx] listening on 915.000 MHz -- 2.4 Msps, 100 kbaud, +/-50 kHz dev, IF +300 kHz, 512 B/frame
Found 1 device(s):
  0:  Realtek, RTL2838UHIDIR, SN: 00000001
Using device 0: Generic RTL2832U OEM
Found Elonics E4000 tuner
Sampling at 2400000 S/s.
Tuned to 915000000 Hz.
Tuner gain set to automatic.
Reading samples in async mode...
[rx] locked: 513 data frames (256.5 KiB), +126 parity
[rx] station ID: DE AD7KM
[rx] OK   sha256 verified -- 262144 bytes -> ./inbox/big.bin
[rx] peak 127/127 (+0.0 dBFS), 31.06% clipped, 520 sync hits, 1 failed CRC
[rx] hint: the front end may be clipping, which destroys an FM signal
     even at high SNR -- if nothing decodes, drop --gain by 6-12 dB

256 KiB byte-identical on the dongle’s own AGC with nothing adjusted — and note what the AGC did with a resonant antenna in front of it. It drove the converter to full scale and clipped 31% of the samples, and the file still arrived with one bad CRC in 639 frames. If a capture like that ever doesn’t decode, --gain takes the AGC out of the loop. 1.2 Msps works too, and is lighter on USB.

Two differences from a HackRF to keep in mind. The dongle hands back unsigned bytes centred on 127.5 where a HackRF gives signed ones, which is why demod has a --format flag. And the tuning range depends on which tuner yours has, which you find out by plugging it in: an R820T2 covers 24–1766 MHz, while the E4000 in the class dongle reaches 2184 MHz but starts at 53 MHz and has a hole from 1095 to 1258 MHz.

$ ./rflink.py rtl -o ./inbox --freq 1200M
[rtl] note: 1200.000 MHz falls in the E4000's L-band gap (1095-1258 MHz); an R820T2 covers it

The dongle is less sensitive than a HackRF at the weak end, but with a resonant antenna the gap is small. Walking the transmitter down, the dongle decoded 64 KiB cleanly at --tx-gain 10 (peak 27/127) and heard nothing at 8; a HackRF receiver on the same bench was still clean at 8 and still recovering 70 of 129 frames at 6. Two to four dB, in other words — the noise figure difference, and a modest argument for spending the --fec airtime on a dongle link you care about.

The antenna matters far more than that. An earlier run of this same test, with the dongle’s stock telescopic whip instead of a 915 MHz resonant antenna, left it deaf at --tx-gain 22 — more than a dozen dB worse than the receiver in front of you now. Before concluding anything about a radio’s sensitivity, check what is screwed onto it.

Three ways to get it wrong

These are the three that actually cost time while this was being built. All three are general to SDR work, not specific to this tool.

Too much gain

This is the one that will get you, because the symptom looks like the opposite of the cause. A GFSK burst has a constant envelope. Once the front end is driven into saturation the envelope is no longer constant, the phase information the discriminator depends on is mangled, and a stronger signal becomes unreadable.

Driving a HackRF receiver into its rails on purpose — --rx-lna 40 --rx-vga 40 --rx-amp 1 against a transmitter at --tx-gain 47 — gives the signature:

[rx] no frames recovered
[rx] peak 128/127 (+0.1 dBFS), 0.11% clipped, 131 sync hits, 131 failed CRC

Every frame arrived. Not one survived. Backing the VGA down until the peak came off the rail — 26 dB here, --rx-vga 40 to 14, with nothing else changed — fixed it completely:

[rx] OK   sha256 verified -- 65536 bytes
[rx] peak 77/127 (-4.3 dBFS), 0.00% clipped, 129 sync hits, 0 failed CRC

Two things about that are worth more than the headline. The first is that the clipped-sample percentage is not the thing to steer by: the HackRF above failed completely with 0.11% of samples at the rail, while an RTL-SDR on its own AGC decoded a whole file with 31% clipped. A few samples pinned at the rail is a symptom of an analogue stage already in compression, and that compression — not the arithmetic of the clipped samples — is what destroys the envelope.

The second is that the usable window is much wider than it looks, and it is bounded at the top only. Measured across this bench, a HackRF decoded a 64 KiB file cleanly at a peak of 4 out of 127, and the RTL decoded cleanly at all eight tuner gains tried, from a peak of 7/127 to full scale. The only setting that failed outright was a front end railed hard. So do not chase a particular level — stay off the rails and let the receiver do the rest. How much you need to back off is a property of your bench, not of the radio: at 14 dB down this one was still railed, and only 26 dB cleared it.

The diagnostic pair is sync hits against failed CRC: hits with no frames means the signal is arriving but the bits are wrong, so fix the level; no hits at all means check the frequency and the antennas.

This is the same point the radio page makes about gain being the parameter people get wrong, with a number attached.

The LO spur

The signal is not transmitted at the frequency you tune to. It is offset 300 kHz up at baseband — the two tones land at +250 and +350 kHz — and mixed back down in software at the far end.

The reason is that a HackRF leaks its local oscillator into the dead centre of its own passband. Put data there and it sits underneath a spur that has nothing to do with your signal. Moving the whole link off DC avoids it at both ends.

The spur is real and takes one capture to measure. Recording dead air on the HackRF Pro, with nothing transmitting anywhere, puts the DC bin 9.8 dB above the surrounding noise floor while +250 and +350 kHz — where the two tones land — sit at the floor.

What it did not do on this bench is cost frames. Running --if-offset 0 against the default in alternating pairs, all the way down to the noise floor at --tx-gain 10, produced no measurable difference: both decoded 64 KiB cleanly at a peak of 4/127. The reason is the receiver design two sections up. A spur parked at DC is a constant added to every discriminator sample, and the per-frame mean subtraction that makes carrier offset free removes it along with the offset.

Keep the offset — it costs nothing, and it still protects against a spur big enough to drive the front end rather than merely sit beneath the signal. But treat this as the worked example of a defence whose value you should measure rather than assume, including when the defence is your own.

Sample rate and aliasing

The default is 2 Msps because it is cheap on USB and CPU. Great Scott Gadgets advise against sampling a HackRF below 8 MHz, and they are right: the MAX2837 baseband filter bottoms out at 1.75 MHz, so at 2 Msps a signal 2 MHz away from where you are tuned folds into the middle of your capture with only about 33 dB of attenuation. In a quiet lab this does not matter. Next to anything else transmitting in the band it might, and the fix is to oversample so the analogue filter sits well inside Nyquist:

$ ./rflink.py loopback notes.pdf -o ./inbox --sample-rate 8M --sps 80

The receiver filters and then decimates before demodulating, so the cost is far less than fourfold — 6.6x realtime at 2 Msps against 2.7x at 8 Msps.

Transmitting legally

Receiving is passive and, across most of the spectrum, unrestricted in the US. Transmitting is not, and this is the one part of the exercise where getting it wrong has consequences outside the lab.

The default of 915 MHz with the amplifier off sits in 902–928 MHz: the US ISM band, where FCC Part 15.247 permits unlicensed operation inside its power and bandwidth limits. That band is also the amateur 33 cm allocation, so a licensed amateur has a second basis for operating there. 70 cm — 420–450 MHz, which contains the 433.92 MHz everyone reaches for — is amateur-only in the US. Other countries allocate differently.

If you are operating under an amateur licence, two rules bite immediately. 47 CFR 97.119 wants your call sign at the end of each communication and at least every ten minutes during one, which --callsign handles by sending a station ID frame in the same modulation as the data. And 47 CFR 97.113(a)(4) prohibits “messages encoded for the purpose of obscuring their meaning” — the PN9 whitening is fine, because it is a keyless published scrambler, but sending an encrypted file over an amateur allocation is not.

The transmitter also refuses outright to key up inside a safety-of-life allocation:

Band What lives there
108–137 MHz Aeronautical navigation and ATC voice
242.5–243.5 MHz Military distress and SAR beacons
406.0–406.1 MHz COSPAS-SARSAT emergency locator beacons
960–1215 MHz DME/TACAN, and ADS-B on 978 and 1090 MHz
1559–1610 MHz GPS L1, Galileo E1, GLONASS L1

None of these overlaps a US amateur allocation, so the guard never stands between you and a band you are licensed for. It exists because 978 MHz is one keystroke away from 915 MHz, especially with a 978 MHz antenna screwed on, and because a bug in your code should not be able to put a carrier into the ADS-B channel. Receiving on those frequencies is untouched.

Reading your own protocol as an attacker

The most useful thing to do with rflink is to turn the course’s own methods on it. Capture it with --capture, open the file in inspectrum or URH, and work out what you can learn without being told. A partial answer:

Every one of those observations transfers directly to the commercial protocols on the other pages. The difference is that here you can read the source and confirm you were right.

Key takeaways

References


Related course pages: Radio Protocols · Other IoT radios · LoRa and LoRaWAN · Zigbee · Z-Wave · Tools of the Trade · Attacks · Schedule

🛠️ Maintenance note: the measured figures on this page — throughput, the 12 dB SNR floor, the gain numbers, the realtime multiples — were taken on one bench with one pair of HackRFs and one E4000 dongle, and should be re-measured rather than trusted if they start looking wrong in lab. The frame layout and the default parameters are set in rflink.py and this page will drift from them if the tool changes; the figures under Anatomy of a frame come straight out of Config, so re-derive them rather than editing by hand. The RTL-SDR tuning ranges assume R820T2 or E4000 silicon, and cheap dongles change tuners without changing model numbers. The regulatory content is US-specific and the Part 97 rules are stable, but the band table should be re-checked against the eCFR rather than against this page.