From 9d704090277a651f722e2828df69243089be3041 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?An=C5=BEe=20Jen=C5=A1terle?= Date: Wed, 11 Nov 2026 18:24:21 +0100 Subject: [PATCH 1/6] Allow executing mfdes sim without probe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Anže Jenšterle --- client/src/cmdhfmfdes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 8ff8ced74..2ca030b4c 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -9330,7 +9330,7 @@ static int CmdHF14ADesSim(const char *Cmd) { arg_str0(NULL, "probe", "", "Candidate-key probe payload (33 bytes)"), arg_param_end }; - CLIExecWithReturn(ctx, Cmd, argtable, false); + CLIExecWithReturn(ctx, Cmd, argtable, true); bool has_probe = arg_get_str(ctx, 1)->count > 0; uint8_t probe[sizeof(desfire_sim_probe_cmd_t)] = {0}; int probe_len = 0; From a9b5dfb97ea7ecca484c5e6141cbbc6f224e2616 Mon Sep 17 00:00:00 2001 From: GiacoBot <64906428+GiacoBot@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:34:26 +0100 Subject: [PATCH 2/6] lf pcf7931 reader: print blocks 0-7 in order, decode block 0/1 The tag does not send block numbers (datasheet 5.1, 6.1); only block 1 (sync pattern and RFB/RLB/RB1 selection) identifies positions. The reader printed raw captures, repeated and unordered. - ReadPCF7931: field off 50ms before each capture so it starts from a tag reset (first block = RFB, or block 1 with RB1, fig 10), record the start sample of each block and return its index in the sequence sent after reset in a pcf7931_read_t reply. Keep the longest capture, at least 10 blocks (a full cycle plus repeats) - DemodPCF7931: capture 12.5 blocks (~0.9s) instead of 4.5, enough for the 9-block cycle (RB1 with a full range sends block 1 twice) to repeat - PMC/block debug prints only at DBG_EXTENDED - client: identify block 1 as the block whose selection explains the observed cycle; it must match the minimal period of the data (a single repeated block was taken for a 2-block selection). Print blocks 0-7 (missing ones as not transmitted) and decode PAC, password, write protected blocks and selection - client: when several blocks fit as block 1 (a full 8-block cycle is rotation symmetric, e.g. a user block ending in 55 C4 reads as RFB 5, RLB 4) pick --rfb, then the one with fewest reserved bits set (fig 8), else print the reset order as #n with the possible RFB values - without block 1: print the blocks in transmission order as RFB+n, list the RFB values that keep block 1 out of the range, number them when only one is possible, or with the new --rfb option - client: reader timeout 15s, covers the no-tag path Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + armsrc/pcf7931.c | 70 ++++++-- armsrc/pcf7931.h | 2 +- client/src/cmdlfpcf7931.c | 345 +++++++++++++++++++++++++++++++++++++- include/pm3_cmd.h | 9 + 5 files changed, 407 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38bf4d13a..ddd3e667c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ 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] +- Changed `lf pcf7931 reader` - prints blocks 0-7 in order and decodes PAC, password, write protection and selection; handles partial selections, new `--rfb` param (@GiacoBot) - Fixed `hf mf staticnested` - `--emu` reports keys not transferred to emulator memory instead of always saying they were (@matrix) - Fixed `hf mf eclr` - waits for the device and reports a missing emulator memory instead of always succeeding (@matrix) - Fixed `hf mf nested` - `--emu` reports keys not transferred to emulator memory instead of always saying they were, a failed single sector recovery no longer returns success (@matrix) diff --git a/armsrc/pcf7931.c b/armsrc/pcf7931.c index c8ea70af0..fb370b913 100644 --- a/armsrc/pcf7931.c +++ b/armsrc/pcf7931.c @@ -25,6 +25,7 @@ #include "util.h" #include "lfsampling.h" #include "string.h" +#include "commonutil.h" #define T0_PCF 8 //period for the pcf7931 in us @@ -34,6 +35,10 @@ // AddBitPCF7931, which cannot address past 255 anyway. #define PCF7931_FRAME_ENTRIES 256 #define ALLOC 16 +// one full 8-block cycle plus repeats, so the client can check the cycle +#define PCF7931_MIN_CAPTURE_BLOCKS 10 +// capture starts inside the first block after reset (tRESET <= 20ms), its PMC lands after this sample +#define PCF7931_FIRST_PMC_MIN 300 // IIR filter consts #define IIR_CONST1 0.1f @@ -57,15 +62,14 @@ #define THRESHOLD 80 // whole blocks one capture can hold, ReadPCF7931 buffers this many -#define PCF7931_CAPTURE_BLOCKS 4 +#define PCF7931_CAPTURE_BLOCKS PCF7931_READ_MAX_BLOCKS // block + PMC (8576T0) in decimated samples #define PCF7931_BLOCK_SAMPLES ((8192 + 384) / DECIMATION) -// bounded capture, a whole BigBuf takes ~13s on PM5. 4.5 blocks always hold 3-4 whole ones +// bounded capture, a whole BigBuf takes ~13s on PM5. 12.5 blocks always hold 11-12 whole ones #define PCF7931_CAPTURE_SAMPLES ((PCF7931_CAPTURE_BLOCKS * PCF7931_BLOCK_SAMPLES) + (PCF7931_BLOCK_SAMPLES / 2)) -size_t DemodPCF7931(uint8_t **outBlocks, bool ledcontrol) { +size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, bool ledcontrol) { uint8_t bits[256] = {0x00}; - uint8_t blocks[8][16]; uint8_t *dest = BigBuf_get_addr(); uint32_t g_GraphTraceLen; // limit g_GraphTraceLen to a little more than 2 data frames. @@ -99,6 +103,8 @@ size_t DemodPCF7931(uint8_t **outBlocks, bool ledcontrol) { uint8_t block_done; size_t num_blocks = 0; + uint32_t blockStart = UINT32_MAX; // first sample of the current block, known only after a PMC + uint32_t prevBlockStart = UINT32_MAX; // first sample of the block that just ended EdgeType expectedNextEdge = FALLING; // direction in which the next edge is expected should go. half_switch = 0; @@ -131,12 +137,15 @@ size_t DemodPCF7931(uint8_t **outBlocks, bool ledcontrol) { // if the clock before also was 16T0, it is a PMC! if (ABS(beforeLastClockDuration - _16T0) < TOLERANCE) { // It's a PMC - Dbprintf(_GREEN_("PMC 16T0 FOUND:") " bitPos: %d, sample: %d", bitPos, sample); + if (g_dbglevel >= DBG_EXTENDED) + Dbprintf(_GREEN_("PMC 16T0 FOUND:") " bitPos: %d, sample: %d", bitPos, sample); sample += PMC_16T0_LEN; // move to the sample after PMC expectedNextEdge = FALLING; samplePosLastEdge = sample; block_done = 1; + prevBlockStart = blockStart; + blockStart = sample; } // 32TO @@ -144,13 +153,16 @@ size_t DemodPCF7931(uint8_t **outBlocks, bool ledcontrol) { // if the clock before also was 16T0, it is a PMC! if (ABS(beforeLastClockDuration - _16T0) < TOLERANCE) { // It's a PMC ! - Dbprintf(_GREEN_("PMC 32T0 FOUND:") " bitPos: %d, sample: %d", bitPos, sample); + if (g_dbglevel >= DBG_EXTENDED) + Dbprintf(_GREEN_("PMC 32T0 FOUND:") " bitPos: %d, sample: %d", bitPos, sample); sample += PMC_32T0_LEN; // move to the sample after PMC expectedNextEdge = FALLING; samplePosLastEdge = sample; block_done = 1; + prevBlockStart = blockStart; + blockStart = sample; // if no pmc, then its a normal bit. // Check if its the second time, the edge changed if yes, then the bit is 0 @@ -182,6 +194,8 @@ size_t DemodPCF7931(uint8_t **outBlocks, bool ledcontrol) { // Toss this block. block_done = 1; + prevBlockStart = blockStart; + blockStart = UINT32_MAX; } if (block_done == 1) { @@ -190,9 +204,10 @@ size_t DemodPCF7931(uint8_t **outBlocks, bool ledcontrol) { // check if it is a complete block. If bitpos <128, it means that we did not receive // a complete block. E.g. at the first start of a transmission. // only save if a complete block is being received. - if (bitPos == 128 && num_blocks < PCF7931_CAPTURE_BLOCKS) { + if (bitPos == 128 && num_blocks < max_blocks) { + outStarts[num_blocks] = prevBlockStart; for (j = 0; j < 16; ++j) { - blocks[num_blocks][j] = + outBlocks[num_blocks * 16 + j] = 128 * bits[j * 8 + 7] + 64 * bits[j * 8 + 6] + 32 * bits[j * 8 + 5] + @@ -226,7 +241,6 @@ size_t DemodPCF7931(uint8_t **outBlocks, bool ledcontrol) { } - memcpy(outBlocks, blocks, 16 * num_blocks); return num_blocks; } @@ -279,6 +293,8 @@ void ReadPCF7931(bool ledcontrol) { uint8_t memory_blocks[maxBlocks][17]; // PCF content uint8_t single_blocks[maxBlocks][17]; // PFC blocks with unknown position uint8_t tmp_blocks[PCF7931_CAPTURE_BLOCKS][16]; // temporary read buffer + uint32_t tmp_starts[PCF7931_CAPTURE_BLOCKS]; + pcf7931_read_t best = {0}; // longest capture, sent to the client int single_blocks_cnt = 0; @@ -296,11 +312,16 @@ void ReadPCF7931(bool ledcontrol) { //j = 0; do { - Dbprintf("ReadPCF7931() -- Reading Loop =========="); + if (g_dbglevel >= DBG_EXTENDED) + Dbprintf("ReadPCF7931() -- Reading Loop =========="); i = 0; + // reset the tag so the capture is aligned to the start of its transmission + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelay(50); + memset(tmp_blocks, 0, sizeof(tmp_blocks)); - n = DemodPCF7931((uint8_t **)tmp_blocks, ledcontrol); + n = DemodPCF7931((uint8_t *)tmp_blocks, tmp_starts, ARRAYLEN(tmp_blocks), ledcontrol); if (!n) ++errors; @@ -353,11 +374,26 @@ void ReadPCF7931(bool ledcontrol) { // Dbprintf("(dbg) got %d blocks (%d/%d found) (%d tries, %d errors)", n, found_blocks, (maxBlocks == 0 ? found_blocks : maxBlocks), tries, errors); // print blocks that have been found - for (i = 0; i < n; ++i) { - print_result("Block found: ", tmp_blocks[i], 16); + if (g_dbglevel >= DBG_EXTENDED) { + for (i = 0; i < n; ++i) { + print_result("Block found: ", tmp_blocks[i], 16); + } } - // blocks are not sorted, stop once a cycle worth of them is printed - found_blocks += n; + // the client sorts the blocks, keep the longest capture + if (n > best.count) { + best.count = n; + memcpy(best.blocks, tmp_blocks, sizeof(best.blocks)); + for (i = 0; i < n; ++i) { + if (tmp_starts[i] == UINT32_MAX || tmp_starts[i] < PCF7931_FIRST_PMC_MIN) { + best.pos[i] = 0xFF; // unknown + } else { + best.pos[i] = 1 + (tmp_starts[i] - PCF7931_FIRST_PMC_MIN) / PCF7931_BLOCK_SAMPLES; + } + if (g_dbglevel >= DBG_EXTENDED) + Dbprintf("block %d start sample %u pos %u", i, tmp_starts[i], best.pos[i]); + } + } + found_blocks = best.count; // i = 0; // if (!found_0_1) { @@ -421,7 +457,7 @@ void ReadPCF7931(bool ledcontrol) { goto end; } - } while (found_blocks < maxBlocks); + } while (found_blocks < PCF7931_MIN_CAPTURE_BLOCKS); end: @@ -450,7 +486,7 @@ end: // field off, so a following command starts from a tag reset FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - reply_ng(CMD_LF_PCF7931_READ, PM3_SUCCESS, NULL, 0); + reply_ng(CMD_LF_PCF7931_READ, PM3_SUCCESS, (uint8_t *)&best, sizeof(best)); } static void RealWritePCF7931( diff --git a/armsrc/pcf7931.h b/armsrc/pcf7931.h index e412a7a66..3972234d4 100644 --- a/armsrc/pcf7931.h +++ b/armsrc/pcf7931.h @@ -24,7 +24,7 @@ typedef enum { RISING } EdgeType; -size_t DemodPCF7931(uint8_t **outBlocks, bool ledcontrol); +size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, bool ledcontrol); bool IsBlock0PCF7931(uint8_t *block); bool IsBlock1PCF7931(const uint8_t *block); void ReadPCF7931(bool ledcontrol); diff --git a/client/src/cmdlfpcf7931.c b/client/src/cmdlfpcf7931.c index 3c3250b11..6fc2aa4a3 100644 --- a/client/src/cmdlfpcf7931.c +++ b/client/src/cmdlfpcf7931.c @@ -22,6 +22,7 @@ #include "comms.h" #include "ui.h" #include "cliparser.h" +#include "commonutil.h" // ARRAYLEN static int CmdHelp(const char *Cmd); @@ -29,6 +30,9 @@ static int CmdHelp(const char *Cmd); #define PCF7931_DEFAULT_OFFSET_WIDTH 0 #define PCF7931_DEFAULT_OFFSET_POSITION 0 +#define PCF7931_BLOCKS 8 +#define PCF7931_BLOCK_SIZE 16 + // Default values - Configuration static struct pcf7931_config configPcf = { {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, @@ -56,22 +60,346 @@ int pcf7931_printConfig(void) { return PM3_SUCCESS; } +#define PCF7931_POS_UNKNOWN 0xFF + +// block numbers sent per cycle according to the selection in block 1 (datasheet fig 10) +static size_t pcf7931_sequence(const uint8_t *blk1, uint8_t *seq) { + uint8_t rfb = blk1[14] & 0x07; + uint8_t rlb = blk1[15] & 0x07; + size_t len = 0; + if (blk1[14] & 0x80) { + seq[len++] = 1; + } + for (uint8_t b = rfb; ; b = (b + 1) & 0x07) { + seq[len++] = b; + if (b == rlb) { + break; + } + } + return len; +} + +// the same block number must always carry the same data +static bool pcf7931_numbering_fits(const pcf7931_read_t *rd, const uint8_t *num, size_t k) { + for (size_t j = 0; j < k; j++) { + if (num[j] == num[k] && num[k] != PCF7931_POS_UNKNOWN && memcmp(rd->blocks[j], rd->blocks[k], PCF7931_BLOCK_SIZE)) { + return false; + } + } + // with PAC set the password reads as zeros + if (num[k] == 0 && (rd->blocks[k][7] & 0x01)) { + static const uint8_t zeros[7] = {0}; + if (memcmp(rd->blocks[k], zeros, sizeof(zeros))) { + return false; + } + } + return true; +} + +// smallest number of blocks per cycle consistent with the data, 0 if none. +// up to 9: with RB1 block 1 is sent twice when RFB..RLB covers all blocks +static size_t pcf7931_period(const pcf7931_read_t *rd) { + for (size_t p = 1; p <= PCF7931_BLOCKS + 1; p++) { + bool ok = true; + for (size_t k = 0; k < rd->count && ok; k++) { + for (size_t j = 0; j < k && ok; j++) { + if (rd->pos[j] == PCF7931_POS_UNKNOWN || rd->pos[k] == PCF7931_POS_UNKNOWN) { + continue; + } + if ((rd->pos[j] % p) == (rd->pos[k] % p) && memcmp(rd->blocks[j], rd->blocks[k], PCF7931_BLOCK_SIZE)) { + ok = false; + } + } + } + if (ok) { + return p; + } + } + return 0; +} + +typedef struct { + uint8_t num[PCF7931_READ_MAX_BLOCKS]; // block number of each received block + const uint8_t *blk1; + bool aligned; // first block after reset is the first of the sequence + int reserved; // reserved bits set in block 1 +} pcf7931_cand_t; + +// bits reserved for future use in block 1 (datasheet fig 8), expected 0 +static int pcf7931_reserved_bits(const uint8_t *blk1) { + int n = __builtin_popcount(blk1[14] & 0x78) + __builtin_popcount(blk1[15] & 0xF8); + for (int i = 8; i < 14; i++) { + n += __builtin_popcount(blk1[i]); + } + return n; +} + +// every numbering in which one received block, taken as block 1, explains all the data +static size_t pcf7931_block1_candidates(const pcf7931_read_t *rd, pcf7931_cand_t *cands, size_t max) { + size_t n = 0; + size_t p = pcf7931_period(rd); + + for (size_t c = 0; c < rd->count; c++) { + if (rd->pos[c] == PCF7931_POS_UNKNOWN) { + continue; + } + uint8_t seq[PCF7931_BLOCKS + 1]; + size_t len = pcf7931_sequence(rd->blocks[c], seq); + // a longer selection could explain any repeating data, it must match the data exactly + if (len != p) { + continue; + } + for (size_t s = 0; s < len; s++) { + if (seq[s] != 1) { + continue; + } + // shift putting block c at sequence index s + size_t off = (s + len - (rd->pos[c] % len)) % len; + pcf7931_cand_t cand = { .blk1 = rd->blocks[c], .aligned = (off == 0), .reserved = pcf7931_reserved_bits(rd->blocks[c]) }; + bool ok = true; + for (size_t k = 0; k < rd->count && ok; k++) { + cand.num[k] = (rd->pos[k] == PCF7931_POS_UNKNOWN) ? PCF7931_POS_UNKNOWN : seq[(rd->pos[k] + off) % len]; + ok = pcf7931_numbering_fits(rd, cand.num, k); + // block 1 may be sent twice per cycle (RB1), both must match + if (ok && cand.num[k] == 1 && memcmp(rd->blocks[k], rd->blocks[c], PCF7931_BLOCK_SIZE)) { + ok = false; + } + } + if (ok == false) { + continue; + } + bool dup = false; + for (size_t i = 0; i < n; i++) { + if (memcmp(cands[i].num, cand.num, rd->count) == 0) { + dup = true; + } + } + if (dup == false && n < max) { + cands[n++] = cand; + } + } + } + return n; +} + +// keep only the candidates matching keep[], unless that would drop all of them +static size_t pcf7931_filter(pcf7931_cand_t *cands, size_t n, const bool *keep) { + size_t m = 0; + for (size_t i = 0; i < n; i++) { + m += keep[i]; + } + if (m == 0 || m == n) { + return n; + } + m = 0; + for (size_t i = 0; i < n; i++) { + if (keep[i]) { + cands[m++] = cands[i]; + } + } + return m; +} + +static void pcf7931_print_memory(const uint8_t **mem) { + PrintAndLogEx(INFO, "-----+-------------------------------------------------"); + for (int b = 0; b < PCF7931_BLOCKS; b++) { + if (mem[b]) { + PrintAndLogEx(SUCCESS, " %2d | %s", b, sprint_hex(mem[b], PCF7931_BLOCK_SIZE)); + } else { + PrintAndLogEx(INFO, " %2d | " _YELLOW_("not transmitted"), b); + } + } + PrintAndLogEx(INFO, "-----+-------------------------------------------------"); + + if (mem[0]) { + bool pac = mem[0][7] & 0x01; + PrintAndLogEx(INFO, "PAC (password check).... %s", pac ? _RED_("enabled") " (password reads as 00)" : _GREEN_("disabled")); + if (pac == false) { + PrintAndLogEx(INFO, "Password................ " _YELLOW_("%s"), sprint_hex(mem[0], 7)); + } + char bwp[3 * PCF7931_BLOCKS + 1] = {0}; + for (int b = 0; b < PCF7931_BLOCKS; b++) { + if (mem[0][8] & (1 << b)) { + snprintf(bwp + strlen(bwp), sizeof(bwp) - strlen(bwp), "%d ", b); + } + } + PrintAndLogEx(INFO, "Write protected blocks.. %s", strlen(bwp) ? bwp : "none"); + } +} + +static void pcf7931_print_blocks(const pcf7931_read_t *rd, int user_rfb) { + const uint8_t *mem[PCF7931_BLOCKS] = {NULL}; + pcf7931_cand_t cands[2 * PCF7931_READ_MAX_BLOCKS]; + size_t nc = pcf7931_block1_candidates(rd, cands, ARRAYLEN(cands)); + + if (nc) { + bool keep[ARRAYLEN(cands)]; + const char *why = NULL; + + for (size_t i = 0; i < nc; i++) { + keep[i] = cands[i].aligned; + } + nc = pcf7931_filter(cands, nc, keep); + if (cands[0].aligned == false) { + PrintAndLogEx(WARNING, "Transmission start not aligned to RFB, numbering from block 1 only"); + } + + if (user_rfb >= 0 && nc > 1) { + for (size_t i = 0; i < nc; i++) { + keep[i] = ((cands[i].blk1[14] & 0x07) == user_rfb); + } + size_t before = nc; + nc = pcf7931_filter(cands, nc, keep); + if (nc < before) { + why = "RFB given"; + } + } + + if (nc > 1) { + int best = INT32_MAX; + for (size_t i = 0; i < nc; i++) { + best = MIN(best, cands[i].reserved); + } + for (size_t i = 0; i < nc; i++) { + keep[i] = (cands[i].reserved == best); + } + size_t before = nc; + nc = pcf7931_filter(cands, nc, keep); + if (nc < before) { + why = "chosen by fewest reserved bits set"; + } + } + + if (nc > 1) { + // order after reset is known, which block is block 1 is not + size_t p = pcf7931_period(rd); + char rfbs[3 * ARRAYLEN(cands) + 1] = {0}; + for (size_t i = 0; i < nc; i++) { + snprintf(rfbs + strlen(rfbs), sizeof(rfbs) - strlen(rfbs), "%u ", cands[i].blk1[14] & 0x07); + } + PrintAndLogEx(WARNING, "More than one block fits as block 1, numbering is ambiguous"); + PrintAndLogEx(INFO, "Possible RFB............ %s", rfbs); + PrintAndLogEx(INFO, "-----+-------------------------------------------------"); + for (size_t i = 0; i < p; i++) { + const uint8_t *blk = NULL; + for (size_t k = 0; k < rd->count; k++) { + if (rd->pos[k] != PCF7931_POS_UNKNOWN && (rd->pos[k] % p) == i) { + blk = rd->blocks[k]; + } + } + if (blk) { + PrintAndLogEx(SUCCESS, " #%zu | %s", i, sprint_hex(blk, PCF7931_BLOCK_SIZE)); + } + } + PrintAndLogEx(INFO, "-----+-------------------------------------------------"); + PrintAndLogEx(HINT, "Hint: #n is the n-th block sent after reset, use `" _YELLOW_("--rfb ") "` to pick the numbering"); + return; + } + + for (size_t k = 0; k < rd->count; k++) { + if (cands[0].num[k] != PCF7931_POS_UNKNOWN) { + mem[cands[0].num[k]] = rd->blocks[k]; + } + } + const uint8_t *blk1 = cands[0].blk1; + + uint8_t seq[PCF7931_BLOCKS + 1]; + size_t len = pcf7931_sequence(blk1, seq); + char order[3 * (PCF7931_BLOCKS + 1) + 1] = {0}; + for (size_t i = 0; i < len; i++) { + snprintf(order + strlen(order), sizeof(order) - strlen(order), "%u ", seq[i]); + } + PrintAndLogEx(INFO, "Transmission cycle...... %s", order); + pcf7931_print_memory(mem); + PrintAndLogEx(INFO, "Selection............... RFB %u, RLB %u, RB1 %u%s%s%s", + blk1[14] & 0x07, blk1[15] & 0x07, blk1[14] >> 7, + why ? " (" : "", why ? why : "", why ? ")" : ""); + return; + } + + // block 1 is not sent: order is known from the reset, block numbers are not + size_t p = pcf7931_period(rd); + if (p == 0 || p >= PCF7931_BLOCKS) { + PrintAndLogEx(WARNING, "Inconsistent read, blocks in received order:"); + for (size_t k = 0; k < rd->count; k++) { + PrintAndLogEx(INFO, "Block ? | %s", sprint_hex(rd->blocks[k], PCF7931_BLOCK_SIZE)); + } + return; + } + + const uint8_t *cycle[PCF7931_BLOCKS] = {NULL}; + for (size_t k = 0; k < rd->count; k++) { + if (rd->pos[k] != PCF7931_POS_UNKNOWN) { + cycle[rd->pos[k] % p] = rd->blocks[k]; + } + } + + // RB1 = 0 and block 1 outside RFB..RLB + char rfb_list[3 * PCF7931_BLOCKS + 1] = {0}; + int ncand = 0, rfb = -1; + for (int r = 0; r < PCF7931_BLOCKS; r++) { + if (((1 - r) & 0x07) >= (int)p) { + snprintf(rfb_list + strlen(rfb_list), sizeof(rfb_list) - strlen(rfb_list), "%d ", r); + ncand++; + rfb = r; + } + } + + PrintAndLogEx(INFO, "Block 1 not identified, the tag does not send block numbers"); + PrintAndLogEx(INFO, "Blocks per cycle........ %zu%s", p, (p == 1) ? " (or more identical blocks)" : ""); + PrintAndLogEx(INFO, "Possible RFB............ %s", rfb_list); + + if (user_rfb >= 0) { + if (((1 - user_rfb) & 0x07) < (int)p) { + PrintAndLogEx(WARNING, "RFB %d would include block 1 in the cycle", user_rfb); + } + rfb = user_rfb; + } else if (ncand != 1) { + PrintAndLogEx(INFO, "-------+-------------------------------------------------"); + for (size_t i = 0; i < p; i++) { + if (cycle[i]) { + PrintAndLogEx(SUCCESS, " RFB+%zu | %s", i, sprint_hex(cycle[i], PCF7931_BLOCK_SIZE)); + } else { + PrintAndLogEx(INFO, " RFB+%zu | " _YELLOW_("not received"), i); + } + } + PrintAndLogEx(INFO, "-------+-------------------------------------------------"); + PrintAndLogEx(HINT, "Hint: blocks are in transmission order, use `" _YELLOW_("--rfb ") "` to number them"); + return; + } + + for (size_t i = 0; i < p; i++) { + mem[(rfb + i) & 0x07] = cycle[i]; + } + pcf7931_print_memory(mem); + PrintAndLogEx(INFO, "Selection............... RFB %d, RLB %d, RB1 0 (%s)", + rfb, (int)((rfb + p - 1) & 0x07), (user_rfb >= 0) ? "RFB given" : "inferred"); +} + static int CmdLFPCF7931Reader(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "lf pcf7931 reader", "read a PCF7931 tag", - "lf pcf7931 reader -@ -> continuous reader mode" + "lf pcf7931 reader -@ -> continuous reader mode\n" + "lf pcf7931 reader --rfb 2 -> number blocks starting at 2 when block 1 is missing or ambiguous" ); void *argtable[] = { arg_param_begin, arg_lit0("@", NULL, "optional - continuous reader mode"), + arg_int0(NULL, "rfb", "<0-7>", "first transmitted block, used when block 1 is missing or ambiguous"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); bool cm = arg_get_lit(ctx, 1); + int rfb = arg_get_int_def(ctx, 2, -1); CLIParserFree(ctx); + if (rfb < -1 || rfb >= PCF7931_BLOCKS) { + PrintAndLogEx(ERR, "RFB must be between 0-7"); + return PM3_EINVARG; + } + if (cm) { PrintAndLogEx(INFO, "Press " _GREEN_("") " to exit"); } @@ -80,10 +408,23 @@ static int CmdLFPCF7931Reader(const char *Cmd) { PacketResponseNG resp; clearCommandBuffer(); SendCommandNG(CMD_LF_PCF7931_READ, NULL, 0); - if (WaitForResponseTimeout(CMD_LF_PCF7931_READ, &resp, 2500) == false) { + if (WaitForResponseTimeout(CMD_LF_PCF7931_READ, &resp, 15000) == false) { PrintAndLogEx(WARNING, "command execution time out"); return PM3_ETIMEOUT; } + + if (resp.length != sizeof(pcf7931_read_t)) { + PrintAndLogEx(ERR, "Wrong reply length, firmware and client do not match"); + return PM3_ESOFT; + } + + pcf7931_read_t *rd = (pcf7931_read_t *)resp.data.asBytes; + rd->count = MIN(rd->count, PCF7931_READ_MAX_BLOCKS); + if (rd->count == 0) { + PrintAndLogEx(WARNING, "No PCF7931 tag found"); + } else { + pcf7931_print_blocks(rd, rfb); + } } while (cm && (kbd_enter_pressed() == false)); return PM3_SUCCESS; diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index b03cd6c27..e82131fc4 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -529,6 +529,15 @@ typedef struct { uint8_t data; } PACKED pcf7931_write_t; +#define PCF7931_READ_MAX_BLOCKS 12 + +// CMD_LF_PCF7931_READ reply payload +typedef struct { + uint8_t count; + uint8_t pos[PCF7931_READ_MAX_BLOCKS]; // index in the sequence sent after tag reset, 0 = RFB (or block 1 if RB1) + uint8_t blocks[PCF7931_READ_MAX_BLOCKS][16]; +} PACKED pcf7931_read_t; + // CMD_LF_HITAGS_SIMULATE / CMD_LF_HITAGU_SIMULATE payload typedef struct { uint8_t tag_mem_supplied; From b96f56cf7bf9750d43d26ad291bf9caf0bd45da6 Mon Sep 17 00:00:00 2001 From: GiacoBot <64906428+GiacoBot@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:11:46 +0100 Subject: [PATCH 3/6] lf pcf7931 reader: give up after 3 empty captures, client timeout 20s With the reset-aligned 12.5-block capture an empty one takes ~1.3s, so 10 of them took 13.4s against the 15s client timeout. A present tag always decodes in the first capture. Co-Authored-By: Claude Opus 5.5 --- armsrc/pcf7931.c | 4 +++- client/src/cmdlfpcf7931.c | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/armsrc/pcf7931.c b/armsrc/pcf7931.c index fb370b913..b287d0b9e 100644 --- a/armsrc/pcf7931.c +++ b/armsrc/pcf7931.c @@ -37,6 +37,8 @@ #define ALLOC 16 // one full 8-block cycle plus repeats, so the client can check the cycle #define PCF7931_MIN_CAPTURE_BLOCKS 10 +// a reset-aligned capture of a present tag always decodes, ~1.3s per empty one +#define PCF7931_NO_TAG_CAPTURES 3 // capture starts inside the first block after reset (tRESET <= 20ms), its PMC lands after this sample #define PCF7931_FIRST_PMC_MIN 300 @@ -326,7 +328,7 @@ void ReadPCF7931(bool ledcontrol) { ++errors; // exit if no block is received - if (errors >= 10 && found_blocks == 0 && single_blocks_cnt == 0) { + if (errors >= PCF7931_NO_TAG_CAPTURES && found_blocks == 0 && single_blocks_cnt == 0) { Dbprintf("[!!] Error, no tag or bad tag"); goto end; } diff --git a/client/src/cmdlfpcf7931.c b/client/src/cmdlfpcf7931.c index 6fc2aa4a3..0ffb7b274 100644 --- a/client/src/cmdlfpcf7931.c +++ b/client/src/cmdlfpcf7931.c @@ -408,7 +408,7 @@ static int CmdLFPCF7931Reader(const char *Cmd) { PacketResponseNG resp; clearCommandBuffer(); SendCommandNG(CMD_LF_PCF7931_READ, NULL, 0); - if (WaitForResponseTimeout(CMD_LF_PCF7931_READ, &resp, 15000) == false) { + if (WaitForResponseTimeout(CMD_LF_PCF7931_READ, &resp, 20000) == false) { PrintAndLogEx(WARNING, "command execution time out"); return PM3_ETIMEOUT; } From 0684715c65ae6c445ef8088e30055e17440f29bb Mon Sep 17 00:00:00 2001 From: GiacoBot <64906428+GiacoBot@users.noreply.github.com> Date: Tue, 10 Nov 2026 18:35:37 +0100 Subject: [PATCH 4/6] lf pcf7931 write: verify via read after write, retry when not confirmed The tag never acknowledges a write, so the client printed "Done!" also when the tag rejected it (wrong password, protected block, missed PMC window). After a good write the tag stays silent during EEPROM access (640T0), sends a PMC and then the programmed block, even outside RFB..RLB, and continues as after reset (datasheet 6.4/6.5). On failure it skips that block. - RealWritePCF7931: keep the field on after the frame and switch to sampling right away (4.5 blocks). Confirm when the decoded blocks follow the read-after-write grid; when that block itself decodes, check the written byte and return the whole block - DecodePCF7931: split from DemodPCF7931 to decode an existing capture; a block with no PMC before it gets its start from the closing PMC - SendCmdPCF7931: frame sending split into SendFramePCF7931 - WritePCF7931: up to 3 attempts while not confirmed (a tag idle for a while often misses the first one); reply status and block - client write: report confirmed with block data, confirmed by timing, or not confirmed Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + armsrc/pcf7931.c | 113 ++++++++++++++++++++++++++++++++------ client/src/cmdlfpcf7931.c | 24 +++++++- 3 files changed, 120 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ddd3e667c..b1a7f56ae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ 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] +- Changed `lf pcf7931 write` - write is verified via the tag's read after write, retried up to 3 times, failures are reported (@GiacoBot) - Changed `lf pcf7931 reader` - prints blocks 0-7 in order and decodes PAC, password, write protection and selection; handles partial selections, new `--rfb` param (@GiacoBot) - Fixed `hf mf staticnested` - `--emu` reports keys not transferred to emulator memory instead of always saying they were (@matrix) - Fixed `hf mf eclr` - waits for the device and reports a missing emulator memory instead of always succeeding (@matrix) diff --git a/armsrc/pcf7931.c b/armsrc/pcf7931.c index b287d0b9e..4a0cf6520 100644 --- a/armsrc/pcf7931.c +++ b/armsrc/pcf7931.c @@ -41,6 +41,13 @@ #define PCF7931_NO_TAG_CAPTURES 3 // capture starts inside the first block after reset (tRESET <= 20ms), its PMC lands after this sample #define PCF7931_FIRST_PMC_MIN 300 +// a PMC is recognised 32T0 into it, 8192T0 after the start of the block it closes +#define PCF7931_PMC_TO_START ((8192 + 32) / DECIMATION) +#define PCF7931_WRITE_ATTEMPTS 3 +// after a good write the read-after-write block follows EEPROM access (640T0) and a PMC (384T0), +// later blocks keep that grid. +-256T0 margin +#define PCF7931_RAW_MIN_START ((640 + 384 - 16 - 256) / DECIMATION) +#define PCF7931_RAW_MAX_START ((640 + 384 - 16 + 256) / DECIMATION) // IIR filter consts #define IIR_CONST1 0.1f @@ -69,11 +76,13 @@ #define PCF7931_BLOCK_SAMPLES ((8192 + 384) / DECIMATION) // bounded capture, a whole BigBuf takes ~13s on PM5. 12.5 blocks always hold 11-12 whole ones #define PCF7931_CAPTURE_SAMPLES ((PCF7931_CAPTURE_BLOCKS * PCF7931_BLOCK_SAMPLES) + (PCF7931_BLOCK_SAMPLES / 2)) +#define PCF7931_WRITE_CAPTURE_BLOCKS 4 +#define PCF7931_WRITE_CAPTURE_SAMPLES ((PCF7931_WRITE_CAPTURE_BLOCKS * PCF7931_BLOCK_SAMPLES) + (PCF7931_BLOCK_SAMPLES / 2)) -size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, bool ledcontrol) { +// decode the blocks of a capture already in BigBuf, g_GraphTraceLen samples long +static size_t DecodePCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, uint32_t g_GraphTraceLen) { uint8_t bits[256] = {0x00}; uint8_t *dest = BigBuf_get_addr(); - uint32_t g_GraphTraceLen; // limit g_GraphTraceLen to a little more than 2 data frames. // To make sure a complete dataframe is in the dataset. // 1 Frame is 16 Byte -> 128byte. at a T0 of 64 -> 8129 Samples per frame. @@ -84,10 +93,6 @@ size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, // TODO: Doublecheck why this is being limited? - seems not to be needed. // g_GraphTraceLen = (g_GraphTraceLen > 18000) ? 18000 : g_GraphTraceLen; - BigBuf_Clear_keep_EM(); - LFSetupFPGAForADC(LF_DIVISOR_125, true); - // returns bits, 8 per sample - g_GraphTraceLen = DoAcquisition(DECIMATION, 8, 0, 0, false, PCF7931_CAPTURE_SAMPLES, 0, 0, ledcontrol) >> 3; if (g_GraphTraceLen < 5) { return 0; } @@ -107,6 +112,7 @@ size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, size_t num_blocks = 0; uint32_t blockStart = UINT32_MAX; // first sample of the current block, known only after a PMC uint32_t prevBlockStart = UINT32_MAX; // first sample of the block that just ended + uint32_t pmcAt = UINT32_MAX; // sample where the PMC closing the block was recognised EdgeType expectedNextEdge = FALLING; // direction in which the next edge is expected should go. half_switch = 0; @@ -141,6 +147,7 @@ size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, // It's a PMC if (g_dbglevel >= DBG_EXTENDED) Dbprintf(_GREEN_("PMC 16T0 FOUND:") " bitPos: %d, sample: %d", bitPos, sample); + pmcAt = sample; sample += PMC_16T0_LEN; // move to the sample after PMC expectedNextEdge = FALLING; @@ -158,6 +165,7 @@ size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, if (g_dbglevel >= DBG_EXTENDED) Dbprintf(_GREEN_("PMC 32T0 FOUND:") " bitPos: %d, sample: %d", bitPos, sample); + pmcAt = sample; sample += PMC_32T0_LEN; // move to the sample after PMC expectedNextEdge = FALLING; @@ -198,6 +206,7 @@ size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, block_done = 1; prevBlockStart = blockStart; blockStart = UINT32_MAX; + pmcAt = UINT32_MAX; } if (block_done == 1) { @@ -208,6 +217,10 @@ size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, // only save if a complete block is being received. if (bitPos == 128 && num_blocks < max_blocks) { outStarts[num_blocks] = prevBlockStart; + // no PMC before it, e.g. after silence: count back from the closing one + if (prevBlockStart == UINT32_MAX && pmcAt != UINT32_MAX && pmcAt >= PCF7931_PMC_TO_START) { + outStarts[num_blocks] = pmcAt - PCF7931_PMC_TO_START; + } for (j = 0; j < 16; ++j) { outBlocks[num_blocks * 16 + j] = 128 * bits[j * 8 + 7] + @@ -246,6 +259,14 @@ size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, return num_blocks; } +size_t DemodPCF7931(uint8_t *outBlocks, uint32_t *outStarts, size_t max_blocks, bool ledcontrol) { + BigBuf_Clear_keep_EM(); + LFSetupFPGAForADC(LF_DIVISOR_125, true); + // returns bits, 8 per sample + uint32_t len = DoAcquisition(DECIMATION, 8, 0, 0, false, PCF7931_CAPTURE_SAMPLES, 0, 0, ledcontrol) >> 3; + return DecodePCF7931(outBlocks, outStarts, max_blocks, len); +} + bool IsBlock0PCF7931(uint8_t *block) { // assuming all RFU bits are set to 0 // if PAC is enabled password is set to 0 @@ -491,11 +512,16 @@ end: reply_ng(CMD_LF_PCF7931_READ, PM3_SUCCESS, (uint8_t *)&best, sizeof(best)); } -static void RealWritePCF7931( +static void SendFramePCF7931(uint32_t *tab, bool ledcontrol); + +// returns PM3_SUCCESS when the tag sent the written block back (read after write). +// *hasBlock tells if that block could be decoded into rawBlock +static int RealWritePCF7931( uint8_t *pass, uint16_t init_delay, int8_t offsetPulseWidth, int8_t offsetPulsePosition, uint8_t address, uint8_t byte, uint8_t data, + uint8_t *rawBlock, bool *hasBlock, bool ledcontrol) { uint32_t tab[PCF7931_FRAME_ENTRIES] = {0}; // data times frame @@ -562,10 +588,50 @@ static void RealWritePCF7931( AddBitPCF7931(1, tab, offsetPulseWidth, offsetPulsePosition);//odd parity // time access memory (640T0) - // Not sure why 335*T0, but should not matter. Since programming should be finished at that point - AddPatternPCF7931((640 + 335)* T0_PCF, 0, 0, tab); + // keep the field up shortly, EEPROM access and the read after write are captured below + AddPatternPCF7931(16 * T0_PCF, 0, 0, tab); - SendCmdPCF7931(tab, ledcontrol); + BigBuf_Clear_keep_EM(); + SendFramePCF7931(tab, ledcontrol); + StopPrecisionCounter(); + + // switch to sampling without dropping the field + FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER | FPGA_LF_ADC_READER_FIELD); + SetAdcMuxFor(ADC_MUXSEL_LOPKD); + FpgaSetupSsc(FPGA_MAJOR_MODE_LF_READER); + StartTicks(); + // the read after write and a few blocks after it are enough + uint32_t len = DoAcquisition(DECIMATION, 8, 0, 0, false, PCF7931_WRITE_CAPTURE_SAMPLES, 0, 0, ledcontrol) >> 3; + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + + uint8_t blocks[PCF7931_WRITE_CAPTURE_BLOCKS][16]; + uint32_t starts[PCF7931_WRITE_CAPTURE_BLOCKS]; + size_t n = DecodePCF7931((uint8_t *)blocks, starts, ARRAYLEN(blocks), len); + *hasBlock = false; + + // on failure there is no read after write and the blocks follow another grid + size_t k = 0; + while (k < n && starts[k] == UINT32_MAX) { + k++; + } + if (k == n) { + return PM3_EFAILED; + } + uint32_t phase = starts[k] % PCF7931_BLOCK_SAMPLES; + if (g_dbglevel >= DBG_EXTENDED) { + Dbprintf("block %u start sample %u phase %u (expected %u..%u)", k, starts[k], phase, PCF7931_RAW_MIN_START, PCF7931_RAW_MAX_START); + } + if (phase < PCF7931_RAW_MIN_START || phase > PCF7931_RAW_MAX_START) { + return PM3_EFAILED; + } + + // the read-after-write block itself was decoded, check the byte + if (starts[k] <= PCF7931_RAW_MAX_START) { + memcpy(rawBlock, blocks[k], 16); + *hasBlock = true; + return (blocks[k][byte & 0x0F] == data) ? PM3_SUCCESS : PM3_EFAILED; + } + return PM3_SUCCESS; } /* Write on a byte of a PCF7931 tag @@ -592,8 +658,19 @@ void WritePCF7931( uint8_t password[7] = {pass1, pass2, pass3, pass4, pass5, pass6, pass7}; - RealWritePCF7931(password, init_delay, offsetPulseWidth, offsetPulsePosition, address, byte, data, ledcontrol); - reply_ng(CMD_LF_PCF7931_WRITE, PM3_SUCCESS, NULL, 0); + uint8_t rawBlock[16] = {0}; + bool hasBlock = false; + int res = PM3_EFAILED; + // rewriting the same byte is harmless; a tag idle for a while often misses the first try + for (int attempt = 0; attempt < PCF7931_WRITE_ATTEMPTS && res != PM3_SUCCESS; attempt++) { + res = RealWritePCF7931(password, init_delay, offsetPulseWidth, offsetPulsePosition, address, byte, data, rawBlock, &hasBlock, ledcontrol); + if (g_dbglevel >= DBG_INFO && res != PM3_SUCCESS) + Dbprintf("write attempt %d not confirmed", attempt + 1); + if (BUTTON_PRESS() || data_available()) + break; + } + // reply carries the read-after-write block when it could be decoded + reply_ng(CMD_LF_PCF7931_WRITE, res, rawBlock, hasBlock ? sizeof(rawBlock) : 0); } @@ -611,6 +688,14 @@ static void WaitUntilPCF7931(uint32_t *elapsed, uint16_t *last, uint32_t target) } void SendCmdPCF7931(uint32_t *tab, bool ledcontrol) { + SendFramePCF7931(tab, ledcontrol); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelay(200); + StopPrecisionCounter(); +} + +// send the frame and leave the field on +static void SendFramePCF7931(uint32_t *tab, bool ledcontrol) { uint16_t u = 0; if (g_dbglevel >= DBG_INFO) { @@ -658,10 +743,6 @@ void SendCmdPCF7931(uint32_t *tab, bool ledcontrol) { } if (ledcontrol) LED_A_OFF(); - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - SpinDelay(200); - - StopPrecisionCounter(); } diff --git a/client/src/cmdlfpcf7931.c b/client/src/cmdlfpcf7931.c index 0ffb7b274..3859d81c6 100644 --- a/client/src/cmdlfpcf7931.c +++ b/client/src/cmdlfpcf7931.c @@ -554,8 +554,28 @@ static int CmdLFPCF7931Write(const char *Cmd) { return PM3_ETIMEOUT; } - PrintAndLogEx(SUCCESS, "Done!"); - PrintAndLogEx(HINT, "Hint: Try " _YELLOW_("`lf pcf7931 reader`") " to verify"); + if (resp.status == PM3_EINVARG) { + PrintAndLogEx(ERR, "Firmware rejected the write request"); + return PM3_EINVARG; + } + + // a good write makes the tag send the written block back (read after write) + bool has_block = (resp.length == PCF7931_BLOCK_SIZE); + if (resp.status != PM3_SUCCESS) { + if (has_block) { + PrintAndLogEx(FAILED, "Tag sent block %u back without the new byte... " _RED_("%s"), block, sprint_hex(resp.data.asBytes, PCF7931_BLOCK_SIZE)); + } else { + PrintAndLogEx(FAILED, "Write not confirmed by the tag"); + PrintAndLogEx(HINT, "Hint: wrong password, write protected block or init delay off. Check with " _YELLOW_("`lf pcf7931 reader`")); + } + return PM3_EFAILED; + } + + if (has_block) { + PrintAndLogEx(SUCCESS, "Write confirmed, block %u now... " _GREEN_("%s"), block, sprint_hex(resp.data.asBytes, PCF7931_BLOCK_SIZE)); + } else { + PrintAndLogEx(SUCCESS, "Write confirmed by tag timing (read after write block not decoded)"); + } return PM3_SUCCESS; } From 28cbc8d1a2747ee2d1510eea222fc6c0847ee1ae Mon Sep 17 00:00:00 2001 From: Gabriele Gristina Date: Wed, 11 Nov 2026 19:48:39 +0100 Subject: [PATCH 5/6] hf mf fchk: report keys and dumps not transferred to emulator memory With `--emu`, `hf mf fchk` printed "Found keys have been transferred to the emulator memory" and returned success whatever mf_elm_set_mem() gave. It also ignored the result of FastDumpWithEcFill(), which itself returned success after "Dump file is PARTIAL complete". The transfer now stops at the first failure with fast mode off, says so and skips the card fill. The fill returns the device status when both keys fail, and the command returns the status that failed. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + client/src/cmdhfmf.c | 26 ++++++++++++++++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38bf4d13a..b4a1eeb9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ 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] +- Fixed `hf mf fchk` - `--emu` reports keys not transferred to emulator memory and a partial card dump into it instead of always succeeding (@matrix) - Fixed `hf mf staticnested` - `--emu` reports keys not transferred to emulator memory instead of always saying they were (@matrix) - Fixed `hf mf eclr` - waits for the device and reports a missing emulator memory instead of always succeeding (@matrix) - Fixed `hf mf nested` - `--emu` reports keys not transferred to emulator memory instead of always saying they were, a failed single sector recovery no longer returns success (@matrix) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index c72e8cc94..a277eb4d5 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -1657,6 +1657,9 @@ static int FastDumpWithEcFill(uint8_t numsectors) { payload.sectorcnt = numsectors; payload.keytype = MF_KEY_A; + // a fill that fails with both keys is reported to the caller + int eml_res = PM3_SUCCESS; + // ecfill key A clearCommandBuffer(); SendCommandNG(CMD_HF_MIFARE_EML_LOAD, (uint8_t *)&payload, sizeof(payload)); @@ -1686,6 +1689,7 @@ static int FastDumpWithEcFill(uint8_t numsectors) { if (resp.status != PM3_SUCCESS) { PrintAndLogEx(FAILED, "fast dump reported back failure w KEY B"); PrintAndLogEx(FAILED, "Dump file is " _RED_("PARTIAL") " complete"); + eml_res = resp.status; } } @@ -1693,7 +1697,7 @@ static int FastDumpWithEcFill(uint8_t numsectors) { return PM3_EFAILED; } - return PM3_SUCCESS; + return eml_res; } static int CmdHF14AMfDump(const char *Cmd) { @@ -4090,6 +4094,8 @@ out: static int CmdHF14AMfChk_fast(const char *Cmd) { CLIParserContext *ctx; + // the result of an emulator memory transfer the command was asked for + int eml_res = PM3_SUCCESS; CLIParserInit(&ctx, "hf mf fchk", "This is a improved checkkeys method speedwise. It checks MIFARE Classic tags sector keys against a dictionary file with keys", "hf mf fchk --mini -k FFFFFFFFFFFF --> Key recovery against MIFARE Mini\n" @@ -4309,12 +4315,20 @@ out: // Disable fast mode on last packet g_conn.block_after_ACK = false; } - mf_elm_set_mem(block, b, 1); + eml_res = mf_elm_set_mem(block, b, 1); + if (eml_res != PM3_SUCCESS) { + g_conn.block_after_ACK = false; + break; + } } - PrintAndLogEx(SUCCESS, "Found keys have been transferred to the emulator memory"); + if (eml_res == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "Found keys have been transferred to the emulator memory"); - if (found_keys == (sectorsCnt << 1)) { - FastDumpWithEcFill(sectorsCnt); + if (found_keys == (sectorsCnt << 1)) { + eml_res = FastDumpWithEcFill(sectorsCnt); + } + } else { + PrintAndLogEx(FAILED, "Found keys have not been transferred to the emulator memory"); } } @@ -4331,7 +4345,7 @@ out2: free(keyBlock); free(e_sector); PrintAndLogEx(NORMAL, ""); - return PM3_SUCCESS; + return eml_res; } static int CmdHF14AMfSmartBrute(const char *Cmd) { From 4f0b81d03e8de933510812fca36324cb01087801 Mon Sep 17 00:00:00 2001 From: Gabriele Gristina Date: Wed, 11 Nov 2026 20:35:35 +0100 Subject: [PATCH 6/6] hf mf chk: report keys not transferred to emulator memory With `--emu`, `hf mf chk` printed "Found keys have been transferred to the emulator memory" and returned success whatever mf_elm_set_mem() gave. It now checks that status, stops the transfer at the first failure with fast mode off, says so and returns the status. With no key found it wrote every trailer back and reported a transfer. It now says "No keys found" and transfers nothing, as `hf mf fchk` does. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + client/src/cmdhfmf.c | 31 +++++++++++++++++++++++++++---- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38bf4d13a..722914f25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ 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] +- Fixed `hf mf chk` - `--emu` reports keys not transferred to emulator memory instead of always saying they were, with no key found it says "No keys found" instead of reporting a transfer (@matrix) - Fixed `hf mf staticnested` - `--emu` reports keys not transferred to emulator memory instead of always saying they were (@matrix) - Fixed `hf mf eclr` - waits for the device and reports a missing emulator memory instead of always succeeding (@matrix) - Fixed `hf mf nested` - `--emu` reports keys not transferred to emulator memory instead of always saying they were, a failed single sector recovery no longer returns success (@matrix) diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index c72e8cc94..528286764 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -4548,6 +4548,8 @@ out: static int CmdHF14AMfChk(const char *Cmd) { CLIParserContext *ctx; + // the result of an emulator memory transfer the command was asked for + int eml_res = PM3_SUCCESS; CLIParserInit(&ctx, "hf mf chk", "Check keys on MIFARE Classic card", "hf mf chk --mini -k FFFFFFFFFFFF --> Check all sectors, all keys against MIFARE Mini\n" @@ -4791,7 +4793,20 @@ out: // else printKeyTable(sectors_cnt, e_sector); - if (transferToEml) { + // with no key found there is nothing to transfer + uint8_t found_keys = 0; + for (int i = 0; i < sectors_cnt; ++i) { + if (e_sector[i].foundKey[0]) { + found_keys++; + } + if (e_sector[i].foundKey[1]) { + found_keys++; + } + } + + if (transferToEml && found_keys == 0) { + PrintAndLogEx(WARNING, "No keys found"); + } else if (transferToEml) { // fast push mode g_conn.block_after_ACK = true; uint8_t block[MFBLOCK_SIZE] = {0x00}; @@ -4812,9 +4827,17 @@ out: // Disable fast mode on last packet g_conn.block_after_ACK = false; } - mf_elm_set_mem(block, blockno, 1); + eml_res = mf_elm_set_mem(block, blockno, 1); + if (eml_res != PM3_SUCCESS) { + g_conn.block_after_ACK = false; + break; + } + } + if (eml_res == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "Found keys have been transferred to the emulator memory"); + } else { + PrintAndLogEx(FAILED, "Found keys have not been transferred to the emulator memory"); } - PrintAndLogEx(SUCCESS, "Found keys have been transferred to the emulator memory"); } if (createDumpFile) { @@ -4837,7 +4860,7 @@ out: } PrintAndLogEx(NORMAL, ""); - return PM3_SUCCESS; + return eml_res; } void showSectorTable(sector_t *k_sector, size_t k_sectors_cnt) {