diff --git a/CHANGELOG.md b/CHANGELOG.md index 63b990f23..15871b6f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Changed `tests/lf_t55xx_writetest.lua` - reads each block three times and names how a bad read differs (`rol1`, `ror5`, `inverted`, `shr1`) instead of only pass/fail (@mfcarroll) - Fixed `lf t55xx detect` - PSK1 now detects at every bit rate and subcarrier. (@iceman1001) - Fixed `lf t55xx detect` - FSK was skipped entirely when the field-clock pair measured as neither legal pair, losing FSK1 at RF/32 and RF/40 and every variant at RF/16 (@iceman1001) +- Fixed `lf t55xx detect` - the block 0 rotation was picked by scan order; the measured broadcast period now settles it (@mfcarroll) +- Fixed `lf t55xx detect` - the psk antenna-settle trim left the graph 160 samples short, so the graph-sample anchor was discarded on most block reads (@mfcarroll) +- Fixed `lf psk demod` - lead-in samples were accepted as a phase shift, complementing the rest of the word (@mfcarroll) +- Fixed `lf fsk demod` - a leading run too short to be a bit was forced to one, fabricating a bit and shifting the word (@mfcarroll) +- Fixed `lf nrz demod` - the samples before the first level change were counted as bits, rotating the word whenever that edge moved (@mfcarroll) - Fixed `lf t55xx dump/read` - blocks were extracted at a bit offset cached from the last `detect` The offset is now anchored in graph samples (@iceman1001) - Fixed `lf t55xx write --verify` - a successful write could be reported as a validation failure, both from the rotated read above and from the pre-write config decoding the post-write signal into garbage (@iceman1001) - Fixed `lf t55xx detect` - the automatic detect after a block 0 write reported a password that was never supplied (@iceman1001) diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index 278035352..eb1006e90 100644 --- a/client/src/cmdlft55xx.c +++ b/client/src/cmdlft55xx.c @@ -61,6 +61,8 @@ static bool t55xx_psk3_probe(bool usepwd, uint32_t password, uint8_t downlink_mo static uint8_t t55xx_measure_broadcast_blocks(bool usepwd, uint32_t password, uint8_t downlink_mode); static uint8_t t55xx_measure_broadcast_blocks_once(bool usepwd, uint32_t password, uint8_t downlink_mode); static size_t t55xx_psk3_resolve(uint8_t nblk, uint32_t *only); +static bool t55xx_block0_rotation_ambiguous(void); +static bool t55xx_resolve_block0_rotation(uint8_t nblk); // Default configuration static t55xx_conf_block_t config = { @@ -80,6 +82,13 @@ static t55xx_memory_item_t cardmem[T55x7_BLOCK_COUNT] = {{0}}; // Regular read mode cycles several blocks and a buffer loaded from a file could be either static bool s_block_read_capture = false; +// samples dropped from the head of a capture before psk demodulation +#define T55XX_PSK_SETTLE_TRIM 160 + +// non-zero while the capture is trimmed, so an anchor recorded inside the trim +// still names an untrimmed sample +static int32_t s_sample_bias = 0; + // A block read repeats one 32 bit word for as long as the field is on. // `offset` is a bit index into a demod buffer that no longer exists once the next acquisition lands, // and the demodulators do not all start on the same bit: @@ -88,16 +97,36 @@ static bool s_block_read_capture = false; static void t55xx_anchor(t55xx_conf_block_t *c, uint8_t offset) { c->offset = offset; c->anchor_valid = (g_DemodClock > 0); - c->anchor_sample = g_DemodStartIdx + ((int32_t)offset * g_DemodClock); - c->anchor_tracelen = (int32_t)g_GraphTraceLen; + c->anchor_sample = g_DemodStartIdx + ((int32_t)offset * g_DemodClock) + s_sample_bias; + c->anchor_tracelen = (int32_t)g_GraphTraceLen + s_sample_bias; } // records a detect candidate against the demodulation that is loaded right now static void t55xx_record_hit(t55xx_conf_block_t *t) { t->block0 = PackBits(t->offset, 32, g_DemodBuffer); t->anchor_valid = (g_DemodClock > 0); - t->anchor_sample = g_DemodStartIdx + ((int32_t)t->offset * g_DemodClock); - t->anchor_tracelen = (int32_t)g_GraphTraceLen; + t->anchor_sample = g_DemodStartIdx + ((int32_t)t->offset * g_DemodClock) + s_sample_bias; + t->anchor_tracelen = (int32_t)g_GraphTraceLen + s_sample_bias; +} + +// skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) +static buffer_savestate_t t55xx_psk_trim_head(void) { + buffer_savestate_t st = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); + st.offset = g_GridOffset; + + char ltrim[16]; + snprintf(ltrim, sizeof(ltrim), "-i %d", T55XX_PSK_SETTLE_TRIM); + CmdLtrim(ltrim); + + s_sample_bias = T55XX_PSK_SETTLE_TRIM; + return st; +} + +static void t55xx_psk_untrim_head(buffer_savestate_t st) { + s_sample_bias = 0; + // restore_bufferS32 returns the length it put back; dropping it leaves the trim in place + g_GraphTraceLen = restore_bufferS32(st, g_GraphBuffer); + g_GridOffset = st.offset; } // the bit offset to read a block at in the demod buffer loaded right now @@ -1247,6 +1276,22 @@ static int CmdT55xxDetect(const char *Cmd) { } } + // Several rotations of the word can read as a configuration and detect takes the first the + // scan reaches. The broadcast period is the tag's own answer to which is real + bool rerotated = false; + + if (found && use_gb == false && t55xx_block0_rotation_ambiguous()) { + + if (nblk == 0) { + nblk = t55xx_measure_broadcast_blocks(config.usepwd, config.pwd, config.downlink_mode); + config.broadcast_blocks = nblk; + } + + if (nblk) { + rerotated = t55xx_resolve_block0_rotation(nblk); + } + } + if (found) { printConfiguration(config); @@ -1255,6 +1300,10 @@ static int CmdT55xxDetect(const char *Cmd) { PrintAndLogEx(SUCCESS, "Broadcast repeats every " _GREEN_("%u") " block(s), so maxblock is a multiple of %u", nblk, nblk); } + if (rerotated) { + PrintAndLogEx(SUCCESS, "Block 0 " _GREEN_("re-anchored") " - the first reading was a rotation the broadcast period contradicts"); + } + if (psk2_out) { PrintAndLogEx(SUCCESS, "psk2 " _RED_("ruled out") " - the psk2 reading of block 0 carries a maxblock contradicted by the broadcast"); } else if (favoured) { @@ -1595,9 +1644,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l if (mod == PM3_MOD_PSK) { - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; - CmdLtrim("-i 160"); + buffer_savestate_t saveState = t55xx_psk_trim_head(); for (int inv = 0; inv < 2; inv++) { if (PSKDemod(fitclk, inv, PM3_T55_FALLBACK_MAXERR, false) != PM3_SUCCESS) { @@ -1631,8 +1678,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l } } - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + t55xx_psk_untrim_head(saveState); if (*hits == before && coherent_ok) { t55xx_psk_coherent(fitclk, clk, tests, hits, downlink_mode); @@ -1980,10 +2026,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 clk = GetPskClock("", false); if (clk > 0) { // allow undo - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; - // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) - CmdLtrim("-i 160"); + buffer_savestate_t saveState = t55xx_psk_trim_head(); if ((PSKDemod(0, 0, 6, false) == PM3_SUCCESS) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) { tests[hits].modulation = DEMOD_PSK1; tests[hits].bitrate = bitRate; @@ -2019,8 +2062,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 } // inverse waves does not affect this demod //undo trim samples - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + t55xx_psk_untrim_head(saveState); // t55xx_search_config_psk(g_GraphBuffer, 1); // t55xx_search_config_psk(g_GraphBuffer, 2); } @@ -2565,6 +2607,167 @@ static void windows_build(t55_windows_t *w) { } } +// the checks a 32 bit word has to pass to be a configuration block for `mode` at +// `clk`, independent of where in a demodulation it was found +static bool t55xx_block0_plausible(uint32_t block0, uint8_t mode, uint8_t clk, int *fndBitRate) { + + uint8_t safer = (block0 >> 28) & 0x0F; //master key + uint8_t resv = (block0 >> 24) & 0x0F; //was 7 // should be only 4 bits if extended mode + // 2nibble must be zeroed. + + if (resv > 0x00) { + return false; + } + + // The master key is 0, or 6 or 9 to select extended mode + if (safer != 0x0 && safer != 0x6 && safer != 0x9) { + return false; + } + + int bitRate = (block0 >> 18) & 0x3F; //bit rate (includes extended mode part of rate) + uint8_t extend = (block0 >> 17) & 0x01; //bit 15 extended mode + uint8_t modread = (block0 >> 12) & 0x1F; + //pskcr = (block0 >> 10) & 0x03; //could check psk cr + //bit 24, 30, 31 are otp, fast write and inverse data - all settable, so no help here + + // Bit 14 selects extended mode, and extended mode only exists under master key 6 or 9. + // Set with any other key the word is not a valid configuration + if (extend && safer != 0x6 && safer != 0x9) { + return false; + } + + //if extended mode + bool extMode = ((safer == 0x6 || safer == 0x9) && extend) ? true : false; + + if (extMode == false) { + + if (bitRate > 7) { + return false; + } + + if (testBitRate(bitRate, clk) == false) { + return false; + } + + } else { //extended mode bitrate = same function to calc bitrate as em4x05 + if (EM4x05_GET_BITRATE(bitRate) != clk) { + return false; + } + } + + //test modulation + if (testModulation(mode, modread) == false) { + return false; + } + + if (fndBitRate) { + *fndBitRate = bitRate; + } + return true; +} + +// true when the maxblock and sequence terminator in `block0` could have produced +// an `nblk` block broadcast period +static bool t55xx_block0_fits_period(uint32_t block0, uint8_t nblk) { + + // ST adds four bit periods per cycle, so a whole number of 32 + // bit blocks rules it out. leans on the measurement, not on + // config.ST, which the psk paths hardcode rather than detect + if (((block0 >> 3) & 1) != 0) { + return false; + } + + const uint8_t mb = (block0 >> 5) & 0x07; + return (mb != 0 && (mb % nblk) == 0); +} + +// how many distinct rotations of `block0` read as a configuration for `mode` at `clk`. more than +// one means detect's answer was scan order, not evidence. `nblk` 0 skips the period constraint +static size_t t55xx_block0_rotations(uint32_t block0, uint8_t mode, uint8_t clk, uint8_t nblk, uint32_t *only) { + + uint32_t seen[32] = {0}; + size_t n = 0; + + for (uint8_t r = 0; r < 32; r++) { + + const uint32_t v = (r == 0) ? block0 : ((block0 << r) | (block0 >> (32 - r))); + + if (t55xx_block0_plausible(v, mode, clk, NULL) == false) { + continue; + } + + if (nblk != 0 && t55xx_block0_fits_period(v, nblk) == false) { + continue; + } + + // a word that is its own rotation offers the same value twice + bool dup = false; + for (size_t i = 0; i < n; i++) { + if (seen[i] == v) { + dup = true; + break; + } + } + if (dup) { + continue; + } + + seen[n++] = v; + } + + if (n == 1 && only != NULL) { + *only = seen[0]; + } + return n; +} + +// the clock the detected bit rate names, for the rotation helpers above +static uint8_t t55xx_config_clock(void) { + static const uint8_t basic[] = {8, 16, 32, 40, 50, 64, 100, 128}; + return basic[config.bitrate & 0x07]; +} + +// more than one rotation of the detected block 0 reads as a configuration +static bool t55xx_block0_rotation_ambiguous(void) { + + if (config.Q5 || config.block0 == 0) { + return false; + } + + return (t55xx_block0_rotations(config.block0, config.modulation, t55xx_config_clock(), 0, NULL) > 1); +} + +// Settle which rotation is real with the tag's own broadcast period and re-anchor on it. Nothing +// surviving means the measurement disagrees with every reading, so leave the detected word alone +static bool t55xx_resolve_block0_rotation(uint8_t nblk) { + + uint32_t only = 0; + if (t55xx_block0_rotations(config.block0, config.modulation, t55xx_config_clock(), nblk, &only) != 1) { + return false; + } + + if (only == config.block0) { + return false; + } + + // measuring the period left a regular read in the demod buffer + if (AcquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, config.usepwd, config.pwd, config.downlink_mode) == false) { + return false; + } + + if (DecodeT55xxBlock() == false) { + return false; + } + + if (t55xx_stream_holds(only) == false) { + return false; + } + + // keep the offset t55xx_stream_holds just anchored + SetConfigWithBlock0Ex(only, config.offset, config.Q5); + return true; +} + static bool test_scan(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, uint16_t start, uint16_t end, const t55_windows_t *w, uint16_t need, bool need_stride) { @@ -2581,58 +2784,8 @@ static bool test_scan(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t cl continue; } - uint8_t safer = PackBits(si, 4, g_DemodBuffer); - si += 4; //master key - uint8_t resv = PackBits(si, 4, g_DemodBuffer); - si += 4; //was 7 & +=7+3 // should be only 4 bits if extended mode - // 2nibble must be zeroed. - - if (resv > 0x00) { - continue; - } - - // The master key is 0, or 6 or 9 to select extended mode - if (safer != 0x0 && safer != 0x6 && safer != 0x9) { - continue; - } - - int bitRate = PackBits(si, 6, g_DemodBuffer); - si += 6; //bit rate (includes extended mode part of rate) - uint8_t extend = PackBits(si, 1, g_DemodBuffer); - si += 1; //bit 15 extended mode - uint8_t modread = PackBits(si, 5, g_DemodBuffer); - si += 5 + 2 + 1; - //uint8_t pskcr = PackBits(si, 2, g_DemodBuffer); si += 2+1; //could check psk cr - //uint8_t nml01 = PackBits(si, 1, g_DemodBuffer); si += 1+5; //bit 24, 30, 31 could be tested for 0 if not extended mode - //uint8_t nml02 = PackBits(si, 2, g_DemodBuffer); si += 2; - - // Bit 14 selects extended mode, and extended mode only exists under master key 6 or 9. - // Set with any other key the word is not a valid configuration - if (extend && safer != 0x6 && safer != 0x9) { - continue; - } - - //if extended mode - bool extMode = ((safer == 0x6 || safer == 0x9) && extend) ? true : false; - - if (extMode == false) { - - if (bitRate > 7) { - continue; - } - - if (testBitRate(bitRate, clk) == false) { - continue; - } - - } else { //extended mode bitrate = same function to calc bitrate as em4x05 - if (EM4x05_GET_BITRATE(bitRate) != clk) { - continue; - } - } - - //test modulation - if (testModulation(mode, modread) == false) { + int bitRate = 0; + if (t55xx_block0_plausible(PackBits(si, 32, g_DemodBuffer), mode, clk, &bitRate) == false) { continue; } @@ -2910,14 +3063,7 @@ int printConfiguration(t55xx_conf_block_t b) { if (b.broadcast_blocks) { size_t kept = 0; for (size_t i = 0; i < ncand; i++) { - const uint8_t mb = (cand[i] >> 5) & 0x07; - // ST adds four bit periods per cycle, so a whole number of 32 - // bit blocks rules it out. leans on the measurement, not on - // config.ST, which the psk paths hardcode rather than detect - if (((cand[i] >> 3) & 1) != 0) { - continue; - } - if (mb != 0 && (mb % b.broadcast_blocks) == 0) { + if (t55xx_block0_fits_period(cand[i], b.broadcast_blocks)) { cand[kept++] = cand[i]; } } diff --git a/common/lfdemod.c b/common/lfdemod.c index 33ee616cc..77c3f6308 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -547,13 +547,16 @@ size_t pskFindFirstPhaseShift(const uint8_t *samples, size_t size, uint8_t *curP uint16_t avgWaveVal = 0, lastAvgWaveVal; size_t i = waveStart, waveEnd, waveLenCnt, firstFullWave; + // waveStart starts as wherever the caller began looking, so the first length is part of a wave, + // not a wave, and judging it accepts a shift that is not there. Baseline on the first peak. + bool wave_from_peak = false; for (; i < loopCnt; i++) { // find peak // was "samples[i] + fc" but why? must have been used to weed out some wave error... removed.. if (samples[i] < samples[i + 1] && samples[i + 1] >= samples[i + 2]) { waveEnd = i + 1; if (g_debugMode == 2) prnt("DEBUG PSK: waveEnd: %zu, waveStart: %zu", waveEnd, waveStart); waveLenCnt = waveEnd - waveStart; - if (waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc + 8)) { //not first peak and is a large wave but not out of whack + if (wave_from_peak && waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc + 8)) { //not first peak and is a large wave but not out of whack lastAvgWaveVal = avgWaveVal / (waveLenCnt); firstFullWave = waveStart; *fullWaveLen = waveLenCnt; @@ -562,6 +565,7 @@ size_t pskFindFirstPhaseShift(const uint8_t *samples, size_t size, uint8_t *curP return firstFullWave; } waveStart = i + 1; + wave_from_peak = true; avgWaveVal = 0; } avgWaveVal += samples[i + 2]; @@ -1902,18 +1906,31 @@ int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, const int *invert, int *s if (dest[i] <= low) bit = 0; dest[i] = bit; } - //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit) + // start on the first level change: it is the earliest sample known to be a + // bit boundary. counting the samples before it as bits rotated the stream + // whenever that edge moved by one, and left startIdx naming no sample size_t lastBit = 0; size_t numBits = 0; + bool anchored = false; for (i = 21; i < *size - 20; i++) { + + bool edge = (dest[i] != dest[i - 1]); + + if (anchored == false) { + if (edge == false) { + continue; + } + *startIdx = (int)i; + if (g_debugMode == 2) prnt("DEBUG NRZ: startIdx %i", *startIdx); + lastBit = i - 1; + anchored = true; + continue; + } + //if transition detected or large number of same bits - store the passed bits - if (dest[i] != dest[i - 1] || (i - lastBit) == (10 * *clk)) { + if (edge || (i - lastBit) == (10 * *clk)) { memset(dest + numBits, dest[i - 1] ^ *invert, (i - lastBit + (*clk / 4)) / *clk); numBits += (i - lastBit + (*clk / 4)) / *clk; - if (lastBit == 0) { - *startIdx = i - (numBits * *clk); - if (g_debugMode == 2) prnt("DEBUG NRZ: startIdx %i", *startIdx); - } lastBit = i - 1; } } @@ -2038,6 +2055,13 @@ static size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t clk, uint8_t in // 0->1 crossing n = (n * fchigh + hclk) / clk; + // A leading run that rounds to no bits is lead-in, not data. Forcing it to one fabricates + // a bit and shifts the word; mid-stream a zero would lose a bit the tag did send. + if (n == 0 && numBits == 0) { + lastval = dest[i]; + continue; + } + if (n == 0) n = 1; @@ -2141,14 +2165,22 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, const int *invert, i = findModStart(dest, *size, fc); //find first phase shift firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, i, fc, &fullWaveLen); - if (firstFullWave == 0) { - // no phase shift detected - could be all 1's or 0's - doesn't matter where we start - // so skip a little to ensure we are past any Start Signal - firstFullWave = 160; - memset(dest, curPhase, firstFullWave / *clock); - } else { - memset(dest, curPhase ^ 1, firstFullWave / *clock); - } + } + + // A first shift less than a bit period in is lead-in, not data. Counting it toggles curPhase + // once too often, and the emitted bit is the running phase, so the rest of the word inverts. + const size_t bit_period = (size_t)(*clock); + if (firstFullWave != 0 && firstFullWave < bit_period) { + curPhase = *invert; + fullWaveLen = 0; + firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, bit_period, fc, &fullWaveLen); + } + + if (firstFullWave == 0) { + // no phase shift detected - could be all 1's or 0's - doesn't matter where we start + // so skip a little to ensure we are past any Start Signal + firstFullWave = 160; + memset(dest, curPhase, firstFullWave / *clock); } else { memset(dest, curPhase ^ 1, firstFullWave / *clock); }