diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f1d1f1b6..ad370b4ab 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] +- Fixed `lf em 4x50 rdbl/info/dump`, `lf search` - RM was sent into the tag data instead of the second listen window on strong, AC-coupled signals, so every command failed; reads now retry within 1 s (@abou28) +- Added `lf em 4x50 config` - runtime EM4x50 reader timings, and `lf_em4x50_tune.lua` to sweep them; extended debug level captures the raw exchange for `data samples` (@abou28) - Updated `/Getting_Started_With_PM5.md` (@innocentbystanderproxmark) - Fixed `hf seos pacs`/`write` - 2K3DES GET/UPDATE DATA no longer fails silently with exit 236; print APDU exchange errors, check DES-CMAC, decode SELECT `85` at its real length, and use short-form `85` when the cryptogram is under 128 bytes - Fixed client build with `-march=x86-64-v3` (CentOS/RHEL 10 default) - false `-Wstringop-overflow` in the EMV AID list table (@r3wretrhy) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 995573916..ab0ca0942 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -2065,6 +2065,14 @@ static void PacketReceived(PacketCommandNG *packet) { em4x50_chk((const char *)packet->data.asBytes, true); break; } + case CMD_LF_EM4X50_CONFIG: { + if (packet->length < sizeof(em4x50_config_t)) { + reply_ng(CMD_LF_EM4X50_CONFIG, PM3_EINVARG, NULL, 0); + break; + } + em4x50_config((const em4x50_config_t *)packet->data.asBytes); + break; + } #endif #ifdef WITH_EM4x70 diff --git a/armsrc/em4x50.c b/armsrc/em4x50.c index eeaf4d3d3..3c5b35e40 100644 --- a/armsrc/em4x50.c +++ b/armsrc/em4x50.c @@ -48,7 +48,6 @@ #define EM4X50_T_TAG_WAITING_FOR_SIGNAL 75 #define EM4X50_T_WAITING_FOR_DBLLIW 1550 #define EM4X50_T_WAITING_FOR_ACK 4 -#define EM4X50_T_TOLERANCE 8 #define EM4X50_T_ZERO_DETECTION 3 // timeout values (empirical) for simulation mode (may vary with regard to reader) @@ -64,9 +63,26 @@ #define EM4X50_TAG_MAX_NO_BYTES 136 #define EM4X50_TIMEOUT_PULSE_EVAL (4 * EM4X50_T_TAG_FULL_PERIOD * CYCLES2TICKS) // 4bit data periods +// read retries, no new attempt after the window (ms) to stay below the client timeout +#define EM4X50_COMMAND_RETRIES 5 +#define EM4X50_T_RETRY_WINDOW 1000 + uint8_t g_High = 190; uint8_t g_Low = 60; +// reader timings, changed at runtime by `lf em 4x50 config` +// centres of the working ranges found by lf_em4x50_tune.lua on a PM3 Easy +// (500 uH antenna): tol 5-15, gap end 28-50, rm 104-164 +#define EM4X50_CONFIG_DEFAULT { \ + .mode = EM4X50_CONFIG_GET, \ + .threshold = 75, \ + .tolerance = 10, \ + .gap_start = 7, \ + .gap_end = 38, \ + .rm_delay = 132, \ +} +static em4x50_config_t s_cfg = EM4X50_CONFIG_DEFAULT; + // indication whether a previous login has been successful, so operations // that require authentication can be handled bool g_Login = false; @@ -77,6 +93,51 @@ bool g_WritePasswordProcess = false; // if reader sends a different password than "expected" -> save it uint32_t g_Password = 0; +// raw ADC capture of a reader exchange into BigBuf (debug level extended), +// fetch with `data samples` +static uint8_t *s_cap = NULL; +static uint32_t s_cap_len = 0; +static uint32_t s_cap_max = 0; + +static void capture_start(void) { + s_cap_len = 0; + s_cap_max = 0; + s_cap = NULL; + if (g_dbglevel >= DBG_EXTENDED) { + BigBuf_free_keep_EM(); + s_cap = BigBuf_get_addr(); + s_cap_max = BigBuf_max_traceLen(); + } +} + +static void capture_report(void) { + if (s_cap != NULL) { + Dbprintf("em4x50 capture: %u samples, high %u low %u", s_cap_len, g_High, g_Low); + } +} + +static inline uint8_t read_sample(void) { + uint8_t s = (uint8_t)FPGA_SSC_RX_Value(); + if (s_cap_len < s_cap_max) { + s_cap[s_cap_len++] = s; + } + return s; +} + +static inline void poll_sample(void) { + if (FPGA_SSC_RX_Ready()) { + read_sample(); + } +} + +// busy wait, keeps sampling so the capture stays continuous +static void reader_wait_cycles(uint32_t cycles) { + uint32_t tval = GetTicks(); + while (GetTicks() - tval < cycles * CYCLES2TICKS) { + poll_sample(); + } +} + // extract and check parities // return result of parity check and extracted plain data static bool extract_parities(uint64_t word, uint32_t *data) { @@ -174,7 +235,7 @@ void em4x50_setup_sim(void) { static bool get_signalproperties(void) { bool signal_found = false; - int no_periods = 32, pct = 75, noise = 140; + int no_periods = 32, pct = s_cfg.threshold, noise = 140; uint8_t sample_ref = 127; uint8_t sample_max_mean = 0; uint8_t sample_max[no_periods]; @@ -238,14 +299,14 @@ static bool get_signalproperties(void) { static bool invalid_bit(void) { // get sample at 3/4 of bit period - WaitUS(EM4X50_T_TAG_THREE_QUARTER_PERIOD * CYCLES2MUSEC); + reader_wait_cycles(EM4X50_T_TAG_THREE_QUARTER_PERIOD); FPGA_SSC_RX_READY_WAIT(); - uint8_t sample = (uint8_t)FPGA_SSC_RX_Value(); + uint8_t sample = read_sample(); // wait until end of bit period - WaitUS(EM4X50_T_TAG_QUARTER_PERIOD * CYCLES2MUSEC); + reader_wait_cycles(EM4X50_T_TAG_QUARTER_PERIOD); // bit in "undefined" state? if (sample <= g_High && sample >= g_Low) @@ -261,11 +322,11 @@ static uint32_t get_pulse_length(void) { // iterates pulse lengths (low -> high -> low) FPGA_SSC_RX_READY_WAIT(); // Wait for valid data received. - volatile uint8_t sample = (uint8_t)FPGA_SSC_RX_Value(); + volatile uint8_t sample = read_sample(); while (sample > g_Low && (GetTicks() < timeout)) { if (FPGA_SSC_RX_Ready()) { - sample = (uint8_t)FPGA_SSC_RX_Value(); + sample = read_sample(); } } @@ -277,7 +338,7 @@ static uint32_t get_pulse_length(void) { while (sample < g_High && (GetTicks() < timeout)) { if (FPGA_SSC_RX_Ready()) { - sample = (uint8_t)FPGA_SSC_RX_Value(); + sample = read_sample(); } } @@ -287,7 +348,7 @@ static uint32_t get_pulse_length(void) { while (sample > g_Low && (GetTicks() < timeout)) { if (FPGA_SSC_RX_Ready()) { - sample = (uint8_t)FPGA_SSC_RX_Value(); + sample = read_sample(); } } @@ -298,10 +359,21 @@ static uint32_t get_pulse_length(void) { return GetTicks() - start_ticks; } +// true if the signal stays below g_High for +static bool no_rising_edge(uint32_t cycles) { + uint32_t tval = GetTicks(); + while (GetTicks() - tval < cycles * CYCLES2TICKS) { + if (FPGA_SSC_RX_Ready() && (read_sample() >= g_High)) { + return false; + } + } + return true; +} + // check if pulse length corresponds to given length static bool check_pulse_length(uint32_t pl, int length) { - return ((pl >= (length - EM4X50_T_TOLERANCE) * CYCLES2TICKS) && - (pl <= (length + EM4X50_T_TOLERANCE) * CYCLES2TICKS)); + return ((pl >= (length - s_cfg.tolerance) * CYCLES2TICKS) && + (pl <= (length + s_cfg.tolerance) * CYCLES2TICKS)); } // send single bit according to EM4x50 application note and datasheet @@ -313,24 +385,24 @@ static void em4x50_reader_send_bit(int bit) { if (bit == 0) { // disable modulation (activate the field) for 7 cycles of carrier - // period (Opt64) + // period (Opt64), set by gap_start Gpio_SSC_DOUT_Low(); - while (GetTicks() - tval < 7 * CYCLES2TICKS); + while (GetTicks() - tval < s_cfg.gap_start * CYCLES2TICKS) poll_sample(); // enable modulation (drop the field) for remaining first // half of bit period Gpio_SSC_DOUT_High(); - while (GetTicks() - tval < EM4X50_T_TAG_HALF_PERIOD * CYCLES2TICKS); + while (GetTicks() - tval < s_cfg.gap_end * CYCLES2TICKS) poll_sample(); // disable modulation for second half of bit period Gpio_SSC_DOUT_Low(); - while (GetTicks() - tval < EM4X50_T_TAG_FULL_PERIOD * CYCLES2TICKS); + while (GetTicks() - tval < EM4X50_T_TAG_FULL_PERIOD * CYCLES2TICKS) poll_sample(); } else { // bit = "1" means disable modulation for full bit period Gpio_SSC_DOUT_Low(); - while (GetTicks() - tval < EM4X50_T_TAG_FULL_PERIOD * CYCLES2TICKS); + while (GetTicks() - tval < EM4X50_T_TAG_FULL_PERIOD * CYCLES2TICKS) poll_sample(); } } @@ -424,13 +496,12 @@ static int find_double_listen_window(bool bcommand) { // command request has to be sent) has gone, so if a // second window follows - sync on this to issue a command - // skip the next bit... - WaitUS(EM4X50_T_TAG_FULL_PERIOD * CYCLES2MUSEC); + // no rising edge for the next two bits means this is + // the second listen window (data has one per bit) + uint32_t window = MIN(s_cfg.rm_delay, 2 * EM4X50_T_TAG_FULL_PERIOD - s_cfg.tolerance); + if (no_rising_edge(window)) { - // ...and check if the following bit does make sense - // (if not it is the correct position within the second - // listen window) - if (invalid_bit()) { + reader_wait_cycles(s_cfg.rm_delay - window); // send RM for request mode em4x50_reader_send_bit(0); @@ -459,6 +530,7 @@ static int find_double_listen_window(bool bcommand) { // function is used to check whether a tag on the proxmark is an // EM4x50 tag or not -> speed up "lf search" process static bool find_em4x50_tag(void) { + capture_start(); return find_single_listen_window(); } @@ -498,7 +570,7 @@ static bool check_ack(bool bliw) { // wait for 2 bits (remaining "bit" of ACK signal + first // "bit" of listen window) - WaitUS(2 * EM4X50_T_TAG_FULL_PERIOD * CYCLES2MUSEC); + reader_wait_cycles(2 * EM4X50_T_TAG_FULL_PERIOD); // check for listen window (if first bit cannot be interpreted // as a valid bit it must belong to a listen window) @@ -623,7 +695,7 @@ static int login(uint32_t password) { // send password em4x50_reader_send_word(password); - WaitUS(EM4X50_T_TAG_TPP * CYCLES2MUSEC); + reader_wait_cycles(EM4X50_T_TAG_TPP); // check if ACK is returned if (check_ack(false)) @@ -718,6 +790,7 @@ void em4x50_login(const uint32_t *password, bool ledcontrol) { if (ledcontrol) LEDsoff(); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); StopTicks(); + capture_report(); reply_ng(CMD_LF_EM4X50_LOGIN, status, NULL, 0); } @@ -894,6 +967,35 @@ static int selective_read(uint32_t addresses, uint32_t *words) { return status; } +// optional login followed by a selective read, retried within +// EM4X50_T_RETRY_WINDOW since a missed listen window is not fatal +static int login_and_read(const em4x50_data_t *etd, uint32_t addresses, uint32_t *words) { + int status = PM3_EFAILED; + uint32_t tstart = GetTicks(); + + for (int i = 0; i < EM4X50_COMMAND_RETRIES; i++) { + + if (BUTTON_PRESS()) { + return PM3_EOPABORTED; + } + + status = PM3_SUCCESS; + + // try to login with given password + if (etd->pwd_given) + status = login(etd->password1); + + if (status == PM3_SUCCESS) + status = selective_read(addresses, words); + + if ((status == PM3_SUCCESS) || (GetTicks() - tstart > EM4X50_T_RETRY_WINDOW * 1500)) { + break; + } + } + + return status; +} + // reads by using "selective read mode" -> bidirectional communication void em4x50_read(const em4x50_data_t *etd, bool ledcontrol) { int status = PM3_EFAILED; @@ -910,21 +1012,15 @@ void em4x50_read(const em4x50_data_t *etd, bool ledcontrol) { LED_D_ON(); } - bool blogin = true; - - // try to login with given password - if (etd->pwd_given) - blogin = (login(etd->password1) == PM3_SUCCESS); - // only one word has to be read -> first word read = last word read - if (blogin) - status = selective_read(etd->addresses, words); + status = login_and_read(etd, etd->addresses, words); } if (ledcontrol) LEDsoff(); Gpio_SSC_DOUT_Low(); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); StopTicks(); + capture_report(); reply_ng(CMD_LF_EM4X50_READ, status, (uint8_t *)words, EM4X50_TAG_MAX_NO_BYTES); } @@ -942,20 +1038,15 @@ void em4x50_info(const em4x50_data_t *etd, bool ledcontrol) { LED_D_ON(); } - bool blogin = true; - // login with given password - if (etd->pwd_given) - blogin = (login(etd->password1) == PM3_SUCCESS); - - if (blogin) { - // read addresses from fwr = 0 to lwr = 33 (0x21) - status = selective_read(0x00002100, words); - } + // login with given password, then + // read addresses from fwr = 0 to lwr = 33 (0x21) + status = login_and_read(etd, 0x00002100, words); } if (ledcontrol) LEDsoff(); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); StopTicks(); + capture_report(); reply_ng(CMD_LF_EM4X50_INFO, status, (uint8_t *)words, EM4X50_TAG_MAX_NO_BYTES); } @@ -980,9 +1071,32 @@ void em4x50_reader(bool ledcontrol) { Gpio_SSC_DOUT_Low(); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); StopTicks(); + capture_report(); reply_ng(CMD_LF_EM4X50_READER, now, (uint8_t *)words, 4 * now); } +// get, set or reset reader timings, replies with the active settings +void em4x50_config(const em4x50_config_t *cfg) { + int status = PM3_SUCCESS; + + if (cfg->mode == EM4X50_CONFIG_RESET) { + s_cfg = (em4x50_config_t)EM4X50_CONFIG_DEFAULT; + } else if (cfg->mode == EM4X50_CONFIG_SET) { + // gap must fit in one bit period, RM within the second listen window + if ((cfg->threshold < 1) || (cfg->threshold > 100) || + (cfg->tolerance < 1) || (cfg->tolerance >= EM4X50_T_TAG_QUARTER_PERIOD) || + (cfg->gap_start >= cfg->gap_end) || (cfg->gap_end >= EM4X50_T_TAG_FULL_PERIOD) || + (cfg->rm_delay < 1) || (cfg->rm_delay > 5 * EM4X50_T_TAG_FULL_PERIOD)) { + status = PM3_EINVARG; + } else { + s_cfg = *cfg; + s_cfg.mode = EM4X50_CONFIG_GET; + } + } + + reply_ng(CMD_LF_EM4X50_CONFIG, status, (uint8_t *)&s_cfg, sizeof(s_cfg)); +} + // writes to specified static int write(uint32_t word, uint32_t addresses) { @@ -1003,7 +1117,7 @@ static int write(uint32_t word, uint32_t addresses) { } else { // wait for T0 * EM4X50_T_TAG_TWA (write access time) - WaitUS(EM4X50_T_TAG_TWA * CYCLES2MUSEC); + reader_wait_cycles(EM4X50_T_TAG_TWA); // look for ACK sequence if (check_ack(false)) { @@ -1011,7 +1125,7 @@ static int write(uint32_t word, uint32_t addresses) { // now EM4x50 needs T0 * EM4X50_T_TAG_TWEE (EEPROM write time = 3.2ms = 50 * 64 periods) // for saving data and should return with ACK for (int i = 0; i < 50; i++) { - WaitUS(EM4X50_T_TAG_FULL_PERIOD * CYCLES2MUSEC); + reader_wait_cycles(EM4X50_T_TAG_FULL_PERIOD); } if (check_ack(false)) @@ -1042,7 +1156,7 @@ static int write_password(uint32_t password, uint32_t new_password) { } else { // wait for T0 * EM4x50_T_TAG_TPP (processing pause time) - WaitUS(EM4X50_T_TAG_TPP * CYCLES2MUSEC); + reader_wait_cycles(EM4X50_T_TAG_TPP); // look for ACK sequence and send rm request // during following listen window @@ -1052,14 +1166,14 @@ static int write_password(uint32_t password, uint32_t new_password) { em4x50_reader_send_word(new_password); // wait for T0 * EM4X50_T_TAG_TWA (write access time) - WaitUS(EM4X50_T_TAG_TWA * CYCLES2MUSEC); + reader_wait_cycles(EM4X50_T_TAG_TWA); if (check_ack(false)) { // now EM4x50 needs T0 * EM4X50_T_TAG_TWEE (EEPROM write time = 3.2ms = 50 * 64 periods) // for saving data and should return with ACK for (int i = 0; i < 50; i++) { - WaitUS(EM4X50_T_TAG_FULL_PERIOD * CYCLES2MUSEC); + reader_wait_cycles(EM4X50_T_TAG_FULL_PERIOD); } if (check_ack(false)) @@ -1137,6 +1251,7 @@ void em4x50_write(const em4x50_data_t *etd, bool ledcontrol) { if (ledcontrol) LEDsoff(); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); StopTicks(); + capture_report(); reply_ng(CMD_LF_EM4X50_WRITE, status, (uint8_t *)words, EM4X50_TAG_MAX_NO_BYTES); } diff --git a/armsrc/em4x50.h b/armsrc/em4x50.h index eb52c36e5..afa2adc36 100644 --- a/armsrc/em4x50.h +++ b/armsrc/em4x50.h @@ -37,5 +37,6 @@ void em4x50_login(const uint32_t *password, bool ledcontrol); void em4x50_sim(const uint32_t *password, bool ledcontrol); void em4x50_reader(bool ledcontrol); void em4x50_chk(const char *filename, bool ledcontrol); +void em4x50_config(const em4x50_config_t *cfg); #endif /* EM4X50_H */ diff --git a/client/luascripts/lf_em4x50_tune.lua b/client/luascripts/lf_em4x50_tune.lua new file mode 100644 index 000000000..57feb815c --- /dev/null +++ b/client/luascripts/lf_em4x50_tune.lua @@ -0,0 +1,188 @@ +local getopt = require('getopt') +local ac = require('ansicolors') +local green = ac.green +local red = ac.red +local yellow = ac.yellow +local res = ac.reset + +copyright = '' +author = '' +version = 'v1.00' +desc = [[ + Sweeps the EM4x50 reader timings (`lf em 4x50 config`) one at a time, + reads a block several times per value and reports the success rate. + For each setting the centre of the widest fully working range is + suggested, then all suggestions are checked together. + Keep the tag still on the antenna while the script runs. To find the + most robust values, place it where reading is hardest (edge, distance). +]] +example = [[ + script run lf_em4x50_tune + script run lf_em4x50_tune -n 20 -s rm + script run lf_em4x50_tune -b 3 -p 12345678 -a +]] +usage = [[ + script run lf_em4x50_tune [-h] [-b block] [-p password] [-n tries] [-s setting] [-f] [-a] +]] +arguments = [[ + -h this help + -b block block to read, 0..33 (default: 32, serial number) + -p password 8 hex digits (default: none) + -n tries reads per value (default: 10) + -s setting sweep only this one: rm, gs, ge, thr, tol (default: all) + -f fine sweep, smaller steps + -a keep the suggested settings (default: restore defaults) +]] + +-- swept values, ordered by importance; fine = step with -f +local sweeps = { + { key = 'rm', name = 'rm delay', from = 64, to = 248, step = 8, fine = 4 }, + { key = 'gs', name = 'gap start', from = 0, to = 24, step = 2, fine = 1 }, + { key = 'ge', name = 'gap end', from = 16, to = 60, step = 4, fine = 2 }, + { key = 'thr', name = 'threshold %', from = 30, to = 95, step = 5, fine = 5 }, + { key = 'tol', name = 'tolerance', from = 2, to = 15, step = 1, fine = 1 }, +} + +local function help() + print(copyright) + print(author) + print(version) + print(desc) + print(ac.cyan .. 'Usage' .. res) + print(usage) + print(ac.cyan .. 'Arguments' .. res) + print(arguments) + print(ac.cyan .. 'Example usage' .. res) + print(example) +end + +local function oops(err) + print(red .. 'ERROR: ' .. res .. err) + core.clearCommandBuffer() + return nil, err +end + +local function config(args) + core.console('lf em 4x50 config ' .. args, true, true) +end + +-- word read from as "XX XX XX XX", nil on failure +local function read_word(block, pwd) + local cmd = 'lf em 4x50 rdbl -b ' .. block + if pwd ~= '' then cmd = cmd .. ' -p ' .. pwd end + local out = core.console(cmd, true, true) or '' + out = out:gsub('\27%[[%d;]*m', '') + return out:match('%s' .. block .. ' | (%x%x %x%x %x%x %x%x) |') +end + +-- successful reads out of , a read must match once it is known +local function score(block, pwd, tries, ref) + local ok = 0 + for _ = 1, tries do + local w = read_word(block, pwd) + if w ~= nil and (ref.word == nil or ref.word == w) then + ref.word = ref.word or w + ok = ok + 1 + end + end + return ok +end + +-- centre of the widest run of values at the best rate +local function pick(results) + local best = 0 + for _, r in ipairs(results) do + if r.ok > best then best = r.ok end + end + if best == 0 then return nil, 0 end + + local run_start, run_len, cur_start, cur_len = 1, 0, 1, 0 + for i, r in ipairs(results) do + if r.ok == best then + if cur_len == 0 then cur_start = i end + cur_len = cur_len + 1 + if cur_len > run_len then run_start, run_len = cur_start, cur_len end + else + cur_len = 0 + end + end + return results[run_start + math.floor((run_len - 1) / 2)].value, best +end + +local function main(args) + local block, pwd, tries, only, apply, fine = '32', '', 10, nil, false, false + + for o, a in getopt.getopt(args, 'hb:p:n:s:fa') do + if o == 'h' then return help() end + if o == 'b' then + local n = tonumber(a) + if not n or n < 0 or n > 33 then return oops('block must be 0..33') end + block = tostring(math.floor(n)) + end + if o == 'p' then + if #a ~= 8 or not a:match('^%x+$') then return oops('password must be 8 hex digits') end + pwd = a + end + if o == 'n' then + tries = tonumber(a) + if not tries or tries < 1 then return oops('invalid number of tries') end + tries = math.floor(tries) + end + if o == 's' then only = a end + if o == 'f' then fine = true end + if o == 'a' then apply = true end + end + + local ref = { word = nil } + config('-d') + local base = score(block, pwd, tries, ref) + print(('defaults: %d/%d reads, block %s = %s'):format(base, tries, block, ref.word or '??')) + + local chosen = {} + for _, s in ipairs(sweeps) do + if only == nil or only == s.key then + print(ac.cyan .. ('--- %s (--%s) ---'):format(s.name, s.key) .. res) + local results = {} + for v = s.from, s.to, (fine and s.fine or s.step) do + if core.kbd_enter_pressed() then + config('-d') + return oops('stopped by user') + end + config('-d --' .. s.key .. ' ' .. v) + local ok = score(block, pwd, tries, ref) + table.insert(results, { value = v, ok = ok }) + local col = (ok == tries) and green or ((ok == 0) and red or yellow) + print(('%4d %s%2d/%d %s%s'):format(v, col, ok, tries, string.rep('#', ok), res)) + end + local v, rate = pick(results) + if v ~= nil then + chosen[s.key] = v + print(('suggested --%s %d (%d/%d)'):format(s.key, v, rate, tries)) + else + print(red .. 'no working value for --' .. s.key .. res) + end + end + end + + local combo = '' + for _, s in ipairs(sweeps) do + if chosen[s.key] ~= nil then + combo = combo .. (' --%s %d'):format(s.key, chosen[s.key]) + end + end + + config('-d' .. combo) + local final = score(block, pwd, tries * 2, ref) + print(ac.cyan .. '--- result ---' .. res) + print(('suggested settings:%s'):format(combo)) + print(('combined: %d/%d reads (defaults: %d/%d)'):format(final, tries * 2, base, tries)) + + if apply then + print(green .. 'kept, until the device restarts. Run `lf em 4x50 config` to see them.' .. res) + else + config('-d') + print('defaults restored, use -a to keep the suggestion') + end +end + +main(args) diff --git a/client/src/cmdlfem4x50.c b/client/src/cmdlfem4x50.c index 8fa3a663e..f2867a0b1 100644 --- a/client/src/cmdlfem4x50.c +++ b/client/src/cmdlfem4x50.c @@ -1348,11 +1348,83 @@ static int CmdEM4x50View(const char *Cmd) { return PM3_SUCCESS; } +static int em4x50_send_config(em4x50_config_t *cfg) { + clearCommandBuffer(); + SendCommandNG(CMD_LF_EM4X50_CONFIG, (uint8_t *)cfg, sizeof(em4x50_config_t)); + PacketResponseNG resp; + if (WaitForResponseTimeout(CMD_LF_EM4X50_CONFIG, &resp, 2000) == false) { + PrintAndLogEx(WARNING, "timeout while waiting for reply"); + return PM3_ETIMEOUT; + } + if (resp.length >= sizeof(em4x50_config_t)) { + memcpy(cfg, resp.data.asBytes, sizeof(em4x50_config_t)); + } + return resp.status; +} + +static int CmdEM4x50Config(const char *Cmd) { + CLIParserContext *ctx; + CLIParserInit(&ctx, "lf em 4x50 config", + "Get or set the reader timings used by EM4x50 commands, in carrier cycles.\n" + "Settings are lost when the device restarts.", + "lf em 4x50 config -> show current settings\n" + "lf em 4x50 config --rm 136 -> send RM 136 cycles after the listen window\n" + "lf em 4x50 config --gs 4 --ge 28 -> field gap of a \"0\" bit from cycle 4 to 28\n" + "lf em 4x50 config -d -> restore defaults\n" + ); + + void *argtable[] = { + arg_param_begin, + arg_lit0("d", "default", "restore default settings"), + arg_int0(NULL, "thr", "<1-100>", "envelope threshold, percent of amplitude (def 75)"), + arg_int0(NULL, "tol", "<1-15>", "pulse length tolerance (def 10)"), + arg_int0(NULL, "gs", "<0-62>", "field gap start in a \"0\" bit (def 7)"), + arg_int0(NULL, "ge", "<1-63>", "field gap end in a \"0\" bit (def 38)"), + arg_int0(NULL, "rm", "<1-320>", "RM start after the first listen window (def 132)"), + arg_param_end + }; + + CLIExecWithReturn(ctx, Cmd, argtable, true); + bool use_default = arg_get_lit(ctx, 1); + int thr = arg_get_int_def(ctx, 2, -1); + int tol = arg_get_int_def(ctx, 3, -1); + int gs = arg_get_int_def(ctx, 4, -1); + int ge = arg_get_int_def(ctx, 5, -1); + int rm = arg_get_int_def(ctx, 6, -1); + CLIParserFree(ctx); + + em4x50_config_t cfg = { .mode = use_default ? EM4X50_CONFIG_RESET : EM4X50_CONFIG_GET }; + int res = em4x50_send_config(&cfg); + + if ((res == PM3_SUCCESS) && ((thr >= 0) || (tol >= 0) || (gs >= 0) || (ge >= 0) || (rm >= 0))) { + if (thr >= 0) cfg.threshold = thr & 0xFF; + if (tol >= 0) cfg.tolerance = tol & 0xFF; + if (gs >= 0) cfg.gap_start = gs & 0xFF; + if (ge >= 0) cfg.gap_end = ge & 0xFF; + if (rm >= 0) cfg.rm_delay = rm & 0xFFFF; + cfg.mode = EM4X50_CONFIG_SET; + res = em4x50_send_config(&cfg); + if (res == PM3_EINVARG) { + PrintAndLogEx(FAILED, "invalid settings, nothing changed"); + } + } + + if (res == PM3_SUCCESS || res == PM3_EINVARG) { + PrintAndLogEx(INFO, "threshold.... " _YELLOW_("%u") " %%", cfg.threshold); + PrintAndLogEx(INFO, "tolerance.... " _YELLOW_("%u"), cfg.tolerance); + PrintAndLogEx(INFO, "gap start.... " _YELLOW_("%u"), cfg.gap_start); + PrintAndLogEx(INFO, "gap end...... " _YELLOW_("%u"), cfg.gap_end); + PrintAndLogEx(INFO, "rm delay..... " _YELLOW_("%u"), cfg.rm_delay); + } + return res; +} + static command_t CommandTable[] = { {"help", CmdHelp, AlwaysAvailable, "This help"}, {"-----------", CmdHelp, AlwaysAvailable, "--------------------- " _CYAN_("operations") " ---------------------"}, {"brute", CmdEM4x50Brute, IfPm3EM4x50, "Bruteforce attack to find password"}, {"chk", CmdEM4x50Chk, IfPm3EM4x50, "Check passwords"}, + {"config", CmdEM4x50Config, IfPm3EM4x50, "Get/set reader timings"}, {"dump", CmdEM4x50Dump, IfPm3EM4x50, "Dump EM4x50 tag"}, {"info", CmdEM4x50Info, IfPm3EM4x50, "Tag information"}, {"login", CmdEM4x50Login, IfPm3EM4x50, "Login into EM4x50 tag"}, diff --git a/doc/commands.json b/doc/commands.json index fd2b16458..26116842f 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -12162,6 +12162,27 @@ ], "usage": "lf em 4x50 chk [-h] [-f ]" }, + "lf em 4x50 config": { + "command": "lf em 4x50 config", + "description": "Get or set the reader timings used by EM4x50 commands, in carrier cycles. Settings are lost when the device restarts.", + "notes": [ + "lf em 4x50 config -> show current settings", + "lf em 4x50 config --rm 136 -> send RM 136 cycles after the listen window", + "lf em 4x50 config --gs 4 --ge 28 -> field gap of a \"0\" bit from cycle 4 to 28", + "lf em 4x50 config -d -> restore defaults" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-d, --default restore default settings", + "--thr <1-100> envelope threshold, percent of amplitude (def 75)", + "--tol <1-15> pulse length tolerance (def 10)", + "--gs <0-62> field gap start in a \"0\" bit (def 7)", + "--ge <1-63> field gap end in a \"0\" bit (def 38)", + "--rm <1-320> RM start after the first listen window (def 132)" + ], + "usage": "lf em 4x50 config [-hd] [--thr <1-100>] [--tol <1-15>] [--gs <0-62>] [--ge <1-63>] [--rm <1-320>]" + }, "lf em 4x50 dump": { "command": "lf em 4x50 dump", "description": "Reads all blocks/words from EM4x50 tag and saves dump in (bin/json) format", @@ -16810,7 +16831,7 @@ } }, "metadata": { - "commands_extracted": 936, + "commands_extracted": 937, "extracted_by": "PM3Help2JSON v1.00", "extracted_on": "2026-10-23T22:15:17+00:00" } diff --git a/doc/commands.md b/doc/commands.md index ff131cbea..20a2cb91e 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -1191,6 +1191,7 @@ Check column "offline" for their availability. |`lf em 4x50 help `|Y |`This help` |`lf em 4x50 brute `|N |`Bruteforce attack to find password` |`lf em 4x50 chk `|N |`Check passwords` +|`lf em 4x50 config `|N |`Get/set reader timings` |`lf em 4x50 dump `|N |`Dump EM4x50 tag` |`lf em 4x50 info `|N |`Tag information` |`lf em 4x50 login `|N |`Login into EM4x50 tag` diff --git a/include/em4x50.h b/include/em4x50.h index c8f7ace15..09d8328d4 100644 --- a/include/em4x50.h +++ b/include/em4x50.h @@ -84,6 +84,20 @@ typedef struct { uint32_t *words; } PACKED em4x50_read_data_response_t; +// CMD_LF_EM4X50_CONFIG payload and reply, reader timings in carrier cycles +#define EM4X50_CONFIG_GET 0 +#define EM4X50_CONFIG_SET 1 +#define EM4X50_CONFIG_RESET 2 + +typedef struct { + uint8_t mode; // EM4X50_CONFIG_* + uint8_t threshold; // envelope thresholds, percent of amplitude + uint8_t tolerance; // pulse length tolerance + uint8_t gap_start; // field gap start within a reader "0" bit + uint8_t gap_end; // field gap end within a reader "0" bit + uint16_t rm_delay; // RM start after the end of the first listen window +} PACKED em4x50_config_t; + // Global variables... extern bool g_Login; extern bool g_WritePasswordProcess; diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 541d3b857..7e3928e76 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -1089,6 +1089,7 @@ typedef struct { #define CMD_LF_EM4X50_READER 0x0251 #define CMD_LF_EM4X50_ESET 0x0252 #define CMD_LF_EM4X50_CHK 0x0253 +#define CMD_LF_EM4X50_CONFIG 0x0254 #define CMD_LF_EM4X70_INFO 0x0260 #define CMD_LF_EM4X70_WRITE 0x0261 #define CMD_LF_EM4X70_UNLOCK 0x0262