Files
heltec-repeater/firmware/test/test_wmbus.c
T

432 lines
18 KiB
C

// Host-side tests for the Wireless M-Bus frame layer.
//
// RF packet lengths are hostile input: the L-field comes straight off the
// air and drives every index used when validating CRCs. These tests defend
// three contracts:
// 1. CRC validation agrees with reality on frames captured from real
// meters, and rejects them after a single bit flip.
// 2. The length formulas are exact for both C-mode frame formats and
// reject values that cannot fit the radio payload.
// 3. No input -- valid, malformed, or adversarial -- reads outside the
// caller's buffer. Run under AddressSanitizer to make that meaningful.
//
// Build/run: firmware/test/run_tests.sh
#include "../main/wmbus.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures;
#define CHECK(cond, ...) do { \
if (!(cond)) { \
printf("FAIL %s:%d: ", __FILE__, __LINE__); \
printf(__VA_ARGS__); \
printf("\n"); \
failures++; \
} \
} while (0)
static int hex2bin(const char *hex, uint8_t *out, size_t maxlen)
{
size_t n = strlen(hex) / 2;
if (n > maxlen) return -1;
for (size_t i = 0; i < n; i++) {
unsigned v;
if (sscanf(hex + 2 * i, "%2x", &v) != 1) return -1;
out[i] = (uint8_t)v;
}
return (int)n;
}
// ---------------------------------------------------------------- vectors
struct vec {
wmbus_frame_fmt_t fmt;
int total_len;
const char *hex;
};
// Frames captured from real meters and reported CRC-valid by the firmware
// on hardware. Independent confirmation that the CRC implementation is not
// merely self-consistent: these bytes were produced by third-party meters.
static const struct vec valid_frames[] = {
{ WMBUS_FRAME_A, 100, "5744685067677604940893CA8C00F3900F002C25C33B1600B630B6FD0A88CB9CF1297AC30030071032D3399DBA4849A49DFA4081C0FB18E97258FBC0494113BA043F4188906E502B841CA86A3797DE729BC0A4BA6C652096FFC471400EA70F96361BF9DF" },
{ WMBUS_FRAME_A, 63, "36446850855862035237B9757244096554A85CFE075800202537D250C8E3C9DE60928BA87627B047F07BF2933C959CDAC9E1838215A16755AB905C1569DAE3" },
{ WMBUS_FRAME_A, 66, "39449344601647611D0762287AAA0000200C13360000004C130000006A5B00426CFFFFCC081336000000C2086C5FE1F63702BB560000326CFFFF046D2E155F3841EF" },
};
static void test_real_frames_validate(void)
{
uint8_t buf[300];
for (size_t i = 0; i < sizeof(valid_frames) / sizeof(valid_frames[0]); i++) {
const struct vec *v = &valid_frames[i];
int n = hex2bin(v->hex, buf, sizeof(buf));
CHECK(n == v->total_len, "vector %zu: hex decodes to %d, expected %d",
i, n, v->total_len);
if (n != v->total_len) continue;
CHECK(wmbus_frame_total_len(v->fmt, buf[0]) == v->total_len,
"vector %zu: length formula gave %d for L=%u, expected %d",
i, wmbus_frame_total_len(v->fmt, buf[0]), buf[0], v->total_len);
CHECK(wmbus_check_crc(v->fmt, buf, n),
"vector %zu: real meter frame rejected by CRC check", i);
}
}
static void test_bitflip_rejected(void)
{
uint8_t buf[300];
for (size_t i = 0; i < sizeof(valid_frames) / sizeof(valid_frames[0]); i++) {
const struct vec *v = &valid_frames[i];
int n = hex2bin(v->hex, buf, sizeof(buf));
if (n != v->total_len) continue;
// Every single-bit flip in the payload must be caught. CRC-16 over
// blocks of <= 16 bytes detects all single-bit errors, so any miss
// is a real defect.
for (int byte = 0; byte < n; byte++) {
for (int bit = 0; bit < 8; bit++) {
buf[byte] ^= (uint8_t)(1u << bit);
bool ok = wmbus_check_crc(v->fmt, buf, n);
buf[byte] ^= (uint8_t)(1u << bit);
if (ok) {
CHECK(false, "vector %zu: bit flip at byte %d bit %d "
"not detected", i, byte, bit);
return; // one report is enough
}
}
}
}
}
static void test_length_formulas(void)
{
// Format A: L counts C,M,A,CI,data without CRCs; block 1 carries 9 of
// those bytes, further blocks up to 16, each with 2 CRC bytes.
CHECK(wmbus_frame_total_len(WMBUS_FRAME_A, 9) == 12,
"A: L=9 should be the 12-byte minimum, got %d",
wmbus_frame_total_len(WMBUS_FRAME_A, 9));
CHECK(wmbus_frame_total_len(WMBUS_FRAME_A, 8) < 0, "A: L=8 must be rejected");
// L=25 -> 1 + 25 + 2*(ceil(15/16)+1) = 30
CHECK(wmbus_frame_total_len(WMBUS_FRAME_A, 25) == 30,
"A: L=25 expected 30, got %d", wmbus_frame_total_len(WMBUS_FRAME_A, 25));
// Format B: L counts everything after itself, CRCs included.
CHECK(wmbus_frame_total_len(WMBUS_FRAME_B, 11) == 12,
"B: L=11 expected 12, got %d", wmbus_frame_total_len(WMBUS_FRAME_B, 11));
CHECK(wmbus_frame_total_len(WMBUS_FRAME_B, 10) < 0, "B: L=10 must be rejected");
CHECK(wmbus_frame_total_len(WMBUS_FRAME_B, 200) == 201,
"B: L=200 expected 201, got %d", wmbus_frame_total_len(WMBUS_FRAME_B, 200));
CHECK(wmbus_frame_total_len(WMBUS_FRAME_UNKNOWN, 50) < 0,
"unknown format must be rejected");
// Nothing may exceed what fits the SX1262 payload alongside 2 mode bytes.
for (int L = 0; L <= 255; L++) {
int a = wmbus_frame_total_len(WMBUS_FRAME_A, (uint8_t)L);
int b = wmbus_frame_total_len(WMBUS_FRAME_B, (uint8_t)L);
CHECK(a <= 253, "A: L=%d produced oversized total %d", L, a);
CHECK(b <= 253, "B: L=%d produced oversized total %d", L, b);
}
}
static void test_frame_format_detection(void)
{
CHECK(wmbus_frame_format(0x54, 0xCD) == WMBUS_FRAME_A, "54CD must be format A");
CHECK(wmbus_frame_format(0x54, 0x3D) == WMBUS_FRAME_B, "543D must be format B");
CHECK(wmbus_frame_format(0x54, 0x00) == WMBUS_FRAME_UNKNOWN, "54 00 is not C-mode");
CHECK(wmbus_frame_format(0x00, 0xCD) == WMBUS_FRAME_UNKNOWN, "00 CD is not C-mode");
// T-mode traffic shares the 0x543D access code, so it lands here too and
// must be classified as not-C1 rather than mis-parsed.
CHECK(wmbus_frame_format(0x3D, 0x54) == WMBUS_FRAME_UNKNOWN, "3D 54 is not C-mode");
}
static void test_builder_roundtrip(void)
{
uint8_t buf[300];
for (int L = 19; L <= 200; L++) {
int n = wmbus_build_test_frame(buf, sizeof(buf), (uint8_t)(L & 0xFF), (uint8_t)L);
if (n < 0) continue; // does not fit: acceptable
CHECK(n == wmbus_frame_total_len(WMBUS_FRAME_A, buf[0]),
"builder L=%d: length %d disagrees with formula %d",
L, n, wmbus_frame_total_len(WMBUS_FRAME_A, buf[0]));
CHECK(wmbus_check_crc(WMBUS_FRAME_A, buf, n),
"builder L=%d: generated frame fails its own CRC check", L);
}
// Must refuse to overrun a short buffer rather than truncate.
uint8_t small[16];
CHECK(wmbus_build_test_frame(small, sizeof(small), 0, 200) < 0,
"builder must refuse a buffer that cannot hold the frame");
}
// Pack cooked bytes independently of the production raw-frame walker. Only
// the CRC primitive is shared (anchored by the captured known-answer test).
static int pack_hop_frame(wmbus_frame_fmt_t fmt, uint8_t *cooked, int len,
uint8_t *raw)
{
assert(len >= 10 && len <= 200);
int total = fmt == WMBUS_FRAME_A
? len + 2 * (1 + (len - 10 + 15) / 16)
: len + (len > 126 ? 4 : 2);
cooked[0] = (uint8_t)(fmt == WMBUS_FRAME_A ? len - 1 : total - 1);
int src = 0, dst = 0;
while (src < len) {
int block = fmt == WMBUS_FRAME_A ? (src == 0 ? 10 : 16) : 126;
if (block > len - src) block = len - src;
memcpy(raw + dst, cooked + src, (size_t)block);
uint16_t crc = wmbus_crc16(cooked + src, (size_t)block);
raw[dst + block] = (uint8_t)(crc >> 8);
raw[dst + block + 1] = (uint8_t)crc;
src += block;
dst += block + 2;
}
assert(dst == total);
return total;
}
static void init_hop_frame(uint8_t *cooked, int len, uint8_t ci)
{
for (int i = 0; i < len; i++) cooked[i] = (uint8_t)(i * 73 + 11);
cooked[1] = 0x44;
cooked[10] = ci;
}
static void check_hop_mark(wmbus_frame_fmt_t fmt, uint8_t *cooked, int len,
int h_offset, uint8_t h_mask)
{
uint8_t raw[300], expected[300];
memset(raw, 0xA5, sizeof(raw));
memset(expected, 0xA5, sizeof(expected));
int total = pack_hop_frame(fmt, cooked, len, raw);
CHECK(wmbus_check_crc(fmt, raw, total), "invalid hop input fixture");
cooked[h_offset] |= h_mask;
pack_hop_frame(fmt, cooked, len, expected);
cooked[h_offset] &= (uint8_t)~h_mask;
CHECK(wmbus_mark_repeated(fmt, raw, total),
"fmt=%d CI=%02X: unmarked frame refused", fmt, cooked[10]);
CHECK(memcmp(raw, expected, sizeof(raw)) == 0,
"fmt=%d CI=%02X: bytes other than H and its CRC changed",
fmt, cooked[10]);
CHECK(wmbus_check_crc(fmt, raw, total), "marked frame has invalid CRC");
CHECK(!wmbus_mark_repeated(fmt, raw, total), "second hop accepted");
CHECK(memcmp(raw, expected, sizeof(raw)) == 0,
"refused second hop changed frame");
if (fmt == WMBUS_FRAME_A) {
uint8_t coded[450], decoded[300];
int coded_len = wmbus_3of6_encode(raw, total, coded, sizeof(coded));
CHECK(coded_len > 0, "marked T1 frame did not encode");
if (coded_len > 0) {
CHECK(wmbus_3of6_first_byte(coded, (size_t)coded_len) == raw[0],
"marked T1 frame lost L-field");
CHECK(wmbus_3of6_decode(coded, (size_t)coded_len, decoded, total) == 0,
"marked T1 frame did not decode");
CHECK(memcmp(decoded, expected, (size_t)total) == 0,
"T1 roundtrip lost hop mark or changed payload");
CHECK(wmbus_check_crc(fmt, decoded, total),
"decoded marked T1 frame has invalid CRC");
}
}
}
static void check_hop_refused(wmbus_frame_fmt_t fmt, uint8_t *cooked, int len)
{
uint8_t raw[300], before[300];
memset(raw, 0xA5, sizeof(raw));
int total = pack_hop_frame(fmt, cooked, len, raw);
memcpy(before, raw, sizeof(raw));
CHECK(wmbus_check_crc(fmt, raw, total), "invalid refusal fixture");
CHECK(!wmbus_mark_repeated(fmt, raw, total),
"fmt=%d CI=%02X: unsupported/repeated frame accepted",
fmt, cooked[10]);
CHECK(memcmp(raw, before, sizeof(raw)) == 0,
"refused frame changed bytes");
}
static void test_hop_tpl(void)
{
static const uint8_t short_ci[] = {
0x67, 0x6E, 0x74, 0x7A, 0x7D, 0x7F, 0x88, 0x8A, 0x9E, 0xC1, 0xC4,
};
static const uint8_t long_ci[] = {
0x68, 0x6F, 0x72, 0x75, 0x7C, 0x7E, 0x87, 0x8B, 0x9F, 0xC2, 0xC5,
};
for (int f = WMBUS_FRAME_A; f <= WMBUS_FRAME_B; f++) {
wmbus_frame_fmt_t fmt = (wmbus_frame_fmt_t)f;
for (int long_header = 0; long_header <= 1; long_header++) {
const uint8_t *cis = long_header ? long_ci : short_ci;
int cf = long_header ? 21 : 13;
uint8_t cooked[200];
for (size_t i = 0; i < sizeof(short_ci); i++) {
// Long bodies cross A's 16-byte blocks and B's 126-byte
// first block; exact comparison protects all ciphertext.
for (int mode = 0; mode <= 5; mode += 5) {
init_hop_frame(cooked, sizeof(cooked), cis[i]);
cooked[1] = i % 2 ? 0x46 : 0x44;
cooked[cf] = 0xA4;
cooked[cf + 1] = (uint8_t)(0xE0 | mode);
check_hop_mark(fmt, cooked, sizeof(cooked), cf, 0x01);
}
}
init_hop_frame(cooked, sizeof(cooked), cis[0]);
cooked[cf] = 0xA4;
cooked[cf + 1] = 7;
check_hop_refused(fmt, cooked, sizeof(cooked));
cooked[cf + 1] = 5;
cooked[cf] |= 0x01;
check_hop_refused(fmt, cooked, sizeof(cooked));
cooked[cf] = 0xA6;
check_hop_refused(fmt, cooked, sizeof(cooked));
// A complete transport header needs no application payload,
// but every shorter prefix must be refused without mutation.
cooked[cf] = 0xA4;
cooked[1] = 0x54; // not a masked variant of SND_NR
check_hop_refused(fmt, cooked, sizeof(cooked));
cooked[1] = 0x44;
check_hop_mark(fmt, cooked, cf + 2, cf, 0x01);
for (int len = 11; len < cf + 2; len++)
check_hop_refused(fmt, cooked, len);
}
}
}
static void test_hop_ell(void)
{
for (int f = WMBUS_FRAME_A; f <= WMBUS_FRAME_B; f++) {
wmbus_frame_fmt_t fmt = (wmbus_frame_fmt_t)f;
for (int long_header = 0; long_header <= 1; long_header++) {
uint8_t cooked[200];
int inner = long_header ? 21 : 13;
init_hop_frame(cooked, sizeof(cooked), long_header ? 0x8E : 0x8C);
cooked[11] = 0xE5; // preserve every non-H/R CC bit
cooked[inner] = 0x72;
cooked[inner + 11] = 0x03; // inner TPL already H=R=1
cooked[inner + 12] = 7; // encrypted/authenticated inner TPL
check_hop_mark(fmt, cooked, sizeof(cooked), 11, 0x10);
// Exactly full and one-byte-over CRC blocks. For long ELL the
// inner TPL crosses A's block boundary; it must remain opaque.
int boundary = fmt == WMBUS_FRAME_A ? 26 : 126;
check_hop_mark(fmt, cooked, boundary, 11, 0x10);
check_hop_mark(fmt, cooked, boundary + 1, 11, 0x10);
cooked[inner] = 0x90; // AFL is opaque beneath a usable ELL
check_hop_mark(fmt, cooked, sizeof(cooked), 11, 0x10);
cooked[inner] = 0x78;
cooked[1] = 0x46;
check_hop_mark(fmt, cooked, inner + 1, 11, 0x10);
for (int len = 11; len <= inner; len++)
check_hop_refused(fmt, cooked, len);
cooked[11] |= 0x10;
check_hop_refused(fmt, cooked, sizeof(cooked));
cooked[11] = 0xE7;
check_hop_refused(fmt, cooked, sizeof(cooked));
}
}
}
static void test_hop_invalid_headers(void)
{
static const uint8_t unsupported_ci[] = {0x78, 0x8D, 0x8F, 0x90, 0x00, 0xFF};
for (int f = WMBUS_FRAME_A; f <= WMBUS_FRAME_B; f++) {
wmbus_frame_fmt_t fmt = (wmbus_frame_fmt_t)f;
uint8_t cooked[40], raw[300], before[300];
for (size_t i = 0; i < sizeof(unsupported_ci); i++) {
init_hop_frame(cooked, sizeof(cooked), unsupported_ci[i]);
cooked[11] = 0;
check_hop_refused(fmt, cooked, sizeof(cooked));
}
init_hop_frame(cooked, sizeof(cooked), 0x8C);
cooked[11] = 0;
// Only these two exact C-fields are valid, not masked variants.
for (int c = 0; c <= 255; c++) {
if (c == 0x44 || c == 0x46) continue;
cooked[1] = (uint8_t)c;
check_hop_refused(fmt, cooked, sizeof(cooked));
}
cooked[1] = 0x44;
check_hop_refused(fmt, cooked, 10); // no CI; A has only block 1
memset(raw, 0xA5, sizeof(raw));
int total = pack_hop_frame(fmt, cooked, sizeof(cooked), raw);
memcpy(before, raw, sizeof(raw));
for (int len = -1; len <= total + 1; len++) {
if (len == total) continue;
CHECK(!wmbus_mark_repeated(fmt, raw, len),
"mismatched raw length %d accepted (actual %d)", len, total);
CHECK(memcmp(raw, before, sizeof(raw)) == 0,
"invalid raw length changed frame");
}
CHECK(!wmbus_mark_repeated(WMBUS_FRAME_UNKNOWN, raw, total),
"unknown format accepted");
CHECK(memcmp(raw, before, sizeof(raw)) == 0,
"unknown format changed frame");
}
}
// Adversarial input: random bytes with a length that disagrees with the
// L-field, exactly what a corrupted reception looks like. Under ASan this
// proves the CRC and hop-header walks never index outside the buffer.
static void test_fuzz_bounds(void)
{
srand(12345);
for (int iter = 0; iter < 200000; iter++) {
int n = 1 + rand() % 260;
uint8_t *buf = malloc((size_t)n);
if (!buf) continue;
for (int i = 0; i < n; i++) buf[i] = (uint8_t)(rand() & 0xFF);
wmbus_frame_fmt_t fmt = (iter % 3 == 0) ? WMBUS_FRAME_A
: (iter % 3 == 1) ? WMBUS_FRAME_B
: WMBUS_FRAME_UNKNOWN;
// The firmware only calls check_crc with a total_len it derived from
// the L-field AND verified against the received byte count; mirror
// both that path and the raw path with mismatched lengths.
int total = wmbus_frame_total_len(fmt, buf[0]);
if (total > 0 && total <= n) {
(void)wmbus_check_crc(fmt, buf, total);
(void)wmbus_mark_repeated(fmt, buf, total);
}
(void)wmbus_check_crc(fmt, buf, n);
(void)wmbus_mark_repeated(fmt, buf, n);
(void)wmbus_hash(buf, (size_t)n);
free(buf);
}
}
static void test_crc_known_answer(void)
{
// EN 13757-4 CRC-16: poly 0x3D65, init 0x0000, MSB first, final
// complement. Anchored on the first block of a real captured frame,
// whose trailing CRC bytes were produced by the meter.
uint8_t block1[10] = {0x57, 0x44, 0x68, 0x50, 0x67, 0x67, 0x76, 0x04, 0x94, 0x08};
uint16_t crc = wmbus_crc16(block1, sizeof(block1));
CHECK(crc == 0x93CA, "CRC of real block 1 expected 0x93CA, got 0x%04X", crc);
// Empty input: init complemented.
CHECK(wmbus_crc16(block1, 0) == 0xFFFF, "CRC of empty input must be 0xFFFF");
}
int main(void)
{
test_crc_known_answer();
test_real_frames_validate();
test_bitflip_rejected();
test_length_formulas();
test_frame_format_detection();
test_builder_roundtrip();
test_hop_tpl();
test_hop_ell();
test_hop_invalid_headers();
test_fuzz_bounds();
if (failures) {
printf("\n%d check(s) FAILED\n", failures);
return 1;
}
printf("all wmbus tests passed\n");
return 0;
}