From: pwpiwi Date: Thu, 9 Jan 2020 14:42:31 +0000 (+0100) Subject: speedup 'hf mf chk' (#901) X-Git-Url: https://git.zerfleddert.de/cgi-bin/gitweb.cgi/proxmark3-svn/commitdiff_plain/a749b1e58b3e2739460a982ca180d79012ab62c8?hp=f0c48553cbe15f3218e4ab37a812df53f845c650 speedup 'hf mf chk' (#901) * add separate timeout for tag response to nr_ar * measure response time and use it for response timeout * don't drop field between keyblocks * some reformatting * some whitespace fixes * fishing for microseconds in TransmitFor14443a() * allow arbitrary number of keys in MifareChkKeys() * and move progress printing to MifareChkKeys() Co-authored-by: uzlonewolf --- diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 0ca9873b..31a3e4cc 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -270,8 +270,7 @@ const bool Mod_Miller_LUT[] = { #define IsMillerModulationNibble1(b) (Mod_Miller_LUT[(b & 0x000000F0) >> 4]) #define IsMillerModulationNibble2(b) (Mod_Miller_LUT[(b & 0x0000000F)]) -static void UartReset() -{ +static void UartReset() { Uart.state = STATE_UNSYNCD; Uart.bitCount = 0; Uart.len = 0; // number of decoded data bytes @@ -280,8 +279,7 @@ static void UartReset() Uart.parityBits = 0; // holds 8 parity bits } -static void UartInit(uint8_t *data, uint8_t *parity) -{ +static void UartInit(uint8_t *data, uint8_t *parity) { Uart.output = data; Uart.parity = parity; Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits @@ -291,8 +289,7 @@ static void UartInit(uint8_t *data, uint8_t *parity) } // use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time -static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) -{ +static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) { Uart.fourBits = (Uart.fourBits << 8) | bit; @@ -447,8 +444,7 @@ const bool Mod_Manchester_LUT[] = { #define IsManchesterModulationNibble2(b) (Mod_Manchester_LUT[(b & 0x000F)]) -static void DemodReset() -{ +static void DemodReset() { Demod.state = DEMOD_UNSYNCD; Demod.len = 0; // number of decoded data bytes Demod.parityLen = 0; @@ -461,16 +457,14 @@ static void DemodReset() Demod.endTime = 0; } -static void DemodInit(uint8_t *data, uint8_t *parity) -{ +static void DemodInit(uint8_t *data, uint8_t *parity) { Demod.output = data; Demod.parity = parity; DemodReset(); } // use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time -static RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_time) -{ +static RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_time) { Demod.twoBits = (Demod.twoBits << 8) | bit; @@ -729,8 +723,7 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { //----------------------------------------------------------------------------- // Prepare tag messages //----------------------------------------------------------------------------- -static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *parity) -{ +static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *parity) { ToSendReset(); // Correction bit, might be removed when not needed @@ -778,8 +771,7 @@ static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *par } -static void Code4bitAnswerAsTag(uint8_t cmd) -{ +static void Code4bitAnswerAsTag(uint8_t cmd) { int i; ToSendReset(); @@ -853,8 +845,7 @@ static void EmLogTraceTag(uint8_t *tag_data, uint16_t tag_len, uint8_t *tag_Pari // Stop when button is pressed // Or return true when command is captured //----------------------------------------------------------------------------- -static int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len) -{ +static int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len) { // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen // only, since we are receiving, not transmitting). // Signal field is off with the appropriate LED @@ -951,8 +942,8 @@ bool prepare_allocated_tag_modulation(tag_response_info_t* response_info, uint8_ // Main loop of simulated tag: receive commands from reader, decide what // response to send, and send it. //----------------------------------------------------------------------------- -void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data) -{ +void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data) { + uint8_t sak; // The first response contains the ATQA (note: bytes are transmitted in reverse order). @@ -1231,8 +1222,7 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data) // prepare a delayed transfer. This simply shifts ToSend[] by a number // of bits specified in the delay parameter. -static void PrepareDelayedTransfer(uint16_t delay) -{ +static void PrepareDelayedTransfer(uint16_t delay) { uint8_t bitmask = 0; uint8_t bits_to_shift = 0; uint8_t bits_shifted = 0; @@ -1261,8 +1251,7 @@ static void PrepareDelayedTransfer(uint16_t delay) // if == 0: transfer immediately and return time of transfer // if != 0: delay transfer until time specified //------------------------------------------------------------------------------------- -static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing) -{ +static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing) { LED_B_ON(); LED_D_ON(); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD); @@ -1270,12 +1259,12 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing uint32_t ThisTransferTime = 0; if (timing) { - if(*timing == 0) { // Measure time + if (*timing == 0) { // Measure time *timing = (GetCountSspClk() + 8) & 0xfffffff8; } else { PrepareDelayedTransfer(*timing & 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks) } - if(MF_DBGLEVEL >= 4 && GetCountSspClk() >= (*timing & 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing"); + if (MF_DBGLEVEL >= 4 && GetCountSspClk() >= (*timing & 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing"); while (GetCountSspClk() < (*timing & 0xfffffff8)); // Delay transfer (multiple of 8 MF clock ticks) LastTimeProxToAirStart = *timing; } else { @@ -1284,12 +1273,9 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing LastTimeProxToAirStart = ThisTransferTime; } - // clear TXRDY - AT91C_BASE_SSC->SSC_THR = SEC_Y; - uint16_t c = 0; for (;;) { - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { + if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = cmd[c]; c++; if(c >= len) { @@ -1306,8 +1292,7 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing //----------------------------------------------------------------------------- // Prepare reader command (in bits, support short frames) to send to FPGA //----------------------------------------------------------------------------- -static void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, const uint8_t *parity) -{ +static void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, const uint8_t *parity) { int i, j; int last; uint8_t b; @@ -1390,8 +1375,7 @@ static void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, cons // Stop when button is pressed (return 1) or field was gone (return 2) // Or return 0 when command is captured //----------------------------------------------------------------------------- -int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity) -{ +int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity) { uint32_t field_off_time = -1; uint32_t samples = 0; int ret = 0; @@ -1475,8 +1459,7 @@ int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity) } -static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen) -{ +static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen) { LED_C_ON(); uint8_t b; @@ -1578,8 +1561,7 @@ int EmSendPrecompiledCmd(tag_response_info_t *response_info) { // If a response is captured return true // If it takes too long return false //----------------------------------------------------------------------------- -static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receivedResponsePar, uint16_t offset) -{ +static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receivedResponsePar, uint16_t offset) { uint32_t c; // Set FPGA mode to "reader listen mode", no modulation (listen @@ -1598,9 +1580,9 @@ static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receive for (;;) { WDT_HIT(); - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { + if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - if(ManchesterDecoding(b, offset, 0)) { + if (ManchesterDecoding(b, offset, 0)) { NextTransferTime = MAX(NextTransferTime, Demod.endTime - (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER)/16 + FRAME_DELAY_TIME_PICC_TO_PCD); return true; } else if (c++ > iso14a_timeout && Demod.state == DEMOD_UNSYNCD) { @@ -1611,13 +1593,13 @@ static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receive } -void ReaderTransmitBitsPar(uint8_t* frame, uint16_t bits, uint8_t *par, uint32_t *timing) -{ +void ReaderTransmitBitsPar(uint8_t* frame, uint16_t bits, uint8_t *par, uint32_t *timing) { + CodeIso14443aBitsAsReaderPar(frame, bits, par); // Send command to tag TransmitFor14443a(ToSend, ToSendMax, timing); - if(trigger) + if (trigger) LED_A_ON(); // Log reader command in trace buffer @@ -1625,14 +1607,12 @@ void ReaderTransmitBitsPar(uint8_t* frame, uint16_t bits, uint8_t *par, uint32_t } -void ReaderTransmitPar(uint8_t* frame, uint16_t len, uint8_t *par, uint32_t *timing) -{ - ReaderTransmitBitsPar(frame, len*8, par, timing); +void ReaderTransmitPar(uint8_t* frame, uint16_t len, uint8_t *par, uint32_t *timing) { + ReaderTransmitBitsPar(frame, len*8, par, timing); } -static void ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing) -{ +static void ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing) { // Generate parity and redirect uint8_t par[MAX_PARITY_SIZE]; GetParity(frame, len/8, par); @@ -1640,8 +1620,7 @@ static void ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing) } -void ReaderTransmit(uint8_t* frame, uint16_t len, uint32_t *timing) -{ +void ReaderTransmit(uint8_t* frame, uint16_t len, uint32_t *timing) { // Generate parity and redirect uint8_t par[MAX_PARITY_SIZE]; GetParity(frame, len, par); @@ -1649,17 +1628,16 @@ void ReaderTransmit(uint8_t* frame, uint16_t len, uint32_t *timing) } -static int ReaderReceiveOffset(uint8_t* receivedAnswer, uint16_t offset, uint8_t *parity) -{ +static int ReaderReceiveOffset(uint8_t* receivedAnswer, uint16_t offset, uint8_t *parity) { if (!GetIso14443aAnswerFromTag(receivedAnswer, parity, offset)) return false; LogTrace(receivedAnswer, Demod.len, Demod.startTime*16 - DELAY_AIR2ARM_AS_READER, Demod.endTime*16 - DELAY_AIR2ARM_AS_READER, parity, false); return Demod.len; } -int ReaderReceive(uint8_t *receivedAnswer, uint8_t *parity) -{ +int ReaderReceive(uint8_t *receivedAnswer, uint8_t *parity) { if (!GetIso14443aAnswerFromTag(receivedAnswer, parity, 0)) return false; + LogTrace(receivedAnswer, Demod.len, Demod.startTime*16 - DELAY_AIR2ARM_AS_READER, Demod.endTime*16 - DELAY_AIR2ARM_AS_READER, parity, false); return Demod.len; } @@ -1696,7 +1674,7 @@ static void iso14a_set_ATS_times(uint8_t *ats) { static int GetATQA(uint8_t *resp, uint8_t *resp_par) { #define WUPA_RETRY_TIMEOUT 10 // 10ms - uint8_t wupa[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP + uint8_t wupa[] = {ISO14443A_CMD_WUPA}; // 0x26 - REQA 0x52 - WAKE-UP uint32_t save_iso14a_timeout = iso14a_get_timeout(); iso14a_set_timeout(1236/(16*8)+1); // response to WUPA is expected at exactly 1236/fc. No need to wait longer. @@ -1737,7 +1715,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u int len; // init card struct - if(p_hi14a_card) { + if (p_hi14a_card) { p_hi14a_card->uidlen = 0; memset(p_hi14a_card->uid, 0, 10); p_hi14a_card->ats_len = 0; @@ -1747,7 +1725,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u return 0; } - if(p_hi14a_card) { + if (p_hi14a_card) { memcpy(p_hi14a_card->atqa, resp, 2); } @@ -2034,8 +2012,8 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u // Read an ISO 14443a tag. Send out commands and store answers. // //----------------------------------------------------------------------------- -void ReaderIso14443a(UsbCommand *c) -{ +void ReaderIso14443a(UsbCommand *c) { + iso14a_command_t param = c->arg[0]; uint8_t *cmd = c->d.asBytes; size_t len = c->arg[1] & 0xffff; diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index df2dcbea..d2a94a78 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -52,4 +52,5 @@ extern int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void * extern int iso14443a_select_card(uint8_t *uid_ptr, iso14a_card_select_t *resp_data, uint32_t *cuid_ptr, bool anticollision, uint8_t num_cascades, bool no_rats); extern void iso14a_set_trigger(bool enable); extern void iso14a_set_timeout(uint32_t timeout); +extern uint32_t iso14a_get_timeout(void); #endif /* __ISO14443A_H */ diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 89afe06a..b9032c5f 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -87,7 +87,7 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) break; }; - if(mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) { + if(mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Auth error"); break; }; @@ -244,7 +244,7 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) } - if(isOK && mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_FIRST)) { + if(isOK && mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_FIRST, NULL)) { isOK = 0; if (MF_DBGLEVEL >= 1) Dbprintf("Auth error"); } @@ -407,7 +407,7 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) break; }; - if(mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) { + if(mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Auth error"); break; }; @@ -705,7 +705,7 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, } uint32_t nt1; - if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL)) { + if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, NULL, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Auth1 error"); continue; } @@ -760,9 +760,8 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, // MIFARE nested authentication. // //----------------------------------------------------------------------------- -void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *datain) -{ - // params +void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *datain) { + uint8_t blockNo = arg0 & 0xff; uint8_t keyType = (arg0 >> 8) & 0xff; uint8_t targetBlockNo = arg1 & 0xff; @@ -771,7 +770,6 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat ui64Key = bytes_to_num(datain, 6); - // variables uint16_t rtr, i, j, len; uint16_t davg; static uint16_t dmin, dmax; @@ -788,11 +786,10 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat pcs = &mpcs; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; - uint32_t auth1_time, auth2_time; + uint32_t auth1_time, auth2_time, authentication_timeout = 0; static uint16_t delta_time; LED_A_ON(); - LED_C_OFF(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); // free eventually allocated BigBuf memory @@ -816,26 +813,26 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat for (rtr = 0; rtr < 17; rtr++) { // prepare next select. No need to power down the card. - if(mifare_classic_halt(pcs, cuid)) { + if (mifare_classic_halt(pcs, cuid)) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Halt error"); rtr--; continue; } // Test if the action was cancelled - if(BUTTON_PRESS()) { + if (BUTTON_PRESS()) { isOK = -2; break; } - if(!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) { + if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Can't select card"); rtr--; continue; }; auth1_time = 0; - if(mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) { + if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Auth1 error"); rtr--; continue; @@ -846,7 +843,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat } else { auth2_time = 0; } - if(mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, &auth2_time)) { + if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_NESTED, &nt2, &auth2_time, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Auth2 error"); rtr--; continue; @@ -891,10 +888,10 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat LED_C_ON(); // get crypted nonces for target sector - for(i=0; i < 2 && !isOK; i++) { // look for exactly two different nonces + for (i=0; i < 2 && !isOK; i++) { // look for exactly two different nonces target_nt[i] = 0; - while(target_nt[i] == 0 && !isOK) { // continue until we have an unambiguous nonce + while (target_nt[i] == 0 && !isOK) { // continue until we have an unambiguous nonce // prepare next select. No need to power down the card. if(mifare_classic_halt(pcs, cuid)) { @@ -903,19 +900,20 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat } // break out of the loop on button press - if(BUTTON_PRESS()) { + if (BUTTON_PRESS()) { isOK = -2; break; } - if(!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) { + if (!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Can't select card"); continue; } auth1_time = 0; - if(mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) { - if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Auth1 error"); + authentication_timeout = 0; + if (mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time, &authentication_timeout)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Auth1 error"); continue; } @@ -972,12 +970,13 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat // ----------------------------- crypto1 destroy crypto1_destroy(pcs); - byte_t buf[4 + 4 * 4]; + uint8_t buf[4 + 4 * 4 + 4]; memcpy(buf, &cuid, 4); memcpy(buf+4, &target_nt[0], 4); memcpy(buf+8, &target_ks[0], 4); memcpy(buf+12, &target_nt[1], 4); memcpy(buf+16, &target_ks[1], 4); + memcpy(buf+20, &authentication_timeout, 4); LED_B_ON(); cmd_send(CMD_ACK, isOK, 0, targetBlockNo + (targetKeyType * 0x100), buf, sizeof(buf)); @@ -989,49 +988,49 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat LEDsoff(); } + //----------------------------------------------------------------------------- // MIFARE check keys. key count up to 85. // //----------------------------------------------------------------------------- -void MifareChkKeys(uint16_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) -{ +void MifareChkKeys(uint16_t arg0, uint32_t arg1, uint8_t arg2, uint8_t *datain) { + uint8_t blockNo = arg0 & 0xff; - uint8_t keyType = (arg0 >> 8) & 0xff; + uint8_t keyType = arg0 >> 8; bool clearTrace = arg1 & 0x01; bool multisectorCheck = arg1 & 0x02; - uint8_t set14aTimeout = (arg1 >> 8) & 0xff; + bool init = arg1 & 0x04; + bool drop_field = arg1 & 0x08; + uint32_t auth_timeout = arg1 >> 16; uint8_t keyCount = arg2; LED_A_ON(); - // clear debug level - int OLD_MF_DBGLEVEL = MF_DBGLEVEL; - MF_DBGLEVEL = MF_DBG_NONE; - - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - + if (init) { + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + } + if (clearTrace) { clear_trace(); } set_tracing(true); - if (set14aTimeout){ - iso14a_set_timeout(set14aTimeout * 10); // timeout: ms = x/106 35-minimum, 50-OK 106-recommended 500-safe - } + // clear debug level. We are expecting lots of authentication failures... + int OLD_MF_DBGLEVEL = MF_DBGLEVEL; + MF_DBGLEVEL = MF_DBG_NONE; + int res = 0; if (multisectorCheck) { TKeyIndex keyIndex = {{0}}; uint8_t sectorCnt = blockNo; - int res = MifareMultisectorChk(datain, keyCount, sectorCnt, keyType, OLD_MF_DBGLEVEL, &keyIndex); - + res = MifareMultisectorChk(datain, keyCount, sectorCnt, keyType, &auth_timeout, OLD_MF_DBGLEVEL, &keyIndex); if (res >= 0) { cmd_send(CMD_ACK, 1, res, 0, keyIndex, 80); } else { cmd_send(CMD_ACK, 0, res, 0, NULL, 0); } } else { - int res = MifareChkBlockKeys(datain, keyCount, blockNo, keyType, OLD_MF_DBGLEVEL); - + res = MifareChkBlockKeys(datain, keyCount, blockNo, keyType, &auth_timeout, OLD_MF_DBGLEVEL); if (res > 0) { cmd_send(CMD_ACK, 1, res, 0, datain + (res - 1) * 6, 6); } else { @@ -1039,12 +1038,14 @@ void MifareChkKeys(uint16_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) } } - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - LED_D_OFF(); + if (drop_field || res != 0) { + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LED_D_OFF(); + } // restore debug level MF_DBGLEVEL = OLD_MF_DBGLEVEL; - + LED_A_OFF(); } @@ -1074,7 +1075,7 @@ void MifarePersonalizeUID(uint8_t keyType, uint8_t perso_option, uint8_t *data) uint8_t block_number = 0; uint64_t key = bytes_to_num(data, 6); - if (mifare_classic_auth(pcs, cuid, block_number, keyType, key, AUTH_FIRST)) { + if (mifare_classic_auth(pcs, cuid, block_number, keyType, key, AUTH_FIRST, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Auth error"); break; } @@ -1175,13 +1176,13 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai for (uint8_t sectorNo = 0; isOK && sectorNo < numSectors; sectorNo++) { ui64Key = emlGetKey(sectorNo, keyType); if (sectorNo == 0){ - if(isOK && mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_FIRST)) { + if(isOK && mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_FIRST, NULL)) { isOK = false; if (MF_DBGLEVEL >= 1) Dbprintf("Sector[%2d]. Auth error", sectorNo); break; } } else { - if(isOK && mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_NESTED)) { + if(isOK && mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_NESTED, NULL)) { isOK = false; if (MF_DBGLEVEL >= 1) Dbprintf("Sector[%2d]. Auth nested error", sectorNo); break; diff --git a/armsrc/mifarecmd.h b/armsrc/mifarecmd.h index c16c3a3e..40bfb965 100644 --- a/armsrc/mifarecmd.h +++ b/armsrc/mifarecmd.h @@ -25,7 +25,7 @@ extern void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t * extern void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); extern void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); extern void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain); -extern void MifareChkKeys(uint16_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain); +extern void MifareChkKeys(uint16_t arg0, uint32_t arg1, uint8_t arg2, uint8_t *datain); extern void MifareSetDbgLvl(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); extern void MifareEMemClr(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); extern void MifareEMemSet(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index fe5a7485..93df109c 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -113,9 +113,7 @@ int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, ecmd[pos] = crypto1_byte(pcs, 0x00, 0) ^ dcmd[pos]; par[0] |= (((filter(pcs->odd) ^ oddparity8(dcmd[pos])) & 0x01) << (7-pos)); } - ReaderTransmitPar(ecmd, sizeof(ecmd), par, timing); - } else { ReaderTransmit(dcmd, sizeof(dcmd), timing); } @@ -143,18 +141,18 @@ int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, return len; } + // mifare classic commands -int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested) -{ - return mifare_classic_authex(pcs, uid, blockNo, keyType, ui64Key, isNested, NULL, NULL); +int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t *auth_timeout) { + + return mifare_classic_authex(pcs, uid, blockNo, keyType, ui64Key, isNested, NULL, NULL, auth_timeout); } -int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t *ntptr, uint32_t *timing) -{ - // variables + +int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t *ntptr, uint32_t *timing, uint32_t *auth_timeout) { + int len; uint32_t pos; - uint8_t tmp4[4]; uint8_t par[1] = {0x00}; byte_t nr[4]; uint32_t nt, ntpp; // Supplied tag nonce @@ -202,8 +200,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN // Generate (encrypted) nr+parity by loading it into the cipher (Nr) par[0] = 0; - for (pos = 0; pos < 4; pos++) - { + for (pos = 0; pos < 4; pos++) { mf_nr_ar[pos] = crypto1_byte(pcs, nr[pos], 0) ^ nr[pos]; par[0] |= (((filter(pcs->odd) ^ oddparity8(nr[pos])) & 0x01) << (7-pos)); } @@ -212,8 +209,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN nt = prng_successor(nt,32); // ar+parity - for (pos = 4; pos < 8; pos++) - { + for (pos = 4; pos < 8; pos++) { nt = prng_successor(nt,8); mf_nr_ar[pos] = crypto1_byte(pcs,0x00,0) ^ (nt & 0xff); par[0] |= (((filter(pcs->odd) ^ oddparity8(nt)) & 0x01) << (7-pos)); @@ -223,17 +219,24 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL); // Receive 4 byte tag answer + uint32_t save_timeout = iso14a_get_timeout(); // save standard timeout + if (auth_timeout && *auth_timeout) { + iso14a_set_timeout(*auth_timeout); // set timeout for authentication response + } + uint32_t auth_timeout_start = GetCountSspClk(); len = ReaderReceive(receivedAnswer, receivedAnswerPar); - if (!len) - { + iso14a_set_timeout(save_timeout); // restore standard timeout + if (!len) { if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout."); return 2; } + if (auth_timeout && !*auth_timeout) { // measure time for future authentication response timeout + *auth_timeout = (GetCountSspClk() - auth_timeout_start - (len * 9 + 2) * 8) / 8 + 1; + } - memcpy(tmp4, receivedAnswer, 4); - ntpp = prng_successor(nt, 32) ^ crypto1_word(pcs, 0,0); + ntpp = prng_successor(nt, 32) ^ crypto1_word(pcs, 0, 0); - if (ntpp != bytes_to_num(tmp4, 4)) { + if (ntpp != bytes_to_num(receivedAnswer, 4)) { if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Error card response."); return 3; } @@ -241,8 +244,8 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN return 0; } -int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) -{ + +int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) { // variables int len; uint8_t bt[2]; @@ -811,7 +814,7 @@ int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData){ // //----------------------------------------------------------------------------- // one key check -int MifareChkBlockKey(uint8_t *uid, uint32_t *cuid, uint8_t *cascade_levels, uint64_t ui64Key, uint8_t blockNo, uint8_t keyType, uint8_t debugLevel) { +int MifareChkBlockKey(uint8_t *uid, uint32_t *cuid, uint8_t *cascade_levels, uint64_t ui64Key, uint8_t blockNo, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel) { struct Crypto1State mpcs = {0, 0}; struct Crypto1State *pcs; @@ -820,7 +823,7 @@ int MifareChkBlockKey(uint8_t *uid, uint32_t *cuid, uint8_t *cascade_levels, uin // Iceman: use piwi's faster nonce collecting part in hardnested. if (*cascade_levels == 0) { // 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)) { + if (!iso14443a_select_card(uid, &card_info, cuid, true, 0, true)) { if (debugLevel >= 1) Dbprintf("ChkKeys: Can't select card"); return 1; } @@ -831,32 +834,25 @@ int MifareChkBlockKey(uint8_t *uid, uint32_t *cuid, uint8_t *cascade_levels, uin default: break; } } else { // no need for anticollision. We can directly select the card - if(!iso14443a_select_card(uid, NULL, NULL, false, *cascade_levels, true)) { + if (!iso14443a_select_card(uid, NULL, NULL, false, *cascade_levels, true)) { if (debugLevel >= 1) Dbprintf("ChkKeys: Can't select card (UID) lvl=%d", *cascade_levels); return 1; } } - if(mifare_classic_auth(pcs, *cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) { -// SpinDelayUs(AUTHENTICATION_TIMEOUT); // it not needs because mifare_classic_auth have timeout from iso14a_set_timeout() + if (mifare_classic_auth(pcs, *cuid, blockNo, keyType, ui64Key, AUTH_FIRST, auth_timeout)) { // authentication failed return 2; } else { -/* // let it be here. it like halt command, but maybe it will work in some strange cases - uint8_t dummy_answer = 0; - ReaderTransmit(&dummy_answer, 1, NULL); - int timeout = GetCountSspClk() + AUTHENTICATION_TIMEOUT; - // wait for the card to become ready again - while(GetCountSspClk() < timeout) {}; -*/ - // it needs after success authentication mifare_classic_halt(pcs, *cuid); } return 0; } + // multi key check -int MifareChkBlockKeys(uint8_t *keys, uint8_t keyCount, uint8_t blockNo, uint8_t keyType, uint8_t debugLevel) { +int MifareChkBlockKeys(uint8_t *keys, uint8_t keyCount, uint8_t blockNo, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel) { + uint8_t uid[10]; uint32_t cuid = 0; uint8_t cascade_levels = 0; @@ -865,14 +861,8 @@ int MifareChkBlockKeys(uint8_t *keys, uint8_t keyCount, uint8_t blockNo, uint8_t int retryCount = 0; for (uint8_t i = 0; i < keyCount; i++) { - // Allow button press / usb cmd to interrupt device - if (BUTTON_PRESS() && !usb_poll_validate_length()) { - Dbprintf("ChkKeys: Cancel operation. Exit..."); - return -2; - } - ui64Key = bytes_to_num(keys + i * 6, 6); - int res = MifareChkBlockKey(uid, &cuid, &cascade_levels, ui64Key, blockNo, keyType, debugLevel); + int res = MifareChkBlockKey(uid, &cuid, &cascade_levels, ui64Key, blockNo, keyType, auth_timeout, debugLevel); // can't select if (res == 1) { @@ -894,14 +884,20 @@ int MifareChkBlockKeys(uint8_t *keys, uint8_t keyCount, uint8_t blockNo, uint8_t continue; // can't auth. wrong key. } + // successful authentication return i + 1; } + if (BUTTON_PRESS()) { + return -2; + } + return 0; } + // multisector multikey check -int MifareMultisectorChk(uint8_t *keys, uint8_t keyCount, uint8_t SectorCount, uint8_t keyType, uint8_t debugLevel, TKeyIndex *keyIndex) { +int MifareMultisectorChk(uint8_t *keys, uint8_t keyCount, uint8_t SectorCount, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel, TKeyIndex *keyIndex) { int res = 0; // int clk = GetCountSspClk(); @@ -911,11 +907,11 @@ int MifareMultisectorChk(uint8_t *keys, uint8_t keyCount, uint8_t SectorCount, u int keyAB = keyType; do { - res = MifareChkBlockKeys(keys, keyCount, FirstBlockOfSector(sc), keyAB & 0x01, debugLevel); - if (res < 0){ + res = MifareChkBlockKeys(keys, keyCount, FirstBlockOfSector(sc), keyAB & 0x01, auth_timeout, debugLevel); + if (res < 0) { return res; } - if (res > 0){ + if (res > 0) { (*keyIndex)[keyAB & 0x01][sc] = res; } } while(--keyAB > 0); @@ -923,7 +919,7 @@ int MifareMultisectorChk(uint8_t *keys, uint8_t keyCount, uint8_t SectorCount, u // Dbprintf("%d %d", GetCountSspClk() - clk, (GetCountSspClk() - clk)/(SectorCount*keyCount*(keyType==2?2:1))); - return 0; + return 1; } diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h index 856040ca..d8f2602e 100644 --- a/armsrc/mifareutil.h +++ b/armsrc/mifareutil.h @@ -9,8 +9,8 @@ // code for work with mifare cards. //----------------------------------------------------------------------------- -#ifndef __MIFAREUTIL_H -#define __MIFAREUTIL_H +#ifndef MIFAREUTIL_H__ +#define MIFAREUTIL_H__ #include #include @@ -19,11 +19,11 @@ #include "usb_cdc.h" // mifare authentication -#define CRYPT_NONE 0 -#define CRYPT_ALL 1 -#define CRYPT_REQUEST 2 -#define AUTH_FIRST 0 -#define AUTH_NESTED 2 +#define CRYPT_NONE 0 +#define CRYPT_ALL 1 +#define CRYPT_REQUEST 2 +#define AUTH_FIRST 0 +#define AUTH_NESTED 2 // reader voltage field detector #define MF_MINFIELDV 4000 @@ -42,10 +42,10 @@ int mifare_sendcmd(uint8_t cmd, uint8_t *data, uint8_t data_size, uint8_t* answe int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); // mifare classic -int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested); -int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t * ntptr, uint32_t *timing); +int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t *auth_timeout); +int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t * ntptr, uint32_t *timing, uint32_t *auth_timeout); int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); -int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid); +int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid); int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); // Ultralight/NTAG... @@ -87,8 +87,8 @@ int emlCheckValBl(int blockNum); // mifare check keys typedef uint8_t TKeyIndex[2][40]; -int MifareChkBlockKey(uint8_t *uid, uint32_t *cuid, uint8_t *cascade_levels, uint64_t ui64Key, uint8_t blockNo, uint8_t keyType, uint8_t debugLevel); -int MifareChkBlockKeys(uint8_t *keys, uint8_t keyCount, uint8_t blockNo, uint8_t keyType, uint8_t debugLevel); -int MifareMultisectorChk(uint8_t *keys, uint8_t keyCount, uint8_t SectorCount, uint8_t keyType, uint8_t debugLevel, TKeyIndex *keyIndex); +int MifareChkBlockKey(uint8_t *uid, uint32_t *cuid, uint8_t *cascade_levels, uint64_t ui64Key, uint8_t blockNo, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel); +int MifareChkBlockKeys(uint8_t *keys, uint8_t keyCount, uint8_t blockNo, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel); +int MifareMultisectorChk(uint8_t *keys, uint8_t keyCount, uint8_t SectorCount, uint8_t keyType, uint32_t *auth_timeout, uint8_t debugLevel, TKeyIndex *keyIndex); #endif diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index 22e6efac..93c3ea65 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -570,7 +570,7 @@ int CmdHF14AMfRestore(const char *Cmd) // Nested //---------------------------------------------- -static void parseParamTDS(const char *Cmd, const uint8_t indx, bool *paramT, bool *paramD, uint8_t *timeout) { +static void parseParamTDS(const char *Cmd, const uint8_t indx, bool *paramT, bool *paramD, uint16_t *timeout) { char ctmp3[4] = {0}; int len = param_getlength(Cmd, indx); if (len > 0 && len < 4){ @@ -582,20 +582,19 @@ static void parseParamTDS(const char *Cmd, const uint8_t indx, bool *paramT, boo // slow and very slow if (ctmp3[0] == 's' || ctmp3[0] == 'S' || ctmp3[1] == 's' || ctmp3[1] == 'S') { - *timeout = 11; // slow + *timeout = MF_CHKKEYS_SLOWTIMEOUT; // slow if (!paramS1 && (ctmp3[1] == 's' || ctmp3[1] == 'S')) { - *timeout = 53; // very slow + *timeout = MF_CHKKEYS_VERYSLOWTIMEOUT; // very slow } if (paramS1 && (ctmp3[2] == 's' || ctmp3[2] == 'S')) { - *timeout = 53; // very slow + *timeout = MF_CHKKEYS_VERYSLOWTIMEOUT; // very slow } } } } -int CmdHF14AMfNested(const char *Cmd) -{ +int CmdHF14AMfNested(const char *Cmd) { int i, j, res, iterations; sector_t *e_sector = NULL; uint8_t blockNo = 0; @@ -606,8 +605,8 @@ int CmdHF14AMfNested(const char *Cmd) uint8_t key[6] = {0, 0, 0, 0, 0, 0}; uint8_t keyBlock[MifareDefaultKeysSize * 6]; uint64_t key64 = 0; - // timeout in units. (ms * 106)/10 or us*0.0106 - uint8_t btimeout14a = MF_CHKKEYS_DEFTIMEOUT; // fast by default + // timeout in units. (ms * 106) or us*0.106 + uint16_t timeout14a = MF_CHKKEYS_DEFTIMEOUT; // fast by default bool autosearchKey = false; @@ -654,10 +653,10 @@ int CmdHF14AMfNested(const char *Cmd) if (param_getchar(Cmd, 1) == '*') { autosearchKey = true; - parseParamTDS(Cmd, 2, &transferToEml, &createDumpFile, &btimeout14a); + parseParamTDS(Cmd, 2, &transferToEml, &createDumpFile, &timeout14a); PrintAndLog("--nested. sectors:%2d, block no:*, eml:%c, dmp=%c checktimeout=%d us", - SectorsCnt, transferToEml?'y':'n', createDumpFile?'y':'n', ((int)btimeout14a * 10000) / 106); + SectorsCnt, transferToEml?'y':'n', createDumpFile?'y':'n', ((uint32_t)timeout14a * 1000) / 106); } else { blockNo = param_get8(Cmd, 1); @@ -676,7 +675,7 @@ int CmdHF14AMfNested(const char *Cmd) } // check if we can authenticate to sector - res = mfCheckKeys(blockNo, keyType, true, 1, key, &key64); + res = mfCheckKeys(blockNo, keyType, timeout14a, true, 1, key, &key64); if (res) { PrintAndLog("Can't authenticate to block:%3d key type:%c key:%s", blockNo, keyType?'B':'A', sprint_hex(key, 6)); return 3; @@ -694,19 +693,19 @@ int CmdHF14AMfNested(const char *Cmd) if (ctmp != 'A' && ctmp != 'a') trgKeyType = 1; - parseParamTDS(Cmd, 6, &transferToEml, &createDumpFile, &btimeout14a); + parseParamTDS(Cmd, 6, &transferToEml, &createDumpFile, &timeout14a); } else { - parseParamTDS(Cmd, 4, &transferToEml, &createDumpFile, &btimeout14a); + parseParamTDS(Cmd, 4, &transferToEml, &createDumpFile, &timeout14a); } PrintAndLog("--nested. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us", - SectorsCnt, blockNo, keyType?'B':'A', transferToEml?'y':'n', createDumpFile?'y':'n', ((int)btimeout14a * 10000) / 106); + SectorsCnt, blockNo, keyType?'B':'A', transferToEml?'y':'n', createDumpFile?'y':'n', ((uint32_t)timeout14a * 1000) / 106); } // one-sector nested if (cmdp == 'o') { // ------------------------------------ one sector working PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo, trgKeyType?'B':'A'); - int16_t isOK = mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true); + int16_t isOK = mfnested(blockNo, keyType, timeout14a, key, trgBlockNo, trgKeyType, keyBlock, true); if (isOK < 0) { switch (isOK) { case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; @@ -754,7 +753,7 @@ int CmdHF14AMfNested(const char *Cmd) } PrintAndLog("Testing known keys. Sector count=%d", SectorsCnt); - mfCheckKeysSec(SectorsCnt, 2, btimeout14a, true, MifareDefaultKeysSize, keyBlock, e_sector); + mfCheckKeysSec(SectorsCnt, 2, timeout14a, true, true, true, MifareDefaultKeysSize, keyBlock, e_sector); // get known key from array bool keyFound = false; @@ -791,7 +790,7 @@ int CmdHF14AMfNested(const char *Cmd) for (trgKeyType = 0; trgKeyType < 2; trgKeyType++) { if (e_sector[sectorNo].foundKey[trgKeyType]) continue; PrintAndLog("-----------------------------------------------"); - int16_t isOK = mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate); + int16_t isOK = mfnested(blockNo, keyType, timeout14a, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate); if(isOK < 0) { switch (isOK) { case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; @@ -814,7 +813,7 @@ int CmdHF14AMfNested(const char *Cmd) e_sector[sectorNo].Key[trgKeyType] = key64; // try to check this key as a key to the other sectors - mfCheckKeysSec(SectorsCnt, 2, btimeout14a, true, 1, keyBlock, e_sector); + mfCheckKeysSec(SectorsCnt, 2, timeout14a, true, true, true, 1, keyBlock, e_sector); } } } @@ -1049,8 +1048,8 @@ int CmdHF14AMfNestedHard(const char *Cmd) } -int CmdHF14AMfChk(const char *Cmd) -{ +int CmdHF14AMfChk(const char *Cmd) { + if (strlen(Cmd)<3) { PrintAndLog("Usage: hf mf chk |<*card memory> [t|d|s|ss] [] []"); PrintAndLog(" * - all sectors"); @@ -1081,7 +1080,7 @@ int CmdHF14AMfChk(const char *Cmd) uint8_t keyType = 0; uint64_t key64 = 0; // timeout in units. (ms * 106)/10 or us*0.0106 - uint8_t btimeout14a = MF_CHKKEYS_DEFTIMEOUT; // fast by default + uint16_t timeout14a = MF_CHKKEYS_DEFTIMEOUT; // fast by default bool param3InUse = false; bool transferToEml = 0; bool createDumpFile = 0; @@ -1134,7 +1133,7 @@ int CmdHF14AMfChk(const char *Cmd) }; } - parseParamTDS(Cmd, 2, &transferToEml, &createDumpFile, &btimeout14a); + parseParamTDS(Cmd, 2, &transferToEml, &createDumpFile, &timeout14a); if (singleBlock & createDumpFile) { PrintAndLog (" block key check () and write to dump file (d) combination is not supported "); @@ -1142,10 +1141,10 @@ int CmdHF14AMfChk(const char *Cmd) return 1; } - param3InUse = transferToEml | createDumpFile | (btimeout14a != MF_CHKKEYS_DEFTIMEOUT); + param3InUse = transferToEml | createDumpFile | (timeout14a != MF_CHKKEYS_DEFTIMEOUT); PrintAndLog("--chk keys. sectors:%2d, block no:%3d, key type:%c, eml:%c, dmp=%c checktimeout=%d us", - SectorsCnt, blockNo, keyType==0?'A':keyType==1?'B':'?', transferToEml?'y':'n', createDumpFile?'y':'n', ((int)btimeout14a * 10000) / 106); + SectorsCnt, blockNo, keyType==0?'A':keyType==1?'B':'?', transferToEml?'y':'n', createDumpFile?'y':'n', ((uint32_t)timeout14a * 1000) / 106); for (i = param3InUse; param_getchar(Cmd, 2 + i); i++) { if (!param_gethex(Cmd, 2 + i, keyBlock + 6 * keycnt, 12)) { @@ -1251,7 +1250,9 @@ int CmdHF14AMfChk(const char *Cmd) for (uint32_t c = 0; c < keycnt; c += max_keys) { uint32_t size = keycnt-c > max_keys ? max_keys : keycnt-c; - res = mfCheckKeysSec(SectorsCnt, keyType, btimeout14a, clearTraceLog, size, &keyBlock[6 * c], e_sector); // timeout is (ms * 106)/10 or us*0.0106 + bool init = (c == 0); + bool drop_field = (c + size == keycnt); + res = mfCheckKeysSec(SectorsCnt, keyType, timeout14a, clearTraceLog, init, drop_field, size, &keyBlock[6 * c], e_sector); // timeout is (ms * 106)/10 or us*0.0106 clearTraceLog = false; if (res != 1) { @@ -1269,27 +1270,23 @@ int CmdHF14AMfChk(const char *Cmd) } else { int keyAB = keyType; do { - for (uint32_t c = 0; c < keycnt; c += max_keys) { - - uint32_t size = keycnt-c > max_keys ? max_keys : keycnt-c; - res = mfCheckKeys(blockNo, keyAB & 0x01, true, size, &keyBlock[6 * c], &key64); - clearTraceLog = false; + res = mfCheckKeys(blockNo, keyAB & 0x01, timeout14a, true, keycnt, keyBlock, &key64); + clearTraceLog = false; - if (res != 1) { - if (!res) { - // Use the common format below - // PrintAndLog("Found valid key:[%d:%c]%012" PRIx64, blockNo, (keyAB & 0x01)?'B':'A', key64); - foundAKey = true; + if (res != 1) { + if (!res) { + // Use the common format below + // PrintAndLog("Found valid key:[%d:%c]%012" PRIx64, blockNo, (keyAB & 0x01)?'B':'A', key64); + foundAKey = true; - // Store the Single Key for display list - // For a single block check, SectorsCnt = Sector that contains the block - e_sector[SectorsCnt-1].foundKey[(keyAB & 0x01)] = true; // flag key found - e_sector[SectorsCnt-1].Key[(keyAB & 0x01)] = key64; // Save key data + // Store the Single Key for display list + // For a single block check, SectorsCnt = Sector that contains the block + e_sector[SectorsCnt-1].foundKey[(keyAB & 0x01)] = true; // flag key found + e_sector[SectorsCnt-1].Key[(keyAB & 0x01)] = key64; // Save key data - } - } else { - PrintAndLog("Command execute timeout"); } + } else { + PrintAndLog("Command execute timeout"); } } while(--keyAB > 0); } diff --git a/client/mifare/mifarehost.c b/client/mifare/mifarehost.c index 3a961ef7..7b710710 100644 --- a/client/mifare/mifarehost.c +++ b/client/mifare/mifarehost.c @@ -10,6 +10,7 @@ #include "mifarehost.h" +#include #include #include #include @@ -115,8 +116,7 @@ static uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint32_t ar, u } -int mfDarkside(uint64_t *key) -{ +int mfDarkside(uint64_t *key) { uint32_t uid = 0; uint32_t nt = 0, nr = 0, ar = 0; uint64_t par_list = 0, ks_list = 0; @@ -196,22 +196,15 @@ int mfDarkside(uint64_t *key) PrintAndLog("Found a possible key. Trying to authenticate...\n"); } - *key = -1; - uint8_t keyBlock[USB_CMD_DATA_SIZE]; - int max_keys = USB_CMD_DATA_SIZE/6; - for (int i = 0; i < keycount; i += max_keys) { - int size = keycount - i > max_keys ? max_keys : keycount - i; - for (int j = 0; j < size; j++) { - if (par_list == 0) { - num_to_bytes(last_keylist[i*max_keys + j], 6, keyBlock+(j*6)); - } else { - num_to_bytes(keylist[i*max_keys + j], 6, keyBlock+(j*6)); - } - } - if (!mfCheckKeys(0, 0, false, size, keyBlock, key)) { - break; - } + uint8_t *keys_to_chk = malloc(keycount * 6); + for (int i = 0; i < keycount; i++) { + num_to_bytes(keylist[i], 6, keys_to_chk+i); } + + *key = -1; + mfCheckKeys(0, 0, 0, false, keycount, keys_to_chk, key); + + free(keys_to_chk); if (*key != -1) { free(last_keylist); @@ -228,37 +221,73 @@ int mfDarkside(uint64_t *key) } -int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){ +int mfCheckKeys(uint8_t blockNo, uint8_t keyType, uint16_t timeout14a, bool clear_trace, uint32_t keycnt, uint8_t *keys, uint64_t *found_key) { - *key = -1; + bool display_progress = false; + uint64_t start_time = msclock(); + uint64_t next_print_time = start_time + 5 * 1000; - UsbCommand c = {CMD_MIFARE_CHKKEYS, {((blockNo & 0xff) | ((keyType & 0xff) << 8)), clear_trace, keycnt}}; - memcpy(c.d.asBytes, keyBlock, 6 * keycnt); - SendCommand(&c); + if (keycnt > 1000) { + PrintAndLog("We have %d keys to check. This will take some time!", keycnt); + PrintAndLog("Press button to abort."); + display_progress = true; + } - UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) - return 1; + uint32_t max_keys = (keycnt > (USB_CMD_DATA_SIZE / 6)) ? (USB_CMD_DATA_SIZE / 6) : keycnt; + *found_key = -1; + bool multisectorCheck = false; + + for (int i = 0, ii = 0; i < keycnt; i += max_keys) { + + if ((i + max_keys) >= keycnt) { + max_keys = keycnt - i; + } - if ((resp.arg[0] & 0xff) != 0x01) { - if (((int)resp.arg[1]) < 0) - return (int)resp.arg[1]; + bool init = (i == 0); + bool drop_field = (max_keys == keycnt); + uint8_t flags = clear_trace | multisectorCheck << 1 | init << 2 | drop_field << 3; - return 2; + UsbCommand c = {CMD_MIFARE_CHKKEYS, {((blockNo & 0xff) | ((keyType & 0xff) << 8)), flags | timeout14a << 16, max_keys}}; + memcpy(c.d.asBytes, keys + i * 6, max_keys * 6); + SendCommand(&c); + + UsbCommand resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) + return 1; + + if ((resp.arg[0] & 0xff) != 0x01) { + if (((int)resp.arg[1]) < 0) { // error + return (int)resp.arg[1]; + } else { // nothing found yet + if (display_progress && msclock() >= next_print_time) { + float brute_force_per_second = (float)(i - ii) / (float)(msclock() - start_time) * 1000.0; + ii = i; + start_time = msclock(); + next_print_time = start_time + 10 * 1000; + PrintAndLog(" %8d keys left | %5.1f keys/sec | worst case %6.1f seconds remaining", keycnt - i, brute_force_per_second, (keycnt-i)/brute_force_per_second); + } + } + } else { // success + *found_key = bytes_to_num(resp.d.asBytes, 6); + return 0; + } } - *key = bytes_to_num(resp.d.asBytes, 6); - return 0; + return 2; // nothing found } -int mfCheckKeysSec(uint8_t sectorCnt, uint8_t keyType, uint8_t timeout14a, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, sector_t * e_sector){ + +int mfCheckKeysSec(uint8_t sectorCnt, uint8_t keyType, uint16_t timeout14a, bool clear_trace, bool init, bool drop_field, uint8_t keycnt, uint8_t * keyBlock, sector_t * e_sector) { uint8_t keyPtr = 0; if (e_sector == NULL) return -1; - UsbCommand c = {CMD_MIFARE_CHKKEYS, {((sectorCnt & 0xff) | ((keyType & 0xff) << 8)), (clear_trace | 0x02)|((timeout14a & 0xff) << 8), keycnt}}; + bool multisectorCheck = true; + uint8_t flags = clear_trace | multisectorCheck << 1 | init << 2 | drop_field << 3; + + UsbCommand c = {CMD_MIFARE_CHKKEYS, {((sectorCnt & 0xff) | ((keyType & 0xff) << 8)), flags | timeout14a << 16, keycnt}}; memcpy(c.d.asBytes, keyBlock, 6 * keycnt); SendCommand(&c); @@ -301,7 +330,7 @@ typedef uint32_t uid; uint32_t blockNo; uint32_t keyType; - uint32_t nt; + uint32_t nt_enc; uint32_t ks1; } StateList_t; @@ -313,12 +342,11 @@ void __attribute__((force_align_arg_pointer)) #endif #endif -*nested_worker_thread(void *arg) -{ +*nested_worker_thread(void *arg) { struct Crypto1State *p1; StateList_t *statelist = arg; - statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid); + statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt_enc ^ statelist->uid); for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; p1++); statelist->len = p1 - statelist->head.slhead; statelist->tail.sltail = --p1; @@ -328,9 +356,8 @@ __attribute__((force_align_arg_pointer)) } -int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate) -{ - uint32_t i, j; +int mfnested(uint8_t blockNo, uint8_t keyType, uint16_t timeout14a, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *resultKey, bool calibrate) { + uint32_t i; uint32_t uid; UsbCommand resp; @@ -344,11 +371,6 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, int isOK = 1; - uint64_t next_print_time = 0; - uint64_t start_time; - float brute_force_time; - float brute_force_per_second; - // flush queue (void)WaitForResponseTimeout(CMD_ACK,NULL,100); @@ -375,11 +397,15 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, statelists[i].blockNo = resp.arg[2] & 0xff; statelists[i].keyType = (resp.arg[2] >> 8) & 0xff; statelists[i].uid = uid; - memcpy(&statelists[i].nt, (void *)(resp.d.asBytes + 4 + i * 8 + 0), 4); + memcpy(&statelists[i].nt_enc, (void *)(resp.d.asBytes + 4 + i * 8 + 0), 4); memcpy(&statelists[i].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4); } - if (statelists[0].nt == statelists[1].nt && statelists[0].ks1 == statelists[1].ks1) + uint32_t authentication_timeout; + memcpy(&authentication_timeout, resp.d.asBytes + 20, 4); + PrintAndLog("Setting authentication timeout to %" PRIu32 "us", authentication_timeout * 1000 / 106); + + if (statelists[0].nt_enc == statelists[1].nt_enc && statelists[0].ks1 == statelists[1].ks1) num_unique_nonces = 1; else num_unique_nonces = 2; @@ -410,14 +436,14 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, savestate = *p1; while(Compare16Bits(p1, savep) == 0 && p1 <= statelists[0].tail.sltail) { *p3 = *p1; - lfsr_rollback_word(p3, statelists[0].nt ^ statelists[0].uid, 0); + lfsr_rollback_word(p3, statelists[0].nt_enc ^ statelists[0].uid, 0); p3++; p1++; } savestate = *p2; while(Compare16Bits(p2, savep) == 0 && p2 <= statelists[1].tail.sltail) { *p4 = *p2; - lfsr_rollback_word(p4, statelists[1].nt ^ statelists[1].uid, 0); + lfsr_rollback_word(p4, statelists[1].nt_enc ^ statelists[1].uid, 0); p4++; p2++; } @@ -435,7 +461,7 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, statelists[1].tail.sltail=--p4; for (i = 0; i < 2; i++) { - PrintAndLog("statelist %d: length:%d block:%02d keytype:%d nt:%08X ks1:%08X", i, statelists[i].len, statelists[i].blockNo, statelists[i].keyType, statelists[i].nt, statelists[i].ks1); + PrintAndLog("statelist %d: length:%d block:%02d keytype:%d nt_enc:%08X ks1:%08X", i, statelists[i].len, statelists[i].blockNo, statelists[i].keyType, statelists[i].nt_enc, statelists[i].ks1); } // the statelists now contain possible keys. The key we are searching for must be in the @@ -450,64 +476,29 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, PrintAndLog("Nonce 1 and 2 are the same!"); } - if (statelists[0].len > 100) { - PrintAndLog("We have %d keys to check. This will take a very long time!", statelists[0].len); - PrintAndLog("Press button to abort."); - } - else if (statelists[0].len < 1) { - PrintAndLog("No candidate keys to check!"); - } - else { - PrintAndLog("We have %d key(s) to check.", statelists[0].len); - } - - uint32_t max_keys = (statelists[0].len > (USB_CMD_DATA_SIZE / 6)) ? (USB_CMD_DATA_SIZE / 6) : statelists[0].len; - keyBlock = calloc(max_keys, 6); - + uint32_t num_keys = statelists[0].len; + keyBlock = calloc(num_keys, 6); if (keyBlock == NULL) { free(statelists[0].head.slhead); free(statelists[1].head.slhead); return -4; } - memset(resultKey, 0, 6); - start_time = msclock(); - next_print_time = start_time + 1 * 1000; - // The list may still contain several key candidates. Test each of them with mfCheckKeys - for (i = 0; i < statelists[0].len; i+=max_keys) { - if (next_print_time <= msclock()) { - brute_force_per_second = ((float)i) / (((float)(msclock() - start_time)) / 1000.0); - brute_force_time = ((float)(statelists[0].len - i)) / brute_force_per_second; - next_print_time = msclock() + 10 * 1000; - PrintAndLog(" %8d keys left | %5.1f keys/sec | worst case %6.1f seconds remaining", statelists[0].len - i, brute_force_per_second, brute_force_time); - } - - if ((i+max_keys) >= statelists[0].len) - max_keys = statelists[0].len - i; - - for (j = 0; j < max_keys; j++) { - crypto1_get_lfsr(statelists[0].head.slhead + i + j, &key64); - num_to_bytes(key64, 6, keyBlock+(j*6)); - } + for (i = 0; i < num_keys; i++) { + crypto1_get_lfsr(statelists[0].head.slhead + i, &key64); + num_to_bytes(key64, 6, keyBlock + i*6); + } - key64 = 0; - isOK = mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, true, max_keys, keyBlock, &key64); + // The list may still contain several key candidates. Test each of them with mfCheckKeys + isOK = mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, authentication_timeout, true, num_keys, keyBlock, &key64); - if (isOK == 1) { // timeout - isOK = -1; - break; - } - else if (isOK < 0) { // -2 is button pressed - break; - } - else if (!isOK) { - num_to_bytes(key64, 6, resultKey); - break; - } + if (isOK == 0) { // success, key found + num_to_bytes(key64, 6, resultKey); } - if (isOK == 0 && statelists[0].len != 1) - PrintAndLog("Key found in %0.2f seconds after checking %d keys\n", ((float)(msclock() - start_time)) / 1000.0, i+max_keys); + if (isOK == 1) { // timeout + isOK = -1; + } free(statelists[0].head.slhead); free(statelists[1].head.slhead); diff --git a/client/mifare/mifarehost.h b/client/mifare/mifarehost.h index 18a8a5e1..82fe7ad8 100644 --- a/client/mifare/mifarehost.h +++ b/client/mifare/mifarehost.h @@ -8,8 +8,8 @@ // High frequency ISO14443A commands //----------------------------------------------------------------------------- -#ifndef MIFAREHOST_H -#define MIFAREHOST_H +#ifndef MIFAREHOST_H__ +#define MIFAREHOST_H__ #include #include @@ -17,18 +17,19 @@ #include "util.h" // defaults -// timeout in units. (ms * 106)/10 or us*0.0106 -// 5 == 500us -#define MF_CHKKEYS_DEFTIMEOUT 5 +// timeout in units. ms * 106 or us * 0.106 +#define MF_CHKKEYS_DEFTIMEOUT 50 // 0.47ms +#define MF_CHKKEYS_SLOWTIMEOUT 106 // 1ms +#define MF_CHKKEYS_VERYSLOWTIMEOUT 530 // 5ms // mfCSetBlock work flags -#define CSETBLOCK_UID 0x01 -#define CSETBLOCK_WUPC 0x02 -#define CSETBLOCK_HALT 0x04 -#define CSETBLOCK_INIT_FIELD 0x08 -#define CSETBLOCK_RESET_FIELD 0x10 -#define CSETBLOCK_SINGLE_OPER 0x1F -#define CSETBLOCK_MAGIC_1B 0x40 +#define CSETBLOCK_UID 0x01 +#define CSETBLOCK_WUPC 0x02 +#define CSETBLOCK_HALT 0x04 +#define CSETBLOCK_INIT_FIELD 0x08 +#define CSETBLOCK_RESET_FIELD 0x10 +#define CSETBLOCK_SINGLE_OPER 0x1F +#define CSETBLOCK_MAGIC_1B 0x40 typedef struct { uint64_t Key[2]; @@ -38,9 +39,9 @@ typedef struct { extern char logHexFileName[FILE_PATH_SIZE]; extern int mfDarkside(uint64_t *key); -extern int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *ResultKeys, bool calibrate); -extern int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t *keyBlock, uint64_t *key); -extern int mfCheckKeysSec(uint8_t sectorCnt, uint8_t keyType, uint8_t timeout14a, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, sector_t * e_sector); +extern int mfnested(uint8_t blockNo, uint8_t keyType, uint16_t timeout14a, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *ResultKeys, bool calibrate); +extern int mfCheckKeys(uint8_t blockNo, uint8_t keyType, uint16_t timeout14a, bool clear_trace, uint32_t keycnt, uint8_t *keyBlock, uint64_t *key); +extern int mfCheckKeysSec(uint8_t sectorCnt, uint8_t keyType, uint16_t timeout14a, bool clear_trace, bool init, bool drop_field, uint8_t keycnt, uint8_t * keyBlock, sector_t * e_sector); extern int mfReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data);