diff --git a/CHANGELOG.md b/CHANGELOG.md index b655b3876..92a8d833d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,26 @@ 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 hardnested` - the device declared `num_nonces * 4` bytes but packs 9 bytes per nonce pair. Thanks @TheArchitect0880 (@iceman1001) +- Changed `hf mfdes detect` - with no `-n` it now sweeps every key number the application declares instead of only key 0 (@iceman1001) +- Fixed `hf mfdes detect` - the card error counter was shared by every key type, so a bad run during the DES pass could abort the AES pass (@iceman1001) +- Fixed `hf mfdes detect` - with no `-f` it drew candidates from the MIFARE Plus 16 byte key list, it now defaults to the bundled `mfdes_default_keys` dictionary (@iceman1001) +- Fixed `hf mfdes detect` - LRP was only found when the key settings happened to be unreadable (@iceman1001) +- Added `hf mfdes chk --schann` - now detect the secure channel EV/EV2/LRP mode; detected per application and can be overridden (@iceman1001) +- Fixed `hf mfdes chk` - found keys were tracked per key number instead of per application, so a key number recovered on one AID was skipped later (@iceman1001) +- Fixed `data modulation` - the 160 sample antenna settle trim was never undone, so the graph buffer stayed short for everything after it (@mfcarroll) +- 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) +- Fixed `hf emrtd info` - now correctly pretty print algos (@iceman1001) - Fixed `trace list -t topaz` - now parses topaz reader frames up to 16 bytes (@iceman1001) - Fixed `hw bwm` - doc and comment references still named the flat `hw bwmsetcap`/`bwmcharge`/`bwmautooff` commands from before the subgroup move (@xilni) - Added TA1=96 support via pwm to sim module `sim024.bin` - v4.66 (@antiklesys) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index c35953ac0..d803ce08e 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -991,9 +991,14 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { uint8_t uid[10] = {0x00}; uint8_t answer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t par[1] = {0x00}; - uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00}; + + // collect straight into the reply buffer, no second copy on the stack + uint8_t respbuf[sizeof(mf_nonces_resp_t) + (MFC_MAX_NONCES * 4)] = {0x00}; + mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + uint8_t *buf = response->nonces; + uint32_t cuid = 0; - int16_t isOK = 0; + int16_t isOK = PM3_SUCCESS; uint16_t num_nonces = 0; uint8_t cascade_levels = 0; uint8_t blockNo = payload->blockno; @@ -1019,7 +1024,7 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { // Test if the action was cancelled if (BUTTON_PRESS()) { - isOK = 2; + isOK = PM3_EOPABORTED; field_off = true; break; } @@ -1072,12 +1077,12 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { LED_C_OFF(); LED_B_ON(); - uint8_t respbuf[PM3_CMD_DATA_SIZE] = {0x00}; - mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + + // one bare 4 byte nonce per entry here, unlike the paired layout used by + // MifareAcquireEncryptedNonces. The loop above already caps num_nonces + uint16_t noncelen = num_nonces * 4; response->cuid = cuid; response->num_nonces = num_nonces; - uint16_t noncelen = MIN((uint16_t)(num_nonces * 4), (uint16_t)(MFC_MAX_NONCES * 4)); - memcpy(response->nonces, buf, noncelen); reply_ng(CMD_HF_MIFARE_ACQ_NONCES, isOK, respbuf, sizeof(mf_nonces_resp_t) + noncelen); LED_B_OFF(); @@ -1106,12 +1111,17 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { uint8_t uid[10] = {0x00}; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t par_enc[1] = {0x00}; - uint8_t buf[PM3_CMD_DATA_SIZE] = {0x00}; + + // collect straight into the reply buffer, no second copy on the stack + uint8_t respbuf[sizeof(mf_nonces_resp_t) + (MFC_MAX_NONCE_PAIRS * MFC_NONCE_PAIR_SIZE)] = {0x00}; + mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + uint8_t *buf = response->nonces; uint64_t ui64Key = bytes_to_num(payload->key, 6); uint32_t cuid = 0; int16_t isOK = PM3_SUCCESS; uint16_t num_nonces = 0; + uint16_t num_pairs = 0; uint8_t nt_par_enc = 0; uint8_t cascade_levels = 0; uint8_t blockNo = payload->blockno; @@ -1139,7 +1149,7 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { uint8_t prev_enc_nt[] = {0, 0, 0, 0}; uint8_t prev_counter = 0; - for (uint16_t i = 0; i <= (MFC_MAX_NONCES * 4) - 9;) { + while (num_pairs < MFC_MAX_NONCE_PAIRS) { // Test if the action was cancelled if (BUTTON_PRESS()) { @@ -1196,14 +1206,15 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { } num_nonces++; + uint16_t ofs = num_pairs * MFC_NONCE_PAIR_SIZE; if (num_nonces % 2) { - memcpy(buf + i, receivedAnswer, 4); + memcpy(buf + ofs, receivedAnswer, 4); nt_par_enc = par_enc[0] & 0xf0; } else { nt_par_enc |= par_enc[0] >> 4; - memcpy(buf + i + 4, receivedAnswer, 4); - memcpy(buf + i + 8, &nt_par_enc, 1); - i += 9; + memcpy(buf + ofs + 4, receivedAnswer, 4); + buf[ofs + 8] = nt_par_enc; + num_pairs++; } @@ -1231,12 +1242,12 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { LED_C_OFF(); crypto1_deinit(pcs); LED_B_ON(); - uint8_t respbuf[PM3_CMD_DATA_SIZE] = {0x00}; - mf_nonces_resp_t *response = (mf_nonces_resp_t *)respbuf; + + // only whole pairs are transferred. An abort or a static nonce bailout can + // leave a dangling first nonce, it has no parity nibble yet so it is dropped + uint16_t noncelen = num_pairs * MFC_NONCE_PAIR_SIZE; response->cuid = cuid; - response->num_nonces = num_nonces; - uint16_t noncelen = MIN((uint16_t)(num_nonces * 4), (uint16_t)(MFC_MAX_NONCES * 4)); - memcpy(response->nonces, buf, noncelen); + response->num_nonces = num_pairs * 2; reply_ng(CMD_HF_MIFARE_ACQ_ENCRYPTED_NONCES, isOK, respbuf, sizeof(mf_nonces_resp_t) + noncelen); LED_B_OFF(); diff --git a/client/lualibs/t55xx_config.lua b/client/lualibs/t55xx_config.lua index f3f1e67e1..fbba524d1 100644 --- a/client/lualibs/t55xx_config.lua +++ b/client/lualibs/t55xx_config.lua @@ -131,11 +131,25 @@ function Config.detect(offline) .. 'Rebuild with `make client` and start a new pm3 session', 0) end - local block0 = out:match('Block0%.+%s*(%x%x%x%x%x%x%x%x)') - if block0 == nil then return nil, out end + -- Everything between the Block0 label and the next field. That covers both + -- forms detect prints: one word, or `ambiguous, one of:` followed by a + -- candidate per line. PSK2 and PSK3 are the same waveform under a + -- different reading, so a candidate list is detect being honest, not + -- detect failing, and the suite has to be able to score it + local seg = out:match('Block0%.+(.-)Downlink mode') or out:match('Block0%.+([^\n]*)') + + local cands = {} + if seg ~= nil then + for w in seg:gmatch('(%x%x%x%x%x%x%x%x)') do + table.insert(cands, w) + end + end + + if #cands == 0 then return nil, out end return { - block0 = block0, + block0 = cands[1], + candidates = cands, modulation = out:match('Modulation%.+%s*([^\n]-)%s*\n'), bitrate = out:match('Bit rate%.+%s*([^\n]-)%s*\n'), offset = out:match('Offset%.+%s*(%d+)'), @@ -265,7 +279,26 @@ function Config.check(report, block0, opts) local found = Config.detect(opts.offline) core.clearCommandBuffer() - local res = report:add(block0, found and found.block0 or nil) + local got, extra = nil, {} + + if found ~= nil then + + got = found.block0 + + -- a word the tag could be holding counts as read back. Say how many + -- readings were live, so an ambiguous pass is not mistaken for a clean one + if #found.candidates > 1 then + + for _, c in ipairs(found.candidates) do + if c:upper() == block0:upper() then got = c end + end + + extra.ok = (got:upper() == block0:upper()) + extra.note = extra.ok and ('ambiguous, 1 of ' .. #found.candidates) or 'MISMATCH' + end + end + + local res = report:add(block0, got, extra) if opts.verbose then core.console('lf t55xx info') diff --git a/client/luascripts/tests/lf_t55xx_writetest.lua b/client/luascripts/tests/lf_t55xx_writetest.lua index 436846bc0..05251def2 100644 --- a/client/luascripts/tests/lf_t55xx_writetest.lua +++ b/client/luascripts/tests/lf_t55xx_writetest.lua @@ -16,7 +16,7 @@ A strict T55x7 test suite: lf t55xx wipe lf t55xx write -b 1 -d 00000000 - lf t55xx write -b 2 -d ffffffff + lf t55xx write -b 2 -d aa5500ff lf t55xx write -b 3 -d 80000000 lf t55xx write -b 4 -d 00000001 @@ -24,6 +24,14 @@ Each row names the configuration word, what it means, what `lf t55xx detect` made of it and how many of the four data blocks read back intact. Markers are also written into the session log ( `rem [ERR:...]` and `rem [SUMMARY:...]` ) +Every block is read three times. A block that reads back differently between +those is marked `unstable`, which is the fault a single read cannot see: the +value is silently wrong rather than missing. A block that is wrong the same way +each time is named where it can be - `rol1`, `ror5`, `inverted`, `shr1` - because +a rotation points at the word boundary and an inversion at psk phase, and the two +want different fixes. Block 1 is `00000000`, which is equal to all of its own +rotations, so a rotated read of it cannot be told from a correct one. + Note: that the card is wiped before each modulation. Needs a T5577 in the field. @@ -161,30 +169,98 @@ local function prepare() return true end +-- a block is read this many times, so that a value which is silently wrong on +-- only some reads is not mistaken for one that is right +local READS = 3 + +local function rol32(v, n) + n = n % 32 + if n == 0 then return v end + return ((v << n) | (v >> (32 - n))) & 0xFFFFFFFF +end + --- --- Read blocks 1-4 back. Returns how many matched and a short note naming the --- ones that did not. +-- Name how `got` differs from `want`, when it can be named. A rotation says the +-- word boundary moved, an inversion says psk picked the opposite phase, and a +-- shift says a demodulation opened a bit early and padded with zero - different +-- faults wanting different fixes, so worth telling apart. A word equal to all of +-- its own rotations carries no boundary information and only gets 'differs'. +local function classify(want, got) + + if got == want then return 'ok' end + + if rol32(want, 1) == want then return 'differs' end + + for n = 1, 31 do + if rol32(want, n) == got then + return (n <= 16) and ('rol' .. n) or ('ror' .. (32 - n)) + end + end + + if (want ~ 0xFFFFFFFF) == got then return 'inverted' end + + for n = 1, 31 do + if (rol32(want, n) ~ 0xFFFFFFFF) == got then + return 'inv+' .. ((n <= 16) and ('rol' .. n) or ('ror' .. (32 - n))) + end + end + + for n = 1, 8 do + if ((want >> n) & 0xFFFFFFFF) == got then return 'shr' .. n end + if ((want << n) & 0xFFFFFFFF) == got then return 'shl' .. n end + end + + return 'differs' +end + +--- +-- Read blocks 1-4 back, READS times each. Returns how many matched on every +-- read and a short note naming what went wrong with the ones that did not. local function read_back(config) local good, bad = 0, {} for block, want in ipairs(DATA_BLOCKS) do - local data = core.t55xx_readblock(block, '0', '0', '') - local got = data and ('%08X'):format(data) or '' + local wantv = tonumber(want, 16) + local seen, first, stable = {}, nil, true - if got:lower() == want:lower() then + for _ = 1, READS do + local data = core.t55xx_readblock(block, '0', '0', '') + local v = data and (data & 0xFFFFFFFF) or nil + table.insert(seen, v) + if first == nil then + first = v + elseif v ~= first then + stable = false + end + end + + if stable and first == wantv then good = good + 1 else - table.insert(bad, tostring(block)) - core.console(format('rem [ERR:READ:%s:%d] block %d: read %s instead of %s', - config, block, block, got, want), false, true) + local what + if stable == false then + what = 'unstable' + else + what = classify(wantv, first) + end + + table.insert(bad, format('b%d %s', block, what)) + + local reads = {} + for _, v in ipairs(seen) do + table.insert(reads, v and ('%08X'):format(v) or '----') + end + core.console(format('rem [ERR:READ:%s:%d] block %d: %s, wanted %s, read %s', + config, block, block, what, want, + table.concat(reads, ' ')), false, true) end end local note = '' if #bad > 0 then - note = 'block ' .. table.concat(bad, ',') .. ' bad' + note = table.concat(bad, ' ') end return good, note end diff --git a/client/resources/aid_desfire.json b/client/resources/aid_desfire.json index a166e32ca..705baa24f 100644 --- a/client/resources/aid_desfire.json +++ b/client/resources/aid_desfire.json @@ -311,6 +311,14 @@ "Description": "SMARTair Credential", "Type": "pacs" }, + { + "AID": "F70090", + "Vendor": "ASSA ABLOY (Timelox / VingCard Elsafe)", + "Country": "SE", + "Name": "Visionline", + "Description": "Hotel access credential", + "Type": "pacs" + }, { "AID": "F51BC0", "Vendor": "STid Group", @@ -873,9 +881,9 @@ }, { "AID": "008800", - "Vendor": "Bank Mega", + "Vendor": "PT Bank Mega Tbk", "Country": "ID", - "Name": "MegaCash", + "Name": "MEGACASH", "Description": "Indonesian stored-value card // FIDs 01: Card Identification; 02: Stored Value; 03: Transaction Records", "Type": "payment system" }, diff --git a/client/src/cmddata.c b/client/src/cmddata.c index 411515da9..979ecc31b 100644 --- a/client/src/cmddata.c +++ b/client/src/cmddata.c @@ -2778,8 +2778,7 @@ static int try_detect_modulation(void) { clk = GetPskClock("", false); if (clk > 0) { // allow undo - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) CmdLtrim("-i 160"); if ((PSKDemod(0, 0, 6, false) == PM3_SUCCESS)) { @@ -2791,8 +2790,7 @@ static int try_detect_modulation(void) { tests[hits].carrier = GetPskCarrier(false); } //undo trim samples - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); } } diff --git a/client/src/cmdhfemrtd.c b/client/src/cmdhfemrtd.c index 04d0748b0..cfde4c9df 100644 --- a/client/src/cmdhfemrtd.c +++ b/client/src/cmdhfemrtd.c @@ -2468,15 +2468,28 @@ static void emrtd_print_cardaccess(const emrtd_cardaccess_t *ca) { PrintAndLogEx(SUCCESS, ""); } - if (info->alg != NULL) { - PrintAndLogEx(SUCCESS, "PACE algorithm........... " _YELLOW_("%s"), info->alg->name); - } else { - PrintAndLogEx(SUCCESS, "PACE algorithm........... " _YELLOW_("unknown") " ( OID %s )", - sprint_hex_inrow((uint8_t *)info->oid, info->oidlen)); + char oidstr[64] = { 0x00 }; + emrtd_oid_to_str(info->oid, info->oidlen, oidstr, sizeof(oidstr)); + if (oidstr[0] == 0x00) { + snprintf(oidstr, sizeof(oidstr), "%s", sprint_hex_inrow((uint8_t *)info->oid, info->oidlen)); } + bool is_pace = ((info->kind == EMRTD_SI_PACE) || (info->kind == EMRTD_SI_PACE_DP)); + + if (info->protocol != NULL) { + PrintAndLogEx(SUCCESS, "%s " _YELLOW_("%s"), + is_pace ? "PACE algorithm..........." : "Protocol.................", + info->protocol); + } else { + PrintAndLogEx(SUCCESS, "Protocol................. " _YELLOW_("unknown")); + } + + PrintAndLogEx(SUCCESS, "OID...................... %s", oidstr); + if (info->version != 0) { - PrintAndLogEx(SUCCESS, "PACE version............. " _YELLOW_("%u"), info->version); + PrintAndLogEx(SUCCESS, "%s " _YELLOW_("%u"), + is_pace ? "PACE version............." : "Version..................", + info->version); } if (info->has_param) { @@ -2488,18 +2501,40 @@ static void emrtd_print_cardaccess(const emrtd_cardaccess_t *ca) { } } + if (info->has_key_id) { + PrintAndLogEx(SUCCESS, "Key id................... " _YELLOW_("%u"), info->key_id); + } + if (info->supported) { PrintAndLogEx(SUCCESS, "Supported by this client. " _GREEN_("yes") "%s", ((int)i == ca->best) ? _GREEN_(" (selected)") : ""); - } else { + } else if (is_pace) { PrintAndLogEx(SUCCESS, "Supported by this client. " _YELLOW_("no") " ( %s )", (info->reason != NULL) ? info->reason : "unsupported"); + } else { + // not a PACE protocol at all, "unsupported PACE algorithm" would be + // the wrong thing to tell the user + PrintAndLogEx(SUCCESS, "Note..................... %s", + (info->reason != NULL) ? info->reason : "not a PACE protocol"); } } if (ca->best < 0) { PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(WARNING, "None of the offered PACE algorithms is supported by this client"); + + bool pace_offered = false; + for (size_t i = 0; i < ca->count; i++) { + if (ca->infos[i].kind == EMRTD_SI_PACE) { + pace_offered = true; + break; + } + } + + if (pace_offered) { + PrintAndLogEx(WARNING, "None of the offered PACE algorithms is supported by this client"); + } else { + PrintAndLogEx(WARNING, "EF_CardAccess does not offer any PACE algorithm"); + } } } diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 6d05b8b50..0a4ffb1d7 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -57,6 +57,10 @@ #define MAX_KEY_LEN 24 #define MAX_KEYS_LIST_LEN 1024 +// how many errors in a row from the card before we give up on a key number +#define MFDES_CHK_MAX_ERRORS 10 +// bundled dictionary used when no -f is given +#define MFDES_DEFAULT_DICT "mfdes_default_keys" #define MFDES_BRUTEAID_RESELECT_ATTEMPTS 5 #define MFDES_BRUTEAID_RESELECT_WAIT_MS 200 #define MFDES_BRUTEAID_MAD_START 0xF0000FU @@ -818,14 +822,14 @@ static int CmdHF14ADesDefault(const char *Cmd) { void *argtable[] = { arg_param_begin, - arg_int0("n", "keyno", "", "Key number"), - arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), - arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), - arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), - arg_str0("m", "cmode", "", "Communicaton mode"), - arg_str0("c", "ccset", "", "Communicaton command set"), - arg_str0(NULL, "schann", "", "Secure channel"), + arg_int0("n", "keyno", "", "Key number"), + arg_str0("t", "algo", "", "Crypt algo"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), + arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), + arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), + arg_str0("m", "cmode", "", "Communicaton mode"), + arg_str0("c", "ccset", "", "Communicaton command set"), + arg_str0(NULL, "schann", "", "Secure channel"), arg_param_end }; CLIExecWithReturn(ctx, Cmd, argtable, true); @@ -856,14 +860,14 @@ static int CmdHF14ADesDefault(const char *Cmd) { PrintAndLogEx(INFO, "-----------" _CYAN_("Default parameters") "---------------------------------"); - PrintAndLogEx(INFO, "Key Num : %d", defaultKeyNum); - PrintAndLogEx(INFO, "Algo : %s", CLIGetOptionListStr(DesfireAlgoOpts, defaultAlgoId)); - PrintAndLogEx(INFO, "Key : %s", sprint_hex(defaultKey, desfire_get_key_length(defaultAlgoId))); - PrintAndLogEx(INFO, "KDF algo : %s", CLIGetOptionListStr(DesfireKDFAlgoOpts, defaultKdfAlgo)); - PrintAndLogEx(INFO, "KDF input : [%d] %s", defaultKdfInputLen, sprint_hex(defaultKdfInput, defaultKdfInputLen)); - PrintAndLogEx(INFO, "Secure chan : %s", CLIGetOptionListStr(DesfireSecureChannelOpts, defaultSecureChannel)); - PrintAndLogEx(INFO, "Command set : %s", CLIGetOptionListStr(DesfireCommandSetOpts, defaultCommSet)); - PrintAndLogEx(INFO, "Comm mode : %s", CLIGetOptionListStr(DesfireCommunicationModeOpts, defaultCommMode)); + PrintAndLogEx(INFO, "Key num........ %d", defaultKeyNum); + PrintAndLogEx(INFO, "Algo........... %s", CLIGetOptionListStr(DesfireAlgoOpts, defaultAlgoId)); + PrintAndLogEx(INFO, "Key............ %s", sprint_hex_inrow(defaultKey, desfire_get_key_length(defaultAlgoId))); + PrintAndLogEx(INFO, "KDF algo....... %s", CLIGetOptionListStr(DesfireKDFAlgoOpts, defaultKdfAlgo)); + PrintAndLogEx(INFO, "KDF input...... [%d] %s", defaultKdfInputLen, sprint_hex_inrow(defaultKdfInput, defaultKdfInputLen)); + PrintAndLogEx(INFO, "Sec chann...... %s", CLIGetOptionListStr(DesfireSecureChannelOpts, defaultSecureChannel)); + PrintAndLogEx(INFO, "Command set.... %s", CLIGetOptionListStr(DesfireCommandSetOpts, defaultCommSet)); + PrintAndLogEx(INFO, "Command mode... %s", CLIGetOptionListStr(DesfireCommunicationModeOpts, defaultCommMode)); return PM3_SUCCESS; } @@ -1272,14 +1276,100 @@ static void DesFill2bPattern( (*startPattern)++; } +// Try every key in `keyList` against every key number the `usedkeys` map marks as +// in use on the currently selected application. Found keys are stored in `found`. +// Returns PM3_SUCCESS, or an error when the application can no longer be selected. +static int AuthCheckDesfireKeyType(DesfireContext_t *dctx, + DesfireSecureChannel secureChannel, + uint32_t curaid, + DesfireCryptoAlgorithm keytype, + const char *keytypestr, + const uint8_t *keyList, size_t keyListStride, uint32_t keyListLen, + const int *usedkeys, + desfire_app_keys_t *found, + bool *result) { + + size_t keylen = desfire_get_key_length(keytype); + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + if (usedkeys[keyno] != 1 || found->keys[keytype][keyno][0] != 0) { + continue; + } + + size_t errcount = 0; + + for (uint32_t curkey = 0; curkey < keyListLen; curkey++) { + + const uint8_t *key = &keyList[curkey * keyListStride]; + + DesfireSetKeyNoClear(dctx, keyno, keytype, (uint8_t *)key); + + int res = DesfireAuthenticate(dctx, secureChannel, false); + if (res == PM3_SUCCESS) { + PrintAndLogEx(SUCCESS, "AID 0x%06X, Found %s Key %02u... " _GREEN_("%s"), + curaid, keytypestr, keyno, sprint_hex_inrow(key, keylen)); + + found->keys[keytype][keyno][0] = 0x01; + memcpy(&found->keys[keytype][keyno][1], key, keylen); + *result = true; + + // EV2 and LRP turn an authenticated context into a "non first" + // auth for the next key number. Start each one clean instead. + DesfireClearSession(dctx); + break; + } + + // anything below 7 means the card gave up before the crypto stage, + // the channel is gone and the application has to be selected again + if (res < 7) { + DropField(); + int selres = DesfireSelectAIDHex(dctx, curaid, false, 0); + if (selres != PM3_SUCCESS) { + return selres; + } + } + + // 4 - answer length doesn't match the algo + // 50 - PICC didn't answer AES, 51 - PICC didn't answer LRP + // the application doesn't use this key type, skip the rest of it + if (res == 4 || res == 50 || res == 51) { + return PM3_SUCCESS; + } + + // 3 - invalid key number. Every key fails the same way, but the + // remaining key numbers are still worth checking + if (res == 3) { + break; + } + + // 1, 2, 5, 6 - transmit or local crypto error. Carry on with the next + // key and only give up on this key number after a run of them + if (res < 7) { + errcount++; + if (errcount > MFDES_CHK_MAX_ERRORS) { + if (g_debugMode) { + PrintAndLogEx(DEBUG, "AID 0x%06X, %s key %02u... too many errors from card, skipping", curaid, keytypestr, keyno); + } + break; + } + } else { + errcount = 0; + } + } + } + + return PM3_SUCCESS; +} + static int AuthCheckDesfire(DesfireContext_t *dctx, DesfireSecureChannel secureChannel, const uint8_t *aid, uint8_t deskeyList[MAX_KEYS_LIST_LEN][8], uint32_t deskeyListLen, uint8_t aeskeyList[MAX_KEYS_LIST_LEN][16], uint32_t aeskeyListLen, uint8_t k3kkeyList[MAX_KEYS_LIST_LEN][24], uint32_t k3kkeyListLen, - uint8_t cmdKdfAlgo, uint8_t kdfInputLen, uint8_t *kdfInput, - uint8_t foundKeys[4][0xE][24 + 1], + bool autoschann, + desfire_app_keys_t *found, bool *result, bool verbose) { @@ -1292,34 +1382,78 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, return PM3_ESOFT; } - int usedkeys[0xF] = {0}; + int usedkeys[DESFIRE_MAX_KEY_COUNT + 1] = {0}; bool des = false; bool tdes = false; bool aes = false; bool k3kdes = false; + bool uselrp = false; + uint8_t data[250] = {0}; size_t datalen = 0; res = DesfireGetKeySettings(dctx, data, &datalen); - if (res != PM3_SUCCESS && datalen < 2) { - PrintAndLogEx(ERR, "Could not get key settings"); - return res; - } - uint8_t num_keys = data[1]; - switch (num_keys >> 6) { - case 0: + if (res == PM3_SUCCESS && datalen >= 2) { + + switch (data[1] >> 6) { + case 0: + des = true; + tdes = true; + break; + case 1: + k3kdes = true; + break; + case 2: + aes = true; + break; + default: + break; + } + + } else { + + // key settings are not readable. Ask the card which AUTH commands it + // answers instead, the same way `hf mfdes detect` does + AuthCommandsChk_t authCmdCheck = {0}; + DesfireCheckAuthCommands(ISW6bAID, curaid, NULL, 0, &authCmdCheck); + + if (authCmdCheck.checked == false) { + PrintAndLogEx(ERR, "AID 0x%06X, could not get key settings", curaid); + DropField(); + return PM3_ESOFT; + } + + if (authCmdCheck.auth) { des = true; tdes = true; - break; - case 1: - k3kdes = true; - break; - case 2: + if (authCmdCheck.authISO) { + k3kdes = true; + } + } + + if (authCmdCheck.authAES || authCmdCheck.authEV2) { aes = true; - break; - default: - break; + } + + if (authCmdCheck.authLRP) { + aes = true; + uselrp = true; + } + + if (des == false && tdes == false && aes == false && k3kdes == false) { + PrintAndLogEx(ERR, "AID 0x%06X, card answers no known auth command", curaid); + DropField(); + return PM3_ESOFT; + } + + // the probe dropped the field behind us + res = DesfireSelectAIDHex(dctx, curaid, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the auth command probe", curaid); + DropField(); + return PM3_ESOFT; + } } // always check master key @@ -1343,153 +1477,78 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, usedkeys[fileList[i].fileSettings.chAccess] = 1; } } else { - for (int i = 0; i < 0xE; i++) + for (int i = 0; i < DESFIRE_MAX_KEY_COUNT; i++) usedkeys[i] = 1; } } else { - for (int i = 0; i < 0xE; i++) + for (int i = 0; i < DESFIRE_MAX_KEY_COUNT; i++) usedkeys[i] = 1; } } + // An AES application runs either the EV1/EV2 channel or LRP and the key + // settings don't say which, so it takes one probe to tell them apart. + if (autoschann && aes && uselrp == false) { + + uselrp = DesfireCheckAuthCmd(ISW6bAID, curaid, 0, MFDES_AUTHENTICATE_EV2F, true); + + // the probe dropped the field behind us + res = DesfireSelectAIDHex(dctx, curaid, false, 0); + if (res != PM3_SUCCESS) { + PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the LRP probe", curaid); + DropField(); + return PM3_ESOFT; + } + } + + if (autoschann && uselrp) { + secureChannel = DACLRP; + } + if (verbose) { PrintAndLogEx(INFO, "Check: %s %s %s %s " NOLF, (des) ? "DES" : "", (tdes) ? "2TDEA" : "", (k3kdes) ? "3TDEA" : "", (aes) ? "AES" : ""); + PrintAndLogEx(NORMAL, "channel: %s " NOLF, CLIGetOptionListStr(DesfireSecureChannelOpts, secureChannel)); PrintAndLogEx(NORMAL, "keys: " NOLF); - for (int i = 0; i < 0xE; i++) + for (int i = 0; i < DESFIRE_MAX_KEY_COUNT; i++) if (usedkeys[i] == 1) PrintAndLogEx(NORMAL, "%02x " NOLF, i); PrintAndLogEx(NORMAL, ""); } - bool badlen = false; + const struct { + bool check; + DesfireCryptoAlgorithm keytype; + const char *name; + const uint8_t *list; + size_t stride; + uint32_t len; + } checks[] = { + { des, T_DES, "DES", (const uint8_t *)deskeyList, sizeof(deskeyList[0]), deskeyListLen }, + { tdes, T_3DES, "2TDEA", (const uint8_t *)aeskeyList, sizeof(aeskeyList[0]), aeskeyListLen }, + { aes, T_AES, "AES", (const uint8_t *)aeskeyList, sizeof(aeskeyList[0]), aeskeyListLen }, + { k3kdes, T_3K3DES, "3TDEA", (const uint8_t *)k3kkeyList, sizeof(k3kkeyList[0]), k3kkeyListLen }, + }; - if (des) { + for (size_t i = 0; i < ARRAYLEN(checks); i++) { - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { + if (checks[i].check == false) { + continue; + } - if (usedkeys[keyno] == 1 && foundKeys[0][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < deskeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_DES, deskeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found DES Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex(deskeyList[curkey], 8)); - foundKeys[0][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[0][keyno][1], deskeyList[curkey], 8); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - if (badlen == true) { - badlen = false; - break; - } - } + // LRP only ever carries AES keys + if (secureChannel == DACLRP && checks[i].keytype != T_AES) { + continue; + } + + res = AuthCheckDesfireKeyType(dctx, secureChannel, curaid, checks[i].keytype, checks[i].name, + checks[i].list, checks[i].stride, checks[i].len, + usedkeys, found, result); + if (res != PM3_SUCCESS) { + DropField(); + return res; } } - if (tdes) { - - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { - - if (usedkeys[keyno] == 1 && foundKeys[1][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < aeskeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_3DES, aeskeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 2TDEA Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex_inrow(aeskeyList[curkey], 16)); - foundKeys[1][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[1][keyno][1], aeskeyList[curkey], 16); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - if (badlen == true) { - badlen = false; - break; - } - } - } - } - - if (aes) { - - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { - - if (usedkeys[keyno] == 1 && foundKeys[2][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < aeskeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_AES, aeskeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found AES Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex_inrow(aeskeyList[curkey], 16)); - foundKeys[2][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[2][keyno][1], aeskeyList[curkey], 16); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - if (badlen == true) { - badlen = false; - break; - } - } - } - } - - if (k3kdes) { - - for (uint8_t keyno = 0; keyno < 0xE; keyno++) { - - if (usedkeys[keyno] == 1 && foundKeys[3][keyno][0] == 0) { - for (uint32_t curkey = 0; curkey < k3kkeyListLen; curkey++) { - DesfireSetKeyNoClear(dctx, keyno, T_3K3DES, k3kkeyList[curkey]); - res = DesfireAuthenticate(dctx, secureChannel, false); - if (res == PM3_SUCCESS) { - PrintAndLogEx(SUCCESS, "AID 0x%06X, Found 3TDEA Key %02u... " _GREEN_("%s"), curaid, keyno, sprint_hex_inrow(k3kkeyList[curkey], 24)); - foundKeys[3][keyno][0] = 0x01; - *result = true; - memcpy(&foundKeys[3][keyno][1], k3kkeyList[curkey], 16); - break; - } else if (res < 7) { - badlen = true; - DropField(); - res = DesfireSelectAIDHex(dctx, curaid, false, 0); - if (res != PM3_SUCCESS) { - return res; - } - break; - } - } - - if (badlen == true) { - break; - } - } - } - } DropField(); return PM3_SUCCESS; } @@ -1502,21 +1561,22 @@ static int CmdHF14aDesChk(const char *Cmd) { uint32_t deskeyListLen = 0; uint32_t aeskeyListLen = 0; uint32_t k3kkeyListLen = 0; - uint8_t foundKeys[4][0xE][24 + 1] = {{{0}}}; CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes chk", "Checks keys with MIFARE DESFire card.", - "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on aid 0x123456\n" - "hf mfdes chk -f mfdes_default_keys -> check keys against all existing aid on card\n" - "hf mfdes chk -f mfdes_default_keys --aid 123456 -> check keys against aid 0x123456\n" - "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on aid 0x123456 and save found keys to `keys.json`\n" - "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on aid 0x123456. Start from key FA00FA00...FA00"); + "hf mfdes chk -f mfdes_default_keys -> check keys against all existing AID on card\n" + "hf mfdes chk --aid 123456 -f mfdes_default_keys -> check keys against AID 0x123456\n" + "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on AID 0x123456 and save found keys to `keys.json`\n" + "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on AID 0x123456. Start from key FA00FA00...FA00\n" + "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on AID 0x123456\n" + "hf mfdes chk -f mfdes_default_keys --schann lrp -> check keys, forcing the LRP secure channel\n" + ); void *argtable[] = { arg_param_begin, arg_str0(NULL, "aid", "", "Use specific AID (3 hex bytes, big endian)"), - arg_str0("k", "key", "", "Key for checking (HEX 16 bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0("f", "file", "", "Filename of dictionary"), arg_lit0(NULL, "pattern1b", "Check all 1-byte combinations of key (0000...0000, 0101...0101, 0202...0202, ...)"), arg_lit0(NULL, "pattern2b", "Check all 2-byte combinations of key (0000...0000, 0001...0001, 0002...0002, ...)"), @@ -1525,6 +1585,7 @@ static int CmdHF14aDesChk(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0(NULL, "kdf", "<0|1|2>", "Key Derivation Function (KDF) (0=None, 1=AN10922, 2=Gallagher)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), + arg_str0(NULL, "schann", "", "Secure channel (default: detected per application)"), arg_lit0("a", "apdu", "Show APDU requests and responses"), arg_param_end }; @@ -1536,7 +1597,7 @@ static int CmdHF14aDesChk(const char *Cmd) { swap24(aid); - uint8_t vkey[16] = {0}; + uint8_t vkey[MAX_KEY_LEN] = {0}; int vkeylen = 0; CLIGetHexWithReturn(ctx, 2, vkey, &vkeylen); @@ -1548,7 +1609,7 @@ static int CmdHF14aDesChk(const char *Cmd) { memcpy(&aeskeyList[aeskeyListLen], vkey, 16); aeskeyListLen++; } else if (vkeylen == 24) { - memcpy(&k3kkeyList[k3kkeyListLen], vkey, 16); + memcpy(&k3kkeyList[k3kkeyListLen], vkey, 24); k3kkeyListLen++; } else { PrintAndLogEx(ERR, "Specified key must have 8, 16 or 24 bytes length."); @@ -1614,7 +1675,19 @@ static int CmdHF14aDesChk(const char *Cmd) { int kdfInputLen = 0; CLIGetHexWithReturn(ctx, 10, kdfInput, &kdfInputLen); - bool APDULogging = arg_get_lit(ctx, 11); + // the secure channel is detected per application unless the user pins one + DesfireSecureChannel secureChannel = DACEV1; + bool autoschann = (arg_get_str(ctx, 11)->count == 0); + if (autoschann == false) { + int schann = DACEV1; + if (CLIGetOptionList(arg_get_str(ctx, 11), DesfireSecureChannelOpts, &schann)) { + CLIParserFree(ctx); + return PM3_EINVARG; + } + secureChannel = schann; + } + + bool APDULogging = arg_get_lit(ctx, 12); CLIParserFree(ctx); SetAPDULogging(APDULogging); @@ -1640,7 +1713,7 @@ static int CmdHF14aDesChk(const char *Cmd) { } bool result = false; - uint8_t app_ids[78] = {0}; + uint8_t app_ids[DESFIRE_MAX_APP_COUNT * 3] = {0}; size_t app_ids_len = 0; clearCommandBuffer(); @@ -1649,7 +1722,6 @@ static int CmdHF14aDesChk(const char *Cmd) { DesfireSetKdf(&dctx, cmdKDFAlgo, kdfInput, kdfInputLen); DesfireSetCommandSet(&dctx, DCCNativeISO); DesfireSetCommMode(&dctx, DCMPlain); - DesfireSecureChannel secureChannel = DACEV1; // save card UID to dctx DesfireGetCardUID(&dctx); @@ -1662,13 +1734,23 @@ static int CmdHF14aDesChk(const char *Cmd) { } - res = DesfireGetAIDList(&dctx, app_ids, &app_ids_len); + uint8_t aidbuf[250] = {0}; + size_t aidbuflen = 0; + res = DesfireGetAIDList(&dctx, aidbuf, &aidbuflen); if (res != PM3_SUCCESS) { PrintAndLogEx(ERR, "Can't get list of applications on tag"); DropField(); return PM3_ESOFT; } + if (aidbuflen > sizeof(app_ids)) { + PrintAndLogEx(WARNING, "Card returned " _YELLOW_("%zu") " applications, only checking the first " _YELLOW_("%d"), aidbuflen / 3, DESFIRE_MAX_APP_COUNT); + aidbuflen = sizeof(app_ids); + } + + memcpy(app_ids, aidbuf, aidbuflen); + app_ids_len = aidbuflen; + if (aidlength != 0) { memcpy(&app_ids[0], aid, 3); app_ids_len = 3; @@ -1730,11 +1812,24 @@ static int CmdHF14aDesChk(const char *Cmd) { } } + desfire_keys_dump_t *dump = calloc(1, sizeof(desfire_keys_dump_t)); + if (dump == NULL) { + PrintAndLogEx(ERR, "Failed to allocate memory"); + DropField(); + return PM3_EMALLOC; + } + dump->appcount = app_ids_len / 3; + for (uint32_t x = 0; x < app_ids_len / 3; x++) { uint32_t curaid = (app_ids[x * 3] & 0xFF) + ((app_ids[(x * 3) + 1] & 0xFF) << 8) + ((app_ids[(x * 3) + 2] & 0xFF) << 16); PrintAndLogEx(INFO, "Checking aid " _YELLOW_("%06X"), curaid); + // found keys are tracked per application. A key number recovered on one + // AID must not stop us from checking the same key number on the next one + desfire_app_keys_t *found = &dump->app[x]; + found->aid = curaid; + bool loadedAllKeys = false; size_t desReadStart = 0; size_t desReadEnd = 1; @@ -1795,7 +1890,18 @@ static int CmdHF14aDesChk(const char *Cmd) { loadedAllKeys = true; } - res = AuthCheckDesfire(&dctx, secureChannel, &app_ids[x * 3], deskeyList, deskeyListLen, aeskeyList, aeskeyListLen, k3kkeyList, k3kkeyListLen, cmdKDFAlgo, kdfInputLen, kdfInput, foundKeys, &foundKeyThisRound, verbose); + res = AuthCheckDesfire(&dctx, + secureChannel, + &app_ids[x * 3], + deskeyList, deskeyListLen, + aeskeyList, aeskeyListLen, + k3kkeyList, k3kkeyListLen, + autoschann, + found, + &foundKeyThisRound, + verbose + ); + if (res == PM3_EOPABORTED) { break; } @@ -1829,31 +1935,19 @@ static int CmdHF14aDesChk(const char *Cmd) { uint8_t sel_1813 = 0; if (WaitForIso14aReply(&resp, 2500, NULL, &sel_1813) == false) { PrintAndLogEx(WARNING, "timeout while waiting for reply"); + free(dump); return PM3_ETIMEOUT; } - iso14a_card_select_t card; - memcpy(&card, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t)); - uint64_t select_status = sel_1813; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision - - uint8_t data[10 + 1 + 2 + 1 + 256 + (4 * 0xE * (24 + 1))] = {0}; - uint8_t atslen = 0; if (select_status == 1 || select_status == 2) { - memcpy(data, card.uid, card.uidlen); - data[10] = card.sak; - data[11] = card.atqa[1]; - data[12] = card.atqa[0]; - atslen = card.ats_len; - data[13] = atslen; - memcpy(&data[14], card.ats, atslen); + memcpy(&dump->card_info, (iso14a_card_select_t *)resp.data.asBytes, sizeof(iso14a_card_select_t)); } - // length: UID(10b)+SAK(1b)+ATQA(2b)+ATSlen(1b)+ATS(atslen)+foundKeys[2][64][AES_KEY_LEN + 1] - memcpy(&data[14 + atslen], foundKeys, 4 * 0xE * (24 + 1)); - saveFileJSON((char *)jsonname, jsfMfDesfireKeys, data, 0xE, NULL); + saveFileJSON((char *)jsonname, jsfMfDesfireKeys_v2, (uint8_t *)dump, sizeof(desfire_keys_dump_t), NULL); } + free(dump); DropField(); return PM3_SUCCESS; } @@ -1884,20 +1978,22 @@ static int DesfireAuthCheck(DesfireContext_t *dctx, DesfireISOSelectWay way, uin static int CmdHF14aDesDetect(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes detect", - "Detect key type and tries to find one from the list.", - "hf mfdes detect -> detect key 0 from PICC level\n" - "hf mfdes detect --schann d40 -> detect key 0 from PICC level via secure channel D40\n" - "hf mfdes detect -f mfdes_default_keys -> detect key 0 from PICC level with help of the standard dictionary\n" - "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and if succeed - save params to defaults (`default` command)\n" - "hf mfdes detect --isoid df01 --save -> detect key 0 and save to defaults with card in the LRP mode"); + "Detect PICC master key, key type, communication mode, command set and channel mode.\n" + "Uses `mfdes_default_keys.dic` per default\n" + " `--save` it saves details to be used with `hf mfdes default`\n", + "hf mfdes detect\n" + "hf mfdes detect --schann d40 -> detect from PICC level via secure channel D40\n" + "hf mfdes detect -f my_keys -> detect from PICC level with your own dictionary\n" + "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and save params to defaults\n" + "hf mfdes detect --isoid df01 --save -> detect and save to defaults with card in the LRP mode"); void *argtable[] = { arg_param_begin, arg_lit0("a", "apdu", "Show APDU requests and responses"), arg_lit0("v", "verbose", "Verbose output"), - arg_int0("n", "keyno", "", "Key number"), + arg_int0("n", "keyno", "", "Key number (def: all)"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -1906,7 +2002,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { arg_str0(NULL, "aid", "", "Application ID (3 hex bytes, big endian)"), arg_str0(NULL, "isoid", "", "Application ISO ID (ISO DF ID) (2 hex bytes, big endian)."), arg_str0(NULL, "dfname", "", "Application ISO DF Name (5-16 hex bytes, big endian)"), - arg_str0("f", "file", "", "Filename of dictionary"), + arg_str0("f", "file", "", "Filename of dictionary (default: `" MFDES_DEFAULT_DICT "`)"), arg_lit0(NULL, "save", "Save found key and parameters to defaults"), arg_param_end }; @@ -1935,6 +2031,19 @@ static int CmdHF14aDesDetect(const char *Cmd) { bool save = arg_get_lit(ctx, 15); + // whether the user pinned a secure channel, or we get to detect one + bool schannset = (arg_get_str(ctx, 10)->count > 0); + + // whether the user asked for one key number, or we sweep the application + bool keynoset = (arg_get_int_count(ctx, 3) > 0); + + // no dictionary given - use the bundled DESFire one. The built-in + // g_mifare_plus_default_keys list is 16 byte AES only, so it can produce + // neither the DES nor the 3K3DES defaults this card family ships with + if (dict_filenamelen == 0) { + dict_filenamelen = snprintf((char *)dict_filename, sizeof(dict_filename), "%s", MFDES_DEFAULT_DICT); + } + SetAPDULogging(APDULogging); CLIParserFree(ctx); @@ -1948,6 +2057,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { bool keytypes[4] = {0}; bool uselrp = false; + uint8_t numkeys = 0; uint8_t data[250] = {0}; size_t datalen = 0; @@ -1956,6 +2066,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { if (res == PM3_SUCCESS && datalen >= 2) { uint8_t num_keys = data[1]; + numkeys = num_keys & 0x0F; switch (num_keys >> 6) { case 0: { @@ -2015,14 +2126,59 @@ static int CmdHF14aDesDetect(const char *Cmd) { } } - if (verbose) { + // An AES application runs either the EV1/EV2 channel or LRP, and the key + // settings byte reads the same for both, so it takes one probe to tell them + // apart. Without this an LRP card is only caught when the key settings + // happen to be unreadable and the fallback above runs. + if (schannset == false && uselrp == false && keytypes[T_AES]) { - if (DesfireMFSelected(selectway, id)) { - PrintAndLogEx(INFO, "Check PICC key num: %d (0x%02x)", dctx.keyNum, dctx.keyNum); - } else { - PrintAndLogEx(INFO, "Check: %s key num: %d (0x%02x)", DesfireWayIDStr(selectway, id), dctx.keyNum, dctx.keyNum); + uselrp = DesfireCheckAuthCmd(selectway, id, dctx.keyNum, MFDES_AUTHENTICATE_EV2F, true); + if (uselrp) { + securechann = DACLRP; } + // the probe dropped the field behind us + res = DesfireSelectAndAuthenticateAppW(&dctx, securechann, selectway, id, true, verbose); + if (res != PM3_SUCCESS) { + DropField(); + PrintAndLogEx(FAILED, "Select or authentication %s " _RED_("failed") " after the LRP probe. Result [%d] %s", DesfireWayIDStr(selectway, id), res, DesfireAuthErrorToStr(res)); + return res; + } + } + + // Without -n we sweep every key number the application declares. All keys + // in one DESFire application share an algo, so the first key number that + // succeeds pins the type down for the rest. + uint8_t keynofirst = dctx.keyNum; + uint8_t keynolast = dctx.keyNum; + if (keynoset == false) { + keynofirst = 0; + keynolast = (numkeys > 0 && numkeys <= DESFIRE_MAX_KEY_COUNT) ? (numkeys - 1) : (DESFIRE_MAX_KEY_COUNT - 1); + } + + // What we worked out about the target. Worth printing even when no key is + // found - knowing the app is AES on LRP with 3 keys is half the answer. + char algostr[64] = {0}; + size_t algolen = 0; + for (uint8_t t = T_DES; t <= T_AES; t++) { + if (keytypes[t] == false) { + continue; + } + algolen += snprintf(algostr + algolen, sizeof(algostr) - algolen, "%s%s", (algolen) ? "/" : "", CLIGetOptionListStr(DesfireAlgoOpts, t)); + } + if (algolen == 0) { + snprintf(algostr, sizeof(algostr), "unknown"); + } + + PrintAndLogEx(INFO, "%s... key num " _YELLOW_("0x%02x") ".." _YELLOW_("0x%02x") ", algo " _YELLOW_("%s") ", channel " _YELLOW_("%s"), + (DesfireMFSelected(selectway, id)) ? "PICC level" : DesfireWayIDStr(selectway, id), + keynofirst, + keynolast, + algostr, + CLIGetOptionListStr(DesfireSecureChannelOpts, securechann) + ); + + if (verbose) { PrintAndLogEx(INFO, "keys: DES: %s 2TDEA: %s 3TDEA: %s AES: %s LRP: %s", keytypes[T_DES] ? _GREEN_("YES") : _RED_("NO"), keytypes[T_3DES] ? _GREEN_("YES") : _RED_("NO"), @@ -2032,72 +2188,42 @@ static int CmdHF14aDesDetect(const char *Cmd) { ); } - // for key types - bool found = false; - size_t errcount = 0; - for (uint8_t ktype = T_DES; ktype <= T_AES; ktype++) { + uint8_t foundcount = 0; + uint8_t totalkeys = keynolast - keynofirst + 1; + bool nocard = false; - if (keytypes[ktype] == false) { - continue; - } + // the first key we find is what --save stores + DesfireContext_t savedctx = {0}; + bool savedctxvalid = false; - dctx.keyType = ktype; + for (uint8_t keyno = keynofirst; keyno <= keynolast && nocard == false; keyno++) { - if (verbose) { - PrintAndLogEx(INFO, "Scan key type: %s", CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType)); - } + dctx.keyNum = keyno; + bool found = false; - if (dict_filenamelen == 0) { - // keys from mifaredefault.h - for (int i = 0; i < g_mifare_plus_default_keys_len; i++) { + // for key types + for (uint8_t ktype = T_DES; ktype <= T_AES && found == false; ktype++) { - uint8_t key[DESFIRE_MAX_KEY_SIZE] = {0}; - if (hex_to_bytes(g_mifare_plus_default_keys[i], key, 16) != 16) { - continue; - } - - if (ktype == T_3K3DES) { - memcpy(&key[16], key, 8); - } - - res = DesfireAuthCheck(&dctx, selectway, id, securechann, key); - if (res == PM3_SUCCESS) { - found = true; - break; // all the params already in the dctx - } - - if (res == -10) { - - if (verbose) { - PrintAndLogEx(ERR, "Can't select AID. There is no connection with card."); - } - - found = false; - break; // we can't select app after invalid 1st auth stages - } - - if (res == -11) { - - if (errcount > 10) { - if (verbose) { - PrintAndLogEx(ERR, "Too much errors (%zu) from card", errcount); - } - break; - } - errcount++; - - } else { - errcount = 0; - } + if (keytypes[ktype] == false) { + continue; } - } else { - // keys from file + dctx.keyType = ktype; + + if (verbose) { + PrintAndLogEx(INFO, "Scan key num %d (0x%02x) type: %s", keyno, keyno, CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType)); + } + + // candidate keys come from the dictionary uint8_t keyList[MAX_KEYS_LIST_LEN * MAX_KEY_LEN] = {0}; uint32_t keyListLen = 0; size_t keylen = desfire_get_key_length(dctx.keyType); size_t endFilePosition = 0; + // errors are counted per key type. A bad run on one must not cut + // the next one short before it has tried a single key + size_t errcount = 0; + while (found == false) { res = loadFileDICTIONARYEx((char *)dict_filename, keyList, sizeof(keyList), NULL, keylen, &keyListLen, endFilePosition, &endFilePosition, verbose); @@ -2105,7 +2231,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { break; } - for (int i = 0; i < keyListLen; i++) { + for (uint32_t i = 0; i < keyListLen; i++) { res = DesfireAuthCheck(&dctx, selectway, id, securechann, &keyList[i * keylen]); if (res == PM3_SUCCESS) { @@ -2118,7 +2244,7 @@ static int CmdHF14aDesDetect(const char *Cmd) { PrintAndLogEx(ERR, "Can't select AID. There is no connection with card."); } - found = false; + nocard = true; break; // we can't select app after invalid 1st auth stages } @@ -2135,51 +2261,69 @@ static int CmdHF14aDesDetect(const char *Cmd) { } else { errcount = 0; } + } + if (nocard) { + break; } if (endFilePosition == 0) { break; } } - } if (found) { - break; + + foundcount++; + + if (DesfireMFSelected(selectway, id)) { + PrintAndLogEx(INFO, _GREEN_("Found") " key num: %d (0x%02x)", dctx.keyNum, dctx.keyNum); + } else { + PrintAndLogEx(INFO, "Found key for: %s key num: %d (0x%02x)", DesfireWayIDStr(selectway, id), dctx.keyNum, dctx.keyNum); + } + + PrintAndLogEx(INFO, "Channel " _GREEN_("%s") " key " _GREEN_("%s") " [%d]: " _GREEN_("%s"), + CLIGetOptionListStr(DesfireSecureChannelOpts, securechann), + CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType), + desfire_get_key_length(dctx.keyType), + sprint_hex_inrow(dctx.key, desfire_get_key_length(dctx.keyType)) + ); + + // every key in an application uses the same algo, so the rest of + // the key numbers only have to try the one that just worked + for (uint8_t t = T_DES; t <= T_AES; t++) { + keytypes[t] = (t == dctx.keyType); + } + + if (savedctxvalid == false) { + savedctx = dctx; + savedctxvalid = true; + } + + } else if (verbose && nocard == false) { + PrintAndLogEx(INFO, "Key num: %d (0x%02x) " _RED_("not found"), keyno, keyno); } } - if (found) { - - if (DesfireMFSelected(selectway, id)) { - PrintAndLogEx(INFO, _GREEN_("Found") " key num: %d (0x%02x)", dctx.keyNum, dctx.keyNum); - } else { - PrintAndLogEx(INFO, "Found key for: %s key num: %d (0x%02x)", DesfireWayIDStr(selectway, id), dctx.keyNum, dctx.keyNum); - } - - PrintAndLogEx(INFO, "channel " _GREEN_("%s") " key " _GREEN_("%s") " [%d]: " _GREEN_("%s"), - CLIGetOptionListStr(DesfireSecureChannelOpts, securechann), - CLIGetOptionListStr(DesfireAlgoOpts, dctx.keyType), - desfire_get_key_length(dctx.keyType), - sprint_hex(dctx.key, desfire_get_key_length(dctx.keyType))); - - } else { + if (foundcount == 0) { PrintAndLogEx(INFO, "Key " _RED_("not found")); + } else if (totalkeys > 1) { + PrintAndLogEx(INFO, "Found " _GREEN_("%u") " of %u keys", foundcount, totalkeys); } DropField(); - if (found && save) { + if (savedctxvalid && save) { - defaultKeyNum = dctx.keyNum; - defaultAlgoId = dctx.keyType; - memcpy(defaultKey, dctx.key, DESFIRE_MAX_KEY_SIZE); - defaultKdfAlgo = dctx.kdfAlgo; - defaultKdfInputLen = dctx.kdfInputLen; - memcpy(defaultKdfInput, dctx.kdfInput, sizeof(dctx.kdfInput)); + defaultKeyNum = savedctx.keyNum; + defaultAlgoId = savedctx.keyType; + memcpy(defaultKey, savedctx.key, DESFIRE_MAX_KEY_SIZE); + defaultKdfAlgo = savedctx.kdfAlgo; + defaultKdfInputLen = savedctx.kdfInputLen; + memcpy(defaultKdfInput, savedctx.kdfInput, sizeof(savedctx.kdfInput)); defaultSecureChannel = securechann; - defaultCommSet = dctx.cmdSet; + defaultCommSet = savedctx.cmdSet; PrintAndLogEx(INFO, "-----------" _CYAN_("Default parameters") "---------------------------------"); PrintAndLogEx(INFO, "Key Num....... %d", defaultKeyNum); @@ -2215,7 +2359,7 @@ static int CmdHF14aDesMAD(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -2389,7 +2533,7 @@ static int CmdHF14ADesSelectApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3332,7 +3476,7 @@ static int CmdHF14ADesBruteDAMSlots(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number (default: 0 / PICC key)"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3538,7 +3682,7 @@ static int CmdHF14ADesAuth(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3637,7 +3781,7 @@ static int CmdHF14ADesSetConfiguration(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3735,8 +3879,8 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { "Change crypto algorithm for PICC key is possible, \n" "but for APP keys crypto algorithm is set by createapp command and can't be changed wo application delete\n" "\n" - "hf mfdes changekey --aid 123456 -> execute with default factory setup. change des key 0 in the app 123456 from 00..00 to 00..00\n" - "hf mfdes changekey --isoid df01 -t aes --schann lrp --newkeyno 01 -> change key 01 via lrp channel" + "hf mfdes changekey --aid 123456 -> execute with default factory setup. change des key 0 in the app 123456 from 00..00 to 00..00\n" + "hf mfdes changekey --isoid df01 -t aes --schann lrp --newkeyno 01 -> change key 01 via lrp channel" "hf mfdes changekey -t des --newalgo aes --newkey 11223344556677889900112233445566 --newver a5 -> change card master key to AES one\n" "hf mfdes changekey --aid 123456 -t aes --key 00000000000000000000000000000000 --newkey 11223344556677889900112233445566 -> change app master key\n" "hf mfdes changekey --aid 123456 -t des -n 0 --newkeyno 1 --oldkey 5555555555555555 --newkey 1122334455667788 -> change key 1 with auth from key 0\n" @@ -3748,7 +3892,7 @@ static int CmdHF14ADesChangeKey(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -3910,7 +4054,7 @@ static int CmdHF14ADesCreateApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4087,7 +4231,7 @@ static int CmdHF14ADesCreateDelegateApp(const char *Cmd) { arg_lit0("a", "apdu", "Show APDU requests and responses"), arg_lit0("v", "verbose", "Verbose output"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4404,7 +4548,7 @@ static int CmdHF14ADesGetDelegateAppInfo(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number (default: 0 / PICC key)"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4496,7 +4640,7 @@ static int CmdHF14ADesDeleteApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4560,7 +4704,7 @@ static int CmdHF14ADesGetUID(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4723,7 +4867,7 @@ static int CmdHF14ADesFormatPICC(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4780,7 +4924,7 @@ static int CmdHF14ADesGetFreeMem(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4845,7 +4989,7 @@ static int CmdHF14ADesChKeySettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -4919,7 +5063,7 @@ static int CmdHF14ADesGetKeyVersions(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number for authentication"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5024,7 +5168,7 @@ static int CmdHF14ADesGetKeySettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5104,7 +5248,7 @@ static int CmdHF14ADesGetAIDs(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5176,7 +5320,7 @@ static int CmdHF14ADesGetAppNames(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5239,9 +5383,10 @@ static int CmdHF14ADesGetFileIDs(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes getfileids", "Get File IDs list from card. Master key needs to be provided or flag --no-auth set.", - "hf mfdes getfileids --aid 123456 -> execute with defaults from `default` command\n" - "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --kdf none --aid 123456 -> execute with default factory setup\n" - "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs"); + "hf mfdes getfileids --aid 123456 -> execute with defaults from `default` command\n" + "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs\n" + "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --aid 123456 -> execute with default factory setup\n" + ); void *argtable[] = { arg_param_begin, @@ -5249,7 +5394,7 @@ static int CmdHF14ADesGetFileIDs(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5326,7 +5471,7 @@ static int CmdHF14ADesGetFileISOIDs(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5401,7 +5546,7 @@ static int CmdHF14ADesGetFileSettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5572,7 +5717,7 @@ static int CmdHF14ADesChFileSettings(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5715,7 +5860,7 @@ static int CmdHF14ADesCreateFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5853,7 +5998,7 @@ static int CmdHF14ADesCreateValueFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo (deft: 2TDEA)"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -5979,7 +6124,7 @@ static int CmdHF14ADesCreateRecordFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6098,7 +6243,7 @@ static int CmdHF14ADesCreateTrMACFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6215,7 +6360,7 @@ static int CmdHF14ADesDeleteFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6293,7 +6438,7 @@ static int CmdHF14ADesValueOperations(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo (deft: 2TDEA)"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6478,7 +6623,7 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { CLIParserContext *ctx; CLIParserInit(&ctx, "hf mfdes clearrecfile", "Clear record file. Master key needs to be provided or flag --no-auth set (depend on cards settings).", - "hf mfdes clearrecfile --aid 123456 --fid 01 -> clear record file for: app=123456, file=01 with defaults from `default` command\n" + "hf mfdes clearrecfile --aid 123456 --fid 01 -> clear record file for: app=123456, file=01 with defaults from `default` command\n" "hf mfdes clearrecfile --isoid df01 --fid 01 --schann lrp -t aes -n 3 -> clear record file for lrp channel with key number 3"); void *argtable[] = { @@ -6487,7 +6632,7 @@ static int CmdHF14ADesClearRecordFile(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -6658,7 +6803,7 @@ static int CmdHF14ADesMakeMFCLicense(const char *Cmd) { void *argtable[] = { arg_param_begin, arg_lit0("v", "verbose", "Show more output"), - arg_str0("k", "key", "", "Key for computing the MAC, must be HEX 16(AES)"), + arg_str0("k", "key", "", "Key for computing the MAC (16 hex bytes)"), arg_str0("b", "blk", "[,[,...]]", "The MFC blocks to map, must be given in ascending order (use the special value 'all' for all blocks)"), arg_lit0(NULL, "ka", "Allow updating key A from inside sector trailers mapped to DESFire files"), arg_lit0(NULL, "kb", "Allow updating key B from inside sector trailers mapped to DESFire files"), @@ -6893,7 +7038,7 @@ static int CmdHF14ADesCreateMFCMapping(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7410,7 +7555,7 @@ static int CmdHF14ADesReadData(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7582,7 +7727,7 @@ static int CmdHF14ADesWriteData(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7922,7 +8067,7 @@ static int CmdHF14ADesLsFiles(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -7997,7 +8142,7 @@ static int CmdHF14ADesLsApp(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -8063,7 +8208,7 @@ static int CmdHF14ADesDump(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), arg_int0("n", "keyno", "", "Key number"), arg_str0("t", "algo", "", "Crypt algo"), - arg_str0("k", "key", "", "Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)"), + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), arg_str0("m", "cmode", "", "Communicaton mode"), @@ -9413,7 +9558,7 @@ static int CmdHF14ADesVerifyCert(const char *Cmd) { arg_lit0("v", "verbose", "Verbose output"), // 3 arg_int0("n", "keyno", "", "Key number for DESFire authentication"), // 4 arg_str0("t", "algo", "", "DESFire auth crypt algo"), // 5 - arg_str0("k", "key", "", "DESFire authentication key"), // 6 + arg_str0("k", "key", "", "Key for authenticate (8|16|24 hex bytes)"), // 6 arg_str0(NULL, "kdf", "", "Key Derivation Function (KDF)"), // 7 arg_str0("i", "kdfi", "", "KDF input (1-31 hex bytes)"), // 8 arg_str0("m", "cmode", "", "Communication mode"), // 9 diff --git a/client/src/cmdhfmfhard.c b/client/src/cmdhfmfhard.c index 3f3f47b1b..88204437f 100644 --- a/client/src/cmdhfmfhard.c +++ b/client/src/cmdhfmfhard.c @@ -1733,9 +1733,18 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ if (initialize == false) { const mf_nonces_resp_t *nresp = (const mf_nonces_resp_t *)resp.data.asBytes; - uint16_t num_sampled_nonces = nresp->num_nonces; + uint16_t num_sampled_nonces = nresp->num_nonces & ~1; // nonces come in pairs const uint8_t *bufp = nresp->nonces; + if (resp.length < sizeof(mf_nonces_resp_t) + ((num_sampled_nonces / 2) * MFC_NONCE_PAIR_SIZE)) { + PrintAndLogEx(FAILED, "Truncated nonce reply, got %u bytes for %u nonces", resp.length, num_sampled_nonces); + if (nonce_file_write) { + fclose(fnonces); + } + DropField(); + return PM3_ESOFT; + } + for (uint16_t i = 0; i < num_sampled_nonces; i += 2) { uint32_t nt_enc1 = bytes_to_num(bufp, 4); uint32_t nt_enc2 = bytes_to_num(bufp + 4, 4); @@ -1760,10 +1769,10 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ num_acquired_nonces += add_res; if (nonce_file_write) { - fwrite(bufp, 1, 9, fnonces); + fwrite(bufp, 1, MFC_NONCE_PAIR_SIZE, fnonces); fflush(fnonces); } - bufp += 9; + bufp += MFC_NONCE_PAIR_SIZE; } //total_num_nonces += num_sampled_nonces; diff --git a/client/src/cmdlf.c b/client/src/cmdlf.c index bf8186d73..26fb3d83f 100644 --- a/client/src/cmdlf.c +++ b/client/src/cmdlf.c @@ -1609,8 +1609,7 @@ static bool check_chiptype(bool getDeviceData) { } //Save the state of the Graph and Demod Buffers - buffer_savestate_t saveState_gb = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState_gb.offset = g_GridOffset; + buffer_savestate_t saveState_gb = save_graphbuffer(); buffer_savestate_t saveState_db = save_buffer8(g_DemodBuffer, g_DemodBufferLen); saveState_db.clock = g_DemodClock; saveState_db.offset = g_DemodStartIdx; @@ -1683,12 +1682,12 @@ static bool check_chiptype(bool getDeviceData) { PrintAndLogEx(INFO, "Couldn't identify a chipset"); out: - restore_buffer8(saveState_db, g_DemodBuffer); + // the detections above demodulate, so the length comes back with the contents + g_DemodBufferLen = restore_buffer8(saveState_db, g_DemodBuffer); g_DemodClock = saveState_db.clock; g_DemodStartIdx = saveState_db.offset; - restore_bufferS32(saveState_gb, g_GraphBuffer); - g_GridOffset = saveState_gb.offset; + restore_graphbuffer(saveState_gb); return retval; } diff --git a/client/src/cmdlft55xx.c b/client/src/cmdlft55xx.c index fc9fbd648..67669749b 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 = { @@ -76,6 +78,137 @@ static t55xx_conf_block_t config = { static t55xx_memory_item_t cardmem[T55x7_BLOCK_COUNT] = {{0}}; +// true when the graph buffer holds an addressed block read, where the tag repeats one word every 32 bits. +// 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: +// manchester anchors on the sequence terminator, +// psk starts at whatever phase transition it finds first. +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) + 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) + 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_graphbuffer(); + + 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_graphbuffer(st); +} + +// the bit offset to read a block at in the demod buffer loaded right now +static bool t55xx_demod_offset(uint8_t *idx) { + + if (g_DemodBufferLen < 32) { + PrintAndLogEx(DEBUG, "DEBUG: (t55xx) demod buffer holds %zu bits, need 32", g_DemodBufferLen); + return false; + } + + int32_t bit = config.offset; + + // a different graph length is a different signal, not another read of the + // same one - fall back to the plain offset rather than resolve against it + if (config.anchor_valid && + g_DemodClock > 0 && + (config.anchor_tracelen == (int32_t)g_GraphTraceLen)) { + + // negative when this demodulation started later than the anchored one + const int32_t delta = config.anchor_sample - g_DemodStartIdx; + const int32_t half = g_DemodClock / 2; + + bit = (delta >= 0) ? ((delta + half) / g_DemodClock) : -((-delta + half) / g_DemodClock); + + // landing outside the buffer means this demodulation started a long way + // from the anchored one. an addressed block read repeats every 32 bits, + // so whole periods can be added or dropped to bring the window back in. + // that is a rescue, not a normalisation - a regular read mode capture + // cycles several blocks and would answer with a different one + while (bit < 0) { + bit += 32; + } + while (bit + 32 > (int32_t)g_DemodBufferLen) { + bit -= 32; + } + } + + if (bit < 0 || bit + 32 > (int32_t)g_DemodBufferLen) { + PrintAndLogEx(WARNING, "The configured offset %d is too big. Possible offset: %zu)", bit, g_DemodBufferLen - 32); + return false; + } + + *idx = (uint8_t)bit; + return true; +} + +// a word that is its own rotation cannot say where the boundary is +static bool t55xx_rotation_unique(uint32_t v) { + for (uint8_t r = 1; r < 32; r++) { + if ((((v << r) | (v >> (32 - r))) & 0xFFFFFFFF) == v) { + return false; + } + } + return true; +} + +// true when the demodulated stream carries `data` at some offset. a block read +// repeats the addressed word, so a hit anywhere proves the tag holds it, no +// matter which bit the demodulator started on. a false hit needs a 32 bit +// coincidence in a few hundred positions. re-anchors on the hit, which is the +// one place a data block can say where its own boundary is +static bool t55xx_stream_holds(uint32_t data) { + + if (g_DemodBufferLen < 32) { + return false; + } + + for (size_t i = 0; i + 32 <= g_DemodBufferLen; i++) { + + if (PackBits(0, 32, g_DemodBuffer + i) != data) { + continue; + } + + if (i <= 255 && t55xx_rotation_unique(data)) { + const uint8_t before = config.offset; + t55xx_anchor(&config, (uint8_t)i); + if (before != config.offset) { + PrintAndLogEx(DEBUG, "DEBUG: (t55xx) re-anchored offset %u -> %u", before, config.offset); + } + } + return true; + } + return false; +} + t55xx_conf_block_t Get_t55xx_Config(void) { return config; } @@ -333,7 +466,7 @@ bool t55xxAcquireAndCompareBlock0(bool usepwd, uint32_t password, uint32_t known for (size_t i = 0; i < g_DemodBufferLen - 32; i++) { uint32_t tmp = PackBits(i, 32, g_DemodBuffer); if (tmp == known_block0) { - config.offset = i; + t55xx_anchor(&config, (uint8_t)i); config.downlink_mode = m; return true; } @@ -351,7 +484,10 @@ bool t55xxAcquireAndDetect(bool usepwd, uint32_t password, uint32_t known_block0 if (AcquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, usepwd, password, m) == false) continue; - if (t55xxTryDetectModulationEx(m, verbose, known_block0, (usepwd) ? password : -1) == false) + // password is uint32_t here, so an untyped -1 would be truncated to + // 0xFFFFFFFF by the ternary before it widens, and the `pwd != -1` + // sentinel check inside would read it as a known password + if (t55xxTryDetectModulationEx(m, verbose, known_block0, (usepwd) ? (uint64_t)password : (uint64_t) - 1) == false) continue; config.downlink_mode = m; @@ -362,9 +498,10 @@ bool t55xxAcquireAndDetect(bool usepwd, uint32_t password, uint32_t known_block0 return false; } -bool t55xxVerifyWrite(uint8_t block, bool page1, bool usepwd, uint8_t override, uint32_t password, uint8_t downlink_mode, uint32_t data) { +static bool t55xx_verify_write_ex(uint8_t block, bool page1, bool usepwd, uint8_t override, uint32_t password, uint8_t downlink_mode, uint32_t data, bool redetect) { uint32_t read_data = 0; + bool ok = false; if (downlink_mode == 0xFF) downlink_mode = config.downlink_mode; @@ -372,23 +509,37 @@ bool t55xxVerifyWrite(uint8_t block, bool page1, bool usepwd, uint8_t override, int res = T55xxReadBlockEx(block, page1, usepwd, override, password, downlink_mode, false); if (res == PM3_SUCCESS) { - if (GetT55xxBlockData(&read_data) == false) - return false; + // the value being anywhere in the stream is the proof, not the value at + // one cached offset. a correct write read back on a different bit + // boundary used to report as a validation failure + ok = t55xx_stream_holds(data); - } else if (res == PM3_EWRONGANSWER) { - - // couldn't decode. Lets see if this was a block 0 write and try read/detect it auto. - // this messes up with ppl config.. - if (block == 0 && page1 == false) { - - if (t55xxAcquireAndDetect(usepwd, password, data, true) == false) - return false; - - return t55xxVerifyWrite(block, page1, usepwd, 2, password, config.downlink_mode, data); + if (ok == false && GetT55xxBlockData(&read_data)) { + ok = (read_data == data); } } - return (read_data == data); + if (ok) { + return true; + } + + // A block 0 write changes how the tag talks, so the configuration held from before the write is stale. + // A: he demodulator fails outright, or + // B:_it succeeds on the wrong modulation and answers with garbage + if (block == 0 && page1 == false && redetect) { + + if (t55xxAcquireAndDetect(usepwd, password, data, true) == false) { + return false; + } + + return t55xx_verify_write_ex(block, page1, usepwd, 2, password, config.downlink_mode, data, false); + } + + return false; +} + +bool t55xxVerifyWrite(uint8_t block, bool page1, bool usepwd, uint8_t override, uint32_t password, uint8_t downlink_mode, uint32_t data) { + return t55xx_verify_write_ex(block, page1, usepwd, override, password, downlink_mode, data, true); } int t55xxWrite(uint8_t block, bool page1, bool usepwd, bool testMode, uint32_t password, uint8_t downlink_mode, uint32_t data) { @@ -461,6 +612,9 @@ void SetConfigWithBlock0Ex(uint32_t block0, uint8_t offset, bool Q5) { config.Q5 = Q5; config.ST = sst; config.usepwd = pwd; + if (config.offset != offset) { + config.anchor_valid = false; + } config.offset = offset; config.block0 = block0; } @@ -580,6 +734,7 @@ static int CmdT55xxSetConfig(const char *Cmd) { // validate user specified offset if (offset > -1 && offset < 0x100) { config.offset = offset; + config.anchor_valid = false; } // validate user specific T5555 / Q5 - use the flag to toggle between T5577 and Q5 @@ -688,8 +843,19 @@ int T55xxReadBlockEx(uint8_t block, bool page1, bool usepwd, uint8_t override, u if (DecodeT55xxBlock() == false) return PM3_EWRONGANSWER; - if (verbose) + // block 0 is the one block whose content is known before it is read, so use + // it to re-anchor this capture rather than trusting the one detect left + if (block == T55x7_CONFIGURATION_BLOCK && + page1 == false && + config.block0Status == AUTODETECT && + config.block0 != 0) { + + t55xx_stream_holds(config.block0); + } + + if (verbose) { printT55xxBlock(block, page1); + } return PM3_SUCCESS; } @@ -993,6 +1159,11 @@ static int CmdT55xxDetect(const char *Cmd) { if (SanityOfflineCheck(use_gb) != PM3_SUCCESS) return PM3_ESOFT; + // a replayed buffer carries no promise about how it was captured + if (use_gb) { + s_block_read_capture = false; + } + if (use_gb == false) { char wakecmd[20] = { 0x00 }; @@ -1102,6 +1273,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); @@ -1110,6 +1297,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) { @@ -1133,6 +1324,39 @@ bool t55xxTryDetectModulation(uint8_t downlink_mode, bool print_config) { #define PM3_T55_FALLBACK_MAXERR 100 +// A demodulation that recovers far fewer bits than its clock implies never locked onto the tag, +// Measured on a T5577 over 56 configurations: +// every correct detection recovered at least 98.8% of g_GraphTraceLen / clk bits +#define T55XX_MIN_DEMOD_YIELD_PCT 80 + +static bool t55xx_demod_yield_ok(uint8_t clk) { + + // what actually produced the bits, which is not always what was asked for + const uint32_t used = (g_DemodClock > 0) ? (uint32_t)g_DemodClock : clk; + + if (used == 0 || g_GraphTraceLen == 0) { + return true; + } + + const size_t expected = g_GraphTraceLen / used; + + // too short to say anything either way + if (expected < 32) { + return true; + } + + if (g_DemodBufferLen * 100 >= expected * T55XX_MIN_DEMOD_YIELD_PCT) { + return true; + } + + PrintAndLogEx(DEBUG, "DEBUG: (t55xx test) clk %u recovered %zu bits of %zu, too few to trust" + , used + , g_DemodBufferLen + , expected + ); + return false; +} + static bool block0_repeats_at_stride(uint8_t offset) { if ((size_t)offset + 64 > g_DemodBufferLen || offset > 255 - 32) { @@ -1141,8 +1365,16 @@ static bool block0_repeats_at_stride(uint8_t offset) { return (PackBits(offset, 32, g_DemodBuffer) == PackBits((uint8_t)(offset + 32), 32, g_DemodBuffer)); } -// psk subcarrier in field clocks, or 0 when it could not be measured, so -// callers can skip the constraint rather than filter on a bad reading +// psk subcarrier in field clocks, or 0 when it could not be measured +// At RF/128 a capture is 93 bits, so a word sitting past bit 29 has no second copy to compare against +static bool block0_stride_not_disproved(uint8_t offset) { + + if ((size_t)offset + 64 > g_DemodBufferLen) { + return true; + } + return block0_repeats_at_stride(offset); +} + static uint8_t t55xx_observed_psk_carrier(void) { const int fc = GetPskCarrier(false); return (fc == 2 || fc == 4 || fc == 8) ? (uint8_t)fc : 0; @@ -1226,11 +1458,16 @@ static void t55xx_psk_coherent(int fitclk, uint8_t clk, t55xx_conf_block_t *test continue; } + // sweeping the bit rates means a wrong one can fit first where an RF/16 signal answers at RF/8 + if (s_block_read_capture && block0_stride_not_disproved(tests[*hits].offset) == false) { + continue; + } + tests[*hits].modulation = modes[variant]; tests[*hits].psk_carrier = t55xx_observed_psk_carrier(); tests[*hits].bitrate = bitRate; tests[*hits].inverted = inverted; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1311,10 +1548,15 @@ static void t55xx_ask_coherent(int fitclk, uint8_t clk, t55xx_conf_block_t *test continue; } + // sweeping the bit rates means a wrong one can fit first, so hold a block read to the 32 bit stride + if (s_block_read_capture && block0_stride_not_disproved(tests[*hits].offset) == false) { + continue; + } + tests[*hits].modulation = mode; tests[*hits].bitrate = bitRate; tests[*hits].inverted = (invert != 0); - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1337,13 +1579,24 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l if (mod == PM3_MOD_FSK) { - static const uint8_t rates[] = { 32, 40, 50, 64, 100, 128 }; + // RF/8 is left out on purpose. A bit period of 8 field clocks cannot + // hold a whole cycle of both tones of either legal pair, and measured + // on a T5577 no fsk variant reads back at RF/8 even with the config + // forced and both inversions tried. + // RF/8 stays out: it gains nothing measured, and on a replayed capture, + // where the 32 bit stride cannot be demanded, it aliases a Q5 fsk2a trace + // into a confident wrong answer + static const uint8_t rates[] = { 16, 32, 40, 50, 64, 100, 128 }; const uint8_t pairs[3][2] = { { (uint8_t)fc_hi, (uint8_t)fc_lo }, { 8, 5 }, { 10, 8 } }; - for (int strict = 1; strict >= 0; strict--) { + // An addressed block read repeats the word every 32 bits, + // a candidate that does not is not a configuration + const int last_pass = s_block_read_capture ? 1 : 0; + + for (int strict = 1; strict >= last_pass; strict--) { for (size_t p = 0; p < ARRAYLEN(pairs); p++) { if (pairs[p][0] == 0 || pairs[p][1] == 0) { @@ -1360,7 +1613,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l continue; } - if (strict && block0_repeats_at_stride(tests[*hits].offset) == false) { + if (strict && block0_stride_not_disproved(tests[*hits].offset) == false) { continue; } @@ -1374,7 +1627,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = m; tests[*hits].bitrate = bitRate; tests[*hits].inverted = (inv != 0); - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1388,9 +1641,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) { @@ -1402,7 +1653,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_PSK1; tests[*hits].bitrate = bitRate; tests[*hits].inverted = (inv != 0); - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1417,15 +1668,14 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].psk_carrier = t55xx_observed_psk_carrier(); tests[*hits].bitrate = bitRate; tests[*hits].inverted = false; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; } } - 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); @@ -1449,7 +1699,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_NRZ; tests[*hits].bitrate = bitRate; tests[*hits].inverted = (inv != 0); - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1465,7 +1715,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_ASK; tests[*hits].bitrate = bitRate; tests[*hits].inverted = false; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].downlink_mode = downlink_mode; (*hits)++; return true; @@ -1478,7 +1728,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_ASK; tests[*hits].bitrate = bitRate; tests[*hits].inverted = true; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].downlink_mode = downlink_mode; (*hits)++; return true; @@ -1490,7 +1740,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_BI; tests[*hits].bitrate = bitRate; tests[*hits].inverted = false; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1503,7 +1753,7 @@ static bool t55xx_fallback_try(pm3_mod_t mod, pm3_enc_t enc, int fc_hi, int fc_l tests[*hits].modulation = DEMOD_BIa; tests[*hits].bitrate = bitRate; tests[*hits].inverted = true; - tests[*hits].block0 = PackBits(tests[*hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[*hits]); tests[*hits].ST = false; tests[*hits].downlink_mode = downlink_mode; (*hits)++; @@ -1630,6 +1880,38 @@ static void t55xx_detect_fallback(t55xx_conf_block_t *tests, uint8_t *hits, uint free(sig); } +// The coherent psk detector is only reached when the fitter ranks psk above ask and nrz, and on a weak psk signal it does not at all. +static void t55xx_psk_sweep(t55xx_conf_block_t *tests, uint8_t *hits, uint8_t downlink_mode) { + + if (s_block_read_capture == false) { + return; + } + + static const uint8_t rates[] = { 8, 16, 32, 40, 50, 64, 100, 128 }; + + const uint8_t before = *hits; + + for (size_t r = 0; r < ARRAYLEN(rates) && *hits == before; r++) { + t55xx_psk_coherent(rates[r], rates[r], tests, hits, downlink_mode); + } +} + +// same argument as t55xx_psk_sweep, for the ask and biphase side +static void t55xx_ask_sweep(t55xx_conf_block_t *tests, uint8_t *hits, uint8_t downlink_mode) { + + if (s_block_read_capture == false) { + return; + } + + static const uint8_t rates[] = { 8, 16, 32, 40, 50, 64, 100, 128 }; + + const uint8_t before = *hits; + + for (size_t r = 0; r < ARRAYLEN(rates) && *hits == before; r++) { + t55xx_ask_coherent(rates[r], rates[r], tests, hits, downlink_mode); + } +} + bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32_t wanted_conf, uint64_t pwd) { t55xx_conf_block_t tests[15] = {0}; @@ -1647,7 +1929,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_FSK2; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1660,7 +1942,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_FSK2a; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1678,7 +1960,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_ASK; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].downlink_mode = downlink_mode; ++hits; } @@ -1692,7 +1974,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_ASK; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].downlink_mode = downlink_mode; ++hits; } @@ -1700,7 +1982,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_BI; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1709,7 +1991,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_BIa; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1721,7 +2003,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_NRZ; tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1731,7 +2013,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_NRZ; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1741,15 +2023,12 @@ 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; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1758,7 +2037,7 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].modulation = DEMOD_PSK1; tests[hits].bitrate = bitRate; tests[hits].inverted = true; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; @@ -1772,27 +2051,34 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 tests[hits].psk_carrier = t55xx_observed_psk_carrier(); tests[hits].bitrate = bitRate; tests[hits].inverted = false; - tests[hits].block0 = PackBits(tests[hits].offset, 32, g_DemodBuffer); + t55xx_record_hit(&tests[hits]); tests[hits].ST = false; tests[hits].downlink_mode = downlink_mode; ++hits; } } // inverse waves does not affect this demod - // no psk3 candidate here on purpose: it would demodulate the same - // as psk2 and only differ in the test() constant, which wants two - // adjacent ones - and this demod recovers rising edges, which are - // never adjacent. psk3 is reached by ruling psk2 out instead, see - // t55xx_psk3_resolve() - //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); } } + // The tag only has two legal fsk pair + // An fsk1 tag at RF/32 counts field clocks as 5 and 6 here + if (hits == 0 && s_block_read_capture) { + t55xx_fallback_try(PM3_MOD_FSK, 0, 0, 0, 0, tests, &hits, downlink_mode, false); + } + + if (hits == 0) { + t55xx_psk_sweep(tests, &hits, downlink_mode); + } + + if (hits == 0) { + t55xx_ask_sweep(tests, &hits, downlink_mode); + } + if (hits == 0) { t55xx_detect_fallback(tests, &hits, downlink_mode); } @@ -1802,6 +2088,9 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 config.bitrate = tests[0].bitrate; config.inverted = tests[0].inverted; config.offset = tests[0].offset; + config.anchor_sample = tests[0].anchor_sample; + config.anchor_tracelen = tests[0].anchor_tracelen; + config.anchor_valid = tests[0].anchor_valid; config.block0 = tests[0].block0; config.Q5 = tests[0].Q5; config.ST = tests[0].ST; @@ -1835,6 +2124,9 @@ bool t55xxTryDetectModulationEx(uint8_t downlink_mode, bool print_config, uint32 config.bitrate = tests[i].bitrate; config.inverted = tests[i].inverted; config.offset = tests[i].offset; + config.anchor_sample = tests[i].anchor_sample; + config.anchor_tracelen = tests[i].anchor_tracelen; + config.anchor_valid = tests[i].anchor_valid; config.block0 = tests[i].block0; config.Q5 = tests[i].Q5; config.ST = tests[i].ST; @@ -1892,13 +2184,8 @@ bool testKnownConfigBlock(uint32_t block0) { bool GetT55xxBlockData(uint32_t *blockdata) { - if (g_DemodBufferLen == 0) - return false; - - uint8_t idx = config.offset; - - if (idx + 32 > g_DemodBufferLen) { - PrintAndLogEx(WARNING, "The configured offset %d is too big. Possible offset: %zu)", idx, g_DemodBufferLen - 32); + uint8_t idx = 0; + if (t55xx_demod_offset(&idx) == false) { return false; } @@ -2142,9 +2429,12 @@ static size_t t55xx_psk3_resolve(uint8_t nblk, uint32_t *only) { void printT55xxBlock(uint8_t blockNum, bool page1) { - uint32_t val = 0; - if (GetT55xxBlockData(&val) == false) + uint8_t idx = 0; + if (t55xx_demod_offset(&idx) == false) { return; + } + + uint32_t val = PackBits(0, 32, g_DemodBuffer + idx); uint8_t bytes[4] = {0}; num_to_bytes(val, 4, bytes); @@ -2153,7 +2443,7 @@ void printT55xxBlock(uint8_t blockNum, bool page1) { const char *note = t55xx_config_psk3_ambiguous() ? _YELLOW_(" <- psk2/psk3 ambiguous") : ""; - PrintAndLogEx(SUCCESS, " %02d | %08X | %s | %s%s", blockNum, val, sprint_bytebits_bin(g_DemodBuffer + config.offset, 32), sprint_ascii(bytes, 4), note); + PrintAndLogEx(SUCCESS, " %02d | %08X | %s | %s%s", blockNum, val, sprint_bytebits_bin(g_DemodBuffer + idx, 32), sprint_ascii(bytes, 4), note); } static bool testModulation(uint8_t mode, uint8_t modread) { @@ -2314,6 +2604,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) { @@ -2330,57 +2781,22 @@ 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; - - //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; } *fndBitRate = bitRate; *offset = (uint8_t)idx; + + PrintAndLogEx(DEBUG, "DEBUG: (t55xx test) accepted mode %u clk %u rate %d offset %u bits %zu of %zu" + , mode + , clk + , bitRate + , idx + , g_DemodBufferLen + , (clk > 0) ? (g_GraphTraceLen / clk) : 0 + ); return true; } @@ -2402,6 +2818,10 @@ bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5) return false; } + if (t55xx_demod_yield_ok(clk) == false) { + return false; + } + // Scan as far as the buffer allows rather than stopping at bit 64. // // The tag repeats its configuration every 32 bits, so a window of 36 @@ -2640,14 +3060,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]; } } @@ -3302,13 +3715,12 @@ static int CmdT55xxInfo(const char *Cmd) { return PM3_ESOFT; } - // too little space to start with - if (g_DemodBufferLen < 32 + config.offset) { + uint8_t boff = 0; + if (t55xx_demod_offset(&boff) == false) { return PM3_ESOFT; } - //PrintAndLogEx(NORMAL, "Offset+32 ==%d\n DemodLen == %d", config.offset + 32, g_DemodBufferLen); - block0 = PackBits(config.offset, 32, g_DemodBuffer); + block0 = PackBits(0, 32, g_DemodBuffer + boff); } PrintAndLogEx(NORMAL, ""); @@ -3711,6 +4123,8 @@ bool AcquireData(uint8_t page, uint8_t block, bool pwdmode, uint32_t password, u payload.pwdmode = pwdmode; payload.downlink_mode = downlink_mode; + s_block_read_capture = (block != REGULAR_READ_MODE_BLOCK); + clearCommandBuffer(); SendCommandNG(CMD_LF_T55XX_READBL, (uint8_t *)&payload, sizeof(payload)); if (WaitForResponseTimeout(CMD_LF_T55XX_READBL, NULL, 2500) == false) { diff --git a/client/src/cmdlft55xx.h b/client/src/cmdlft55xx.h index a0ded1fa7..750e51d17 100644 --- a/client/src/cmdlft55xx.h +++ b/client/src/cmdlft55xx.h @@ -20,6 +20,7 @@ #define CMDLFT55XX_H__ #include "common.h" +#include #define T55x7_CONFIGURATION_BLOCK 0x00 #define T55x7_PWD_BLOCK 0x07 @@ -158,10 +159,13 @@ typedef struct { } bitrate; bool Q5; bool ST; - uint8_t psk_carrier; // observed psk subcarrier in field clocks, 2/4/8. 0 = not measured - uint8_t broadcast_blocks; // measured blocks per regular-read cycle. 0 = not measured - bool psk3_favoured; // data blocks lean psk3, but do not settle it - bool pwd_known; // usepwd below reflects a live detect, not a default + int32_t anchor_sample; + int32_t anchor_tracelen; // graph length it was taken on, so a loaded file + bool anchor_valid; // anchor_sample came from a live demodulation + uint8_t psk_carrier; // observed psk subcarrier in field clocks, 2/4/8. 0 = not measured + uint8_t broadcast_blocks; // measured blocks per regular-read cycle. 0 = not measured + bool psk3_favoured; // data blocks lean psk3, but do not settle it + bool pwd_known; // usepwd below reflects a live detect, not a default bool usepwd; uint32_t pwd; enum { diff --git a/client/src/cmdlfti.c b/client/src/cmdlfti.c index 17d843a7c..57965d8d2 100644 --- a/client/src/cmdlfti.c +++ b/client/src/cmdlfti.c @@ -89,8 +89,7 @@ int demodTI(bool verbose) { 1, 1, 1, 1, 1, 1, 1, 1 }; - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); int lowLen = ARRAYLEN(LowTone); int highLen = ARRAYLEN(HighTone); @@ -278,8 +277,7 @@ int demodTI(bool verbose) { out: if (retval != PM3_SUCCESS) { - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); } return retval; diff --git a/client/src/cmdlfvisa2000.c b/client/src/cmdlfvisa2000.c index 092f38e30..93e8ff466 100644 --- a/client/src/cmdlfvisa2000.c +++ b/client/src/cmdlfvisa2000.c @@ -84,8 +84,7 @@ static uint8_t visa_parity(uint32_t id) { //see ASKDemod for what args are accepted int demodVisa2k(bool verbose) { (void) verbose; // unused so far - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); //CmdAskEdgeDetect(""); @@ -93,8 +92,7 @@ int demodVisa2k(bool verbose) { bool st = true; if (ASKDemod_ext(64, 0, 0, 0, false, false, false, 1, &st) != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: ASK/Manchester Demod failed"); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } size_t size = g_DemodBufferLen; @@ -109,8 +107,7 @@ int demodVisa2k(bool verbose) { else PrintAndLogEx(DEBUG, "DEBUG: Error - Visa2k: ans: %d", ans); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } setDemodBuff(g_DemodBuffer, 96, ans); @@ -128,8 +125,7 @@ int demodVisa2k(bool verbose) { // test checksums if (chk != calc) { PrintAndLogEx(DEBUG, "DEBUG: error: Visa2000 checksum (%s) %x - %x\n", _RED_("fail"), chk, calc); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } // parity @@ -137,8 +133,7 @@ int demodVisa2k(bool verbose) { uint8_t chk_par = (raw3 & 0xFF0) >> 4; if (calc_par != chk_par) { PrintAndLogEx(DEBUG, "DEBUG: error: Visa2000 parity (%s) %x - %x\n", _RED_("fail"), chk_par, calc_par); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } PrintAndLogEx(SUCCESS, "Visa2000 - Card " _GREEN_("%u") ", Raw: %08X%08X%08X", raw2, raw1, raw2, raw3); diff --git a/client/src/cmdlfzx8211.c b/client/src/cmdlfzx8211.c index 793cc3d54..00e19d152 100644 --- a/client/src/cmdlfzx8211.c +++ b/client/src/cmdlfzx8211.c @@ -41,8 +41,7 @@ static int CmdHelp(const char *Cmd); // see ASKDemod for what args are accepted int demodzx(bool verbose) { (void) verbose; // unused so far - buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); - saveState.offset = g_GridOffset; + buffer_savestate_t saveState = save_graphbuffer(); // CmdAskEdgeDetect(""); @@ -50,8 +49,7 @@ int demodzx(bool verbose) { bool st = true; if (ASKDemod_ext(64, 0, 0, 0, false, false, false, 1, &st) != PM3_SUCCESS) { PrintAndLogEx(DEBUG, "DEBUG: Error - ZX: ASK/Manchester Demod failed"); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } size_t size = g_DemodBufferLen; @@ -66,8 +64,7 @@ int demodzx(bool verbose) { else PrintAndLogEx(DEBUG, "DEBUG: Error - ZX: ans: %d", ans); - restore_bufferS32(saveState, g_GraphBuffer); - g_GridOffset = saveState.offset; + restore_graphbuffer(saveState); return PM3_ESOFT; } setDemodBuff(g_DemodBuffer, 96, ans); diff --git a/client/src/emrtd/emrtd_pace.c b/client/src/emrtd/emrtd_pace.c index 1af3a8674..b8aa44047 100644 --- a/client/src/emrtd/emrtd_pace.c +++ b/client/src/emrtd/emrtd_pace.c @@ -26,6 +26,8 @@ #include #include #include +#include +#include #include "crypto/libpcrypto.h" // sha1hash, sha256hash, des_encrypt/decrypt, pcrypto_rng_* #include "ui.h" // PrintAndLogEx @@ -86,6 +88,140 @@ static const emrtd_pacesdp_t pacesdp_table[] = { {32, NULL, 0, false, MBEDTLS_ECP_DP_NONE} }; +// Every SecurityInfo protocol that can share EF_CardAccess / EF_DG14 with the +// PACE entries. EF_CardAccess is a SET OF SecurityInfo, so a document lists +// everything it supports in there, not just PACE. TR-03110 part 3, A.1.1.1 +// covers the 0.4.0.127.0.7.2.2.x arcs, ICAO 9303-11 section 9 the ICAO ones. +// We do not run these protocols, but naming them beats printing a hex blob. +typedef struct { + size_t oidlen; + uint8_t oid[EMRTD_PACE_OID_MAXLEN]; + emrtd_si_t kind; + const char *name; +} emrtd_secinfo_t; + +// 0.4.0.127.0.7.2.2, bsi-de protocols(2) smartcard(2) +#define BSI_SC 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02 +// 2.23.136.1.1, id-icao-mrtd-security +#define ICAO_SEC 0x67, 0x81, 0x08, 0x01, 0x01 + +static const emrtd_secinfo_t secinfo_table[] = { +// len oid kind name + // id-PK, ChipAuthenticationPublicKeyInfo + {8, {BSI_SC, 0x01}, EMRTD_SI_PK, "Chip Authentication Public Key"}, + {9, {BSI_SC, 0x01, 0x01}, EMRTD_SI_PK, "Chip Authentication Public Key, DH"}, + {9, {BSI_SC, 0x01, 0x02}, EMRTD_SI_PK, "Chip Authentication Public Key, ECDH"}, + + // id-TA, TerminalAuthenticationInfo. The signature arcs below it show up in + // CV certificates rather than in EF_CardAccess, they are here for lookups. + {8, {BSI_SC, 0x02}, EMRTD_SI_TA, "Terminal Authentication"}, + {9, {BSI_SC, 0x02, 0x01}, EMRTD_SI_TA, "Terminal Authentication, RSA"}, + {10, {BSI_SC, 0x02, 0x01, 0x01}, EMRTD_SI_TA, "Terminal Authentication, RSA PKCS#1 v1.5 SHA-1"}, + {10, {BSI_SC, 0x02, 0x01, 0x02}, EMRTD_SI_TA, "Terminal Authentication, RSA PKCS#1 v1.5 SHA-256"}, + {10, {BSI_SC, 0x02, 0x01, 0x03}, EMRTD_SI_TA, "Terminal Authentication, RSA PSS SHA-1"}, + {10, {BSI_SC, 0x02, 0x01, 0x04}, EMRTD_SI_TA, "Terminal Authentication, RSA PSS SHA-256"}, + {10, {BSI_SC, 0x02, 0x01, 0x05}, EMRTD_SI_TA, "Terminal Authentication, RSA PKCS#1 v1.5 SHA-512"}, + {10, {BSI_SC, 0x02, 0x01, 0x06}, EMRTD_SI_TA, "Terminal Authentication, RSA PSS SHA-512"}, + {9, {BSI_SC, 0x02, 0x02}, EMRTD_SI_TA, "Terminal Authentication, ECDSA"}, + {10, {BSI_SC, 0x02, 0x02, 0x01}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-1"}, + {10, {BSI_SC, 0x02, 0x02, 0x02}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-224"}, + {10, {BSI_SC, 0x02, 0x02, 0x03}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-256"}, + {10, {BSI_SC, 0x02, 0x02, 0x04}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-384"}, + {10, {BSI_SC, 0x02, 0x02, 0x05}, EMRTD_SI_TA, "Terminal Authentication, ECDSA SHA-512"}, + + // id-CA. The 9 byte arcs are ChipAuthenticationDomainParameterInfo, the + // 10 byte ones ChipAuthenticationInfo. + {8, {BSI_SC, 0x03}, EMRTD_SI_CA, "Chip Authentication"}, + {9, {BSI_SC, 0x03, 0x01}, EMRTD_SI_CA_DP, "Chip Authentication, DH"}, + {10, {BSI_SC, 0x03, 0x01, 0x01}, EMRTD_SI_CA, "Chip Authentication, DH, 3DES-CBC-CBC"}, + {10, {BSI_SC, 0x03, 0x01, 0x02}, EMRTD_SI_CA, "Chip Authentication, DH, AES-CMAC-128"}, + {10, {BSI_SC, 0x03, 0x01, 0x03}, EMRTD_SI_CA, "Chip Authentication, DH, AES-CMAC-192"}, + {10, {BSI_SC, 0x03, 0x01, 0x04}, EMRTD_SI_CA, "Chip Authentication, DH, AES-CMAC-256"}, + {9, {BSI_SC, 0x03, 0x02}, EMRTD_SI_CA_DP, "Chip Authentication, ECDH"}, + {10, {BSI_SC, 0x03, 0x02, 0x01}, EMRTD_SI_CA, "Chip Authentication, ECDH, 3DES-CBC-CBC"}, + {10, {BSI_SC, 0x03, 0x02, 0x02}, EMRTD_SI_CA, "Chip Authentication, ECDH, AES-CMAC-128"}, + {10, {BSI_SC, 0x03, 0x02, 0x03}, EMRTD_SI_CA, "Chip Authentication, ECDH, AES-CMAC-192"}, + {10, {BSI_SC, 0x03, 0x02, 0x04}, EMRTD_SI_CA, "Chip Authentication, ECDH, AES-CMAC-256"}, + + // id-PACE. The leaves live in pacealg_table, these two are the + // PACEDomainParameterInfo arcs. + {8, {BSI_SC, 0x04}, EMRTD_SI_PACE, "PACE"}, + {9, {BSI_SC, 0x04, 0x01}, EMRTD_SI_PACE_DP, "PACE, DH domain parameters"}, + {9, {BSI_SC, 0x04, 0x02}, EMRTD_SI_PACE_DP, "PACE, ECDH domain parameters"}, + + // id-RI. 9 byte arcs are RestrictedIdentificationDomainParameterInfo. + {8, {BSI_SC, 0x05}, EMRTD_SI_RI, "Restricted Identification"}, + {9, {BSI_SC, 0x05, 0x01}, EMRTD_SI_RI_DP, "Restricted Identification, DH"}, + {10, {BSI_SC, 0x05, 0x01, 0x01}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-1"}, + {10, {BSI_SC, 0x05, 0x01, 0x02}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-224"}, + {10, {BSI_SC, 0x05, 0x01, 0x03}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-256"}, + {10, {BSI_SC, 0x05, 0x01, 0x04}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-384"}, + {10, {BSI_SC, 0x05, 0x01, 0x05}, EMRTD_SI_RI, "Restricted Identification, DH, SHA-512"}, + {9, {BSI_SC, 0x05, 0x02}, EMRTD_SI_RI_DP, "Restricted Identification, ECDH"}, + {10, {BSI_SC, 0x05, 0x02, 0x01}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-1"}, + {10, {BSI_SC, 0x05, 0x02, 0x02}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-224"}, + {10, {BSI_SC, 0x05, 0x02, 0x03}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-256"}, + {10, {BSI_SC, 0x05, 0x02, 0x04}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-384"}, + {10, {BSI_SC, 0x05, 0x02, 0x05}, EMRTD_SI_RI, "Restricted Identification, ECDH, SHA-512"}, + + {8, {BSI_SC, 0x06}, EMRTD_SI_CI, "Card Info Locator"}, + {8, {BSI_SC, 0x07}, EMRTD_SI_EIDSECURITY, "eID Security"}, + {8, {BSI_SC, 0x08}, EMRTD_SI_PT, "Privileged Terminal"}, + + {5, {ICAO_SEC}, EMRTD_SI_UNKNOWN, "ICAO MRTD security"}, + {6, {ICAO_SEC, 0x05}, EMRTD_SI_AA, "Active Authentication"}, + {6, {ICAO_SEC, 0x0D}, EMRTD_SI_EFDIR, "EF.DIR"}, + + {0, {0}, EMRTD_SI_UNKNOWN, NULL} +}; + +#undef BSI_SC +#undef ICAO_SEC + +const char *emrtd_secinfo_name(const uint8_t *oid, size_t oidlen, emrtd_si_t *kind) { + const emrtd_secinfo_t *best = NULL; + + // longest prefix wins, so an arc we did not enumerate still resolves to its + // family instead of falling through to "unknown" + for (int i = 0; secinfo_table[i].name != NULL; i++) { + const emrtd_secinfo_t *e = &secinfo_table[i]; + if ((e->oidlen > oidlen) || (memcmp(e->oid, oid, e->oidlen) != 0)) { + continue; + } + if ((best == NULL) || (e->oidlen > best->oidlen)) { + best = e; + } + } + + if (best == NULL) { + if (kind != NULL) { + *kind = EMRTD_SI_UNKNOWN; + } + return NULL; + } + + if (kind != NULL) { + *kind = best->kind; + } + return best->name; +} + +void emrtd_oid_to_str(const uint8_t *oid, size_t oidlen, char *out, size_t outlen) { + if ((out == NULL) || (outlen == 0)) { + return; + } + out[0] = 0x00; + + mbedtls_asn1_buf buf; + buf.tag = MBEDTLS_ASN1_OID; + buf.len = oidlen; + buf.p = (uint8_t *)oid; + + if (mbedtls_oid_get_numeric_string(out, outlen, &buf) < 0) { + out[0] = 0x00; + } +} + const emrtd_pacealg_t *emrtd_pace_alg_by_oid(const uint8_t *oid, size_t oidlen) { for (int i = 0; pacealg_table[i].name != NULL; i++) { if (pacealg_table[i].oidlen == oidlen && memcmp(pacealg_table[i].oid, oid, oidlen) == 0) { @@ -492,14 +628,51 @@ static bool emrtd_asn1_uint(const uint8_t *value, size_t valuelen, uint32_t *out // The PACEDomainParameterInfo protocol OIDs, TR-03110 part 3, A.1.1. // 0.4.0.127.0.7.2.2.4.1 (DH) and .2 (ECDH) +// 0.4.0.127.0.7.2.2.4, id-PACE itself +static const uint8_t oid_pace[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04}; static const uint8_t oid_pace_dh_dp[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x01}; static const uint8_t oid_pace_ecdh_dp[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x04, 0x02}; static void emrtd_pace_classify(emrtd_paceinfo_t *info) { info->supported = false; + // Only PACEInfo entries are candidates for the session. The rest of + // EF_CardAccess describes protocols this client does not run, say so + // instead of calling them unsupported PACE algorithms. + switch (info->kind) { + case EMRTD_SI_PACE: + break; + case EMRTD_SI_PACE_DP: + info->reason = "domain parameter definition, informational"; + return; + case EMRTD_SI_CA: + case EMRTD_SI_CA_DP: + case EMRTD_SI_PK: + info->reason = "not a PACE protocol, EAC Chip Authentication is not implemented"; + return; + case EMRTD_SI_TA: + info->reason = "not a PACE protocol, needs an EAC inspection system certificate"; + return; + case EMRTD_SI_RI: + case EMRTD_SI_RI_DP: + info->reason = "not a PACE protocol, needs an EAC sector key"; + return; + case EMRTD_SI_AA: + info->reason = "not a PACE protocol, uses the public key in EF_DG15"; + return; + case EMRTD_SI_CI: + case EMRTD_SI_EIDSECURITY: + case EMRTD_SI_PT: + case EMRTD_SI_EFDIR: + info->reason = "informational, not a PACE protocol"; + return; + case EMRTD_SI_UNKNOWN: + info->reason = "unknown protocol OID"; + return; + } + if (info->alg == NULL) { - info->reason = "unknown protocol OID"; + info->reason = "unknown PACE algorithm OID"; return; } @@ -601,43 +774,45 @@ static void emrtd_pace_parse_securityinfo(const uint8_t *seq, size_t seqlen, emr memcpy(info->oid, val, vlen); info->oidlen = vlen; info->alg = emrtd_pace_alg_by_oid(val, vlen); + info->protocol = emrtd_secinfo_name(val, vlen, &info->kind); - if (is_domain_param) { - // SEQUENCE { OID, AlgorithmIdentifier, INTEGER parameterId OPTIONAL } - if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { - return; - } - if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) && (tag == ASN1_TAG_INTEGER)) { - uint32_t v = 0; - if (emrtd_asn1_uint(val, vlen, &v) && (v <= 0xFF)) { - info->has_param = true; - info->param_id = (uint8_t)v; - info->sdp = emrtd_pace_sdp_by_id(info->param_id); - } - } - info->supported = false; - info->reason = "domain parameter definition, informational"; - out->count++; - return; + if (info->alg != NULL) { + // a PACEInfo we can act on, pacealg_table has the better name + info->kind = EMRTD_SI_PACE; + info->protocol = info->alg->name; + } else if (is_domain_param) { + info->kind = EMRTD_SI_PACE_DP; + } else if ((vlen > sizeof(oid_pace)) && (memcmp(val, oid_pace, sizeof(oid_pace)) == 0)) { + // an id-PACE arc we do not implement, still a PACEInfo and not a + // domain parameter definition + info->kind = EMRTD_SI_PACE; } - // PACEInfo ::= SEQUENCE { protocol OID, version INTEGER, parameterId INTEGER OPTIONAL } - if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) == false) { - return; - } - if (tag != ASN1_TAG_INTEGER) { - return; - } - if (emrtd_asn1_uint(val, vlen, &info->version) == false) { - return; + // Second element: + // PACEInfo / ChipAuthenticationInfo / TerminalAuthenticationInfo version INTEGER + // PACEDomainParameterInfo / ChipAuthenticationPublicKeyInfo an AlgorithmIdentifier + // or SubjectPublicKeyInfo + // Take it as the version only when it really is an INTEGER. + if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) && (tag == ASN1_TAG_INTEGER)) { + emrtd_asn1_uint(val, vlen, &info->version); } + // Third element, an optional INTEGER. For the PACE entries that is the + // standardized domain parameter id of table A.2, for the Chip + // Authentication ones it is a keyId and must not be read as a curve. if (emrtd_tlv_next(&cur, end, &tag, &val, &vlen) && (tag == ASN1_TAG_INTEGER)) { uint32_t v = 0; - if (emrtd_asn1_uint(val, vlen, &v) && (v <= 0xFF)) { - info->has_param = true; - info->param_id = (uint8_t)v; - info->sdp = emrtd_pace_sdp_by_id(info->param_id); + if (emrtd_asn1_uint(val, vlen, &v)) { + if ((info->kind == EMRTD_SI_PACE) || (info->kind == EMRTD_SI_PACE_DP)) { + if (v <= 0xFF) { + info->has_param = true; + info->param_id = (uint8_t)v; + info->sdp = emrtd_pace_sdp_by_id(info->param_id); + } + } else { + info->has_key_id = true; + info->key_id = v; + } } } diff --git a/client/src/emrtd/emrtd_pace.h b/client/src/emrtd/emrtd_pace.h index e42f8189d..5e76ec7be 100644 --- a/client/src/emrtd/emrtd_pace.h +++ b/client/src/emrtd/emrtd_pace.h @@ -57,6 +57,27 @@ typedef enum { EMRTD_PACE_CIPHER_AES256, } emrtd_pace_cipher_t; +// EF_CardAccess is a SET OF SecurityInfo, not a list of PACE algorithms. A +// document announces everything it can do in there, so Chip Authentication and +// Terminal Authentication share the file with the PACE entries. Only +// EMRTD_SI_PACE entries are candidates for the session we are about to open. +typedef enum { + EMRTD_SI_UNKNOWN = 0, + EMRTD_SI_PACE, // PACEInfo + EMRTD_SI_PACE_DP, // PACEDomainParameterInfo + EMRTD_SI_CA, // ChipAuthenticationInfo + EMRTD_SI_CA_DP, // ChipAuthenticationDomainParameterInfo + EMRTD_SI_PK, // ChipAuthenticationPublicKeyInfo + EMRTD_SI_TA, // TerminalAuthenticationInfo + EMRTD_SI_RI, // RestrictedIdentificationInfo + EMRTD_SI_RI_DP, // RestrictedIdentificationDomainParameterInfo + EMRTD_SI_CI, // CardInfoLocator + EMRTD_SI_EIDSECURITY, // eIDSecurityInfo + EMRTD_SI_PT, // PrivilegedTerminalInfo + EMRTD_SI_AA, // ActiveAuthenticationInfo + EMRTD_SI_EFDIR, // EFDIRInfo +} emrtd_si_t; + typedef struct emrtd_pacealg_s { const char *name; emrtd_pace_ka_t ka; @@ -79,12 +100,16 @@ typedef struct emrtd_pacesdp_s { // One parsed SecurityInfo out of EF_CardAccess typedef struct { - const emrtd_pacealg_t *alg; // NULL when the OID is unknown to us + const emrtd_pacealg_t *alg; // NULL unless this is a PACEInfo we know + emrtd_si_t kind; // which SecurityInfo this is + const char *protocol; // pretty name, NULL when the OID is unknown uint8_t oid[EMRTD_PACE_OID_MAXLEN]; size_t oidlen; uint32_t version; bool has_param; uint8_t param_id; + bool has_key_id; // ChipAuthentication* keyId, not a PACE thing + uint32_t key_id; const emrtd_pacesdp_t *sdp; // NULL when param_id is unknown/absent bool supported; const char *reason; // why not supported, NULL when it is @@ -151,6 +176,11 @@ int emrtd_retail_mac(const uint8_t *key, const uint8_t *input, size_t inputlen, // Table lookups //----------------------------------------------------------------------------- const emrtd_pacealg_t *emrtd_pace_alg_by_oid(const uint8_t *oid, size_t oidlen); +// Names any SecurityInfo protocol OID, PACE or not. Longest prefix wins, so an +// arc we did not enumerate still resolves to its family. NULL when unknown. +const char *emrtd_secinfo_name(const uint8_t *oid, size_t oidlen, emrtd_si_t *kind); +// Dotted decimal form of a BER encoded OID body, for reporting +void emrtd_oid_to_str(const uint8_t *oid, size_t oidlen, char *out, size_t outlen); const emrtd_pacesdp_t *emrtd_pace_sdp_by_id(uint8_t id); const char *emrtd_pace_cipher_name(emrtd_pace_cipher_t cipher); diff --git a/client/src/emrtd/emrtd_pacetest.c b/client/src/emrtd/emrtd_pacetest.c index 463a790b9..d0646601d 100644 --- a/client/src/emrtd/emrtd_pacetest.c +++ b/client/src/emrtd/emrtd_pacetest.c @@ -547,6 +547,67 @@ static bool test_cardaccess(void) { return res; } +static bool test_cardaccess_secinfo(void) { + // EF_CardAccess is a SET OF SecurityInfo, not a list of PACE algorithms. + // This is the shape a document with EAC has: + // PACEInfo ECDH-GM-AES-CMAC-128, v2, BrainpoolP256r1 + // TerminalAuthenticationInfo id-TA, v1 + // ChipAuthenticationInfo id-CA-ECDH-AES-CBC-CMAC-128, v1, keyId 16 + const char *blob = + "3137" + "3012" "060A04007F0007020204020202010202010D" + "300D" "060804007F0007020202" "020101" + "3012" "060A04007F00070202030202" "020101" "020110"; + + uint8_t data[128] = { 0x00 }; + size_t datalen = unhex(blob, data, sizeof(data)); + + emrtd_cardaccess_t ca; + bool res = (datalen > 0); + res = res && (emrtd_pace_parse_cardaccess(data, datalen, &ca) == PM3_SUCCESS); + // the non-PACE entries must survive parsing, they used to be dropped or + // reported as unknown PACE algorithms + res = res && (ca.count == 3); + res = res && (ca.best == 0); + + res = res && (ca.infos[0].kind == EMRTD_SI_PACE) && (ca.infos[0].supported); + res = res && (ca.infos[0].has_param) && (ca.infos[0].param_id == 13); + + res = res && (ca.infos[1].kind == EMRTD_SI_TA); + res = res && (ca.infos[1].alg == NULL) && (ca.infos[1].supported == false); + res = res && (ca.infos[1].version == 1); + res = res && (ca.infos[1].protocol != NULL) && + (strcmp(ca.infos[1].protocol, "Terminal Authentication") == 0); + + res = res && (ca.infos[2].kind == EMRTD_SI_CA); + res = res && (ca.infos[2].alg == NULL) && (ca.infos[2].supported == false); + res = res && (ca.infos[2].version == 1); + res = res && (ca.infos[2].protocol != NULL) && + (strcmp(ca.infos[2].protocol, "Chip Authentication, ECDH, AES-CMAC-128") == 0); + // a ChipAuthenticationInfo keyId is not a standardized domain parameter id + res = res && (ca.infos[2].has_param == false); + res = res && (ca.infos[2].has_key_id) && (ca.infos[2].key_id == 16); + res = res && (ca.infos[2].sdp == NULL); + + // an id-TA arc we did not enumerate still resolves to its family + const uint8_t ta_odd[] = {0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x02, 0x02, 0x7F}; + emrtd_si_t kind = EMRTD_SI_UNKNOWN; + const char *name = emrtd_secinfo_name(ta_odd, sizeof(ta_odd), &kind); + res = res && (kind == EMRTD_SI_TA) && (name != NULL); + + // and something outside both roots must stay unknown + const uint8_t bogus[] = {0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D}; + res = res && (emrtd_secinfo_name(bogus, sizeof(bogus), &kind) == NULL); + res = res && (kind == EMRTD_SI_UNKNOWN); + + char oidstr[64] = { 0x00 }; + emrtd_oid_to_str(ca.infos[1].oid, ca.infos[1].oidlen, oidstr, sizeof(oidstr)); + res = res && (strcmp(oidstr, "0.4.0.127.0.7.2.2.2") == 0); + + PrintAndLogEx(SUCCESS, "SecurityInfos.... ( %s )", (res) ? _GREEN_("ok") : _RED_("fail")); + return res; +} + // Chip Authentication Mapping. // // The chip sends t = SK.Map.IC * SK.CA.IC^-1 mod n encrypted with KSenc, so @@ -667,6 +728,7 @@ bool emrtd_test(bool verbose) { res = test_kdf() && res; res = test_nonce() && res; res = test_cardaccess() && res; + res = test_cardaccess_secinfo() && res; res = test_gm() && res; res = test_ec_keygen() && res; res = test_token() && res; diff --git a/client/src/fileutils.c b/client/src/fileutils.c index 0763efc7a..42a98f3f2 100644 --- a/client/src/fileutils.c +++ b/client/src/fileutils.c @@ -982,6 +982,53 @@ int prepareJSON(json_t *root, JSONFileType ftype, uint8_t *data, size_t datalen, } break; } + case jsfMfDesfireKeys_v2: { + + // key lengths and names, indexed by DesfireCryptoAlgorithm + static const char *algo_name[DESFIRE_MAX_ALGO_COUNT] = {"DES", "2TDEA", "3TDEA", "AES"}; + static const uint8_t algo_keylen[DESFIRE_MAX_ALGO_COUNT] = { + DES_KEY_LEN, T2DES_KEY_LEN, T3DES_KEY_LEN, AES_KEY_LEN + }; + + desfire_keys_dump_t *dump = (desfire_keys_dump_t *)(void *)data; + + JsonSaveStr(root, "FileType", "mfdes v2"); + + if (dump->card_info.uidlen > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.UID", dump->card_info.uid, dump->card_info.uidlen); + JsonSaveBufAsHexCompact(root, "$.Card.SAK", &dump->card_info.sak, 1); + JsonSaveBufAsHexCompact(root, "$.Card.ATQA", dump->card_info.atqa, 2); + if (dump->card_info.ats_len > 0) { + JsonSaveBufAsHexCompact(root, "$.Card.ATS", dump->card_info.ats, dump->card_info.ats_len); + } + } + + uint8_t appcount = dump->appcount; + if (appcount > DESFIRE_MAX_APP_COUNT) { + appcount = DESFIRE_MAX_APP_COUNT; + } + + for (uint8_t i = 0; i < appcount; i++) { + + desfire_app_keys_t *app = &dump->app[i]; + + for (uint8_t algo = 0; algo < DESFIRE_MAX_ALGO_COUNT; algo++) { + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + if (app->keys[algo][keyno][0] == 0) { + continue; + } + + snprintf(path, sizeof(path), "$.Applications.%06X.%s.%u.Key", + app->aid, algo_name[algo], keyno); + + JsonSaveBufAsHexCompact(root, path, &app->keys[algo][keyno][1], algo_keylen[algo]); + } + } + } + break; + } case jsfCustom: { (*callback)(root); break; @@ -2700,6 +2747,65 @@ int loadFileJSONex(const char *preferredName, void *data, size_t maxdatalen, siz goto out; } + if (!strcmp(ctype, "mfdes v2")) { + + if (maxdatalen < sizeof(desfire_keys_dump_t)) { + PrintAndLogEx(ERR, "loadFileJSONex: maxdatalen=%zu, need %zu for a mfdes v2 dump", maxdatalen, sizeof(desfire_keys_dump_t)); + retval = PM3_EMALLOC; + goto out; + } + + JsonLoadBufAsHex(root, "$.Card.UID", udata.mfdes->card_info.uid, sizeof(udata.mfdes->card_info.uid), &len); + udata.mfdes->card_info.uidlen = len; + JsonLoadBufAsHex(root, "$.Card.SAK", &udata.mfdes->card_info.sak, 1, &len); + JsonLoadBufAsHex(root, "$.Card.ATQA", udata.mfdes->card_info.atqa, 2, &len); + JsonLoadBufAsHex(root, "$.Card.ATS", udata.mfdes->card_info.ats, sizeof(udata.mfdes->card_info.ats), &len); + udata.mfdes->card_info.ats_len = len; + + // key lengths indexed by DesfireCryptoAlgorithm + static const char *algo_name[DESFIRE_MAX_ALGO_COUNT] = {"DES", "2TDEA", "3TDEA", "AES"}; + static const uint8_t algo_keylen[DESFIRE_MAX_ALGO_COUNT] = { + DES_KEY_LEN, T2DES_KEY_LEN, T3DES_KEY_LEN, AES_KEY_LEN + }; + + json_t *apps = json_object_get(root, "Applications"); + if (json_is_object(apps)) { + + const char *aidstr = NULL; + json_t *value = NULL; + + json_object_foreach(apps, aidstr, value) { + + if (udata.mfdes->appcount >= DESFIRE_MAX_APP_COUNT) { + PrintAndLogEx(WARNING, "loadFileJSONex: more than %d applications in file, ignoring the rest", DESFIRE_MAX_APP_COUNT); + break; + } + + desfire_app_keys_t *app = &udata.mfdes->app[udata.mfdes->appcount]; + app->aid = strtoul(aidstr, NULL, 16) & 0xFFFFFF; + + for (uint8_t algo = 0; algo < DESFIRE_MAX_ALGO_COUNT; algo++) { + + for (uint8_t keyno = 0; keyno < DESFIRE_MAX_KEY_COUNT; keyno++) { + + snprintf(blocks, sizeof(blocks), "$.%s.%u.Key", algo_name[algo], keyno); + + len = 0; + JsonLoadBufAsHex(value, blocks, &app->keys[algo][keyno][1], algo_keylen[algo], &len); + if (len == algo_keylen[algo]) { + app->keys[algo][keyno][0] = 0x01; + } + } + } + + udata.mfdes->appcount++; + } + } + + *datalen = sizeof(desfire_keys_dump_t); + goto out; + } + if (!strcmp(ctype, "14b v2")) { size_t sptr = 0; for (int i = 0; i < (maxdatalen / 4); i++) { diff --git a/client/src/fileutils.h b/client/src/fileutils.h index 7323a66e2..b53077d2e 100644 --- a/client/src/fileutils.h +++ b/client/src/fileutils.h @@ -33,6 +33,14 @@ #include "cmdhftopaz.h" // TOPAZ defines #include "mifare/mifaredefault.h" // MFP / AES defines #include "iso15.h" // iso15_tag_t +#include "desfire.h" // desfire_app_keys_t + +// keys recovered from a DESFire PICC by `hf mfdes chk`, one entry per application +typedef struct { + iso14a_card_select_t card_info; + uint8_t appcount; + desfire_app_keys_t app[DESFIRE_MAX_APP_COUNT]; +} desfire_keys_dump_t; typedef union { void *v; @@ -42,6 +50,7 @@ typedef union { iso14a_mf_extdump_t *mfc; iso14a_mf_dump_ev1_t *mfc_ev1; iso15_tag_t *iso15; + desfire_keys_dump_t *mfdes; } udata_t; typedef enum { @@ -69,6 +78,7 @@ typedef enum { jsfMfPlusKeys, jsfCustom, jsfMfDesfireKeys, + jsfMfDesfireKeys_v2, jsfEM4x05, jsfEM4x69, jsfEM4x50, diff --git a/client/src/graph.c b/client/src/graph.c index 80c1e4dc0..8df84d829 100644 --- a/client/src/graph.c +++ b/client/src/graph.c @@ -648,3 +648,21 @@ size_t restore_buffer8(buffer_savestate_t saveState, uint8_t *dest) { return index; } + +// Save/restore the graph buffer as a unit: contents, length and grid offset. +// A caller that drops restore_bufferS32()'s return leaves g_GraphTraceLen short. +buffer_savestate_t save_graphbuffer(void) { + buffer_savestate_t saveState = save_bufferS32(g_GraphBuffer, g_GraphTraceLen); + saveState.offset = g_GridOffset; + return saveState; +} + +void restore_graphbuffer(buffer_savestate_t saveState) { + size_t len = restore_bufferS32(saveState, g_GraphBuffer); + if (len == 0) { + // nothing was restored, so leave the buffer and its length alone + return; + } + g_GraphTraceLen = len; + g_GridOffset = saveState.offset; +} diff --git a/client/src/graph.h b/client/src/graph.h index 6f0822f96..1a46d6362 100644 --- a/client/src/graph.h +++ b/client/src/graph.h @@ -67,6 +67,9 @@ size_t restore_buffer32(buffer_savestate_t saveState, uint32_t *dest); size_t restore_bufferS32(buffer_savestate_t saveState, int32_t *dest); size_t restore_buffer8(buffer_savestate_t saveState, uint8_t *dest); +buffer_savestate_t save_graphbuffer(void); +void restore_graphbuffer(buffer_savestate_t saveState); + #define MAX_GRAPH_TRACE_LEN (40000 * 32) #define GRAPH_SAVE 1 #define GRAPH_RESTORE 0 diff --git a/client/src/scripting.c b/client/src/scripting.c index 8901de663..efe75ec44 100644 --- a/client/src/scripting.c +++ b/client/src/scripting.c @@ -416,12 +416,51 @@ static int l_kbd_enter_pressed(lua_State *L) { /** * @brief Calls the command line parser to deal with the command. This enables * lua-scripts to do stuff like "core.console('hf mf mifare')" + * core.console(cmd [, capture [, quiet]]) + * + * Same idea as the python binding + * `capture` hands the command's output back as a string, + * `quiet` keeps it off the// terminal * @param L * @return */ static int l_CmdConsole(lua_State *L) { - CommandReceived((char *)luaL_checkstring(L, 1)); - return 0; + + const char *cmd = luaL_checkstring(L, 1); + + const bool capture = (lua_isnoneornil(L, 2) == 0) && lua_toboolean(L, 2); + const bool quiet = (lua_isnoneornil(L, 3) == 0) && lua_toboolean(L, 3); + + const uint8_t prev_printAndLog = g_printAndLog; + + if (capture) { + g_printAndLog |= PRINTANDLOG_GRAB; + // anything left in the grabber belongs to an earlier call + g_grabbed_output.idx = 0; + } + + if (quiet) { + g_printAndLog &= ~PRINTANDLOG_PRINT; + } + + CommandReceived((char *)cmd); + + g_printAndLog = prev_printAndLog; + + if (capture == false) { + return 0; + } + + if (g_grabbed_output.ptr == NULL) { + lua_pushstring(L, ""); + return 1; + } + + g_grabbed_output.ptr[g_grabbed_output.idx] = 0; + lua_pushstring(L, g_grabbed_output.ptr); + + g_grabbed_output.idx = 0; + return 1; } static int l_iso15693_crc(lua_State *L) { 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); } diff --git a/common_arm/usb/usb_cdc_at32.c b/common_arm/usb/usb_cdc_at32.c index f4a6087c2..2c6b7d4b8 100644 --- a/common_arm/usb/usb_cdc_at32.c +++ b/common_arm/usb/usb_cdc_at32.c @@ -508,6 +508,21 @@ int usb_write(const uint8_t *data, const size_t len) { // Have a cup of tea? } + // End a packet-aligned CDC transfer with a zero-length packet. Without + // this short packet, a host read larger than this reply can remain pending. + // Use the low-level sender: usb_write() intentionally rejects len == 0. + // Keep this in the synchronous path, not the asynchronous sample stream. + if ((len % USBD_CDC_IN_MAXPACKET_SIZE) == 0) { + if (usb_vcp_send_data(udev, (uint8_t *) data, 0) != SUCCESS) { + return PM3_EIO; + } + while (pcdc->g_tx_completed != 1) { + if (usb_check() == false) { + return PM3_EIO; + } + } + } + return PM3_SUCCESS; } diff --git a/doc/commands.json b/doc/commands.json index 7a7c8b627..1f94cb5e9 100644 --- a/doc/commands.json +++ b/doc/commands.json @@ -6223,7 +6223,7 @@ }, "hf mf gdmgetblk": { "command": "hf mf gdmgetblk", - "description": "Read public block(s) from a GDM card", + "description": "Read public block(s) from a GDM card. With no wakeup flag it auto-detects the card's access mode (WUPA magic auth, gen1a, or gdm alt).", "notes": [ "hf mf gdmgetblk --blk 0", "hf mf gdmgetblk --sec 1 --gdm" @@ -6234,15 +6234,15 @@ "--blk block to read", "--sec sector to read", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm use gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmgetblk [-h] [--blk ] [--sec ] [-k ] [--gdm] [--gen1a] [--wupa]" }, "hf mf gdmgetcfg": { "command": "hf mf gdmgetcfg", - "description": "Get configuration data from a GDM card. By default uses GDM alt wakeup (20/23). Use `--gen1a` or `--wupa` to override.", + "description": "Get configuration data from a GDM card. With no wakeup flag it auto-detects the card's access mode (tries WUPA magic auth, then gen1a, then gdm alt). Use `--gdm`/`--gen1a`/`--wupa` to force one.", "notes": [ "hf mf gdmgetcfg", "hf mf gdmgetcfg --gen1a", @@ -6252,15 +6252,15 @@ "options": [ "-h, --help This help", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm use gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmgetcfg [-h] [-k ] [--gdm] [--gen1a] [--wupa]" }, "hf mf gdmgethidblk": { "command": "hf mf gdmgethidblk", - "description": "Read hidden block(s) from a GDM card", + "description": "Read hidden block(s) from a GDM card. With no wakeup flag it auto-detects the card's access mode (WUPA magic auth, gen1a, or gdm alt).", "notes": [ "hf mf gdmgethidblk --blk 0", "hf mf gdmgethidblk --sec 1 --gdm" @@ -6271,9 +6271,9 @@ "--blk block to read", "--sec sector to read", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm use gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmgethidblk [-h] [--blk ] [--sec ] [-k ] [--gdm] [--gen1a] [--wupa]" }, @@ -6292,7 +6292,7 @@ }, "hf mf gdmsetblk": { "command": "hf mf gdmsetblk", - "description": "Set public block data on a GDM card By default uses GDM alt wakeup (20/23). Use `--gen1a` or `--wupa` to override. `--force` param is used to override warnings like bad ACL writes. if not specified, it will exit if detected", + "description": "Set public block data on a GDM card With no wakeup flag it auto-detects the card's access mode (gen1a, gdm alt, or WUPA magic auth). `--force` param is used to override warnings like bad ACL writes. if not specified, it will exit if detected", "notes": [ "hf mf gdmsetblk --blk 1 -d 000102030405060708090a0b0c0d0e0f", "hf mf gdmsetblk --blk 1 -d 000102030405060708090a0b0c0d0e0f --gen1a", @@ -6304,19 +6304,20 @@ "--blk public block number", "-d, --data bytes to write, 16 hex bytes", "-k, --key key, 6 hex bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "--force override warnings" ], "usage": "hf mf gdmsetblk [-h] --blk -d [-k ] [--gdm] [--gen1a] [--wupa] [--force]" }, "hf mf gdmsetcfg": { "command": "hf mf gdmsetcfg", - "description": "Set configuration data on a GDM card Can either write raw 16 bytes (-d) or configure specific flags. If flags are provided, it will read the config, update flags, and write it back.", + "description": "Set configuration data on a GDM card Can either write raw 16 bytes (-d) or configure specific flags. If flags are provided, it will read the config, update flags, and write it back. With no wakeup flag it auto-detects the card's access mode (WUPA magic auth, gen1a, or gdm alt). `access:` flags select how this command talks to the card; `config:` flags change what is stored.", "notes": [ "hf mf gdmsetcfg -d 850000000000000000005A5A00000008", - "hf mf gdmsetcfg --cuid on --gen1 on", + "hf mf gdmsetcfg --cuid on --wakestyle gen1a", + "hf mf gdmsetcfg --wakestyle off", "hf mf gdmsetcfg --shadow off --sigsec off --wupa -k FFFFFFFFFFFF" ], "offline": false, @@ -6324,22 +6325,22 @@ "-h, --help This help", "-d, --data raw bytes to write, 16 hex bytes", "-k, --key key 6 bytes (only for regular wakeup)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", - "--gen1 Gen1 mode (7A FF)", - "--cuid Gen2/CUID mode", - "--cl2 CL2 mode (7-byte UID) - pair with `hf mf gdmsetuid -u <7-byte>` to set a valid UID", - "--shadow Shadow mode", - "--magicauth Magic auth", - "--statenc Static encrypted nonce", - "--sigsec Signature sector" + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", + "--cuid config: Gen2/CUID mode", + "--cl2 config: CL2 mode (7-byte UID) - pair with `hf mf gdmsetuid -u <7-byte>`", + "--shadow config: Shadow mode", + "--magicauth config: Magic auth (what --wupa uses)", + "--statenc config: Static encrypted nonce", + "--sigsec config: Signature sector", + "--wakestyle config: backdoor - gdm (7AFF85), gen1a (7AFF00), or off (8500, seal)" ], - "usage": "hf mf gdmsetcfg [-h] [-d ] [-k ] [--gdm] [--gen1a] [--wupa] [--gen1 ] [--cuid ] [--cl2 ] [--shadow ] [--magicauth ] [--statenc ] [--sigsec ]" + "usage": "hf mf gdmsetcfg [-h] [-d ] [-k ] [--gdm] [--gen1a] [--wupa] [--cuid ] [--cl2 ] [--shadow ] [--magicauth ] [--statenc ] [--sigsec ] [--wakestyle ]" }, "hf mf gdmsethidblk": { "command": "hf mf gdmsethidblk", - "description": "Write hidden block data on a GDM card. Hidden blocks 0-7 map to the card's hidden sector area. By default uses GDM alt wakeup (20/23). Use `--gen1a` or `--wupa` to override. `--force` param is used to override warnings like bad BCC or ACL writes. if not specified, it will exit if detected", + "description": "Write hidden block data on a GDM card. Hidden blocks 0-7 map to the card's hidden sector area. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected. `--force` param is used to override warnings like bad BCC or ACL writes. if not specified, it will exit if detected", "notes": [ "hf mf gdmsethidblk --blk 0 -d 880494716904EA0C2394510800000000", "hf mf gdmsethidblk --blk 0 -d 880494716904EA0C2394510800000000 --gen1a", @@ -6352,16 +6353,16 @@ "--blk hidden block number (0-7)", "-d, --data bytes to write, 16 hex bytes", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "--force override warnings" ], "usage": "hf mf gdmsethidblk [-h] --blk -d [-k ] [--gdm] [--gen1a] [--wupa] [--force]" }, "hf mf gdmsetsig": { "command": "hf mf gdmsetsig", - "description": "Set MFC EV1 signature on a GDM card", + "description": "Set MFC EV1 signature on a GDM card. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", "notes": [ "hf mf gdmsetsig -s <64 hex chars>" ], @@ -6370,15 +6371,15 @@ "-h, --help This help", "-s, --sig 32-byte signature (64 hex characters)", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)" + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)" ], "usage": "hf mf gdmsetsig [-h] -s [-k ] [--gdm] [--gen1a] [--wupa]" }, "hf mf gdmsetuid": { "command": "hf mf gdmsetuid", - "description": "Set UID on a GDM card", + "description": "Set UID on a GDM card. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", "notes": [ "hf mf gdmsetuid -u 01020304", "hf mf gdmsetuid -u 01020304050607 --gen1a" @@ -6388,16 +6389,16 @@ "-h, --help This help", "-u, --uid UID to set (4 or 7 hex bytes)", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "--f3d use F3 perso mode (writes to hidden block 1 instead of 0)" ], "usage": "hf mf gdmsetuid [-h] -u [-k ] [--gdm] [--gen1a] [--wupa] [--f3d]" }, "hf mf gdmwipe": { "command": "hf mf gdmwipe", - "description": "Wipe a GDM card to factory defaults", + "description": "Wipe a GDM card to factory defaults. With no wakeup flag it auto-detects a backdoor (gen1a or gdm alt); a WUPA-only card is rejected.", "notes": [ "hf mf gdmwipe --gdm" ], @@ -6405,9 +6406,9 @@ "options": [ "-h, --help This help", "-k, --key key 6 bytes (only for --wupa mode)", - "--gdm use gdm alt (20/23) magic wakeup (default)", - "--gen1a use gen1a (40/43) magic wakeup", - "--wupa use regular wakeup (WUPA + magic auth with key)", + "--gdm access: force gdm alt (20/23) magic wakeup", + "--gen1a access: force gen1a (40/43) magic wakeup", + "--wupa access: force regular wakeup (WUPA + magic auth with key)", "-a, --all wipe 4K card (40 sectors) instead of 1K card (16 sectors)" ], "usage": "hf mf gdmwipe [-ha] [-k ] [--gdm] [--gen1a] [--wupa]" @@ -7206,7 +7207,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7256,7 +7257,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number (default: 0 / PICC key)", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7310,7 +7311,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7343,7 +7344,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7367,17 +7368,18 @@ "command": "hf mfdes chk", "description": "Checks keys with MIFARE DESFire card.", "notes": [ - "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on aid 0x123456", - "hf mfdes chk -f mfdes_default_keys -> check keys against all existing aid on card", - "hf mfdes chk -f mfdes_default_keys --aid 123456 -> check keys against aid 0x123456", - "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on aid 0x123456 and save found keys to `keys.json`", - "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on aid 0x123456. Start from key FA00FA00...FA00" + "hf mfdes chk -f mfdes_default_keys -> check keys against all existing AID on card", + "hf mfdes chk --aid 123456 -f mfdes_default_keys -> check keys against AID 0x123456", + "hf mfdes chk --aid 123456 --pattern1b -j keys -> check all 1-byte keys pattern on AID 0x123456 and save found keys to `keys.json`", + "hf mfdes chk --aid 123456 --pattern2b --startp2b FA00 -> check all 2-byte keys pattern on AID 0x123456. Start from key FA00FA00...FA00", + "hf mfdes chk --aid 123456 -k 000102030405060708090a0b0c0d0e0f -> check key on AID 0x123456", + "hf mfdes chk -f mfdes_default_keys --schann lrp -> check keys, forcing the LRP secure channel" ], "offline": false, "options": [ "-h, --help This help", "--aid Use specific AID (3 hex bytes, big endian)", - "-k, --key Key for checking (HEX 16 bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "-f, --file Filename of dictionary", "--pattern1b Check all 1-byte combinations of key (0000...0000, 0101...0101, 0202...0202, ...)", "--pattern2b Check all 2-byte combinations of key (0000...0000, 0001...0001, 0002...0002, ...)", @@ -7386,9 +7388,10 @@ "-v, --verbose Verbose output", "--kdf <0|1|2> Key Derivation Function (KDF) (0=None, 1=AN10922, 2=Gallagher)", "-i, --kdfi KDF input (1-31 hex bytes)", + "--schann Secure channel (default: detected per application)", "-a, --apdu Show APDU requests and responses" ], - "usage": "hf mfdes chk [-hva] [--aid ] [-k ] [-f ] [--pattern1b] [--pattern2b] [--startp2b ] [-j ] [--kdf <0|1|2>] [-i ]" + "usage": "hf mfdes chk [-hva] [--aid ] [-k ] [-f ] [--pattern1b] [--pattern2b] [--startp2b ] [-j ] [--kdf <0|1|2>] [-i ] [--schann ]" }, "hf mfdes chkeysettings": { "command": "hf mfdes chkeysettings", @@ -7404,7 +7407,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7429,7 +7432,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7486,7 +7489,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7523,7 +7526,7 @@ "-a, --apdu Show APDU requests and responses", "-v, --verbose Verbose output", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7567,7 +7570,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7611,7 +7614,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7647,7 +7650,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7684,7 +7687,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7723,7 +7726,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo (deft: 2TDEA)", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7756,7 +7759,7 @@ "-h, --help This help", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7778,7 +7781,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7802,7 +7805,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7817,22 +7820,22 @@ }, "hf mfdes detect": { "command": "hf mfdes detect", - "description": "Detect key type and tries to find one from the list.", + "description": "Detect PICC master key, key type, communication mode, command set and channel mode. Uses `mfdes_default_keys.dic` per default `--save` it saves details to be used with `hf mfdes default`", "notes": [ - "hf mfdes detect -> detect key 0 from PICC level", - "hf mfdes detect --schann d40 -> detect key 0 from PICC level via secure channel D40", - "hf mfdes detect -f mfdes_default_keys -> detect key 0 from PICC level with help of the standard dictionary", - "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and if succeed - save params to defaults (`default` command)", - "hf mfdes detect --isoid df01 --save -> detect key 0 and save to defaults with card in the LRP mode" + "hf mfdes detect", + "hf mfdes detect --schann d40 -> detect from PICC level via secure channel D40", + "hf mfdes detect -f my_keys -> detect from PICC level with your own dictionary", + "hf mfdes detect --aid 123456 -n 2 --save -> detect key 2 from app 123456 and save params to defaults", + "hf mfdes detect --isoid df01 --save -> detect and save to defaults with card in the LRP mode" ], "offline": false, "options": [ "-h, --help This help", "-a, --apdu Show APDU requests and responses", "-v, --verbose Verbose output", - "-n, --keyno Key number", + "-n, --keyno Key number (def: all)", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7841,7 +7844,7 @@ "--aid Application ID (3 hex bytes, big endian)", "--isoid Application ISO ID (ISO DF ID) (2 hex bytes, big endian).", "--dfname Application ISO DF Name (5-16 hex bytes, big endian)", - "-f, --file Filename of dictionary", + "-f, --file Filename of dictionary (default: `mfdes_default_keys`)", "--save Save found key and parameters to defaults" ], "usage": "hf mfdes detect [-hav] [-n ] [-t ] [-k ] [--kdf ] [-i ] [-m ] [-c ] [--schann ] [--aid ] [--isoid ] [--dfname ] [-f ] [--save]" @@ -7859,7 +7862,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7886,7 +7889,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7909,7 +7912,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7933,7 +7936,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7956,7 +7959,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7982,7 +7985,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number (default: 0 / PICC key)", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -7998,8 +8001,8 @@ "description": "Get File IDs list from card. Master key needs to be provided or flag --no-auth set.", "notes": [ "hf mfdes getfileids --aid 123456 -> execute with defaults from `default` command", - "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --kdf none --aid 123456 -> execute with default factory setup", - "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs" + "hf mfdes getfileids --dfname D2760000850100 -> select DF by name and get file IDs", + "hf mfdes getfileids -n 0 -t des -k 0000000000000000 --aid 123456 -> execute with default factory setup" ], "offline": false, "options": [ @@ -8008,7 +8011,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8038,7 +8041,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8067,7 +8070,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8096,7 +8099,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8124,7 +8127,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number for authentication", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8154,7 +8157,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8256,7 +8259,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8284,7 +8287,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8315,7 +8318,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8338,7 +8341,7 @@ "options": [ "-h, --help This help", "-v, --verbose Show more output", - "-k, --key Key for computing the MAC, must be HEX 16(AES)", + "-k, --key Key for computing the MAC (16 hex bytes)", "-b, --blk [,[,...]] The MFC blocks to map, must be given in ascending order (use the special value 'all' for all blocks)", "--ka Allow updating key A from inside sector trailers mapped to DESFire files", "--kb Allow updating key B from inside sector trailers mapped to DESFire files", @@ -8398,7 +8401,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8435,7 +8438,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8498,7 +8501,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8540,7 +8543,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo (deft: 2TDEA)", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -8604,7 +8607,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number for DESFire authentication", "-t, --algo DESFire auth crypt algo", - "-k, --key DESFire authentication key", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communication mode", @@ -8652,7 +8655,7 @@ "-v, --verbose Verbose output", "-n, --keyno Key number", "-t, --algo Crypt algo", - "-k, --key Key for authenticate (HEX 8(DES), 16(2TDEA or AES) or 24(3TDEA) bytes)", + "-k, --key Key for authenticate (8|16|24 hex bytes)", "--kdf Key Derivation Function (KDF)", "-i, --kdfi KDF input (1-31 hex bytes)", "-m, --cmode Communicaton mode", @@ -9416,6 +9419,30 @@ ], "usage": "hf mfu keygen [-hr] [-u ] [-b ]" }, + "hf mfu ndefformat": { + "command": "hf mfu ndefformat", + "description": "Format a MIFARE Ultralight / NTAG tag for NDEF by writing the Capability Container to block 3, followed by an empty NDEF message. Writes NXP factory delivery content for the detected tag type. Block 3 is One Time Programmable; unknown types and unreachable CCs are refused. Note: the tag is re-selected and re-authenticated for each block written.", + "notes": [ + "hf mfu ndefformat", + "hf mfu ndefformat -v", + "hf mfu ndefformat --erase", + "hf mfu ndefformat -k FFFFFFFF", + "hf mfu ndefformat -k 49454D4B41455242214E4143554F5946", + "hf mfu ndefformat -d E1101200 --force" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-k, --key Authentication key (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)", + "-l Swap entered key endianness", + "-d, --data Capability Container to write, 4 bytes. Overrides the detected type", + "--erase Also zero the rest of the NDEF data area", + "--force Continue on an unknown tag type, or with an oversized -d value", + "-v, --verbose Verbose output", + "--schann use secure channel. Must have key" + ], + "usage": "hf mfu ndefformat [-hlv] [-k ] [-d ] [--erase] [--force] [--schann]" + }, "hf mfu ndefread": { "command": "hf mfu ndefread", "description": "Prints NFC Data Exchange Format (NDEF)", @@ -10874,83 +10901,92 @@ ], "usage": "hw break [-h]" }, - "hw bwmautooff": { - "command": "hw bwmautooff", - "description": "Toggle automatic power-off when the PM5 is unplugged from USB (BWM only). Default is on. When on, the board powers itself down ~10s after USB is removed, so a BWM-equipped PM5 doesn't silently drain the battery. Button power-on is unaffected. Disable for standalone/BLE use on battery. Runtime only: resets to on at each boot.", - "notes": [ - "hw bwmautooff --off -> disable auto power-off", - "hw bwmautooff --on -> re-enable auto power-off" - ], - "offline": false, - "options": [ - "-h, --help This help", - "--on enable auto power-off (default)", - "--off disable auto power-off" - ], - "usage": "hw bwmautooff [-h] [--on] [--off]" - }, - "hw bwmcharge": { - "command": "hw bwmcharge", + "hw bwm charge": { + "command": "hw bwm charge", "description": "Enable or disable BWM battery charging by clearing/setting the AW32001E charge-enable bit (CEB, REG01[3]). PM5 only. One-shot: the charger watchdog reverts this after ~160 s unless serviced, so charging may stop on its own. Use to nudge a top-up.", "notes": [ - "hw bwmcharge -on -> enable charging", - "hw bwmcharge --off -> disable charging" + "hw bwm charge off -> disable charging", + "hw bwm charge on -> enable charging" ], "offline": false, "options": [ - "-h, --help This help", - "--on enable charging (default)", - "--off disable charging" + "-h, --help This help" ], - "usage": "hw bwmcharge [-h] [--on] [--off]" + "usage": "hw bwm charge [-h]" }, - "hw bwmsetcap": { - "command": "hw bwmsetcap", + "hw bwm help": { + "command": "hw bwm help", + "description": "help This help --------------------------------------------------------------------------------------- hw bwm autooff available offline: no Toggle automatic power-off when the PM5 is unplugged from USB (BWM only). Default is on. When on, the board powers itself down ~10s after USB is removed, so a BWM-equipped PM5 doesn't silently drain the battery. Button power-on is unaffected. Disable for standalone/BLE use on battery. Runtime only: resets to on at each boot.", + "notes": [ + "hw bwm autooff off -> disable auto power-off", + "hw bwm autooff on -> re-enable auto power-off" + ], + "offline": true, + "options": [ + "-h, --help This help" + ], + "usage": "hw bwm autooff [-h]" + }, + "hw bwm setcap": { + "command": "hw bwm setcap", "description": "Program the BWM fuel gauge (BQ27427) Design Capacity for the fitted cell. Run ONCE after fitting or replacing the battery. This triggers a gauge config-update; do not run it repeatedly, as that disrupts the Impedance Track learning cycle. PM5 only.", "notes": [ - "hw bwmsetcap -> set design capacity to default 500 mAh", - "hw bwmsetcap --cap 500 -> set design capacity to 500 mAh" + "hw bwm setcap -> set design capacity to default 500 mAh", + "hw bwm setcap --cap 500 -> set design capacity to 500 mAh" ], "offline": false, "options": [ "-h, --help This help", "--cap design capacity in mAh (default 500)" ], - "usage": "hw bwmsetcap [-h] [--cap ]" + "usage": "hw bwm setcap [-h] [--cap ]" }, - "hw bwmvchg": { - "command": "hw bwmvchg", + "hw bwm upgrade": { + "command": "hw bwm upgrade", + "description": "Reflash the BWM (ESP32) firmware over the BWM link - no header, no soldering. Requires a BWM that still responds; this updates a wrong-version ESP, it cannot recover a fully bricked one (that still needs the 5-pin header + esptool).", + "notes": [ + "hw bwm upgrade -f bwm_esp32.bin" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-f, --file ESP32 firmware image (.bin)", + "--delay per-chunk delay to pace the slow AT32<->ESP UART (default 20)" + ], + "usage": "hw bwm upgrade [-h] -f [--delay ]" + }, + "hw bwm vchg": { + "command": "hw bwm vchg", "description": "Set the BWM charger (AW32001E) charge-voltage regulation target. Lowering it below 4.2 V reduces top-of-charge stress and extends cell life. Snaps to the nearest 15 mV step; clamped to 3600..4200 mV. This is a runtime register write (reverts on the charger watchdog / POR); the firmware re-applies the 4100 mV default at every boot. PM5 only.", "notes": [ - "hw bwmvchg -> set charge voltage to default 4100 mV (->4.095 V)", - "hw bwmvchg --mv 4200 -> set charge voltage to 4200 mV" + "hw bwm vchg -> set charge voltage to default 4100 mV (->4.095 V)", + "hw bwm vchg --mv 4200 -> set charge voltage to 4200 mV" ], "offline": false, "options": [ "-h, --help This help", "--mv charge voltage in mV (default 4100, clamped 3600..4200)" ], - "usage": "hw bwmvchg [-h] [--mv ]" + "usage": "hw bwm vchg [-h] [--mv ]" }, - "hw bwmwifi": { - "command": "hw bwmwifi", - "description": "Bring up the BWM in STA + TCP-server mode: join a WiFi network and start a TCP server so the client can connect over WiFi. PM5 only.", + "hw bwm wifi": { + "command": "hw bwm wifi", + "description": "Bring up the BWM in STA + TCP-server mode: join a WiFi network and start a TCP server so the client can connect over WiFi. PM5 only. Sub-actions (no dashes): 'status' shows state, 'stop' tears WiFi down.", "notes": [ - "hw bwmwifi --ssid Home --pwd secret -> port 7777", - "hw bwmwifi --ssid Home --pwd secret --port 9000", - "hw bwmwifi --status -> show connection state + IP" + "hw bwm wifi status -> show connection state + IP", + "hw bwm wifi stop -> tear down WiFi, back to BLE-only", + "hw bwm wifi --ssid Home --pwd secret -> bring up, port 7777", + "hw bwm wifi --ssid Home --pwd secret --port 9000" ], "offline": false, "options": [ "-h, --help This help", - "--ssid WiFi SSID to join (omit with --stop)", + "--ssid WiFi SSID to join", "--pwd WiFi password (omit for open network)", "--port TCP server listen port (default 7777)", - "--hostname DHCP hostname (default Proxmark5)", - "--stop tear down WiFi and return to BLE-only", - "--status show current WiFi connection state + IP" + "--hostname DHCP hostname (default Proxmark5)" ], - "usage": "hw bwmwifi [-h] [--ssid ] [--pwd ] [--port ] [--hostname ] [--stop] [--status]" + "usage": "hw bwm wifi [-h] [--ssid ] [--pwd ] [--port ] [--hostname ]" }, "hw connect": { "command": "hw connect", @@ -11086,15 +11122,22 @@ "command": "hw qc_pm5", "description": "QC Test for the PM5", "notes": [ - "hw qc_pm5 -> run QC test with default 20 second timeout", - "hw qc_pm5 -t 3 -> run QC test with a 3 second timeout" + "hw qc_pm5 -> run hardware QC test with default 20 second timeout", + "hw qc_pm5 -t 3 -> run hardware QC test with a 3 second timeout", + "hw qc_pm5 --iolow --pwd -> drive PM5 test IO low", + "hw qc_pm5 --iohigh --pwd -> drive PM5 test IO high", + "hw qc_pm5 --ioreset --pwd -> reset PM5 test IO to default" ], "offline": false, "options": [ "-h, --help This help", - "-t, --timeout test sequence timeout in seconds (default 20)" + "-t, --timeout test sequence timeout in seconds (default 20)", + "--iolow drive PM5 test IO low", + "--iohigh drive PM5 test IO high", + "--ioreset reset PM5 test IO to default", + "--pwd QC test password in hex (required for IO tests)" ], - "usage": "hw qc_pm5 [-h] [-t ]" + "usage": "hw qc_pm5 [-h] [-t ] [--iolow ] [--iohigh ] [--ioreset ] [--pwd ]" }, "hw readmem": { "command": "hw readmem", @@ -15407,21 +15450,27 @@ }, "nfc type1 help": { "command": "nfc type1 help", - "description": "-------- -------------- NFC Forum Tag Type 1 --------------- -------- --------------------- General --------------------- help This help ======================================================================================= nfc type2 { NFC Forum Tag Type 2... } --------------------------------------------------------------------------------------- nfc type2 read available offline: no Prints NFC Data Exchange Format (NDEF)", + "description": "-------- -------------- NFC Forum Tag Type 1 --------------- -------- --------------------- General --------------------- help This help ======================================================================================= nfc type2 { NFC Forum Tag Type 2... } --------------------------------------------------------------------------------------- nfc type2 format available offline: no Format a MIFARE Ultralight / NTAG tag for NDEF by writing the Capability Container to block 3, followed by an empty NDEF message. Writes NXP factory delivery content for the detected tag type. Block 3 is One Time Programmable; unknown types and unreachable CCs are refused. Note: the tag is re-selected and re-authenticated for each block written.", "notes": [ - "hf mfu ndefread -> shows NDEF data", - "hf mfu ndefread -k ffffffff -> shows NDEF data with key", - "hf mfu ndefread -f myfilename -> save raw NDEF to file" + "hf mfu ndefformat", + "hf mfu ndefformat -v", + "hf mfu ndefformat --erase", + "hf mfu ndefformat -k FFFFFFFF", + "hf mfu ndefformat -k 49454D4B41455242214E4143554F5946", + "hf mfu ndefformat -d E1101200 --force" ], "offline": true, "options": [ "-h, --help This help", - "-l Swap entered key's endianness", - "-f, --file Save raw NDEF to file", + "-k, --key Authentication key (UL-C/UL-AES 16 bytes, EV1/NTAG 4 bytes)", + "-l Swap entered key endianness", + "-d, --data Capability Container to write, 4 bytes. Overrides the detected type", + "--erase Also zero the rest of the NDEF data area", + "--force Continue on an unknown tag type, or with an oversized -d value", "-v, --verbose Verbose output", "--schann use secure channel. Must have key" ], - "usage": "hf mfu ndefread [-hlv] [-k Replace default key for NDEF] [-f ] [--schann]" + "usage": "hf mfu ndefformat [-hlv] [-k ] [-d ] [--erase] [--force] [--schann]" }, "nfc type1 read": { "command": "nfc type1 read", @@ -15451,6 +15500,24 @@ ], "usage": "hf 14a ndefformat [-hv]" }, + "nfc type2 read": { + "command": "nfc type2 read", + "description": "Prints NFC Data Exchange Format (NDEF)", + "notes": [ + "hf mfu ndefread -> shows NDEF data", + "hf mfu ndefread -k ffffffff -> shows NDEF data with key", + "hf mfu ndefread -f myfilename -> save raw NDEF to file" + ], + "offline": false, + "options": [ + "-h, --help This help", + "-l Swap entered key's endianness", + "-f, --file Save raw NDEF to file", + "-v, --verbose Verbose output", + "--schann use secure channel. Must have key" + ], + "usage": "hf mfu ndefread [-hlv] [-k Replace default key for NDEF] [-f ] [--schann]" + }, "nfc type2 write": { "command": "nfc type2 write", "description": "Write NFC Data Exchange Format (NDEF) records to a MIFARE Ultralight / NTAG tag. The tag must already be NDEF formatted, ie carry a Capability Container in block 3. Combine several of --uri, --text and --aar to build a multi record message, records are added in that order. Alternatively supply raw NDEF bytes with -d or -f, those get wrapped in a TLV container automatically when they are not already. Use `nfc encode` to build such raw bytes offline. Note: the tag is re-selected and re-authenticated for every block written, so a large message takes a while.", @@ -16427,8 +16494,8 @@ } }, "metadata": { - "commands_extracted": 912, + "commands_extracted": 918, "extracted_by": "PM3Help2JSON v1.00", - "extracted_on": "2026-09-04T11:31:07+00:00" + "extracted_on": "2026-09-11T13:13:54+00:00" } } diff --git a/doc/commands.md b/doc/commands.md index 79b30d2b7..8446cbe64 100644 --- a/doc/commands.md +++ b/doc/commands.md @@ -759,6 +759,7 @@ Check column "offline" for their availability. |`hf mfu dump `|N |`Dump MIFARE Ultralight family tag to binary file` |`hf mfu incr `|N |`Increments Ev1/NTAG counter` |`hf mfu info `|N |`Tag information` +|`hf mfu ndefformat `|N |`Format tag as NDEF, writes the Capability Container` |`hf mfu ndefread `|N |`Prints NDEF records from card` |`hf mfu ndefwrite `|N |`Write NDEF records to card` |`hf mfu rdbl `|N |`Read block` @@ -1016,7 +1017,7 @@ Check column "offline" for their availability. |`hw fpga `|N |`Fpga commands` |`hw fpgaoff `|N |`Turn off FPGA on device` |`hw ant_pm5 `|N |`Control the antennal of pm5` -|`hw qc_pm5 `|N |`Perform QC test for the PM5` +|`hw qc_pm5 `|N |`Perform QC test (hardware or IO) for the PM5` |`hw factorydata `|N |`Get/Set the factory data for Device` |`hw lcd `|N |`Send command/data to LCD` |`hw lcdreset `|N |`Hardware reset LCD` @@ -1028,15 +1029,25 @@ Check column "offline" for their availability. |`hw setmux `|N |`Set the ADC mux to a specific value` |`hw standalone `|N |`Start installed standalone mode on device` |`hw tia `|N |`Trigger a Timing Interval Acquisition to re-adjust the RealTimeCounter divider` -|`hw bwmsetcap `|N |`Set BWM fuel-gauge design capacity (PM5, run once after battery change)` -|`hw bwmvchg `|N |`Set BWM charger charge-voltage target (PM5, default 4100 mV)` -|`hw bwmcharge `|N |`Enable/disable BWM battery charging (PM5, one-shot)` -|`hw bwmautooff `|N |`Toggle auto power-off on USB unplug (PM5, BWM)` -|`hw bwmwifi `|N |`Bring up BWM WiFi (STA + TCP server) for a tcp: connection (PM5)` |`hw tune `|N |`Measure tuning of device antenna` |`hw decay `|N |`Measure HF antenna decay after field-off` +### hw bwm + + { BWM (battery/wireless module) commands... } + +|command |offline |description +|------- |------- |----------- +|`hw bwm help `|Y |`This help` +|`hw bwm autooff `|N |`Toggle auto power-off on USB unplug` +|`hw bwm charge `|N |`Enable/disable battery charging (one-shot)` +|`hw bwm setcap `|N |`Set fuel-gauge design capacity (run once after battery change)` +|`hw bwm upgrade `|N |`Reflash BWM (ESP32) firmware over the BWM link, no header` +|`hw bwm vchg `|N |`Set charger charge-voltage target (default 4100 mV)` +|`hw bwm wifi `|N |`Bring up WiFi (STA + TCP server) for a tcp: connection` + + ### lf { Low frequency commands... } @@ -1667,6 +1678,7 @@ Check column "offline" for their availability. |command |offline |description |------- |------- |----------- +|`nfc type2 format `|N |`format MIFARE Ultralight / NTAG as NFC Forum Tag Type 2` |`nfc type2 read `|N |`read NFC Forum Tag Type 2` |`nfc type2 write `|N |`write NFC Forum Tag Type 2` |`nfc type2 help `|Y |`This help` diff --git a/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md b/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md index 42012b894..3dcc7e403 100644 --- a/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md +++ b/doc/md/PM5_Start_Here/Getting_Started_With_PM5.md @@ -104,7 +104,23 @@ hf 14a read --drop ## Do this exactly once. * The very first time for a new battery: ```hw bwm setcap --cap 500``` -* Do a full charge/discharge cycle for it to learn the real capacity. +* Your PM5 will learn about the battery through usage. + +## Flash the BWM +* Make sure your BWM has enough charge in the battery `hw status` 50%+ should work. +* Get the latest firmware: + * Go [here](https://github.com/RfidResearchGroup/Proxmark5_BWM_esp32/actions/workflows/esp-idf-build.yml): + * Click on the latest workflow run (As of this writing that's "Merge pull request #3 from nieldk/master") + * Scroll all the way to the bottom, you'll see **Artifacts** + * Click on "proxmark5_bwm_master" which will start a download for `proxmark5_bwm_master.zip` + * Unzip this file somehwere, remember that location + * The upgrade command is: `hw bwm upgrade -f proxmark5_ble_wifi_module.bin` + * This will take some time, you'll see the Progress in % displayed on the screen until the process is done. + * Once you see "BWM Rebooting into the new image" you know the upgrade finished. + * Wait a few seconds (under 10) and unplug and replug the Proxmark5 back into the usb port. + * Once reconnected, you can run `hw status` and you'll see: + * `BWM fw version...... 1` where 1 is the current fw version. As of 2026-09-10, the most current version is 1. + * You have finished flashing the BWM. ### Operation diff --git a/include/desfire.h b/include/desfire.h index 37716f11d..298acc069 100644 --- a/include/desfire.h +++ b/include/desfire.h @@ -30,4 +30,16 @@ typedef enum { T_AES = 0x03 } DesfireCryptoAlgorithm; +#define DESFIRE_MAX_ALGO_COUNT 4 // T_DES ... T_AES +#define DESFIRE_MAX_KEY_COUNT 0x0E // key numbers 0x00 ... 0x0D +#define DESFIRE_MAX_APP_COUNT 64 // applications we keep track of per PICC + +// Keys recovered for one application. +// keys[algo][keyno][0] is the found flag, keys[algo][keyno][1..] the key itself. +// `algo` is a DesfireCryptoAlgorithm, `keyno` the DESFire key number. +typedef struct { + uint32_t aid; + uint8_t keys[DESFIRE_MAX_ALGO_COUNT][DESFIRE_MAX_KEY_COUNT][DESFIRE_MAX_KEY_SIZE + 1]; +} desfire_app_keys_t; + #endif diff --git a/include/pm3_cmd.h b/include/pm3_cmd.h index 56f643c35..c0268adcd 100644 --- a/include/pm3_cmd.h +++ b/include/pm3_cmd.h @@ -541,6 +541,14 @@ typedef struct { // most 4 byte nonces that fit alongside the reply header in one frame #define MFC_MAX_NONCES ((PM3_CMD_DATA_SIZE - sizeof(mf_nonces_resp_t)) / 4) +// ACQ_ENCRYPTED_NONCES does not store bare nonces. It stores pairs: two 4 byte +// encrypted nonces followed by one byte holding both their encrypted parity +// nibbles, high nibble first. num_nonces in the reply counts nonces, so the +// payload is always (num_nonces / 2) * MFC_NONCE_PAIR_SIZE bytes and +// num_nonces is always even. +#define MFC_NONCE_PAIR_SIZE 9 +#define MFC_MAX_NONCE_PAIRS ((PM3_CMD_DATA_SIZE - sizeof(mf_nonces_resp_t)) / MFC_NONCE_PAIR_SIZE) + // CMD_HF_MIFARE_CHKKEYS_FAST payload. // Replaces three bit-packed oldargs: // arg0 = sectorcnt | firstchunk<<8 | lastchunk<<12 | singlesector_params<<16 diff --git a/tools/pm3_tests.sh b/tools/pm3_tests.sh index a63279319..b0f257ab6 100755 --- a/tools/pm3_tests.sh +++ b/tools/pm3_tests.sh @@ -468,6 +468,7 @@ while true; do if ! CheckExecute "data qrcode invalid hex" "$CLIENTBIN -c 'data qrcode -d zz' 2>&1" "QR data must contain only hex characters"; then break; fi if ! CheckExecute "data qrcode odd hex" "$CLIENTBIN -c 'data qrcode -d a' 2>&1" "QR data must contain an even number of hex digits"; then break; fi if ! CheckExecute "data qrcode spaced hex" "$CLIENTBIN -c 'data qrcode -d \"aa bb\"' 2>&1" "Spaces are not supported; encode a space byte as 20"; then break; fi + if ! CheckExecute "data modulation keeps trace" "$CLIENTBIN -c 'data load -f traces/lf_Q5_mod-psk1-32-4.pm3; data modulation; data autocorr -w 99999'" "smaller than trace \\( 20000 samples \\)"; then break; fi if ! CheckExecute "mfu pwdgen test" "$CLIENTBIN -c 'hf mfu pwdgen --test'" "Selftest ok"; then break; fi if ! CheckExecute "mfu keygen test" "$CLIENTBIN -c 'hf mfu keygen --uid 11223344556677'" "80 B1 C2 71 D8 A0"; then break; fi if ! CheckExecute "jooki encode test" "$CLIENTBIN -c 'hf jooki encode --test'" "04 28 F4 DA F0 4A 81 \( ok \)"; then break; fi