diff --git a/CHANGELOG.md b/CHANGELOG.md index 6e0930e15..b66c483d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] - Fixed `hf mf nested` - tests every key candidate, follows cards whose nonce distance varies, single sector retries (@matrix) +- Fixed `hf mf chk`, `hf mf staticnested` and other key checks - a card that stops answering no longer locks the device (@matrix) +- Changed `hf mf staticnested` and `hf mf autopwn` - say "Card stopped answering" when the card is lost (@matrix) +- Fixed `hf mf rdbl`, `hf mf fchk`, `hf 14a info` and other MIFARE reader commands - the emulator memory is kept instead of being reset to zeros (@matrix) +- Added ISO/IEC 14443-4 error recovery to the reader - a lost or damaged answer is asked for again with R(NAK) instead of failing the exchange, `hw status` reports how often that was needed (@iceman1001) +- Fixed `hf mfdes chk` - an exchange the card never answered is no longer counted as a wrong key or as a missing application, such candidates are retried and what stays uncovered is reported instead of hiding behind "No keys found" (@iceman1001) +- Fixed `hf mfdes detect` - an exchange the card never answered is no longer counted as a wrong key (@iceman1001) - Update Amiibo database (@tpglitch) - Changed `lf pcf7931 write` - write is verified via the tag's read after write, retried up to 3 times, failures are reported (@GiacoBot) - Changed `lf pcf7931 reader` - prints blocks 0-7 in order and decodes PAC, password, write protection and selection; handles partial selections, new `--rfb` param (@GiacoBot) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index ba1444a45..597677101 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -803,6 +803,12 @@ static void SendStatus(uint32_t wait) { Dbprintf(" ToSendMax........... %d", ts->max); Dbprintf(" ToSend BUFFERSIZE... %d", TOSEND_BUFFER_SIZE); +#ifdef WITH_ISO14443a + uint32_t retrans = 0, retrans_lost = 0; + iso14_get_retrans(&retrans, &retrans_lost); + Dbprintf(" 14443-4 retrans..... %u asked, %u still lost", retrans, retrans_lost); +#endif + #ifdef CHIP_AT91SAM7S while ((AT91C_BASE_PMC->PMC_MCFR & AT91C_CKGR_MAINRDY) == 0); // Wait for MAINF value to become available... diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 661a1d9fe..e6d434865 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -4214,6 +4214,82 @@ b8 b7 b6 b5 b4 b3 b2 b1 b5,b6 = 00 - DESELECT 11 - WTX */ +// ISO/IEC 14443-4 7.5.6 leaves the retransmission count to the PCD. Two extra +// tries cover a lost frame without stretching a dead link into seconds. +#define ISO14_MAX_RETRANS 2 + +// how often a frame had to be asked for again, and how often that did not +// help. `hw status` reports both: recovered losses are otherwise invisible +static uint32_t iso14_retrans; +static uint32_t iso14_retrans_lost; + +void iso14_get_retrans(uint32_t *retrans, uint32_t *lost) { + *retrans = iso14_retrans; + *lost = iso14_retrans_lost; +} + +// Did a 14443-4 block survive the air? PCB + CRC is the shortest legal one. +static bool iso14_block_valid(const uint8_t *data, uint16_t len) { + return (len >= 3 && CheckCrc14A(data, len)); +} + +// Is this block an answer to the block we just sent? The PICC echoes our +// block number, so a mismatch is a frame from another step of the exchange and +// must not be handed to the caller as data. S-blocks carry no block number. +static bool iso14_answer_valid(const uint8_t *data, uint16_t len) { + + if (iso14_block_valid(data, len) == false) { + return false; + } + + if ((data[0] & 0xC0) == 0xC0) { // S-block, e.g. WTX + return true; + } + + if ((data[0] & 0xD0) == 0x90) { // R(NAK), never an answer + return false; + } + + return ((data[0] & 0x01) == iso14_pcb_blocknum); +} + +// ISO/IEC 14443-4 7.5.6 error recovery. A lost or damaged answer is a +// transmission error, not a dead link. R(NAK) asks the PICC to send its last +// block again, which costs nothing when the loss was ours to begin with; if +// that brings back no usable answer the PICC never got `block`, so repeat it. +// Returns the answer length, 0 when the link stays silent, -3 on user abort. +static int iso14_recover(const uint8_t *block, uint16_t block_len, uint8_t *data, uint16_t data_len) { + + for (uint8_t i = 0; i < ISO14_MAX_RETRANS; i++) { + + if (BUTTON_PRESS() || data_available()) { + return -3; + } + + iso14_retrans++; + + uint8_t nak[3] = {0x00, 0x00, 0x00}; + nak[0] = 0xB2 | iso14_pcb_blocknum; // r-block + NAK + AddCrc14A(nak, 1); + ReaderTransmit(nak, sizeof(nak), NULL); + + uint16_t len = ReaderReceive(data, data_len, parity_array); + if (iso14_answer_valid(data, len)) { + return len; + } + + ReaderTransmit(block, block_len, NULL); + + len = ReaderReceive(data, data_len, parity_array); + if (iso14_answer_valid(data, len)) { + return len; + } + } + + iso14_retrans_lost++; + return 0; +} + int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, uint16_t data_len, uint8_t *res) { // PCB(1) + APDU + CRC(2) has to fit inside one ISO14443 frame, which is // also the limit ReaderTransmit() can encode into the tosend buffer. @@ -4222,6 +4298,7 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u } uint8_t real_cmd[MAX_FRAME_SIZE] = {0}; + uint16_t real_cmd_len = cmd_len + 3; if (cmd_len) { // ISO 14443 APDU frame: PCB [CID] [NAD] APDU CRC PCB=0x02 @@ -4239,26 +4316,31 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u } AddCrc14A(real_cmd, cmd_len + 1); - ReaderTransmit(real_cmd, cmd_len + 3, NULL); + ReaderTransmit(real_cmd, real_cmd_len, NULL); // tearoff occurred if (tearoff_hook() == PM3_ETEAROFF) { return -1; } - size_t len = ReaderReceive(data, data_len, parity_array); uint8_t *data_bytes = (uint8_t *) data; + uint16_t len = ReaderReceive(data, data_len, parity_array); - if (len == 0) { - return 0; // DATA LINK ERROR + if (iso14_block_valid(data_bytes, len) == false) { + int rc = iso14_recover(real_cmd, real_cmd_len, data_bytes, data_len); + if (rc <= 0) { + return rc; // 0 - DATA LINK ERROR, -3 - aborted + } + len = rc; } uint32_t save_iso14a_timeout = iso14a_get_timeout(); // S-Block WTX - while (len && ((data_bytes[0] & 0xF2) == 0xF2)) { + while ((data_bytes[0] & 0xF2) == 0xF2) { if (BUTTON_PRESS() || data_available()) { + iso14a_set_timeout(save_iso14a_timeout); return -3; } @@ -4281,15 +4363,25 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u // retrieve the result again (with increased timeout) len = ReaderReceive(data_bytes, data_len, parity_array); + if (iso14_block_valid(data_bytes, len) == false) { + int rc = iso14_recover(real_cmd, real_cmd_len, data_bytes, data_len); + if (rc <= 0) { + iso14a_set_timeout(save_iso14a_timeout); + return rc; // 0 - DATA LINK ERROR, -3 - aborted + } + len = rc; + } } iso14a_set_timeout(save_iso14a_timeout); + // the CRC was checked on the way in, so a damaged frame can no longer + // toggle the block number + // if we received an I- or R(ACK)-Block with a block number equal to the // current block number, toggle the current block number - if (len >= 3 // PCB+CRC = 3 bytes - && ((data_bytes[0] & 0xC0) == 0 // I-Block - || (data_bytes[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0 + if (((data_bytes[0] & 0xC0) == 0 // I-Block + || (data_bytes[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0 && (data_bytes[0] & 0x01) == iso14_pcb_blocknum) { // equal block numbers iso14_pcb_blocknum ^= 1; } @@ -4299,16 +4391,10 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u *res = data_bytes[0]; } - if (len >= 3 && !CheckCrc14A(data_bytes, len)) { - return -1; - } - - if (len) { - // cut frame byte - len -= 1; - for (int i = 0; i < len; i++) { - data_bytes[i] = data_bytes[i + 1]; - } + // cut frame byte + len -= 1; + for (uint16_t i = 0; i < len; i++) { + data_bytes[i] = data_bytes[i + 1]; } return len; @@ -4430,14 +4516,18 @@ void ReaderIso14443a(PacketCommandNG *c) { FpgaDisableTracing(); uint8_t res = 0; - arg0 = iso14_apdu( - cmd, - len, - ((param & ISO14A_SEND_CHAINING) == ISO14A_SEND_CHAINING), - buf, - ISO14A_RESP_MAXLEN, - &res - ); + int apdu_len = iso14_apdu( + cmd, + len, + ((param & ISO14A_SEND_CHAINING) == ISO14A_SEND_CHAINING), + buf, + ISO14A_RESP_MAXLEN, + &res + ); + + // an error carries no data. Letting it through as a length would + // reply with a bogus frame size + arg0 = (apdu_len > 0) ? apdu_len : 0; response->len = arg0; response->sel = res; @@ -4655,8 +4745,8 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype) { iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); set_tracing(true); uint8_t mf_auth[4] = { keytype, block, 0x00, 0x00 }; @@ -4985,8 +5075,8 @@ void DetectNACKbug(void) { // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces). int32_t sync_cycles = PRNG_SEQUENCE_LENGTH; - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); set_tracing(true); iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); @@ -5200,7 +5290,7 @@ void DetectNACKbug(void) { num_to_bytes(i, 2, data + 2); reply_ng(CMD_HF_MIFARE_NACK_DETECT, status, data, 4); - BigBuf_free(); + BigBuf_free_keep_EM(); hf_field_off(); set_tracing(false); } diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index 05253f36b..3b2954c3e 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -187,6 +187,7 @@ uint32_t iso14a_last_rx_start(void); void iso14443a_setup(uint8_t fpga_minor_mode); int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, uint16_t data_len, uint8_t *res); +void iso14_get_retrans(uint32_t *retrans, uint32_t *lost); int iso14443a_select_card(uint8_t *uid_ptr, iso14a_card_select_t *p_card, uint32_t *cuid_ptr, bool anticollision, uint8_t num_cascades, bool no_rats); int iso14443a_select_cardEx(uint8_t *uid_ptr, iso14a_card_select_t *p_card, uint32_t *cuid_ptr, bool anticollision, uint8_t num_cascades, bool no_rats, diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 401644a22..c0b01460c 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -203,7 +203,7 @@ OUT: FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); set_tracing(false); - BigBuf_free(); + BigBuf_free_keep_EM(); return retval; } @@ -250,7 +250,7 @@ OUT: FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); set_tracing(false); - BigBuf_free(); + BigBuf_free_keep_EM(); return retval; } @@ -499,8 +499,8 @@ out: if (foundkeys || packet->lastchunk) { set_tracing(false); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); } g_dbglevel = oldbg; } @@ -582,8 +582,8 @@ void MifareUReadCard(mful_readblock_t *packet) { iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); // free eventually allocated BigBuf memory - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); set_tracing(true); // params @@ -676,7 +676,7 @@ void MifareUReadCard(mful_readblock_t *packet) { reply_ng(CMD_HF_MIFAREU_READCARD, PM3_SUCCESS, (uint8_t *)&payload, sizeof(payload)); LEDsoff(); - BigBuf_free(); + BigBuf_free_keep_EM(); set_tracing(false); } @@ -1014,8 +1014,8 @@ void MifareAcquireNonces(const mf_acquire_nonces_t *payload) { LED_A_ON(); LED_C_OFF(); - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); set_tracing(true); if (initialize) { @@ -1143,8 +1143,8 @@ void MifareAcquireEncryptedNonces(const mf_acquire_nonces_t *payload) { LED_A_ON(); LED_C_OFF(); - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); set_tracing(false); if (initialize) { @@ -1310,8 +1310,8 @@ int MifareAcquireStaticEncryptedNonces(uint32_t flags, const uint8_t *key, bool LED_A_ON(); LED_C_OFF(); - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); set_tracing(false); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); @@ -1597,8 +1597,8 @@ void MifareNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, uint8 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); // free eventually allocated BigBuf memory - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); set_tracing(true); @@ -1848,8 +1848,8 @@ void MifareStaticNested(uint8_t blockNo, uint8_t keyType, uint8_t targetBlockNo, iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); // free eventually allocated BigBuf memory - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); set_tracing(true); int8_t isOK = PM3_ESOFT; // reply_ng() takes int8_t, match it @@ -2302,8 +2302,8 @@ out: if (foundkeys == allkeys || lastchunk) { set_tracing(false); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); } g_dbglevel = oldbg; return; @@ -2528,8 +2528,8 @@ OUT: reply_ng(CMD_HF_MIFARE_CHKKEYS_FAST, PM3_EMALLOC, NULL, 0); set_tracing(false); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); g_dbglevel = oldbg; return; } @@ -2543,8 +2543,8 @@ OUT: set_tracing(false); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_free_keep_EM(); + BigBuf_Clear_keep_EM(); // special trick ecfill if (use_flashmem && foundkeys == allkeys) { @@ -2578,6 +2578,9 @@ OUT: g_dbglevel = oldbg; } +// selections in a row MifareChkKeys() may lose before it gives up on the card +#define CHK_SELECT_RETRIES 10 + void MifareChkKeys(uint8_t *datain, uint8_t reserved_mem) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); @@ -2628,16 +2631,33 @@ void MifareChkKeys(uint8_t *datain, uint8_t reserved_mem) { set_tracing(false); + // a card that stops answering ends the check instead of holding the device in the retry + int16_t status = PM3_SUCCESS; + uint8_t select_fails = 0; + for (uint16_t i = 0; i < key_count; i++) { + // Allow button press / usb cmd to interrupt device + if (BUTTON_PRESS() || data_available()) { + status = PM3_EOPABORTED; + break; + } + + WDT_HIT(); + + // 0 is no card, 3 an ATQA without anticollision bits: both leave nothing selected + int sel; // Iceman: use piwi's faster nonce collecting part in hardnested. if (have_uid == false) { // need a full select cycle to get the uid first iso14a_card_select_t card_info; - if (iso14443a_select_card(uid, &card_info, &cuid, true, 0, true) == false) { + sel = iso14443a_select_card(uid, &card_info, &cuid, true, 0, true); + if (sel != 1 && sel != 2) { if (g_dbglevel >= DBG_ERROR) Dbprintf("ChkKeys: Can't select card (ALL)"); - if (i) { - --i; // try same key once again + if (++select_fails > CHK_SELECT_RETRIES) { + status = PM3_ECARDEXCHANGE; + break; } + --i; // try same key once again, 0 wraps and the loop brings it back continue; } switch (card_info.uidlen) { @@ -2655,14 +2675,18 @@ void MifareChkKeys(uint8_t *datain, uint8_t reserved_mem) { } have_uid = true; } else { // no need for anticollision. We can directly select the card - if (iso14443a_select_card(uid, NULL, NULL, false, cascade_levels, true) == false) { + sel = iso14443a_select_card(uid, NULL, NULL, false, cascade_levels, true); + if (sel != 1 && sel != 2) { if (g_dbglevel >= DBG_ERROR) Dbprintf("ChkKeys: Can't select card (UID)"); - if (i) { - --i; // try same key once again + if (++select_fails > CHK_SELECT_RETRIES) { + status = PM3_ECARDEXCHANGE; + break; } + --i; // try same key once again, 0 wraps and the loop brings it back continue; } } + select_fails = 0; key = bytes_to_num(datain + i * 6, 6); if (mifare_classic_auth(pcs, cuid, blockNo, keyType, key, AUTH_FIRST)) { @@ -2678,7 +2702,7 @@ void MifareChkKeys(uint8_t *datain, uint8_t reserved_mem) { LED_B_ON(); crypto1_deinit(pcs); - reply_ng(CMD_HF_MIFARE_CHKKEYS, PM3_SUCCESS, (uint8_t *)&keyresult, sizeof(keyresult)); + reply_ng(CMD_HF_MIFARE_CHKKEYS, status, (uint8_t *)&keyresult, sizeof(keyresult)); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); set_tracing(false); @@ -3329,7 +3353,7 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { if (g_dbglevel >= DBG_ERROR) DbpString("Magic ident: failed to allocate buffers"); reply_ng(CMD_HF_MIFARE_CIDENT, PM3_EMALLOC, NULL, 0); switch_off(); - BigBuf_free(); + BigBuf_free_keep_EM(); return; } @@ -3532,7 +3556,7 @@ void MifareCIdent(bool is_mfc, uint8_t keytype, uint8_t *key) { reply_ng(CMD_HF_MIFARE_CIDENT, PM3_SUCCESS, (uint8_t *)&flag, sizeof(uint16_t)); // turns off OnSuccessMagic(); - BigBuf_free(); + BigBuf_free_keep_EM(); } void MifareHasStaticNonce(void) { @@ -3594,7 +3618,7 @@ OUT: reply_ng(CMD_HF_MIFARE_STATIC_NONCE, retval, data, sizeof(data)); // turns off OnSuccessMagic(); - BigBuf_free(); + BigBuf_free_keep_EM(); crypto1_deinit(pcs); } @@ -3802,7 +3826,7 @@ OUT: reply_ng(CMD_HF_MIFARE_STATIC_ENCRYPTED_NONCE, retval, data, sizeof(data)); // turns off OnSuccessMagic(); - BigBuf_free(); + BigBuf_free_keep_EM(); } void OnSuccessMagic(void) { @@ -3854,7 +3878,7 @@ void MifareGen3UID(uint8_t uidlen, uint8_t *uid) { if (old_uid == NULL || cmd == NULL || card_info == NULL) { if (g_dbglevel >= DBG_ERROR) DbpString("Gen3 UID: failed to allocate buffers"); reply_ng(CMD_HF_MIFARE_GEN3UID, PM3_EMALLOC, NULL, 0); - BigBuf_free(); + BigBuf_free_keep_EM(); return; } @@ -3883,7 +3907,7 @@ OUT: reply_ng(CMD_HF_MIFARE_GEN3UID, retval, old_uid, uidlen); // turns off OnSuccessMagic(); - BigBuf_free(); + BigBuf_free_keep_EM(); } void MifareGen3Blk(uint8_t block_len, uint8_t *block) { @@ -3898,7 +3922,7 @@ void MifareGen3Blk(uint8_t block_len, uint8_t *block) { if (cmd == NULL || card_info == NULL) { if (g_dbglevel >= DBG_ERROR) DbpString("Gen3 blk: failed to allocate buffers"); reply_ng(CMD_HF_MIFARE_GEN3BLK, PM3_EMALLOC, NULL, 0); - BigBuf_free(); + BigBuf_free_keep_EM(); return; } @@ -3956,7 +3980,7 @@ OUT: reply_ng(CMD_HF_MIFARE_GEN3BLK, retval, &cmd[sizeof(block_cmd)], MIFARE_BLOCK_SIZE); // turns off OnSuccessMagic(); - BigBuf_free(); + BigBuf_free_keep_EM(); } void MifareGen3Freez(void) { @@ -3980,7 +4004,7 @@ OUT: reply_ng(CMD_HF_MIFARE_GEN3FREEZ, retval, NULL, 0); // turns off OnSuccessMagic(); - BigBuf_free(); + BigBuf_free_keep_EM(); } void MifareG4ReadBlk(uint8_t blockno, uint8_t *pwd, uint8_t workFlags) { @@ -4056,7 +4080,7 @@ OUT: set_tracing(false); } - BigBuf_free(); + BigBuf_free_keep_EM(); } void MifareG4WriteBlk(uint8_t blockno, uint8_t *pwd, uint8_t *data, uint8_t workFlags) { @@ -4139,7 +4163,7 @@ OUT: set_tracing(false); } - BigBuf_free(); + BigBuf_free_keep_EM(); } void MifareSetMod(uint8_t *datain) { @@ -4161,7 +4185,7 @@ void MifareSetMod(uint8_t *datain) { if (uid == NULL || buf == NULL || par == NULL) { if (g_dbglevel >= DBG_ERROR) DbpString("SetMod: failed to allocate buffers"); reply_ng(CMD_HF_MIFARE_SETMOD, PM3_EMALLOC, NULL, 0); - BigBuf_free(); + BigBuf_free_keep_EM(); return; } @@ -4207,7 +4231,7 @@ void MifareSetMod(uint8_t *datain) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); - BigBuf_free(); + BigBuf_free_keep_EM(); } diff --git a/client/src/cmdhfmf.c b/client/src/cmdhfmf.c index 1e1e64c52..35ccb1d36 100644 --- a/client/src/cmdhfmf.c +++ b/client/src/cmdhfmf.c @@ -2658,6 +2658,9 @@ static int CmdHF14AMfNestedStatic(const char *Cmd) { case PM3_EOPABORTED : PrintAndLogEx(WARNING, "aborted via keyboard."); break; + case PM3_ECARDEXCHANGE : + PrintAndLogEx(FAILED, "Card stopped answering"); + break; case PM3_ESOFT : // No any key found? // Try to force decryption using measured nonce instead of automatic detection (some card types may misjudge) @@ -3966,6 +3969,12 @@ tryStaticnested: free(fptr); return isOK; } + case PM3_ECARDEXCHANGE: { + PrintAndLogEx(FAILED, "\nCard stopped answering"); + free(e_sector); + free(fptr); + return isOK; + } case PM3_ESOFT: { PrintAndLogEx(WARNING, "No key found, next try..."); force_detect_dist = 1; diff --git a/client/src/cmdhfmfdes.c b/client/src/cmdhfmfdes.c index 2ca030b4c..b0e213b07 100644 --- a/client/src/cmdhfmfdes.c +++ b/client/src/cmdhfmfdes.c @@ -67,6 +67,8 @@ #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 +// extra tries for a candidate the PICC gave no verdict on +#define MFDES_CHK_MAX_RETRY 2 // bundled dictionary used when no -f is given #define MFDES_DEFAULT_DICT "mfdes_default_keys" #define MFDES_BRUTEAID_RESELECT_ATTEMPTS 5 @@ -1395,8 +1397,56 @@ static void DesChkPrependKey(uint8_t *keyList, size_t stride, uint32_t *keyListL *keyListLen = len + 1; } +// What a dictionary check could not cover. Either one makes the search +// non-exhaustive, so "No keys found" alone would be a misleading result. +typedef struct { + uint32_t untested; // candidate authentications the PICC gave no verdict on + uint32_t skippedaid; // applications that could not be selected at all +} desfire_chk_gaps_t; + +// Select `aid`, retrying while the exchange fails on the link. PM3_EAPDU_FAIL +// is the PICC itself answering, so that one is final: the application really +// isn't there. Anything else is a lost exchange and worth another try. +static int DesChkSelectAID(DesfireContext_t *dctx, uint32_t aid) { + + int res = PM3_ESOFT; + + for (uint8_t attempt = 0; attempt <= MFDES_CHK_MAX_RETRY; attempt++) { + + res = DesfireSelectAIDHex(dctx, aid, false, 0); + if (res == PM3_SUCCESS || res == PM3_EAPDU_FAIL) { + break; + } + + DropField(); + } + + return res; +} + +// Did the PICC rule on this candidate key? Only AUTHENTICATION_ERROR is it +// refusing the key. No status byte at all, no answer content or an aborted +// exchange means the key was never evaluated, and leaves the PICC waiting for +// the second auth frame with a 14443-4 block number that no longer matches +// ours. Only a reselect clears both. +static bool DesChkNoVerdict(int res, uint8_t respcode) { + + if (res == DESFIRE_AUTH_NO_ANSWER || + res == DESFIRE_AUTH_NO_DATA1 || + res == DESFIRE_AUTH_NO_DATA2) { + return true; + } + + if (res == DESFIRE_AUTH_TX1_FAIL) { + return (respcode == MFDES_E_COMMAND_ABORTED); + } + + return (res == DESFIRE_AUTH_TX2_FAIL && respcode != MFDES_E_AUTHENTICATION_ERROR); +} + // 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`. +// in use on the currently selected application. Found keys are stored in `found`, +// and `gaps` collects what could not be covered. // Returns PM3_SUCCESS, or an error when the application can no longer be selected. static int AuthCheckDesfireKeyType(DesfireContext_t *dctx, DesfireSecureChannel secureChannel, @@ -1406,7 +1456,8 @@ static int AuthCheckDesfireKeyType(DesfireContext_t *dctx, const uint8_t *keyList, size_t keyListStride, uint32_t keyListLen, const int *usedkeys, desfire_app_keys_t *found, - bool *result) { + bool *result, + desfire_chk_gaps_t *gaps) { size_t keylen = desfire_get_key_length(keytype); @@ -1422,9 +1473,37 @@ static int AuthCheckDesfireKeyType(DesfireContext_t *dctx, const uint8_t *key = &keyList[curkey * keyListStride]; - DesfireSetKeyNoClear(dctx, keyno, keytype, (uint8_t *)key); + int res = 0; + bool noverdict = false; + + for (uint8_t attempt = 0; ; attempt++) { + + DesfireSetKeyNoClear(dctx, keyno, keytype, (uint8_t *)key); + + res = DesfireAuthenticate(dctx, secureChannel, false); + if (res == PM3_SUCCESS) { + break; + } + + noverdict = DesChkNoVerdict(res, dctx->lastRespCode); + + // the card gave up before the crypto stage, so the channel is + // gone and the application has to be selected again + if (DESFIRE_AUTH_PRE_CRYPTO(res) || noverdict) { + DropField(); + int selres = DesChkSelectAID(dctx, curaid); + if (selres != PM3_SUCCESS) { + // whatever is left of this application goes unchecked + gaps->skippedaid++; + return selres; + } + } + + if (noverdict == false || attempt >= MFDES_CHK_MAX_RETRY) { + break; + } + } - int res = DesfireAuthenticate(dctx, secureChannel, false); if (res == PM3_SUCCESS) { // the AID is already on the "Checking aid" line above PrintAndLogEx(SUCCESS, "Found " _GREEN_("%s") " Key %02u... " _GREEN_("%s"), @@ -1440,37 +1519,40 @@ static int AuthCheckDesfireKeyType(DesfireContext_t *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; + // the retries are spent and the card still gave no verdict, so this + // candidate stays unchecked and the search is not exhaustive + if (noverdict) { + gaps->untested++; + if (g_debugMode) { + PrintAndLogEx(DEBUG, "AID 0x%06X, %s key %02u... no verdict on %s, [%d] %s", + curaid, keytypestr, keyno, sprint_hex_inrow(key, keylen), + res, DesfireAuthErrorToStr(res)); } } - // 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) { + if (res == DESFIRE_AUTH_RNDB_LEN || + res == DESFIRE_AUTH_NO_AES || + res == DESFIRE_AUTH_NO_LRP) { return PM3_SUCCESS; } - // 3 - invalid key number. Every key fails the same way, but the + // invalid key number. Every key fails the same way, but the // remaining key numbers are still worth checking - if (res == 3) { + if (res == DESFIRE_AUTH_NO_FRAME) { 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) { + // a 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 (DESFIRE_AUTH_PRE_CRYPTO(res) || noverdict) { 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); } + // the rest of the list is never tried against this key number + gaps->untested += keyListLen - curkey - 1; break; } } else { @@ -1491,13 +1573,22 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, bool autoschann, desfire_app_keys_t *found, bool *result, + desfire_chk_gaps_t *gaps, bool verbose) { uint32_t curaid = (aid[0] & 0xFF) + ((aid[1] & 0xFF) << 8) + ((aid[2] & 0xFF) << 16); - int res = DesfireSelectAIDHex(dctx, curaid, false, 0); + int res = DesChkSelectAID(dctx, curaid); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "AID 0x%06X does not exist.", curaid); + + // only the PICC answering is proof that the application isn't there + if (res == PM3_EAPDU_FAIL) { + PrintAndLogEx(ERR, "AID 0x%06X does not exist.", curaid); + } else { + PrintAndLogEx(ERR, "AID 0x%06X, can't select it, keys " _YELLOW_("not checked"), curaid); + gaps->skippedaid++; + } + DropField(); return PM3_ESOFT; } @@ -1542,7 +1633,8 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, DesfireCheckAuthCommands(ISW6bAID, curaid, NULL, 0, &authCmdCheck); if (authCmdCheck.checked == false) { - PrintAndLogEx(ERR, "AID 0x%06X, could not get key settings", curaid); + PrintAndLogEx(ERR, "AID 0x%06X, could not get key settings, keys " _YELLOW_("not checked"), curaid); + gaps->skippedaid++; DropField(); return PM3_ESOFT; } @@ -1574,9 +1666,10 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, } // the probe dropped the field behind us - res = DesfireSelectAIDHex(dctx, curaid, false, 0); + res = DesChkSelectAID(dctx, curaid); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the auth command probe", curaid); + PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the auth command probe, keys " _YELLOW_("not checked"), curaid); + gaps->skippedaid++; DropField(); return PM3_ESOFT; } @@ -1627,9 +1720,10 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, uselrp = DesfireCheckAuthCmd(ISW6bAID, curaid, 0, MFDES_AUTHENTICATE_EV2F, true); // the probe dropped the field behind us - res = DesfireSelectAIDHex(dctx, curaid, false, 0); + res = DesChkSelectAID(dctx, curaid); if (res != PM3_SUCCESS) { - PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the LRP probe", curaid); + PrintAndLogEx(ERR, "AID 0x%06X, can't re-select after the LRP probe, keys " _YELLOW_("not checked"), curaid); + gaps->skippedaid++; DropField(); return PM3_ESOFT; } @@ -1678,7 +1772,7 @@ static int AuthCheckDesfire(DesfireContext_t *dctx, res = AuthCheckDesfireKeyType(dctx, secureChannel, curaid, checks[i].keytype, checks[i].name, checks[i].list, checks[i].stride, checks[i].len, - usedkeys, found, result); + usedkeys, found, result, gaps); if (res != PM3_SUCCESS) { DropField(); return res; @@ -1855,6 +1949,7 @@ static int CmdHF14aDesChk(const char *Cmd) { } bool result = false; + desfire_chk_gaps_t gaps = {0}; uint8_t app_ids[DESFIRE_MAX_APP_COUNT * 3] = {0}; size_t app_ids_len = 0; @@ -2064,6 +2159,7 @@ static int CmdHF14aDesChk(const char *Cmd) { autoschann, found, &foundKeyThisRound, + &gaps, verbose ); @@ -2084,6 +2180,25 @@ static int CmdHF14aDesChk(const char *Cmd) { PrintAndLogEx(WARNING, "No keys found"); } + // neither a candidate the PICC never ruled on nor an application that could + // not be selected is a tested candidate + if (gaps.untested || gaps.skippedaid) { + + PrintAndLogEx(WARNING, "Search was " _YELLOW_("not exhaustive")); + + if (gaps.untested) { + PrintAndLogEx(WARNING, " %u candidate%s got no verdict from the card", + gaps.untested, (gaps.untested == 1) ? "" : "s"); + } + + if (gaps.skippedaid) { + PrintAndLogEx(WARNING, " %u application%s could not be selected", + gaps.skippedaid, (gaps.skippedaid == 1) ? "" : "s"); + } + + PrintAndLogEx(HINT, "Hint: reposition the card and run the check again"); + } + // save keys to json if ((jsonnamelen > 0) && result) { DropField(); @@ -2107,7 +2222,9 @@ static int CmdHF14aDesChk(const char *Cmd) { free(dump); DropField(); - return PM3_SUCCESS; + + // an incomplete search must not look like a completed one to a script + return (gaps.untested || gaps.skippedaid) ? PM3_EPARTIAL : PM3_SUCCESS; } static int CmdHF14ADesList(const char *Cmd) { @@ -2123,13 +2240,15 @@ static int DesfireAuthCheck(DesfireContext_t *dctx, DesfireISOSelectWay way, uin return PM3_SUCCESS; } - // 4 - the challenge the PICC sent is the wrong length for this algo - // 50 - PICC didn't answer AES, 51 - PICC didn't answer LRP - // the application holds no key of this type, so every key in the list fails - // the same way and there is nothing to learn from trying the rest - bool wrongalgo = (res == 4 || res == 50 || res == 51); + // the challenge was the wrong length for this algo, or the PICC didn't + // answer AES / LRP at all: the application holds no key of this type, so + // every key in the list fails the same way and there is nothing to learn + // from trying the rest + bool wrongalgo = (res == DESFIRE_AUTH_RNDB_LEN || + res == DESFIRE_AUTH_NO_AES || + res == DESFIRE_AUTH_NO_LRP); - if (res < 7) { + if (DESFIRE_AUTH_PRE_CRYPTO(res) || DesChkNoVerdict(res, dctx->lastRespCode)) { DropField(); if (DesfireSelect(dctx, way, appID, NULL) != PM3_SUCCESS) { return -10; diff --git a/client/src/cmdhfmfsen.c b/client/src/cmdhfmfsen.c index 5682b5cba..35f6baa6e 100644 --- a/client/src/cmdhfmfsen.c +++ b/client/src/cmdhfmfsen.c @@ -862,7 +862,7 @@ static int fm11_collect_nonces_from_default_key_fallback(const fm11_keylist_t *d } PrintAndLogEx(WARNING, "Initial key did not collect nonce evidence, continuing dictionary search"); } - if (res == PM3_ETIMEOUT || res == PM3_EOPABORTED) { + if (res == PM3_ETIMEOUT || res == PM3_EOPABORTED || res == PM3_ECARDEXCHANGE) { retval = res; break; } @@ -2384,7 +2384,7 @@ normal_out: fm11_print_key_hit_row(nonce_count, sec32, kt, keys_found[sec32][kt], found_key); break; } - if (res == PM3_ETIMEOUT || res == PM3_EOPABORTED) { + if (res == PM3_ETIMEOUT || res == PM3_EOPABORTED || res == PM3_ECARDEXCHANGE) { retval = res; break; } @@ -2663,7 +2663,7 @@ static int fm11_verify_candidates(uint8_t real_sec, uint8_t key_type, const fm11 real_sec, key_type ? 'B' : 'A'); return PM3_ESOFT; } - if (res == PM3_EOPABORTED) { + if (res == PM3_EOPABORTED || res == PM3_ECARDEXCHANGE) { fm11_sen_clear_inplace(); return res; } @@ -3432,7 +3432,7 @@ int HFMFSENRecover(bool keep_nonces, bool no_oob, bool reader_mode, bool offline } total_candidates = fm11_count_unfound_candidates(candidates, found_key); - } else if (res == PM3_ETIMEOUT || res == PM3_EOPABORTED) { + } else if (res == PM3_ETIMEOUT || res == PM3_EOPABORTED || res == PM3_ECARDEXCHANGE) { retval = res; goto out; } else { diff --git a/client/src/mifare/desfirecore.c b/client/src/mifare/desfirecore.c index d5906c076..eea7d25a6 100644 --- a/client/src/mifare/desfirecore.c +++ b/client/src/mifare/desfirecore.c @@ -245,59 +245,61 @@ const char *DesfireGetErrorString(int res, uint16_t *sw) { const char *DesfireAuthErrorToStr(int error) { switch (error) { - case 1: - return "Sending auth command failed"; - case 2: + case DESFIRE_AUTH_TX1_FAIL: + return "Authentication failed. PICC rejected the auth command"; + case DESFIRE_AUTH_NO_DATA1: return "Authentication failed. No data received"; - case 3: + case DESFIRE_AUTH_NO_FRAME: return "Authentication failed. Invalid key number."; - case 4: + case DESFIRE_AUTH_RNDB_LEN: return "Authentication failed. Length of answer doesn't match algo length"; - case 5: + case DESFIRE_AUTH_SETKEY_DEC: return "mbedtls_aes_setkey_dec failed"; - case 6: + case DESFIRE_AUTH_SETKEY_ENC: return "mbedtls_aes_setkey_enc failed"; - case 7: - return "Sending auth response (2nd frame) failed"; - case 8: + case DESFIRE_AUTH_TX2_FAIL: + return "Authentication failed. PICC rejected the 2nd auth frame"; + case DESFIRE_AUTH_NO_DATA2: return "Authentication failed. Card timeout."; - case 9: + case DESFIRE_AUTH_NOT_OK: return "Authentication failed."; - case 10: + case DESFIRE_AUTH_SETKEY_DEC2: return "mbedtls_aes_setkey_dec failed"; - case 11: + case DESFIRE_AUTH_RNDA_MISMATCH: return "Authentication failed. Cannot verify Session Key."; - case 12: + case DESFIRE_AUTH_CMAC_FAIL: return "Authentication failed. Cannot verify CMAC."; - case 50: + case DESFIRE_AUTH_NO_AES: return "PICC returned not an AES answer"; - case 51: + case DESFIRE_AUTH_NO_LRP: return "PICC returned not an LRP answer"; - case 100: + case DESFIRE_AUTH_NO_ANSWER: + return "Authentication inconclusive. PICC gave no status byte"; + case DESFIRE_AUTH_NO_METHOD: return "Can't find auth method for provided channel parameters."; - case 200: + case DESFIRE_AUTH_SELECT_FAIL: return "Can't select application."; - case 201: + case DESFIRE_AUTH_NO_CHANNEL: return "Authentication returned no error but channel not authenticated."; - case 202: + case DESFIRE_AUTH_SELECT_ISO_FAIL: return "Can't select application by ISO ID."; - case 203: + case DESFIRE_AUTH_SELECT_EF_FAIL: return "Can't select file by ISO ID."; - case 301: + case DESFIRE_AUTH_ISO_CHAL: return "ISO Get challenge error."; - case 302: + case DESFIRE_AUTH_ISO_CHAL_LEN: return "ISO Get challenge returned wrong length."; - case 303: + case DESFIRE_AUTH_ISO_ENC_RND1: return "Crypto encode piccrnd1 error."; - case 304: + case DESFIRE_AUTH_ISO_EXT_AUTH: return "External authenticate error."; - case 305: + case DESFIRE_AUTH_ISO_INT_AUTH: return "Internal authenticate error."; - case 306: + case DESFIRE_AUTH_ISO_INT_LEN: return "Internal authenticate returned wrong length."; - case 307: + case DESFIRE_AUTH_ISO_DEC_RND2: return "Crypto decode piccrnd2 error."; - case 308: + case DESFIRE_AUTH_ISO_RND_FAIL: return "Random numbers don't match. Authentication failed."; default: break; @@ -1193,7 +1195,7 @@ int DesfireSelectAndAuthenticateEx(DesfireContext_t *dctx, DesfireSecureChannel res = DesfireAnticollision(verbose); if (res != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Desfire anticollision " _RED_("failed")); - return 200; + return DESFIRE_AUTH_SELECT_FAIL; } if (verbose) { @@ -1204,7 +1206,7 @@ int DesfireSelectAndAuthenticateEx(DesfireContext_t *dctx, DesfireSecureChannel res = DesfireSelectAIDHex(dctx, aid, false, 0); if (res != PM3_SUCCESS) { PrintAndLogEx(FAILED, "Desfire %s select " _RED_("failed"), DesfireWayIDStr(ISW6bAID, aid)); - return 200; + return DESFIRE_AUTH_SELECT_FAIL; } if (verbose) { @@ -1229,8 +1231,8 @@ int DesfireSelectAndAuthenticateEx(DesfireContext_t *dctx, DesfireSecureChannel PrintAndLogEx(INFO, "Desfire " _GREEN_("authenticated")); } } else { - PrintAndLogEx(FAILED, "Desfire %s authentication " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(ISW6bAID, aid), 201, DesfireAuthErrorToStr(201)); - return 201; + PrintAndLogEx(FAILED, "Desfire %s authentication " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(ISW6bAID, aid), DESFIRE_AUTH_NO_CHANNEL, DesfireAuthErrorToStr(DESFIRE_AUTH_NO_CHANNEL)); + return DESFIRE_AUTH_NO_CHANNEL; } } @@ -1260,7 +1262,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } - return 200; + return DESFIRE_AUTH_SELECT_FAIL; } if (verbose) { @@ -1281,7 +1283,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } - return 200; + return DESFIRE_AUTH_SELECT_FAIL; } if (verbose) { @@ -1297,7 +1299,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } - return 202; + return DESFIRE_AUTH_SELECT_ISO_FAIL; } if (verbose) { PrintAndLogEx(INFO, "%s is " _GREEN_("selected"), DesfireWayIDStr(way, id)); @@ -1312,7 +1314,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } - return 202; + return DESFIRE_AUTH_SELECT_ISO_FAIL; } if (verbose) { @@ -1331,7 +1333,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } - return 200; + return DESFIRE_AUTH_SELECT_FAIL; } if (verbose) { @@ -1347,7 +1349,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } - return 202; + return DESFIRE_AUTH_SELECT_ISO_FAIL; } if (verbose) { PrintAndLogEx(INFO, "%s is " _GREEN_("selected"), DesfireWayIDStr(way, id)); @@ -1361,7 +1363,7 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s if (res == PM3_ECARDEXCHANGE || res == PM3_ETIMEOUT || res == PM3_ERFTRANS) { return res; } - return 203; + return DESFIRE_AUTH_SELECT_EF_FAIL; } if (verbose) { @@ -1381,8 +1383,8 @@ int DesfireSelectAndAuthenticateW(DesfireContext_t *dctx, DesfireSecureChannel s PrintAndLogEx(INFO, "Desfire " _GREEN_("authenticated")); } } else { - PrintAndLogEx(FAILED, "Desfire %s authentication " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(way, id), 201, DesfireAuthErrorToStr(201)); - return 201; + PrintAndLogEx(FAILED, "Desfire %s authentication " _RED_("failed") ". Result [%d] %s", DesfireWayIDStr(way, id), DESFIRE_AUTH_NO_CHANNEL, DesfireAuthErrorToStr(DESFIRE_AUTH_NO_CHANNEL)); + return DESFIRE_AUTH_NO_CHANNEL; } } @@ -1428,7 +1430,7 @@ static int DesfireAuthenticateEV1(DesfireContext_t *dctx, DesfireSecureChannel s } size_t recv_len = 0; - uint8_t respcode = 0; + uint8_t respcode = 0xFF; uint8_t recv_data[256] = {0}; if (verbose) @@ -1437,15 +1439,17 @@ static int DesfireAuthenticateEV1(DesfireContext_t *dctx, DesfireSecureChannel s // Let's send our auth command int res = DesfireExchangeEx(false, dctx, subcommand, &dctx->keyNum, 1, &respcode, recv_data, &recv_len, false, 0); if (res != PM3_SUCCESS) { - return 1; + // 0xFF means no status byte came back at all. The PICC said nothing + // about the key, so the attempt is inconclusive and not a refusal + return (respcode == 0xFF) ? 60 : 1; } if (!recv_len) { - return 2; + return DESFIRE_AUTH_NO_DATA1; } if (respcode != MFDES_ADDITIONAL_FRAME) { - return 3; + return DESFIRE_AUTH_NO_FRAME; } uint32_t expectedlen = 8; @@ -1454,7 +1458,7 @@ static int DesfireAuthenticateEV1(DesfireContext_t *dctx, DesfireSecureChannel s } if (recv_len != expectedlen) { - return 4; + return DESFIRE_AUTH_RNDB_LEN; } // Part 2 @@ -1509,15 +1513,17 @@ static int DesfireAuthenticateEV1(DesfireContext_t *dctx, DesfireSecureChannel s res = DesfireExchangeEx(false, dctx, MFDES_ADDITIONAL_FRAME, both, bothlen, &respcode, recv_data, &recv_len, false, 0); if (res != PM3_SUCCESS) { - return 7; + // a wrong key is the PICC answering this frame with AUTHENTICATION_ERROR. + // No status byte at all is a lost exchange, not a verdict on the key + return (respcode == 0xFF) ? 60 : 7; } if (!recv_len) { - return 8; + return DESFIRE_AUTH_NO_DATA2; } if (respcode != MFDES_S_OPERATION_OK) { - return 9; + return DESFIRE_AUTH_NOT_OK; } // Part 4 @@ -1542,7 +1548,7 @@ static int DesfireAuthenticateEV1(DesfireContext_t *dctx, DesfireSecureChannel s PrintAndLogEx(DEBUG, "Expected_RndA : %s", sprint_hex(RndA, rndlen)); PrintAndLogEx(DEBUG, "Generated_RndA : %s", sprint_hex(encRndA, rndlen)); } - return 11; + return DESFIRE_AUTH_RNDA_MISMATCH; } } @@ -1576,7 +1582,7 @@ static int DesfireAuthenticateEV2(DesfireContext_t *dctx, DesfireSecureChannel s uint8_t *key = dctx->key; size_t recv_len = 0; - uint8_t respcode = 0; + uint8_t respcode = 0xFF; uint8_t recv_data[256] = {0}; if (verbose) @@ -1586,25 +1592,27 @@ static int DesfireAuthenticateEV2(DesfireContext_t *dctx, DesfireSecureChannel s uint8_t cdata[] = {dctx->keyNum, 0x00}; int res = DesfireExchangeEx(false, dctx, subcommand, cdata, (firstauth) ? sizeof(cdata) : 1, &respcode, recv_data, &recv_len, false, 0); if (res != PM3_SUCCESS) { - return 1; + // 0xFF means no status byte came back at all. The PICC said nothing + // about the key, so the attempt is inconclusive and not a refusal + return (respcode == 0xFF) ? 60 : 1; } if (!recv_len) { - return 2; + return DESFIRE_AUTH_NO_DATA1; } if (respcode != MFDES_ADDITIONAL_FRAME) { - return 3; + return DESFIRE_AUTH_NO_FRAME; } size_t rdataindx = 0; if (recv_len != CRYPTO_AES_BLOCK_SIZE) { if (recv_len == CRYPTO_AES_BLOCK_SIZE + 1) { if (recv_data[0] != 0x00) - return 50; + return DESFIRE_AUTH_NO_AES; rdataindx = 1; } else { - return 4; + return DESFIRE_AUTH_RNDB_LEN; } } @@ -1613,7 +1621,7 @@ static int DesfireAuthenticateEV2(DesfireContext_t *dctx, DesfireSecureChannel s // Part 3 if (aes_decode(IV, key, encRndB, RndB, CRYPTO_AES_BLOCK_SIZE)) - return 5; + return DESFIRE_AUTH_SETKEY_DEC; if (g_debugMode > 1) { PrintAndLogEx(DEBUG, "encRndB: %s", sprint_hex(encRndB, CRYPTO_AES_BLOCK_SIZE)); @@ -1634,29 +1642,31 @@ static int DesfireAuthenticateEV2(DesfireContext_t *dctx, DesfireSecureChannel s } if (aes_encode(IV, key, tmp, both, CRYPTO_AES_BLOCK_SIZE * 2)) - return 6; + return DESFIRE_AUTH_SETKEY_ENC; if (g_debugMode > 1) { PrintAndLogEx(DEBUG, "EncBoth: %s", sprint_hex(both, CRYPTO_AES_BLOCK_SIZE * 2)); } res = DesfireExchangeEx(false, dctx, MFDES_ADDITIONAL_FRAME, both, CRYPTO_AES_BLOCK_SIZE * 2, &respcode, recv_data, &recv_len, false, 0); if (res != PM3_SUCCESS) { - return 7; + // a wrong key is the PICC answering this frame with AUTHENTICATION_ERROR. + // No status byte at all is a lost exchange, not a verdict on the key + return (respcode == 0xFF) ? 60 : 7; } if (!recv_len) { - return 8; + return DESFIRE_AUTH_NO_DATA2; } if (respcode != MFDES_S_OPERATION_OK) { - return 9; + return DESFIRE_AUTH_NOT_OK; } // Part 4 uint8_t data[32] = {0}; if (aes_decode(IV, key, recv_data, data, recv_len)) - return 10; + return DESFIRE_AUTH_SETKEY_DEC2; // rotate rndA to check memcpy(rotRndA, RndA, CRYPTO_AES_BLOCK_SIZE); @@ -1669,7 +1679,7 @@ static int DesfireAuthenticateEV2(DesfireContext_t *dctx, DesfireSecureChannel s PrintAndLogEx(DEBUG, "Expected_RndA' : %s", sprint_hex(rotRndA, CRYPTO_AES_BLOCK_SIZE)); PrintAndLogEx(DEBUG, "Generated_RndA' : %s", sprint_hex(recRndA, CRYPTO_AES_BLOCK_SIZE)); } - return 11; + return DESFIRE_AUTH_RNDA_MISMATCH; } if (firstauth) { @@ -1706,10 +1716,10 @@ static int DesfireAuthenticateISO(DesfireContext_t *dctx, DesfireSecureChannel s size_t xlen = 0; int res = DesfireISOGetChallenge(dctx, dctx->keyType, piccrnd, &xlen); if (res != PM3_SUCCESS) - return 301; + return DESFIRE_AUTH_ISO_CHAL; if (xlen != rndlen) - return 302; + return DESFIRE_AUTH_ISO_CHAL_LEN; uint8_t both[32] = {0}; memcpy(both, hostrnd, rndlen); @@ -1722,17 +1732,17 @@ static int DesfireAuthenticateISO(DesfireContext_t *dctx, DesfireSecureChannel s // external authenticate res = DesfireISOExternalAuth(dctx, dctx->appSelected, dctx->keyNum, dctx->keyType, both); if (res != PM3_SUCCESS) - return 304; + return DESFIRE_AUTH_ISO_EXT_AUTH; // internal authenticate uint8_t rnddata[64] = {0}; xlen = 0; res = DesfireISOInternalAuth(dctx, dctx->appSelected, dctx->keyNum, dctx->keyType, hostrnd2, rnddata, &xlen); if (res != PM3_SUCCESS) - return 305; + return DESFIRE_AUTH_ISO_INT_AUTH; if (xlen != rndlen * 2) - return 306; + return DESFIRE_AUTH_ISO_INT_LEN; // decode rnddata uint8_t piccrnd2[64] = {0}; @@ -1740,7 +1750,7 @@ static int DesfireAuthenticateISO(DesfireContext_t *dctx, DesfireSecureChannel s // check if (memcmp(hostrnd2, &piccrnd2[rndlen], rndlen) != 0) - return 308; + return DESFIRE_AUTH_ISO_RND_FAIL; DesfireGenSessionKeyEV1(hostrnd, piccrnd2, dctx->keyType, dctx->sessionKeyEnc); DesfireClearIV(dctx); @@ -1763,7 +1773,7 @@ static int DesfireAuthenticateLRP(DesfireContext_t *dctx, DesfireSecureChannel s uint8_t *key = dctx->key; size_t recv_len = 0; - uint8_t respcode = 0; + uint8_t respcode = 0xFF; uint8_t recv_data[256] = {0}; if (verbose) @@ -1773,23 +1783,25 @@ static int DesfireAuthenticateLRP(DesfireContext_t *dctx, DesfireSecureChannel s uint8_t cdata[] = {dctx->keyNum, 0x01, 0x02}; int res = DesfireExchangeEx(false, dctx, subcommand, cdata, (firstauth) ? sizeof(cdata) : 1, &respcode, recv_data, &recv_len, false, 0); if (res != PM3_SUCCESS) { - return 1; + // 0xFF means no status byte came back at all. The PICC said nothing + // about the key, so the attempt is inconclusive and not a refusal + return (respcode == 0xFF) ? 60 : 1; } if (!recv_len) { - return 2; + return DESFIRE_AUTH_NO_DATA1; } if (respcode != MFDES_ADDITIONAL_FRAME) { - return 3; + return DESFIRE_AUTH_NO_FRAME; } if (recv_len != CRYPTO_AES_BLOCK_SIZE + 1) { - return 4; + return DESFIRE_AUTH_RNDB_LEN; } if (recv_data[0] != 0x01) - return 51; + return DESFIRE_AUTH_NO_LRP; // PICC return RndB in plain memcpy(RndB, &recv_data[1], 16); @@ -1820,15 +1832,17 @@ static int DesfireAuthenticateLRP(DesfireContext_t *dctx, DesfireSecureChannel s res = DesfireExchangeEx(false, dctx, MFDES_ADDITIONAL_FRAME, both, CRYPTO_AES_BLOCK_SIZE * 2, &respcode, recv_data, &recv_len, false, 0); if (res != PM3_SUCCESS) { - return 7; + // a wrong key is the PICC answering this frame with AUTHENTICATION_ERROR. + // No status byte at all is a lost exchange, not a verdict on the key + return (respcode == 0xFF) ? 60 : 7; } if (!recv_len) { - return 8; + return DESFIRE_AUTH_NO_DATA2; } if (respcode != MFDES_S_OPERATION_OK) { - return 9; + return DESFIRE_AUTH_NOT_OK; } // Part 4 @@ -1851,7 +1865,7 @@ static int DesfireAuthenticateLRP(DesfireContext_t *dctx, DesfireSecureChannel s PrintAndLogEx(DEBUG, "Expected cmac : %s", sprint_hex(recCMAC, CRYPTO_AES_BLOCK_SIZE)); PrintAndLogEx(DEBUG, "Generated cmac : %s", sprint_hex(cmac, CRYPTO_AES_BLOCK_SIZE)); } - return 12; + return DESFIRE_AUTH_CMAC_FAIL; } // decode data @@ -1913,7 +1927,7 @@ int DesfireAuthenticate(DesfireContext_t *dctx, DesfireSecureChannel secureChann if (secureChannel == DACLRP) return DesfireAuthenticateLRP(dctx, secureChannel, (DesfireIsAuthenticated(dctx) == false), verbose); - return 100; + return DESFIRE_AUTH_NO_METHOD; } bool DesfireCheckAuthCmd(DesfireISOSelectWay way, uint32_t appID, uint8_t keyNum, uint8_t authcmd, bool checklrp) { diff --git a/client/src/mifare/desfirecore.h b/client/src/mifare/desfirecore.h index 194d18207..f62887f15 100644 --- a/client/src/mifare/desfirecore.h +++ b/client/src/mifare/desfirecore.h @@ -28,6 +28,52 @@ #define DESFIRE_TX_FRAME_MAX_LEN 54 #define DESFIRE_BUFFER_SIZE 65538 +// DesfireAuthenticate() / DesfireSelectAndAuthenticate*() result codes. +// PM3_SUCCESS means authenticated; everything else names the stage that did +// not complete. The numbers are printed to the user, so they stay put. +// +// first auth frame, the one carrying the key number +#define DESFIRE_AUTH_TX1_FAIL 1 // PICC answered with an error status +#define DESFIRE_AUTH_NO_DATA1 2 // answered without data +#define DESFIRE_AUTH_NO_FRAME 3 // answer wasn't ADDITIONAL_FRAME +#define DESFIRE_AUTH_RNDB_LEN 4 // RndB length doesn't match the algo +#define DESFIRE_AUTH_SETKEY_DEC 5 // mbedtls_aes_setkey_dec failed +#define DESFIRE_AUTH_SETKEY_ENC 6 // mbedtls_aes_setkey_enc failed +// second auth frame, the one carrying RndA + RndB'. A wrong key is the PICC +// answering this one with AUTHENTICATION_ERROR +#define DESFIRE_AUTH_TX2_FAIL 7 // PICC answered with an error status +#define DESFIRE_AUTH_NO_DATA2 8 // answered without data +#define DESFIRE_AUTH_NOT_OK 9 // answer status wasn't OPERATION_OK +#define DESFIRE_AUTH_SETKEY_DEC2 10 // mbedtls_aes_setkey_dec failed +#define DESFIRE_AUTH_RNDA_MISMATCH 11 // session key can't be verified +#define DESFIRE_AUTH_CMAC_FAIL 12 // CMAC can't be verified +// the application holds no key of this type +#define DESFIRE_AUTH_NO_AES 50 // PICC didn't answer AES +#define DESFIRE_AUTH_NO_LRP 51 // PICC didn't answer LRP +// no status byte came back at all, so the PICC said nothing about the key. +// Inconclusive: not the same as the PICC refusing it +#define DESFIRE_AUTH_NO_ANSWER 60 +#define DESFIRE_AUTH_NO_METHOD 100 // no auth method for these parameters +// select / channel +#define DESFIRE_AUTH_SELECT_FAIL 200 +#define DESFIRE_AUTH_NO_CHANNEL 201 // no error, yet not authenticated +#define DESFIRE_AUTH_SELECT_ISO_FAIL 202 +#define DESFIRE_AUTH_SELECT_EF_FAIL 203 +// ISO mode authentication +#define DESFIRE_AUTH_ISO_CHAL 301 // get challenge error +#define DESFIRE_AUTH_ISO_CHAL_LEN 302 // get challenge wrong length +#define DESFIRE_AUTH_ISO_ENC_RND1 303 // crypto encode piccrnd1 error +#define DESFIRE_AUTH_ISO_EXT_AUTH 304 // external authenticate error +#define DESFIRE_AUTH_ISO_INT_AUTH 305 // internal authenticate error +#define DESFIRE_AUTH_ISO_INT_LEN 306 // internal authenticate wrong length +#define DESFIRE_AUTH_ISO_DEC_RND2 307 // crypto decode piccrnd2 error +#define DESFIRE_AUTH_ISO_RND_FAIL 308 // random numbers don't match + +// true for the codes that end the exchange before the second auth frame goes +// out: no secure channel was established and the application has to be +// selected again +#define DESFIRE_AUTH_PRE_CRYPTO(res) ((res) >= DESFIRE_AUTH_TX1_FAIL && (res) < DESFIRE_AUTH_TX2_FAIL) + enum DesfireISOSelectControlEnum { ISSMFDFEF = 0x00, ISSChildDF = 0x01, diff --git a/client/src/mifare/mifarehost.c b/client/src/mifare/mifarehost.c index 14ea62886..49071c31d 100644 --- a/client/src/mifare/mifarehost.c +++ b/client/src/mifare/mifarehost.c @@ -992,7 +992,7 @@ int mf_static_nested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trg sprint_hex_inrow(resultKey, MIFARE_KEY_SIZE) ); return PM3_SUCCESS; - } else if (res == PM3_ETIMEOUT || res == PM3_EOPABORTED) { + } else if (res == PM3_ETIMEOUT || res == PM3_EOPABORTED || res == PM3_ECARDEXCHANGE) { PrintAndLogEx(NORMAL, ""); free(mem); return res;