From 696b8357b62b4e162f68a07c1d9da0649b0e3622 Mon Sep 17 00:00:00 2001 From: iceman1001 Date: Sat, 12 Sep 2026 15:09:53 +0200 Subject: [PATCH] add hf thinfilm sniff, and hold the tag's real frame period hf thinfilm sniff passively records the frames a Kovio tag beams at a reader. Kovio is tag-talks-first and the reader never sends a command, so only the tag side is decoded - use 'hf 14a sniff' to watch a reader's poll loop. Same DMA loop, overrun recovery and nibble de-interleave as SniffIso14443a(). ManchesterDecoding_Thinfilm() is no longer static and takes non_real_time, the same way ManchesterDecodingEx() does. A DMA sniff loop cannot timestamp with GetCountSspClk(); the clock has run on past the frame by the time the samples are processed. Only the decoder is RAMFUNC (724 bytes), not the sniff loop, since dropping the Miller decode roughly halves the per sample work. The loop counts overrun recoveries and DMA stalls separately, so a lossy capture says so instead of looking like a quiet tag. With that, the sim's frame period could be measured instead of guessed. A genuine tag repeats every 65536 carrier periods - 2**16, it clocks a 16 bit counter off the carrier - holding that to within 65520..65920. So 25% duty cycle, not the continuous beam assumed when the gap was shortened to 500us in a96756033. Revert to the tag's real rate. SimulateThinFilm() now waits on the previous frame start rather than delaying a fixed amount, so the field poll comes out of the gap instead of adding on top of it, and the period stays right if the poll cost ever changes. Measured back with a second pm3 sniffing: 65561 carrier periods against the genuine tag's 65588, inside the tag's own jitter. Rig: pm3 simulating, second pm3 sniffing, Pixel 9a reading, all three at once. Builds clean for PM3RDV4 and PM5. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 2 + armsrc/thinfilm.c | 190 +++++++++++++++++++++++++++++++++++-- armsrc/thinfilm.h | 1 + client/src/cmdhfthinfilm.c | 54 +++++++++++ 4 files changed, 239 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 82966d484..15d9e7d33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [unreleased][unreleased] +- Added `hf thinfilm sniff` - passively records the frames a Thinfilm / NFC Barcode tag beams at a reader (@iceman1001) +- Fixed `hf thinfilm sim` - it now holds the genuine tag's measured 65536 carrier period frame rate instead of a fixed delay (@iceman1001) - Changed `mem spiffs upload`/`mem spiffs dump` - both now print inline progress, and a refused write is reported with the byte it stopped at instead of claiming success (@iceman1001) - Fixed `mem spiffs dump` - a file of 64K or more wrapped the uint16_t `BigBuf_calloc()` takes, the download now streams one frame at a time (@iceman1001) - Fixed SPIFFS flash layer - a failed erase was reported to SPIFFS as success, letting it write into an un-erased sector where NOR AND-semantics silently mangled file data (@iceman1001) diff --git a/armsrc/thinfilm.c b/armsrc/thinfilm.c index 625c10247..7d6e3ce3c 100644 --- a/armsrc/thinfilm.c +++ b/armsrc/thinfilm.c @@ -56,14 +56,177 @@ void ReadThinFilm(void) { BigBuf_free(); } +//----------------------------------------------------------------------------- +// Passively record the frames a Kovio / Thinfilm tag beams at a reader. +// Kovio is tag-talks-first and the reader never sends a command, so only the tag +// side is decoded. Use `hf 14a sniff` to watch a reader's poll loop. +//----------------------------------------------------------------------------- +int SniffThinFilm(void) { + + LEDsoff(); + + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); + + BigBuf_free(); + BigBuf_Clear_ext(false); + clear_trace(); + set_tracing(true); + + // The frames (tag -> reader) that we are receiving. + uint8_t *resp = BigBuf_calloc(MAX_FRAME_SIZE); + uint8_t *resp_par = BigBuf_calloc(MAX_PARITY_SIZE); + + if (resp == NULL || resp_par == NULL) { + if (g_dbglevel >= DBG_ERROR) { + DbpString("Sniff thinfilm: failed to allocate buffers"); + } + BigBuf_free(); + return PM3_EMALLOC; + } + + Demod14aInit(resp, MAX_FRAME_SIZE, resp_par); + + if (g_dbglevel >= DBG_INFO) { + DbpString("Press " _GREEN_("pm3 button") " to abort sniffing"); + } + + // The DMA buffer, used to stream samples from the FPGA + dmabuf8_t *dma = get_dma8(); + uint8_t *data = dma->buf; + + if (FpgaSetupSscRxDmaRepeat((uint8_t *)dma->buf, DMA_BUFFER_SIZE) == false) { + if (g_dbglevel > DBG_ERROR) { + Dbprintf("FpgaSetupSscRxDmaRepeat failed. Exiting"); + } + BigBuf_free(); + return PM3_EIO; + } + + tDemod14a *demod = GetDemod14a(); + + uint8_t previous_data = 0; + uint32_t rx_samples = 0; + uint32_t overrun_skips = 0; + uint32_t dma_stalls = 0; + uint32_t frames = 0; + uint16_t checker = 12000; + int dataLen; + + // loop and listen + while (BUTTON_PRESS() == false) { + + WDT_HIT(); + LED_A_ON(); + + if (checker-- == 0) { + if (data_available()) { + break; + } + checker = 12000; + } + + register int readBufDataP = data - dma->buf; + register int dmaBufDataP = DMA_BUFFER_SIZE - FPGA_SSC_DMA_RX_Remaining_Count(); + if (readBufDataP <= dmaBufDataP) { + dataLen = dmaBufDataP - readBufDataP; + } else { + dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP; + } + + // DMA fully stalled: both buffers exhausted. Re-arm primary + secondary, + // resync the read pointer, and drop the in-flight frame. + if (FPGA_SSC_DMA_RX_Primary_Done()) { + FPGA_SSC_DMA_RX_Refresh_Both(dma->buf, DMA_BUFFER_SIZE); + data = dma->buf; + rx_samples += DMA_BUFFER_SIZE; + Demod14aReset(); + dma_stalls++; + continue; + } + + // Fell behind the DMA write pointer; skip to catch up rather than abort. + if (dataLen > (9 * DMA_BUFFER_SIZE / 10)) { + data = dma->buf + dmaBufDataP; + if (data == dma->buf + DMA_BUFFER_SIZE) { + data = dma->buf; + } + rx_samples += dataLen; + Demod14aReset(); + overrun_skips++; + continue; + } + + // The MCU is processing data fast enough that the DMA has not yet received any new data. + if (dataLen < 1) { + continue; + } + + // secondary buffer exhausted, primary still running - refill secondary + if (FPGA_SSC_DMA_RX_Secondary_Done()) { + FPGA_SSC_DMA_RX_Refresh_Secondary(dma->buf, DMA_BUFFER_SIZE); + } + + LED_A_OFF(); + + // Need two samples to feed the Manchester decoder + if (rx_samples & 0x01) { + + uint8_t tagdata = (previous_data << 4) | (*data & 0x0F); + + if (ManchesterDecoding_Thinfilm(tagdata, (rx_samples - 1) * 4)) { + + LED_B_ON(); + frames++; + + if (LogTrace(resp, + demod->len, + demod->startTime * 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, + demod->endTime * 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, + NULL, + false) == false) { + break; + } + + // ready to receive another frame + Demod14aReset(); + LED_B_OFF(); + } + } + + previous_data = *data; + rx_samples++; + data++; + if (data == dma->buf + DMA_BUFFER_SIZE) { + data = dma->buf; + } + } // end main loop + + FpgaDisableTracing(); + + if (g_dbglevel >= DBG_ERROR) { + Dbprintf("Thinfilm sniff, " _YELLOW_("%u") " frames | trace len " _YELLOW_("%d"), + frames, + BigBuf_get_traceLen() + ); + if (overrun_skips || dma_stalls) { + Dbprintf(_RED_("[!] sniffer dropped frames") " | overrun recoveries " _YELLOW_("%u") " | DMA stalls " _YELLOW_("%u"), + overrun_skips, dma_stalls); + } + } + + switch_off(); + set_tracing(false); + return PM3_SUCCESS; +} + #define SEC_D 0xf0 #define SEC_E 0x0f #define SEC_F 0x00 -// Frame delimiter. A reader needs some unmodulated carrier to find the start of a -// frame (our own demod wants three quiet bytes), but a Kovio tag is only read by -// landing a frame inside the reader's poll slot, so keep the gap short. -#define THINFILM_FRAME_GAP_US 500 +// A genuine Kovio tag repeats its frame every 65536 carrier periods - measured off +// `hf thinfilm sniff`, 2**16 because it clocks a 16 bit counter off the carrier. +// ssp_clk is carrier / 16, so hold 4096 ssp ticks from one frame start to the next. +#define THINFILM_FRAME_PERIOD_SSP 4096 // A 32 sample average costs about 3.8 ms, since every sample pays a 42.7 us ADC // startup and a 40 us sample & hold. That is fine once, for the baseline, but in @@ -179,6 +342,9 @@ void SimulateThinFilm(uint8_t *data, size_t len) { uint16_t hf_peak = hf_baseline; uint32_t sends = 0; + // let the first frame go out without waiting + uint32_t frame_start = GetCountSspClk() - THINFILM_FRAME_PERIOD_SSP; + int8_t status = PM3_SUCCESS; CodeThinfilmAsTag(data, len); @@ -229,14 +395,22 @@ void SimulateThinFilm(uint8_t *data, size_t len) { } if (AdcRssiDataToMilliVolt(hf_av - hf_baseline, ADC_RSSI_CH_HF) > 1375) { - uint32_t start_time = GetCountSspClk(); + // hold the tag's repeat rate. Waiting on the frame start rather than + // delaying a fixed amount takes the field poll above out of the gap + // instead of adding it on top. + while ((GetCountSspClk() - frame_start) < THINFILM_FRAME_PERIOD_SSP) { + WDT_HIT(); + if (BUTTON_PRESS()) { + break; + } + } + + frame_start = GetCountSspClk(); EmSendCmdThinfilmRaw(ts->buf, ts->max); sends++; // one tosend byte == one 106 kbit/s bit == 8 ssp clk ticks - LogTrace(data, len, start_time * 16, (start_time + (ts->max * 8)) * 16, NULL, false); - - SpinDelayUs(THINFILM_FRAME_GAP_US); + LogTrace(data, len, frame_start * 16, (frame_start + (ts->max * 8)) * 16, NULL, false); } } diff --git a/armsrc/thinfilm.h b/armsrc/thinfilm.h index 7e7c5ac62..3880142a9 100644 --- a/armsrc/thinfilm.h +++ b/armsrc/thinfilm.h @@ -22,6 +22,7 @@ #include "common.h" void ReadThinFilm(void); +int SniffThinFilm(void); void SimulateThinFilm(uint8_t *data, size_t len); #endif /* __ISO14443A_H */ diff --git a/client/src/cmdhfthinfilm.c b/client/src/cmdhfthinfilm.c index e13badb05..54e4699a2 100644 --- a/client/src/cmdhfthinfilm.c +++ b/client/src/cmdhfthinfilm.c @@ -205,6 +205,59 @@ int CmdHfThinFilmSim(const char *Cmd) { return PM3_SUCCESS; } +static int CmdHfThinFilmSniff(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "hf thinfilm sniff", + "Sniff the frames a Thinfilm / NFC Barcode tag beams at a reader.\n" + "The tag talks first and the reader sends nothing, so only the tag side\n" + "is decoded. Use `hf thinfilm list` to view collected data.", + "hf thinfilm sniff\n" + "hf thinfilm sniff -i" + ); + + void *argtable[] = { + arg_param_begin, + arg_lit0("i", "interactive", "Console will not be returned until sniff finishes or is aborted"), + arg_param_end + }; + CLIExecWithReturn(ctx, Cmd, argtable, true); + + bool interactive = arg_get_lit(ctx, 1); + CLIParserFree(ctx); + + clearCommandBuffer(); + SendCommandNG(CMD_HF_THINFILM_SNIFF, NULL, 0); + + if (interactive == false) { + PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " to abort sniffing"); + return PM3_SUCCESS; + } + + PrintAndLogEx(INFO, "Press " _GREEN_("pm3 button") " or " _GREEN_("") " to abort sniffing"); + + PacketResponseNG resp; + bool keypress = kbd_enter_pressed(); + + while (keypress == false) { + keypress = kbd_enter_pressed(); + + if (WaitForResponseTimeout(CMD_HF_THINFILM_SNIFF, &resp, 500)) { + break; + } + } + + if (keypress) { + // inform device to break the sniff loop since client has exited + SendCommandNG(CMD_BREAK_LOOP, NULL, 0); + WaitForResponse(CMD_HF_THINFILM_SNIFF, &resp); + } + + PrintAndLogEx(INFO, "Done!"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("hf thinfilm list") "` to view captured tracelog"); + PrintAndLogEx(HINT, "Hint: Try `" _YELLOW_("trace save -h") "` to save tracelog for later analysing"); + return PM3_SUCCESS; +} + static int CmdHfThinFilmList(const char *Cmd) { return CmdTraceListAlias(Cmd, "hf thinfilm", "thinfilm"); } @@ -214,6 +267,7 @@ static command_t CommandTable[] = { {"info", CmdHfThinFilmInfo, IfPm3NfcBarcode, "Tag information"}, {"list", CmdHfThinFilmList, AlwaysAvailable, "List NFC Barcode / Thinfilm history"}, {"sim", CmdHfThinFilmSim, IfPm3NfcBarcode, "Fake Thinfilm tag"}, + {"sniff", CmdHfThinFilmSniff, IfPm3NfcBarcode, "Sniff Thinfilm tag communication"}, {NULL, NULL, NULL, NULL} };