From: iceman1001 Date: Tue, 24 Mar 2015 10:45:31 +0000 (+0100) Subject: Merge branch 'master' of https://github.com/Proxmark/proxmark3 X-Git-Url: http://cvs.zerfleddert.de/cgi-bin/gitweb.cgi/proxmark3-svn/commitdiff_plain/0ec548dc2122f9bc0f0b536db5fa1a12f1f5c16a?ds=inline Merge branch 'master' of https://github.com/Proxmark/proxmark3 Conflicts: armsrc/lfops.c client/cmddata.c client/cmdlf.c client/cmdlft55xx.c client/cmdlft55xx.h client/scripts/test_t55x7_bi.lua --- 0ec548dc2122f9bc0f0b536db5fa1a12f1f5c16a diff --cc armsrc/BigBuf.c index 703ade65,703ade65..2fb50a47 --- a/armsrc/BigBuf.c +++ b/armsrc/BigBuf.c @@@ -171,18 -171,18 +171,19 @@@ bool RAMFUNC LogTrace(const uint8_t *bt traceLen += iLen; // parity bytes -- if (parity != NULL && iLen != 0) { ++ if (iLen != 0) { ++ if (parity != NULL) { memcpy(trace + traceLen, parity, num_paritybytes); ++ } else { ++ memset(trace + traceLen, 0x00, num_paritybytes); ++ } } traceLen += num_paritybytes; -- if(traceLen +4 < max_traceLen) -- { //If it hadn't been cleared, for whatever reason.. -- memset(trace+traceLen,0x44, 4); -- } -- return TRUE; } ++ ++ int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwParity, int readerToTag) { /** @@@ -224,6 -224,6 +225,8 @@@ return TRUE; } ++ ++ // Emulator memory uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length){ uint8_t* mem = BigBuf_get_EM_addr(); diff --cc armsrc/Makefile index 14ddbc05,75ccdece..1c03e5a3 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@@ -18,7 -18,7 +18,7 @@@ SRC_LF = lfops.c hitag2.c lfsampling. SRC_ISO15693 = iso15693.c iso15693tools.c SRC_ISO14443a = epa.c iso14443a.c mifareutil.c mifarecmd.c mifaresniff.c SRC_ISO14443b = iso14443.c --SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c ++SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c desfire_key.c desfire_crypto.c mifaredesfire.c SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c THUMBSRC = start.c \ diff --cc armsrc/apps.h index 3fe8acae,928a3075..ea298acb --- a/armsrc/apps.h +++ b/armsrc/apps.h @@@ -14,13 -14,11 +14,20 @@@ #include #include -#include "common.h" -#include "hitag2.h" -#include "mifare.h" +#include +#include +#include +#include #include "../common/crc32.h" #include "BigBuf.h" +#include "../include/hitag2.h" ++#include "../include/mifare.h" ++//#include ++//#include ++//#include "des.h" ++//#include "aes.h" ++#include "desfire.h" ++ extern const uint8_t OddByteParity[256]; extern int rsamples; // = 0; @@@ -170,7 -165,7 +177,7 @@@ void EPA_PACE_Collect_Nonce(UsbCommand void ReaderMifare(bool first_try); int32_t dist_nt(uint32_t nt1, uint32_t nt2); void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *data); --void MifareUReadBlock(uint8_t arg0,uint8_t *datain); ++void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareUC_Auth1(uint8_t arg0, uint8_t *datain); void MifareUC_Auth2(uint32_t arg0, uint8_t *datain); void MifareUReadCard(uint8_t arg0, int Pages, uint8_t *datain); @@@ -207,6 -202,6 +214,17 @@@ void OnError(uint8_t reason) ++// desfire_crypto.h ++void *mifare_cryto_preprocess_data (desfiretag_t tag, void *data, size_t *nbytes, off_t offset, int communication_settings); ++void *mifare_cryto_postprocess_data (desfiretag_t tag, void *data, ssize_t *nbytes, int communication_settings); ++void mifare_cypher_single_block (desfirekey_t key, uint8_t *data, uint8_t *ivect, MifareCryptoDirection direction, MifareCryptoOperation operation, size_t block_size); ++void mifare_cypher_blocks_chained (desfiretag_t tag, desfirekey_t key, uint8_t *ivect, uint8_t *data, size_t data_size, MifareCryptoDirection direction, MifareCryptoOperation operation); ++size_t key_block_size (const desfirekey_t key); ++size_t padded_data_length (const size_t nbytes, const size_t block_size); ++size_t maced_data_length (const desfirekey_t key, const size_t nbytes); ++size_t enciphered_data_length (const desfiretag_t tag, const size_t nbytes, int communication_settings); ++void cmac_generate_subkeys (desfirekey_t key); ++void cmac (const desfirekey_t key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac); /// iso15693.h diff --cc armsrc/iso14443a.c index e7477789,ac839cfd..9cd0cfdc --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@@ -213,6 -213,6 +213,12 @@@ void AppendCrc14443a(uint8_t* data, in ComputeCrc14443(CRC_14443_A,data,len,data+len,data+len+1); } ++void AppendCrc14443b(uint8_t* data, int len) ++{ ++ ComputeCrc14443(CRC_14443_B,data,len,data+len,data+len+1); ++} ++ ++ //============================================================================= // ISO 14443 Type A - Miller decoder //============================================================================= @@@ -232,13 -232,13 +238,17 @@@ static tUart Uart; // Lookup-Table to decide if 4 raw bits are a modulation. --// We accept two or three consecutive "0" in any position with the rest "1" ++// We accept the following: ++// 0001 - a 3 tick wide pause ++// 0011 - a 2 tick wide pause, or a three tick wide pause shifted left ++// 0111 - a 2 tick wide pause shifted left ++// 1001 - a 2 tick wide pause shifted right const bool Mod_Miller_LUT[] = { -- TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, -- TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE ++ FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, ++ FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE }; --#define IsMillerModulationNibble1(b) (Mod_Miller_LUT[(b & 0x00F0) >> 4]) --#define IsMillerModulationNibble2(b) (Mod_Miller_LUT[(b & 0x000F)]) ++#define IsMillerModulationNibble1(b) (Mod_Miller_LUT[(b & 0x000000F0) >> 4]) ++#define IsMillerModulationNibble2(b) (Mod_Miller_LUT[(b & 0x0000000F)]) void UartReset() { @@@ -248,8 -248,8 +258,6 @@@ Uart.parityLen = 0; // number of decoded parity bytes Uart.shiftReg = 0; // shiftreg to hold decoded data bits Uart.parityBits = 0; // holds 8 parity bits -- Uart.twoBits = 0x0000; // buffer for 2 Bits -- Uart.highCnt = 0; Uart.startTime = 0; Uart.endTime = 0; } @@@ -258,6 -258,6 +266,7 @@@ void UartInit(uint8_t *data, uint8_t *p { Uart.output = data; Uart.parity = parity; ++ Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits UartReset(); } @@@ -265,40 -265,40 +274,37 @@@ static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) { -- Uart.twoBits = (Uart.twoBits << 8) | bit; ++ Uart.fourBits = (Uart.fourBits << 8) | bit; if (Uart.state == STATE_UNSYNCD) { // not yet synced -- if (Uart.highCnt < 2) { // wait for a stable unmodulated signal -- if (Uart.twoBits == 0xffff) { -- Uart.highCnt++; -- } else { -- Uart.highCnt = 0; -- } -- } else { -- Uart.syncBit = 0xFFFF; // not set -- // we look for a ...1111111100x11111xxxxxx pattern (the start bit) -- if ((Uart.twoBits & 0xDF00) == 0x1F00) Uart.syncBit = 8; // mask is 11x11111 xxxxxxxx, -- // check for 00x11111 xxxxxxxx -- else if ((Uart.twoBits & 0xEF80) == 0x8F80) Uart.syncBit = 7; // both masks shifted right one bit, left padded with '1' -- else if ((Uart.twoBits & 0xF7C0) == 0xC7C0) Uart.syncBit = 6; // ... -- else if ((Uart.twoBits & 0xFBE0) == 0xE3E0) Uart.syncBit = 5; -- else if ((Uart.twoBits & 0xFDF0) == 0xF1F0) Uart.syncBit = 4; -- else if ((Uart.twoBits & 0xFEF8) == 0xF8F8) Uart.syncBit = 3; -- else if ((Uart.twoBits & 0xFF7C) == 0xFC7C) Uart.syncBit = 2; -- else if ((Uart.twoBits & 0xFFBE) == 0xFE3E) Uart.syncBit = 1; -- if (Uart.syncBit != 0xFFFF) { // found a sync bit ++ Uart.syncBit = 9999; // not set ++ // The start bit is one ore more Sequence Y followed by a Sequence Z (... 11111111 00x11111). We need to distinguish from ++ // Sequence X followed by Sequence Y followed by Sequence Z (111100x1 11111111 00x11111) ++ // we therefore look for a ...xx11111111111100x11111xxxxxx... pattern ++ // (12 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's) ++#define ISO14443A_STARTBIT_MASK 0x07FFEF80 // mask is 00000111 11111111 11101111 10000000 ++#define ISO14443A_STARTBIT_PATTERN 0x07FF8F80 // pattern is 00000111 11111111 10001111 10000000 ++ if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 0)) == ISO14443A_STARTBIT_PATTERN >> 0) Uart.syncBit = 7; ++ else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 1)) == ISO14443A_STARTBIT_PATTERN >> 1) Uart.syncBit = 6; ++ else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 2)) == ISO14443A_STARTBIT_PATTERN >> 2) Uart.syncBit = 5; ++ else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 3)) == ISO14443A_STARTBIT_PATTERN >> 3) Uart.syncBit = 4; ++ else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 4)) == ISO14443A_STARTBIT_PATTERN >> 4) Uart.syncBit = 3; ++ else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 5)) == ISO14443A_STARTBIT_PATTERN >> 5) Uart.syncBit = 2; ++ else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 6)) == ISO14443A_STARTBIT_PATTERN >> 6) Uart.syncBit = 1; ++ else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 7)) == ISO14443A_STARTBIT_PATTERN >> 7) Uart.syncBit = 0; ++ ++ if (Uart.syncBit != 9999) { // found a sync bit Uart.startTime = non_real_time?non_real_time:(GetCountSspClk() & 0xfffffff8); Uart.startTime -= Uart.syncBit; Uart.endTime = Uart.startTime; Uart.state = STATE_START_OF_COMMUNICATION; } -- } } else { -- if (IsMillerModulationNibble1(Uart.twoBits >> Uart.syncBit)) { -- if (IsMillerModulationNibble2(Uart.twoBits >> Uart.syncBit)) { // Modulation in both halves - error ++ if (IsMillerModulationNibble1(Uart.fourBits >> Uart.syncBit)) { ++ if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation in both halves - error UartReset(); } else { // Modulation in first half = Sequence Z = logic "0" if (Uart.state == STATE_MILLER_X) { // error - must not follow after X @@@ -322,7 -322,7 +328,7 @@@ } } } else { -- if (IsMillerModulationNibble2(Uart.twoBits >> Uart.syncBit)) { // Modulation second half = Sequence X = logic "1" ++ if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation second half = Sequence X = logic "1" Uart.bitCount++; Uart.shiftReg = (Uart.shiftReg >> 1) | 0x100; // add a 1 to the shiftreg Uart.state = STATE_MILLER_X; @@@ -358,12 -358,12 +364,10 @@@ return TRUE; // we are finished with decoding the raw data sequence } else { UartReset(); // Nothing received - start over -- Uart.highCnt = 1; } } if (Uart.state == STATE_START_OF_COMMUNICATION) { // error - must not follow directly after SOC UartReset(); -- Uart.highCnt = 1; } else { // a logic "0" Uart.bitCount++; Uart.shiftReg = (Uart.shiftReg >> 1); // add a 0 to the shiftreg @@@ -680,6 -680,6 +684,9 @@@ void RAMFUNC SnoopIso14443a(uint8_t par // And ready to receive another response. DemodReset(); ++ // And reset the Miller decoder including itS (now outdated) input buffer ++ UartInit(receivedCmd, receivedCmdPar); ++ LED_C_OFF(); } TagIsActive = (Demod.state != DEMOD_UNSYNCD); @@@ -1337,7 -1337,7 +1344,7 @@@ void CodeIso14443aBitsAsReaderPar(cons } // Only transmit parity bit if we transmitted a complete byte -- if (j == 8) { ++ if (j == 8 && parity != NULL) { // Get the parity bit if (parity[i>>3] & (0x80 >> (i&0x0007))) { // Sequence X @@@ -1631,6 -1631,6 +1638,7 @@@ static int GetIso14443aAnswerFromTag(ui } } ++ void ReaderTransmitBitsPar(uint8_t* frame, uint16_t bits, uint8_t *par, uint32_t *timing) { CodeIso14443aBitsAsReaderPar(frame, bits, par); @@@ -1646,11 -1646,11 +1654,13 @@@ } } ++ void ReaderTransmitPar(uint8_t* frame, uint16_t len, uint8_t *par, uint32_t *timing) { ReaderTransmitBitsPar(frame, len*8, par, timing); } ++ void ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing) { // Generate parity and redirect @@@ -1659,6 -1659,6 +1669,7 @@@ ReaderTransmitBitsPar(frame, len, par, timing); } ++ void ReaderTransmit(uint8_t* frame, uint16_t len, uint32_t *timing) { // Generate parity and redirect @@@ -1719,6 -1719,6 +1730,11 @@@ int iso14443a_select_card(byte_t *uid_p memset(uid_ptr,0,10); } ++ // check for proprietary anticollision: ++ if ((resp[0] & 0x1F) == 0) { ++ return 3; ++ } ++ // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in // which case we need to make a cascade 2 request and select - this is a long UID // While the UID is not complete, the 3nd bit (from the right) is set in the SAK. @@@ -1851,7 -1851,7 +1867,7 @@@ void iso14443a_setup(uint8_t fpga_minor DemodReset(); UartReset(); NextTransferTime = 2*DELAY_ARM2AIR_AS_READER; -- iso14a_set_timeout(1050); // 10ms default ++ iso14a_set_timeout(50*106); // 10ms default } int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, void *data) { @@@ -1927,15 -1927,15 +1943,38 @@@ void ReaderIso14443a(UsbCommand *c if(param & ISO14A_RAW) { if(param & ISO14A_APPEND_CRC) { ++ if(param & ISO14A_TOPAZMODE) { ++ AppendCrc14443b(cmd,len); ++ } else { AppendCrc14443a(cmd,len); ++ } len += 2; if (lenbits) lenbits += 16; } -- if(lenbits>0) { ++ if(lenbits>0) { // want to send a specific number of bits (e.g. short commands) ++ if(param & ISO14A_TOPAZMODE) { ++ int bits_to_send = lenbits; ++ uint16_t i = 0; ++ ReaderTransmitBitsPar(&cmd[i++], MIN(bits_to_send, 7), NULL, NULL); // first byte is always short (7bits) and no parity ++ bits_to_send -= 7; ++ while (bits_to_send > 0) { ++ ReaderTransmitBitsPar(&cmd[i++], MIN(bits_to_send, 8), NULL, NULL); // following bytes are 8 bit and no parity ++ bits_to_send -= 8; ++ } ++ } else { GetParity(cmd, lenbits/8, par); -- ReaderTransmitBitsPar(cmd, lenbits, par, NULL); ++ ReaderTransmitBitsPar(cmd, lenbits, par, NULL); // bytes are 8 bit with odd parity ++ } ++ } else { // want to send complete bytes only ++ if(param & ISO14A_TOPAZMODE) { ++ uint16_t i = 0; ++ ReaderTransmitBitsPar(&cmd[i++], 7, NULL, NULL); // first byte: 7 bits, no paritiy ++ while (i < len) { ++ ReaderTransmitBitsPar(&cmd[i++], 8, NULL, NULL); // following bytes: 8 bits, no paritiy ++ } } else { -- ReaderTransmit(cmd,len, NULL); ++ ReaderTransmit(cmd,len, NULL); // 8 bits, odd parity ++ } } arg0 = ReaderReceive(buf, par); cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf)); @@@ -2805,7 -2802,7 +2846,7 @@@ void RAMFUNC SniffMifare(uint8_t param if (MfSniffLogic(receivedCmd, Uart.len, Uart.parity, Uart.bitCount, TRUE)) break; /* And ready to receive another command. */ -- UartReset(); ++ UartInit(receivedCmd, receivedCmdPar); /* And also reset the demod code */ DemodReset(); @@@ -2822,6 -2819,6 +2863,8 @@@ // And ready to receive another response. DemodReset(); ++ // And reset the Miller decoder including its (now outdated) input buffer ++ UartInit(receivedCmd, receivedCmdPar); } TagIsActive = (Demod.state != DEMOD_UNSYNCD); } diff --cc armsrc/iso14443a.h index be8775ce,1e978e88..3344de43 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@@ -57,15 -56,15 +57,14 @@@ typedef struct // DROP_FIRST_HALF, } state; uint16_t shiftReg; -- uint16_t bitCount; ++ int16_t bitCount; uint16_t len; uint16_t byteCntMax; uint16_t posCnt; uint16_t syncBit; uint8_t parityBits; uint8_t parityLen; -- uint16_t highCnt; -- uint16_t twoBits; ++ uint32_t fourBits; uint32_t startTime, endTime; uint8_t *output; uint8_t *parity; diff --cc armsrc/lfops.c index 7537d63f,7bbc739d..6eb89912 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@@ -1206,14 -1183,14 +1214,15 @@@ void T55xxReadTrace(void) } if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { dest[i] = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - ++i; - LED_D_OFF(); - - if (i >= bufferlength) break; + i++; + LED_D_OFF(); + + if (i >= bufferlength) break; - } - } - + } + } + + cmd_send(CMD_ACK,0,0,0,0,0); + cmd_send(CMD_ACK,0,0,0,0,0); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off LED_D_OFF(); } diff --cc armsrc/mifarecmd.c index 94bc1c1c,a16cbf16..69b5b53c --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@@ -16,7 -16,7 +16,8 @@@ #include "mifarecmd.h" #include "apps.h" #include "util.h" -- ++//#include "../client/loclass/des.h" ++#include "des.h" #include "crc.h" //----------------------------------------------------------------------------- @@@ -104,14 -104,14 +105,14 @@@ void MifareUC_Auth1(uint8_t arg0, uint8 if(!iso14443a_select_card(uid, NULL, &cuid)) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); -- //OnError(0); ++ OnError(0); return; }; if(mifare_ultra_auth1(cuid, dataoutbuf)){ if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication part1: Fail."); -- //OnError(1); ++ OnError(1); return; } @@@ -138,7 -138,7 +139,7 @@@ void MifareUC_Auth2(uint32_t arg0, uint if(mifare_ultra_auth2(cuid, key, dataoutbuf)){ if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication part2: Fail..."); -- //OnError(1); ++ OnError(1); return; } @@@ -151,13 -151,13 +152,21 @@@ LEDsoff(); } --void MifareUReadBlock(uint8_t arg0,uint8_t *datain) ++void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) { uint8_t blockNo = arg0; byte_t dataout[16] = {0x00}; uint8_t uid[10] = {0x00}; ++ uint8_t key[8] = {0x00}; uint32_t cuid; -- ++ bool usePwd = false; ++ ++ usePwd = (arg1 == 1); ++ ++ // use password ++ if ( usePwd ) ++ memcpy(key, datain, 8); ++ LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@@ -167,22 -167,22 +176,82 @@@ int len = iso14443a_select_card(uid, NULL, &cuid); if(!len) { -- if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); -- //OnError(1); ++ if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%d)",len); ++ OnError(1); return; }; -- ++ ++ // authenticate here. ++ if ( usePwd ) { ++ ++ uint8_t a[8] = { 0x01 }; ++ uint8_t b[8] = { 0x00 }; ++ uint8_t enc_b[8] = { 0x00 }; ++ uint8_t ab[16] = { 0x00 }; ++ ++ uint8_t transKey[8] = { 0x00 }; ++ ++ uint16_t len; ++ uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; ++ uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; ++ ++ len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL); ++ if (len == 1) { ++ if (MF_DBGLEVEL >= MF_DBG_ERROR) ++ Dbprintf("Cmd Error: %02x", receivedAnswer[0]); ++ OnError(1); ++ return; ++ } ++ ++// memcpy(dataout, receivedAnswer, 11); ++ ++ // tag nonce. ++ memcpy(enc_b,receivedAnswer+1,8); ++ ++ // decrypt nonce. ++ des_dec(enc_b, b, key ); ++ ++ Dbprintf("enc_B: %02x %02x %02x %02x %02x %02x %02x %02x", enc_b[0],enc_b[1],enc_b[2],enc_b[3],enc_b[4],enc_b[5],enc_b[6],enc_b[7] ); ++ ++ rol(b,8); ++ ++ memcpy(ab ,a,8); ++ memcpy(ab+8,b,8); ++ ++ Dbprintf("AB: %02x %02x %02x %02x %02x %02x %02x %02x", ab[0],ab[1],ab[2],ab[3],ab[4],ab[5],ab[6],ab[7] ); ++ Dbprintf("AB: %02x %02x %02x %02x %02x %02x %02x %02x", ab[8],ab[9],ab[10],ab[11],ab[12],ab[13],ab[14],ab[15] ); ++ ++ // encrypt ++ des_enc(ab, ab, key); ++ ++ Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x", ab[0],ab[1],ab[2],ab[3],ab[4],ab[5],ab[6],ab[7] ); ++ Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x", ab[8],ab[9],ab[10],ab[11],ab[12],ab[13],ab[14],ab[15] ); ++ ++ len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, ab, receivedAnswer, receivedAnswerPar, NULL); ++ if (len == 1) { ++ if (MF_DBGLEVEL >= MF_DBG_ERROR) ++ Dbprintf("Cmd Error: %02x", receivedAnswer[0]); ++ OnError(1); ++ return; ++ } ++ ++ // ++ memcpy(transKey, receivedAnswer+1, 8); ++ Dbprintf("TRANSACTIONKEY: %02x %02x %02x %02x %02x %02x %02x %02x", transKey[0],transKey[1],transKey[2],transKey[3], ++ transKey[4],transKey[5],transKey[6],transKey[7] ); ++ } ++ len = mifare_ultra_readblock(cuid, blockNo, dataout); if(len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block error"); -- //OnError(2); ++ OnError(2); return; }; len = mifare_ultra_halt(cuid); if(len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Halt error"); -- //OnError(3); ++ OnError(3); return; }; @@@ -261,8 -261,8 +330,8 @@@ void MifareReadSector(uint8_t arg0, uin void MifareUReadCard(uint8_t arg0, int arg1, uint8_t *datain) { -- // params -- uint8_t sectorNo = arg0; ++ // params ++ uint8_t sectorNo = arg0; int Pages = arg1; int count_Pages = 0; byte_t dataout[176] = {0x00};; @@@ -283,8 -283,8 +352,8 @@@ if (!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) -- Dbprintf("Can't select card"); -- //OnError(1); ++ Dbprintf("Can't select card (RC:%d)",len); ++ OnError(1); return; } @@@ -295,7 -295,7 +364,7 @@@ if (len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block %d error",i); -- //OnError(2); ++ OnError(2); return; } else { count_Pages++; @@@ -306,7 -306,7 +375,7 @@@ if (len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Halt error"); -- //OnError(3); ++ OnError(3); return; } @@@ -1143,14 -1143,14 +1212,14 @@@ void Mifare_DES_Auth1(uint8_t arg0, uin if(!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); -- //OnError(1); ++ OnError(1); return; }; if(mifare_desfire_des_auth1(cuid, dataout)){ if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication part1: Fail."); -- //OnError(4); ++ OnError(4); return; } @@@ -1173,7 -1173,7 +1242,7 @@@ void Mifare_DES_Auth2(uint32_t arg0, ui if( isOK) { if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Authentication part2: Failed"); -- //OnError(4); ++ OnError(4); return; } diff --cc armsrc/mifaredesfire.c index 57376151,00000000..979e2f39 mode 100644,000000..100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@@ -1,507 -1,0 +1,508 @@@ +#include "mifaredesfire.h" +#include "des.h" ++#include "BigBuf.h" + +#define MAX_APPLICATION_COUNT 28 +#define MAX_FILE_COUNT 16 +#define MAX_DESFIRE_FRAME_SIZE 60 +#define NOT_YET_AUTHENTICATED 255 +#define FRAME_PAYLOAD_SIZE (MAX_DESFIRE_FRAME_SIZE - 5) +#define RECEIVE_SIZE 64 + +// the block number for the ISO14443-4 PCB +uint8_t pcb_blocknum = 0; +// Deselect card by sending a s-block. the crc is precalced for speed +static uint8_t deselect_cmd[] = {0xc2,0xe0,0xb4}; + +//static uint8_t __msg[MAX_FRAME_SIZE] = { 0x0A, 0x00, 0x00, /* ..., */ 0x00 }; +/* PCB CID CMD PAYLOAD */ +//static uint8_t __res[MAX_FRAME_SIZE]; + +bool InitDesfireCard(){ + + byte_t cardbuf[USB_CMD_DATA_SIZE] = {0x00}; + + iso14a_card_select_t *card = (iso14a_card_select_t*)cardbuf; + - iso14a_set_tracing(TRUE); ++ set_tracing(TRUE); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + int len = iso14443a_select_card(NULL,card,NULL); + + if (!len) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) + Dbprintf("Can't select card"); + OnError(1); + return false; + } + return true; +} + +// ARG0 flag enums +enum { + NONE = 0x00, + INIT = 0x01, + DISCONNECT = 0x02, + CLEARTRACE = 0x04, + BAR = 0x08, +} CmdOptions ; + +void MifareSendCommand(uint8_t arg0, uint8_t arg1, uint8_t *datain){ + + /* ARG0 contains flags. + 0x01 = init card. + 0x02 = Disconnect + 0x03 + */ + uint8_t flags = arg0; + size_t datalen = arg1; + uint8_t resp[RECEIVE_SIZE]; + memset(resp,0,sizeof(resp)); + + if (MF_DBGLEVEL >= 4) { + Dbprintf(" flags : %02X", flags); + Dbprintf(" len : %02X", datalen); + print_result(" RX : ", datain, datalen); + } + + if ( flags & CLEARTRACE ){ - iso14a_clear_trace(); ++ clear_trace(); + } + + if ( flags & INIT ){ + if ( !InitDesfireCard() ) + return; + } + + int len = DesfireAPDU(datain, datalen, resp); + if (MF_DBGLEVEL >= 4) { + print_result("ERR <--: ", resp, len); + } + + if ( !len ) { + OnError(2); + return; + } + + // reset the pcb_blocknum, + pcb_blocknum = 0; + + if ( flags & DISCONNECT ){ + OnSuccess(); + } + + cmd_send(CMD_ACK,1,len,0,resp,len); +} + +void MifareDesfireGetInformation(){ + + int len = 0; + uint8_t resp[USB_CMD_DATA_SIZE] = {0x00}; + uint8_t dataout[USB_CMD_DATA_SIZE] = {0x00}; + byte_t cardbuf[USB_CMD_DATA_SIZE] = {0x00}; + + /* + 1 = PCB 1 + 2 = cid 2 + 3 = desfire command 3 + 4-5 = crc 4 key + 5-6 crc + PCB == 0x0A because sending CID byte. + CID == 0x00 first card? + */ - iso14a_clear_trace(); - iso14a_set_tracing(TRUE); ++ clear_trace(); ++ set_tracing(TRUE); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + // card select - information + iso14a_card_select_t *card = (iso14a_card_select_t*)cardbuf; + byte_t isOK = iso14443a_select_card(NULL, card, NULL); + if ( isOK == 0) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) { + Dbprintf("Can't select card"); + } + OnError(1); + return; + } + + memcpy(dataout,card->uid,7); + + LED_A_ON(); + LED_B_OFF(); + LED_C_OFF(); + + uint8_t cmd[] = {GET_VERSION}; + size_t cmd_len = sizeof(cmd); + + len = DesfireAPDU(cmd, cmd_len, resp); + if ( !len ) { + print_result("ERROR <--: ", resp, len); + OnError(2); + return; + } + + LED_A_OFF(); + LED_B_ON(); + memcpy(dataout+7,resp+3,7); + + // ADDITION_FRAME 1 + cmd[0] = ADDITIONAL_FRAME; + len = DesfireAPDU(cmd, cmd_len, resp); + if ( !len ) { + print_result("ERROR <--: ", resp, len); + OnError(2); + return; + } + + LED_B_OFF(); + LED_C_ON(); + memcpy(dataout+7+7,resp+3,7); + + // ADDITION_FRAME 2 + len = DesfireAPDU(cmd, cmd_len, resp); + if ( !len ) { + print_result("ERROR <--: ", resp, len); + OnError(2); + return; + } + + memcpy(dataout+7+7+7,resp+3,14); + + cmd_send(CMD_ACK,1,0,0,dataout,sizeof(dataout)); + + // reset the pcb_blocknum, + pcb_blocknum = 0; + OnSuccess(); +} + +void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain){ + + int len = 0; + //uint8_t PICC_MASTER_KEY8[8] = { 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47}; + uint8_t PICC_MASTER_KEY16[16] = { 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f }; + uint8_t null_key_data8[8] = {0x00}; + //uint8_t null_key_data16[16] = {0x00}; + //uint8_t new_key_data8[8] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; + //uint8_t new_key_data16[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF}; + + uint8_t resp[256] = {0x00}; + uint8_t IV[16] = {0x00}; + + size_t datalen = datain[0]; + + uint8_t cmd[40] = {0x00}; + uint8_t encRndB[16] = {0x00}; + uint8_t decRndB[16] = {0x00}; + uint8_t nonce[16] = {0x00}; + uint8_t both[32] = {0x00}; + uint8_t encBoth[32] = {0x00}; + + InitDesfireCard(); + + // 3 olika sätt att authenticera. AUTH (CRC16) , AUTH_ISO (CRC32) , AUTH_AES (CRC32) + // 4 olika crypto algo DES, 3DES, 3K3DES, AES + // 3 olika kommunikations sätt, PLAIN,MAC,CRYPTO + + // des, nyckel 0, + switch (mode){ + case 1:{ + if (algo == 1) { + + uint8_t keybytes[8] = {0x00}; + uint8_t RndA[8] = {0x00}; + uint8_t RndB[8] = {0x00}; + + if (datain[1] == 0xff){ + memcpy(keybytes,null_key_data8,8); + } else{ + memcpy(keybytes, datain+1, datalen); + } + + struct desfire_key defaultkey = {0}; + desfirekey_t key = &defaultkey; + Desfire_des_key_new(keybytes, key); + + cmd[0] = AUTHENTICATE; + cmd[1] = keyno; //keynumber + len = DesfireAPDU(cmd, 2, resp); + if ( !len ) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnError(3); + return; + } + + if ( resp[2] == 0xaf ){ + } else { + DbpString("Authetication failed. Invalid key number."); + OnError(3); + return; + } + + memcpy( encRndB, resp+3, 8); + + des_dec(&decRndB, &encRndB, key->data); + memcpy(RndB, decRndB, 8); + rol(decRndB,8); + + // This should be random + uint8_t decRndA[8] = {0x00}; + memcpy(RndA, decRndA, 8); + uint8_t encRndA[8] = {0x00}; + + des_dec(&encRndA, &decRndA, key->data); + + memcpy(both, encRndA, 8); + + for (int x = 0; x < 8; x++) { + decRndB[x] = decRndB[x] ^ encRndA[x]; + } + + des_dec(&encRndB, &decRndB, key->data); + + memcpy(both + 8, encRndB, 8); + + cmd[0] = ADDITIONAL_FRAME; + memcpy(cmd+1, both, 16 ); + + len = DesfireAPDU(cmd, 17, resp); + if ( !len ) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnError(3); + return; + } + + if ( resp[2] == 0x00 ){ + + struct desfire_key sessionKey = {0}; + desfirekey_t skey = &sessionKey; + Desfire_session_key_new( RndA, RndB , key, skey ); + //print_result("SESSION : ", skey->data, 8); + + memcpy(encRndA, resp+3, 8); + des_dec(&encRndA, &encRndA, key->data); + rol(decRndA,8); + for (int x = 0; x < 8; x++) { + if (decRndA[x] != encRndA[x]) { + DbpString("Authetication failed. Cannot varify PICC."); + OnError(4); + return; + } + } + + //Change the selected key to a new value. + /* + + cmd[0] = CHANGE_KEY; + cmd[1] = keyno; + + uint8_t newKey[16] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; + + uint8_t first, second; + uint8_t buff1[8] = {0x00}; + uint8_t buff2[8] = {0x00}; + uint8_t buff3[8] = {0x00}; + + memcpy(buff1,newKey, 8); + memcpy(buff2,newKey + 8, 8); + + ComputeCrc14443(CRC_14443_A, newKey, 16, &first, &second); + memcpy(buff3, &first, 1); + memcpy(buff3 + 1, &second, 1); + + des_dec(&buff1, &buff1, skey->data); + memcpy(cmd+2,buff1,8); + + for (int x = 0; x < 8; x++) { + buff2[x] = buff2[x] ^ buff1[x]; + } + des_dec(&buff2, &buff2, skey->data); + memcpy(cmd+10,buff2,8); + + for (int x = 0; x < 8; x++) { + buff3[x] = buff3[x] ^ buff2[x]; + } + des_dec(&buff3, &buff3, skey->data); + memcpy(cmd+18,buff3,8); + + // The command always times out on the first attempt, this will retry until a response + // is recieved. + len = 0; + while(!len) { + len = DesfireAPDU(cmd,26,resp); + } + */ + + OnSuccess(); + cmd_send(CMD_ACK,1,0,0,skey->data,8); + + } else { + DbpString("Authetication failed."); + OnError(6); + return; + } + + } + } + break; + case 2: + //SendDesfireCommand(AUTHENTICATE_ISO, &keyno, resp); + break; + case 3:{ + + //defaultkey + uint8_t keybytes[16] = {0x00}; + if (datain[1] == 0xff){ + memcpy(keybytes,PICC_MASTER_KEY16,16); + } else{ + memcpy(keybytes, datain+1, datalen); + } + + struct desfire_key defaultkey = {0x00}; + desfirekey_t key = &defaultkey; + Desfire_aes_key_new( keybytes, key); + + AesCtx ctx; + if ( AesCtxIni(&ctx, IV, key->data, KEY128, CBC) < 0 ){ + if( MF_DBGLEVEL >= 4) { + Dbprintf("AES context failed to init"); + } + OnError(7); + return; + } + + cmd[0] = AUTHENTICATE_AES; + cmd[1] = 0x00; //keynumber + len = DesfireAPDU(cmd, 2, resp); + if ( !len ) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnError(3); + return; + } + + memcpy( encRndB, resp+3, 16); + + // dekryptera tagnonce. + AesDecrypt(&ctx, encRndB, decRndB, 16); + rol(decRndB,16); + memcpy(both, nonce,16); + memcpy(both+16, decRndB ,16 ); + AesEncrypt(&ctx, both, encBoth, 32 ); + + cmd[0] = ADDITIONAL_FRAME; + memcpy(cmd+1, encBoth, 32 ); + + len = DesfireAPDU(cmd, 33, resp); // 1 + 32 == 33 + if ( !len ) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) { + DbpString("Authentication failed. Card timeout."); + } + OnError(3); + return; + } + + if ( resp[2] == 0x00 ){ + // Create AES Session key + struct desfire_key sessionKey = {0}; + desfirekey_t skey = &sessionKey; + Desfire_session_key_new( nonce, decRndB , key, skey ); + print_result("SESSION : ", skey->data, 16); + } else { + DbpString("Authetication failed."); + OnError(7); + return; + } + break; + } + } + + OnSuccess(); + cmd_send(CMD_ACK,1,len,0,resp,len); +} + +// 3 olika ISO sätt att skicka data till DESFIRE (direkt, inkapslat, inkapslat ISO) +// cmd = cmd bytes to send +// cmd_len = length of cmd +// dataout = pointer to response data array +int DesfireAPDU(uint8_t *cmd, size_t cmd_len, uint8_t *dataout){ + + size_t len = 0; + size_t wrappedLen = 0; + uint8_t wCmd[USB_CMD_DATA_SIZE] = {0}; + - uint8_t *resp = ((uint8_t *)BigBuf) + RECV_RESP_OFFSET; - uint8_t *resp_par = ((uint8_t *)BigBuf) + RECV_RESP_PAR_OFFSET; ++ uint8_t resp[MAX_FRAME_SIZE]; ++ uint8_t par[MAX_PARITY_SIZE]; + + wrappedLen = CreateAPDU( cmd, cmd_len, wCmd); + + if (MF_DBGLEVEL >= 4) { + print_result("WCMD <--: ", wCmd, wrappedLen); + } + ReaderTransmit( wCmd, wrappedLen, NULL); + - len = ReaderReceive(resp, resp_par); ++ len = ReaderReceive(resp, par); + + if( len == 0x00 ){ + if (MF_DBGLEVEL >= 4) { + Dbprintf("fukked"); + } + return FALSE; //DATA LINK ERROR + } + // if we received an I- or R(ACK)-Block with a block number equal to the + // current block number, toggle the current block number + else if (len >= 4 // PCB+CID+CRC = 4 bytes + && ((resp[0] & 0xC0) == 0 // I-Block + || (resp[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0 + && (resp[0] & 0x01) == pcb_blocknum) // equal block numbers + { + pcb_blocknum ^= 1; //toggle next block + } + + memcpy(dataout, resp, len); + return len; +} + +// CreateAPDU +size_t CreateAPDU( uint8_t *datain, size_t len, uint8_t *dataout){ + + size_t cmdlen = MIN(len+4, USB_CMD_DATA_SIZE-1); + + uint8_t cmd[cmdlen]; + memset(cmd, 0, cmdlen); + + cmd[0] = 0x0A; // 0x0A = skicka cid, 0x02 = ingen cid. Särskilda bitar // + cmd[0] |= pcb_blocknum; // OR the block number into the PCB + cmd[1] = 0x00; // CID: 0x00 //TODO: allow multiple selected cards + + memcpy(cmd+2, datain, len); + AppendCrc14443a(cmd, len+2); + + memcpy(dataout, cmd, cmdlen); + + return cmdlen; +} + + // crc_update(&desfire_crc32, 0, 1); /* CMD_WRITE */ + // crc_update(&desfire_crc32, addr, addr_sz); + // crc_update(&desfire_crc32, byte, 8); + // uint32_t crc = crc_finish(&desfire_crc32); + +void OnSuccess(){ + pcb_blocknum = 0; + ReaderTransmit(deselect_cmd, 3 , NULL); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); +} + +void OnError(uint8_t reason){ + pcb_blocknum = 0; + ReaderTransmit(deselect_cmd, 3 , NULL); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + cmd_send(CMD_ACK,0,reason,0,0,0); + LEDsoff(); +} diff --cc client/Makefile index ae116dd6,81af0149..4fd41b46 --- a/client/Makefile +++ b/client/Makefile @@@ -94,6 -84,6 +94,8 @@@ CMDSRCS = nonce2key/crapto1.c cmdhficlass.c \ cmdhfmf.c \ cmdhfmfu.c \ ++ cmdhfmfdes.c \ ++ cmdhftopaz.c \ cmdhw.c \ cmdlf.c \ cmdlfio.c \ diff --cc client/cmdhf.c index 22063bbb,22063bbb..eba70a66 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@@ -23,6 -23,6 +23,8 @@@ #include "cmdhficlass.h" #include "cmdhfmf.h" #include "cmdhfmfu.h" ++#include "cmdhfmfdes.h" ++#include "cmdhftopaz.h" #include "protocols.h" static int CmdHelp(const char *Cmd); @@@ -141,6 -141,6 +143,26 @@@ void annotateIso15693(char *exp, size_ } } ++ ++void annotateTopaz(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) ++{ ++ switch(cmd[0]) { ++ case TOPAZ_REQA :snprintf(exp, size, "REQA");break; ++ case TOPAZ_WUPA :snprintf(exp, size, "WUPA");break; ++ case TOPAZ_RID :snprintf(exp, size, "RID");break; ++ case TOPAZ_RALL :snprintf(exp, size, "RALL");break; ++ case TOPAZ_READ :snprintf(exp, size, "READ");break; ++ case TOPAZ_WRITE_E :snprintf(exp, size, "WRITE-E");break; ++ case TOPAZ_WRITE_NE :snprintf(exp, size, "WRITE-NE");break; ++ case TOPAZ_RSEG :snprintf(exp, size, "RSEG");break; ++ case TOPAZ_READ8 :snprintf(exp, size, "READ8");break; ++ case TOPAZ_WRITE_E8 :snprintf(exp, size, "WRITE-E8");break; ++ case TOPAZ_WRITE_NE8 :snprintf(exp, size, "WRITE-NE8");break; ++ default: snprintf(exp,size,"?"); break; ++ } ++} ++ ++ /** 06 00 = INITIATE 0E xx = SELECT ID (xx = Chip-ID) @@@ -172,7 -172,7 +194,34 @@@ void annotateIso14443b(char *exp, size_ } /** -- * @brief iso14443B_CRC_Ok Checks CRC in command or response ++ * @brief iso14443A_CRC_check Checks CRC in command or response ++ * @param isResponse ++ * @param data ++ * @param len ++ * @return 0 : CRC-command, CRC not ok ++ * 1 : CRC-command, CRC ok ++ * 2 : Not crc-command ++ */ ++ ++uint8_t iso14443A_CRC_check(bool isResponse, uint8_t* data, uint8_t len) ++{ ++ uint8_t b1,b2; ++ ++ if(len <= 2) return 2; ++ ++ if(isResponse & (len < 6)) return 2; ++ ++ ComputeCrc14443(CRC_14443_A, data, len-2, &b1, &b2); ++ if (b1 != data[len-2] || b2 != data[len-1]) { ++ return 0; ++ } else { ++ return 1; ++ } ++} ++ ++ ++/** ++ * @brief iso14443B_CRC_check Checks CRC in command or response * @param isResponse * @param data * @param len @@@ -190,8 -190,8 +239,9 @@@ uint8_t iso14443B_CRC_check(bool isResp ComputeCrc14443(CRC_14443_B, data, len-2, &b1, &b2); if(b1 != data[len-2] || b2 != data[len-1]) { return 0; -- } ++ } else { return 1; ++ } } /** @@@ -255,11 -255,11 +305,66 @@@ uint8_t iclass_CRC_check(bool isRespons } } --uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles) ++ ++bool is_last_record(uint16_t tracepos, uint8_t *trace, uint16_t traceLen) { -- bool isResponse; -- uint16_t duration, data_len, parity_len; ++ return(tracepos + sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint16_t) >= traceLen); ++} ++ ++ ++bool next_record_is_response(uint16_t tracepos, uint8_t *trace) ++{ ++ uint16_t next_records_datalen = *((uint16_t *)(trace + tracepos + sizeof(uint32_t) + sizeof(uint16_t))); ++ ++ return(next_records_datalen & 0x8000); ++} ++ ++ ++bool merge_topaz_reader_frames(uint32_t timestamp, uint32_t *duration, uint16_t *tracepos, uint16_t traceLen, uint8_t *trace, uint8_t *frame, uint8_t *topaz_reader_command, uint16_t *data_len) ++{ ++ ++#define MAX_TOPAZ_READER_CMD_LEN 16 ++ uint32_t last_timestamp = timestamp + *duration; ++ ++ if ((*data_len != 1) || (frame[0] == TOPAZ_WUPA) || (frame[0] == TOPAZ_REQA)) return false; ++ ++ memcpy(topaz_reader_command, frame, *data_len); ++ ++ while (!is_last_record(*tracepos, trace, traceLen) && !next_record_is_response(*tracepos, trace)) { ++ uint32_t next_timestamp = *((uint32_t *)(trace + *tracepos)); ++ *tracepos += sizeof(uint32_t); ++ uint16_t next_duration = *((uint16_t *)(trace + *tracepos)); ++ *tracepos += sizeof(uint16_t); ++ uint16_t next_data_len = *((uint16_t *)(trace + *tracepos)) & 0x7FFF; ++ *tracepos += sizeof(uint16_t); ++ uint8_t *next_frame = (trace + *tracepos); ++ *tracepos += next_data_len; ++ if ((next_data_len == 1) && (*data_len + next_data_len <= MAX_TOPAZ_READER_CMD_LEN)) { ++ memcpy(topaz_reader_command + *data_len, next_frame, next_data_len); ++ *data_len += next_data_len; ++ last_timestamp = next_timestamp + next_duration; ++ } else { ++ // rewind and exit ++ *tracepos = *tracepos - next_data_len - sizeof(uint16_t) - sizeof(uint16_t) - sizeof(uint32_t); ++ break; ++ } ++ uint16_t next_parity_len = (next_data_len-1)/8 + 1; ++ *tracepos += next_parity_len; ++ } ++ ++ *duration = last_timestamp - timestamp; ++ ++ return true; ++} ++ ++ ++uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles, bool markCRCBytes) ++{ ++ bool isResponse; ++ uint16_t data_len, parity_len; ++ uint32_t duration; ++ uint8_t topaz_reader_command[9]; uint32_t timestamp, first_timestamp, EndOfTransmissionTimestamp; char explanation[30] = {0}; @@@ -290,29 -290,29 +395,31 @@@ uint8_t *parityBytes = trace + tracepos; tracepos += parity_len; ++ if (protocol == TOPAZ && !isResponse) { ++ // topaz reader commands come in 1 or 9 separate frames with 7 or 8 Bits each. ++ // merge them: ++ if (merge_topaz_reader_frames(timestamp, &duration, &tracepos, traceLen, trace, frame, topaz_reader_command, &data_len)) { ++ frame = topaz_reader_command; ++ } ++ } ++ //Check the CRC status uint8_t crcStatus = 2; if (data_len > 2) { -- uint8_t b1, b2; -- if(protocol == ICLASS) -- { ++ switch (protocol) { ++ case ICLASS: crcStatus = iclass_CRC_check(isResponse, frame, data_len); -- -- }else if (protocol == ISO_14443B) -- { ++ break; ++ case ISO_14443B: ++ case TOPAZ: crcStatus = iso14443B_CRC_check(isResponse, frame, data_len); -- } -- else if (protocol == ISO_14443A){//Iso 14443a -- -- ComputeCrc14443(CRC_14443_A, frame, data_len-2, &b1, &b2); -- -- if (b1 != frame[data_len-2] || b2 != frame[data_len-1]) { -- if(!(isResponse & (data_len < 6))) -- { -- crcStatus = 0; -- } -- } ++ break; ++ case ISO_14443A: ++ crcStatus = iso14443A_CRC_check(isResponse, frame, data_len); ++ break; ++ default: ++ break; } } //0 CRC-command, CRC not ok @@@ -334,19 -334,19 +441,22 @@@ uint8_t parityBits = parityBytes[j>>3]; if (isResponse && (oddparity != ((parityBits >> (7-(j&0x0007))) & 0x01))) { snprintf(line[j/16]+(( j % 16) * 4),110, "%02x! ", frame[j]); -- } else { snprintf(line[j/16]+(( j % 16) * 4),110, "%02x ", frame[j]); } } -- if(crcStatus == 1) ++ ++ if (markCRCBytes) { ++ if(crcStatus == 0 || crcStatus == 1) {//CRC-command -- char *pos1 = line[(data_len-2)/16]+(((data_len-2) % 16) * 4)-1; ++ char *pos1 = line[(data_len-2)/16]+(((data_len-2) % 16) * 4); (*pos1) = '['; -- char *pos2 = line[(data_len)/16]+(((data_len) % 16) * 4)-2; -- (*pos2) = ']'; ++ char *pos2 = line[(data_len)/16]+(((data_len) % 16) * 4); ++ sprintf(pos2, "%c", ']'); ++ } } ++ if(data_len == 0) { if(data_len == 0){ @@@ -361,18 -361,18 +471,19 @@@ if(!isResponse) { -- if(protocol == ICLASS) -- annotateIclass(explanation,sizeof(explanation),frame,data_len); -- else if (protocol == ISO_14443A) -- annotateIso14443a(explanation,sizeof(explanation),frame,data_len); -- else if(protocol == ISO_14443B) -- annotateIso14443b(explanation,sizeof(explanation),frame,data_len); ++ switch(protocol) { ++ case ICLASS: annotateIclass(explanation,sizeof(explanation),frame,data_len); break; ++ case ISO_14443A: annotateIso14443a(explanation,sizeof(explanation),frame,data_len); break; ++ case ISO_14443B: annotateIso14443b(explanation,sizeof(explanation),frame,data_len); break; ++ case TOPAZ: annotateTopaz(explanation,sizeof(explanation),frame,data_len); break; ++ default: break; ++ } } int num_lines = MIN((data_len - 1)/16 + 1, 16); for (int j = 0; j < num_lines ; j++) { if (j == 0) { -- PrintAndLog(" %9d | %9d | %s | %-64s| %s| %s", ++ PrintAndLog(" %10d | %10d | %s |%-64s | %s| %s", (timestamp - first_timestamp), (EndOfTransmissionTimestamp - first_timestamp), (isResponse ? "Tag" : "Rdr"), @@@ -387,20 -387,20 +498,16 @@@ } } -- if (tracepos + sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint16_t) > traceLen) return traceLen; ++ if (is_last_record(tracepos, trace, traceLen)) return traceLen; -- bool next_isResponse = *((uint16_t *)(trace + tracepos + 6)) & 0x8000; -- -- if (showWaitCycles && !isResponse && next_isResponse) { ++ if (showWaitCycles && !isResponse && next_record_is_response(tracepos, trace)) { uint32_t next_timestamp = *((uint32_t *)(trace + tracepos)); -- if (next_timestamp != 0x44444444) { PrintAndLog(" %9d | %9d | %s | fdt (Frame Delay Time): %d", (EndOfTransmissionTimestamp - first_timestamp), (next_timestamp - first_timestamp), " ", (next_timestamp - EndOfTransmissionTimestamp)); } -- } return tracepos; } @@@ -409,34 -409,34 +516,35 @@@ int CmdHFList(const char *Cmd) { bool showWaitCycles = false; ++ bool markCRCBytes = false; char type[40] = {0}; int tlen = param_getstr(Cmd,0,type); -- char param = param_getchar(Cmd, 1); ++ char param1 = param_getchar(Cmd, 1); ++ char param2 = param_getchar(Cmd, 2); bool errors = false; uint8_t protocol = 0; //Validate params -- if(tlen == 0) -- { ++ ++ if(tlen == 0) { errors = true; } -- if(param == 'h' || (param !=0 && param != 'f')) -- { ++ ++ if(param1 == 'h' ++ || (param1 != 0 && param1 != 'f' && param1 != 'c') ++ || (param2 != 0 && param2 != 'f' && param2 != 'c')) { errors = true; } -- if(!errors) -- { -- if(strcmp(type, "iclass") == 0) -- { ++ ++ if(!errors) { ++ if(strcmp(type, "iclass") == 0) { protocol = ICLASS; -- }else if(strcmp(type, "14a") == 0) -- { ++ } else if(strcmp(type, "14a") == 0) { protocol = ISO_14443A; -- } -- else if(strcmp(type, "14b") == 0) -- { ++ } else if(strcmp(type, "14b") == 0) { protocol = ISO_14443B; -- }else if(strcmp(type,"raw")== 0) -- { ++ } else if(strcmp(type,"topaz")== 0) { ++ protocol = TOPAZ; ++ } else if(strcmp(type,"raw")== 0) { protocol = -1;//No crc, no annotations }else{ errors = true; @@@ -445,13 -445,13 +553,15 @@@ if (errors) { PrintAndLog("List protocol data in trace buffer."); -- PrintAndLog("Usage: hf list [f]"); ++ PrintAndLog("Usage: hf list [f][c]"); PrintAndLog(" f - show frame delay times as well"); ++ PrintAndLog(" c - mark CRC bytes"); PrintAndLog("Supported values:"); PrintAndLog(" raw - just show raw data without annotations"); PrintAndLog(" 14a - interpret data as iso14443a communications"); PrintAndLog(" 14b - interpret data as iso14443b communications"); PrintAndLog(" iclass - interpret data as iclass communications"); ++ PrintAndLog(" topaz - interpret data as topaz communications"); PrintAndLog(""); PrintAndLog("example: hf list 14a f"); PrintAndLog("example: hf list iclass"); @@@ -459,10 -459,10 +569,13 @@@ } -- if (param == 'f') { ++ if (param1 == 'f' || param2 == 'f') { showWaitCycles = true; } ++ if (param1 == 'c' || param2 == 'c') { ++ markCRCBytes = true; ++ } uint8_t *trace; uint16_t tracepos = 0; @@@ -496,7 -496,7 +609,7 @@@ while(tracepos < traceLen) { -- tracepos = printTraceLine(tracepos, traceLen, trace, protocol, showWaitCycles); ++ tracepos = printTraceLine(tracepos, traceLen, trace, protocol, showWaitCycles, markCRCBytes); } free(trace); @@@ -514,9 -514,9 +627,11 @@@ static command_t CommandTable[] {"legic", CmdHFLegic, 0, "{ LEGIC RFIDs... }"}, {"iclass", CmdHFiClass, 1, "{ ICLASS RFIDs... }"}, {"mf", CmdHFMF, 1, "{ MIFARE RFIDs... }"}, -- {"mfu", CmdHFMFUltra, 1, "{ MIFARE Ultralight RFIDs... }"}, -- {"tune", CmdHFTune, 0, "Continuously measure HF antenna tuning"}, -- {"list", CmdHFList, 1, "List protocol data in trace buffer"}, ++ {"mfu", CmdHFMFUltra, 1, "{ MIFARE Ultralight RFIDs... }"}, ++ {"mfdes", CmdHFMFDes, 1, "{ MIFARE Desfire RFIDs... }"}, ++ {"topaz", CmdHFTopaz, 1, "{ TOPAZ (NFC Type 1) RFIDs... }"}, ++ {"tune", CmdHFTune, 0, "Continuously measure HF antenna tuning"}, ++ {"list", CmdHFList, 1, "List protocol data in trace buffer"}, {NULL, NULL, 0, NULL} }; diff --cc client/cmdhf14a.c index bce7f4d6,d36ebb8b..6fc4d2a0 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@@ -140,7 -140,7 +140,7 @@@ int CmdHF14AReader(const char *Cmd iso14a_card_select_t card; memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); -- uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS ++ uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision if(select_status == 0) { PrintAndLog("iso14443a card select failed"); @@@ -152,6 -152,6 +152,18 @@@ return 0; } ++ if(select_status == 3) { ++ PrintAndLog("Card doesn't support standard iso14443-3 anticollision"); ++ PrintAndLog("ATQA : %02x %02x", card.atqa[1], card.atqa[0]); ++ // disconnect ++ c.arg[0] = 0; ++ c.arg[1] = 0; ++ c.arg[2] = 0; ++ SendCommand(&c); ++ return 0; ++ } ++ ++ PrintAndLog("ATQA : %02x %02x", card.atqa[1], card.atqa[0]); PrintAndLog(" UID : %s", sprint_hex(card.uid, card.uidlen)); PrintAndLog(" SAK : %02x [%d]", card.sak, resp.arg[0]); @@@ -497,16 -497,16 +509,18 @@@ int CmdHF14ASnoop(const char *Cmd) return 0; } ++ int CmdHF14ACmdRaw(const char *cmd) { UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; -- uint8_t reply=1; -- uint8_t crc=0; -- uint8_t power=0; -- uint8_t active=0; -- uint8_t active_select=0; ++ bool reply=1; ++ bool crc = FALSE; ++ bool power = FALSE; ++ bool active = FALSE; ++ bool active_select = FALSE; uint16_t numbits=0; ++ bool bTimeout = FALSE; uint32_t timeout=0; -- uint8_t bTimeout=0; ++ bool topazmode = FALSE; char buf[5]=""; int i=0; uint8_t data[USB_CMD_DATA_SIZE]; @@@ -522,9 -522,9 +536,11 @@@ PrintAndLog(" -s active signal field ON with select"); PrintAndLog(" -b number of bits to send. Useful for send partial byte"); PrintAndLog(" -t timeout in ms"); ++ PrintAndLog(" -T use Topaz protocol to send command"); return 0; } ++ // strip while (*cmd==' ' || *cmd=='\t') cmd++; @@@ -533,19 -533,19 +549,19 @@@ if (cmd[i]=='-') { switch (cmd[i+1]) { case 'r': -- reply=0; ++ reply = FALSE; break; case 'c': -- crc=1; ++ crc = TRUE; break; case 'p': -- power=1; ++ power = TRUE; break; case 'a': -- active=1; ++ active = TRUE; break; case 's': -- active_select=1; ++ active_select = TRUE; break; case 'b': sscanf(cmd+i+2,"%d",&temp); @@@ -555,13 -555,13 +571,16 @@@ i-=2; break; case 't': -- bTimeout=1; ++ bTimeout = TRUE; sscanf(cmd+i+2,"%d",&temp); timeout = temp; i+=3; while(cmd[i]!=' ' && cmd[i]!='\0') { i++; } i-=2; break; ++ case 'T': ++ topazmode = TRUE; ++ break; default: PrintAndLog("Invalid option"); return 0; @@@ -591,10 -591,10 +610,15 @@@ PrintAndLog("Invalid char on input"); return 0; } ++ if(crc && datalen>0 && datalen MAX_TIMEOUT) { timeout = MAX_TIMEOUT; @@@ -615,11 -615,11 +639,16 @@@ } c.arg[2] = 13560000 / 1000 / (8*16) * timeout; // timeout in ETUs (time to transfer 1 bit, approx. 9.4 us) } ++ if(power) c.arg[0] |= ISO14A_NO_DISCONNECT; ++ if(datalen>0) c.arg[0] |= ISO14A_RAW; ++ if(topazmode) ++ c.arg[0] |= ISO14A_TOPAZMODE; ++ // Max buffer is USB_CMD_DATA_SIZE c.arg[1] = (datalen & 0xFFFF) | (numbits << 16); memcpy(c.d.asBytes,data,datalen); @@@ -635,6 -635,6 +664,7 @@@ return 0; } ++ static void waitCmd(uint8_t iSelect) { uint8_t *recv; diff --cc client/cmdhfmfdes.c index 75aaa084,00000000..c3cdde2c mode 100644,000000..100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@@ -1,685 -1,0 +1,686 @@@ +//----------------------------------------------------------------------------- +// Copyright (C) 2014 Iceman +// +// This code is licensed to you under the terms of the GNU GPL, version 2 or, +// at your option, any later version. See the LICENSE.txt file for the text of +// the license. +//----------------------------------------------------------------------------- +// High frequency MIFARE Desfire commands +//----------------------------------------------------------------------------- + +#include +#include +#include +#include - #include ++//#include ++#include "loclass/des.h" +#include "cmdmain.h" +#include "proxmark3.h" +#include "../include/common.h" +#include "../include/mifare.h" +#include "../common/iso14443crc.h" +#include "data.h" +#include "ui.h" +#include "cmdparser.h" +#include "util.h" +#include "cmdhfmfdes.h" + +uint8_t CMDPOS = 0; +uint8_t LENPOS = 1; + +uint8_t key_zero_data[16] = { 0x00 }; +uint8_t key_ones_data[16] = { 0x01 }; +uint8_t key_defa_data[16] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f }; +uint8_t key_picc_data[16] = { 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f }; + +static int CmdHelp(const char *Cmd); +static void xor(unsigned char * dst, unsigned char * src, size_t len); +static int32_t le24toh (uint8_t data[3]); + + +int CmdHF14ADesWb(const char *Cmd) +{ +/* uint8_t blockNo = 0; + uint8_t keyType = 0; + uint8_t key[6] = {0, 0, 0, 0, 0, 0}; + uint8_t bldata[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + char cmdp = 0x00; + + if (strlen(Cmd)<3) { + PrintAndLog("Usage: hf mf wrbl "); + PrintAndLog(" sample: hf mf wrbl 0 A FFFFFFFFFFFF 000102030405060708090A0B0C0D0E0F"); + return 0; + } + + blockNo = param_get8(Cmd, 0); + cmdp = param_getchar(Cmd, 1); + if (cmdp == 0x00) { + PrintAndLog("Key type must be A or B"); + return 1; + } + if (cmdp != 'A' && cmdp != 'a') keyType = 1; + if (param_gethex(Cmd, 2, key, 12)) { + PrintAndLog("Key must include 12 HEX symbols"); + return 1; + } + if (param_gethex(Cmd, 3, bldata, 32)) { + PrintAndLog("Block data must include 32 HEX symbols"); + return 1; + } + PrintAndLog("--block no:%02x key type:%02x key:%s", blockNo, keyType, sprint_hex(key, 6)); + PrintAndLog("--data: %s", sprint_hex(bldata, 16)); + + UsbCommand c = {CMD_MIFARE_WRITEBL, {blockNo, keyType, 0}}; + memcpy(c.d.asBytes, key, 6); + memcpy(c.d.asBytes + 10, bldata, 16); + SendCommand(&c); + + UsbCommand resp; + if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + uint8_t isOK = resp.arg[0] & 0xff; + PrintAndLog("isOk:%02x", isOK); + } else { + PrintAndLog("Command execute timeout"); + } + */ + return 0; +} + +int CmdHF14ADesRb(const char *Cmd) +{ + // uint8_t blockNo = 0; + // uint8_t keyType = 0; + // uint8_t key[6] = {0, 0, 0, 0, 0, 0}; + + // char cmdp = 0x00; + + + // if (strlen(Cmd)<3) { + // PrintAndLog("Usage: hf mf rdbl "); + // PrintAndLog(" sample: hf mf rdbl 0 A FFFFFFFFFFFF "); + // return 0; + // } + + // blockNo = param_get8(Cmd, 0); + // cmdp = param_getchar(Cmd, 1); + // if (cmdp == 0x00) { + // PrintAndLog("Key type must be A or B"); + // return 1; + // } + // if (cmdp != 'A' && cmdp != 'a') keyType = 1; + // if (param_gethex(Cmd, 2, key, 12)) { + // PrintAndLog("Key must include 12 HEX symbols"); + // return 1; + // } + // PrintAndLog("--block no:%02x key type:%02x key:%s ", blockNo, keyType, sprint_hex(key, 6)); + + // UsbCommand c = {CMD_MIFARE_READBL, {blockNo, keyType, 0}}; + // memcpy(c.d.asBytes, key, 6); + // SendCommand(&c); + + // UsbCommand resp; + // if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + // uint8_t isOK = resp.arg[0] & 0xff; + // uint8_t * data = resp.d.asBytes; + + // if (isOK) + // PrintAndLog("isOk:%02x data:%s", isOK, sprint_hex(data, 16)); + // else + // PrintAndLog("isOk:%02x", isOK); + // } else { + // PrintAndLog("Command execute timeout"); + // } + + return 0; +} + +int CmdHF14ADesInfo(const char *Cmd){ + + UsbCommand c = {CMD_MIFARE_DESFIRE_INFO}; + SendCommand(&c); + UsbCommand resp; + + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + PrintAndLog("Command execute timeout"); + return 0; + } + uint8_t isOK = resp.arg[0] & 0xff; + if ( !isOK ){ + PrintAndLog("Command unsuccessful"); + return 0; + } + PrintAndLog(""); + PrintAndLog("-- Desfire Information --------------------------------------"); + PrintAndLog("-------------------------------------------------------------"); + PrintAndLog(" UID : %s",sprint_hex(resp.d.asBytes, 7)); + PrintAndLog(" Batch number : %s",sprint_hex(resp.d.asBytes+28,5)); + PrintAndLog(" Production date : week %02x, 20%02x",resp.d.asBytes[33], resp.d.asBytes[34]); + PrintAndLog(" -----------------------------------------------------------"); + PrintAndLog(" Hardware Information"); + PrintAndLog(" Vendor Id : %s", GetVendorStr(resp.d.asBytes[7])); + PrintAndLog(" Type : 0x%02X",resp.d.asBytes[8]); + PrintAndLog(" Subtype : 0x%02X",resp.d.asBytes[9]); + PrintAndLog(" Version : %d.%d",resp.d.asBytes[10], resp.d.asBytes[11]); + PrintAndLog(" Storage size : %s",GetCardSizeStr(resp.d.asBytes[12])); + PrintAndLog(" Protocol : %s",GetProtocolStr(resp.d.asBytes[13])); + PrintAndLog(" -----------------------------------------------------------"); + PrintAndLog(" Software Information"); + PrintAndLog(" Vendor Id : %s",GetVendorStr(resp.d.asBytes[14])); + PrintAndLog(" Type : 0x%02X",resp.d.asBytes[15]); + PrintAndLog(" Subtype : 0x%02X",resp.d.asBytes[16]); + PrintAndLog(" Version : %d.%d",resp.d.asBytes[17], resp.d.asBytes[18]); + PrintAndLog(" storage size : %s", GetCardSizeStr(resp.d.asBytes[19])); + PrintAndLog(" Protocol : %s", GetProtocolStr(resp.d.asBytes[20])); + PrintAndLog("-------------------------------------------------------------"); + + // Master Key settings + GetKeySettings(NULL); + + // Free memory on card + c.cmd = CMD_MIFARE_DESFIRE; + c.arg[0] = (INIT | DISCONNECT); + c.arg[1] = 0x01; + c.d.asBytes[0] = GET_FREE_MEMORY; + SendCommand(&c); + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + return 0; + } + + uint8_t tmp[3]; + memcpy(tmp, resp.d.asBytes+3,3); + + PrintAndLog(" Available free memory on card : %d bytes", le24toh( tmp )); + PrintAndLog("-------------------------------------------------------------"); + + /* + Card Master key (CMK) 0x00 AID = 00 00 00 (card level) + Application Master Key (AMK) 0x00 AID != 00 00 00 + Application keys (APK) 0x01-0x0D + Application free 0x0E + Application never 0x0F + + ACCESS RIGHTS: + keys 0,1,2,3 C + keys 4,5,6,7 RW + keys 8,9,10,11 W + keys 12,13,14,15 R + + */ + + return 1; +} + +char * GetVendorStr( uint8_t id){ + static char buf[30]; + char *retStr = buf; + + if ( id == 0x04 ) + sprintf(retStr, "0x%02X (NXP)",id); + else + sprintf(retStr,"0x%02X (Unknown)",id); + return buf; +} + +/* + The 7 MSBits (= n) code the storage size itself based on 2^n, + the LSBit is set to '0' if the size is exactly 2^n + and set to '1' if the storage size is between 2^n and 2^(n+1). + For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. +*/ +char * GetCardSizeStr( uint8_t fsize ){ + + static char buf[30]; + char *retStr = buf; + + uint16_t usize = 1 << ((fsize >>1) + 1); + uint16_t lsize = 1 << (fsize >>1); + + // is LSB set? - if ( fsize & (1 << 0 ) ) ++ if ( fsize & 1 ) + sprintf(retStr, "0x%02X (%d - %d bytes)",fsize, usize, lsize); + else + sprintf(retStr, "0x%02X (%d bytes)", fsize, lsize); + return buf; +} + +char * GetProtocolStr(uint8_t id){ + + static char buf[30]; + char *retStr = buf; + + if ( id == 0x05) + sprintf(retStr,"0x%02X (ISO 14443-3, 14443-4)", id); + else - sprintf(retStr,"0x%02X", id); ++ sprintf(retStr,"0x%02X (Unknown)", id); + return buf; +} + +void GetKeySettings( uint8_t *aid){ + + char messStr[512] = {0x00}; + char *str = messStr; + uint8_t isOK = 0; + uint32_t options = NONE; + UsbCommand c; + UsbCommand resp; + + //memset(messStr, 0x00, 512); + + c.cmd = CMD_MIFARE_DESFIRE; + + if ( aid == NULL ){ + PrintAndLog(" CMK - PICC, Card Master Key settings "); + PrintAndLog(""); + c.arg[CMDPOS] = (INIT | DISCONNECT); + c.arg[LENPOS] = 0x01; + c.d.asBytes[0] = GET_KEY_SETTINGS; // 0x45 + SendCommand(&c); + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1000) ) {return;} + isOK = resp.arg[0] & 0xff; + if ( !isOK ){ + PrintAndLog(" Can't select master application"); + return; + } + + str = (resp.d.asBytes[3] & (1 << 3 )) ? "YES":"NO"; + PrintAndLog(" [0x08] Configuration changeable : %s", str); + str = (resp.d.asBytes[3] & (1 << 2 )) ? "NO":"YES"; + PrintAndLog(" [0x04] CMK required for create/delete : %s",str); + str = (resp.d.asBytes[3] & (1 << 1 )) ? "NO":"YES"; + PrintAndLog(" [0x02] Directory list access with CMK : %s",str); + str = (resp.d.asBytes[3] & (1 << 0 )) ? "YES" : "NO"; + PrintAndLog(" [0x01] CMK is changeable : %s", str); + + c.arg[LENPOS] = 0x02; //LEN + c.d.asBytes[0] = GET_KEY_VERSION; //0x64 + c.d.asBytes[1] = 0x00; + SendCommand(&c); + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1000) ) { + return; + } + isOK = resp.arg[0] & 0xff; + if ( !isOK ){ + PrintAndLog(" Can't read key-version"); + return; + } + PrintAndLog(""); + PrintAndLog(" Max number of keys : %d", resp.d.asBytes[4]); + PrintAndLog(" Master key Version : %d (0x%02x)", resp.d.asBytes[3], resp.d.asBytes[3]); + PrintAndLog(" ----------------------------------------------------------"); + + c.arg[LENPOS] = 0x02; //LEN + c.d.asBytes[0] = AUTHENTICATE; //0x0A + c.d.asBytes[1] = 0x00; // KEY 0 + SendCommand(&c); + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1000) ) {return;} + isOK = resp.d.asBytes[2] & 0xff; + PrintAndLog(" [0x0A] Authenticate : %s", ( isOK==0xAE ) ? "NO":"YES"); + + c.d.asBytes[0] = AUTHENTICATE_ISO; //0x1A + SendCommand(&c); + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1000) ) {return;} + isOK = resp.d.asBytes[2] & 0xff; + PrintAndLog(" [0x1A] Authenticate ISO : %s", ( isOK==0xAE ) ? "NO":"YES"); + + c.d.asBytes[0] = AUTHENTICATE_AES; //0xAA + SendCommand(&c); + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1000) ) {return;} + isOK = resp.d.asBytes[2] & 0xff; + PrintAndLog(" [0xAA] Authenticate AES : %s", ( isOK==0xAE ) ? "NO":"YES"); + PrintAndLog(""); + PrintAndLog(" ----------------------------------------------------------"); + + } else { + PrintAndLog(" AMK - Application Master Key settings"); + + // SELECT AID + c.arg[0] = (INIT | CLEARTRACE); + c.arg[LENPOS] = 0x04; + c.d.asBytes[0] = SELECT_APPLICATION; // 0x5a + memcpy(c.d.asBytes+1, aid, 3); + SendCommand(&c); + + if (!WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + PrintAndLog(" Timed-out"); + return; + } + isOK = resp.arg[0] & 0xff; + if ( !isOK ){ + PrintAndLog(" Can't select AID: %s",sprint_hex(aid,3)); + return; + } + + // KEY SETTINGS + options = NONE; + c.arg[0] = options; + c.arg[LENPOS] = 0x01; + c.d.asBytes[0] = GET_KEY_SETTINGS; // 0x45 + SendCommand(&c); + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + return; + } + isOK = resp.arg[0] & 0xff; + if ( !isOK ){ + PrintAndLog(" Can't read Application Master key settings"); + } else { + // Access rights. + uint8_t rights = (resp.d.asBytes[3] >> 4 && 0xff); + switch (rights){ + case 0x00: + str = "AMK authentication is necessary to change any key (default)"; + break; + case 0x0e: + str = "Authentication with the key to be changed (same KeyNo) is necessary to change a key"; + break; + case 0x0f: + str = "All keys (except AMK,see Bit0) within this application are frozen"; + break; + default: + str = "Authentication with the specified key is necessary to change any ley. A change key and a PICC master key (CMK) can only be changed after authentication with the master key. For keys other then the master or change key, an authentication with the same key is needed."; + break; + } + PrintAndLog("Changekey Access rights"); + PrintAndLog("-- %s",str); + PrintAndLog(""); + // same as CMK + str = (resp.d.asBytes[3] & (1 << 3 )) ? "YES":"NO"; + PrintAndLog(" 0x08 Configuration changeable : %s", str); + str = (resp.d.asBytes[3] & (1 << 2 )) ? "NO":"YES"; + PrintAndLog(" 0x04 AMK required for create/delete : %s",str); + str = (resp.d.asBytes[3] & (1 << 1 )) ? "NO":"YES"; + PrintAndLog(" 0x02 Directory list access with AMK : %s",str); + str = (resp.d.asBytes[3] & (1 << 0 )) ? "YES" : "NO"; + PrintAndLog(" 0x01 AMK is changeable : %s", str); + } + + // KEY VERSION - AMK + c.arg[0] = NONE; + c.arg[LENPOS] = 0x02; + c.d.asBytes[0] = GET_KEY_VERSION; //0x64 + c.d.asBytes[1] = 0x00; + SendCommand(&c); + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + PrintAndLog(" Timed-out"); + return; + } + + int numOfKeys; + + isOK = resp.arg[0] & 0xff; + if ( !isOK ){ + PrintAndLog(" Can't read Application Master key version. Trying all keys"); + numOfKeys = MAX_NUM_KEYS; + } + else{ + numOfKeys = resp.d.asBytes[4]; + PrintAndLog(""); + PrintAndLog(" Max number of keys : %d", numOfKeys ); + PrintAndLog(" Application Master key Version : %d (0x%02x)", resp.d.asBytes[3], resp.d.asBytes[3]); + PrintAndLog("-------------------------------------------------------------"); + } + + // LOOP over numOfKeys that we got before. + // From 0x01 to numOfKeys. We already got 0x00. (AMK) + for(int i=0x01; i<=0x0f; ++i){ + + } + + + } +} + +int CmdHF14ADesEnumApplications(const char *Cmd){ + + uint8_t isOK = 0x00; + uint8_t aid[3]; + uint32_t options = (INIT | DISCONNECT); + + UsbCommand c = {CMD_MIFARE_DESFIRE, {options , 0x01 }}; + c.d.asBytes[0] = GET_APPLICATION_IDS; //0x6a + + SendCommand(&c); + UsbCommand resp; + + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + return 0; + } + isOK = resp.arg[0] & 0xff; + if ( !isOK ){ + PrintAndLog("Command unsuccessful"); + return 0; + } + PrintAndLog(""); + PrintAndLog("-- Desfire Enumerate Applications ---------------------------"); + PrintAndLog("-------------------------------------------------------------"); + + UsbCommand respAid; + UsbCommand respFiles; + + uint8_t num = 0; + int max = resp.arg[1] -3 -2; + + for(int i=3; i<=max; i+=3){ + PrintAndLog(" Aid %d : %02X %02X %02X ",num ,resp.d.asBytes[i],resp.d.asBytes[i+1],resp.d.asBytes[i+2]); + num++; + + aid[0] = resp.d.asBytes[i]; + aid[1] = resp.d.asBytes[i+1]; + aid[2] = resp.d.asBytes[i+2]; + GetKeySettings(aid); + + // Select Application + c.arg[CMDPOS] = INIT; + c.arg[LENPOS] = 0x04; + c.d.asBytes[0] = SELECT_APPLICATION; // 0x5a + c.d.asBytes[1] = resp.d.asBytes[i]; + c.d.asBytes[2] = resp.d.asBytes[i+1]; + c.d.asBytes[3] = resp.d.asBytes[i+2]; + SendCommand(&c); + + if (!WaitForResponseTimeout(CMD_ACK,&respAid,1500) ) { + PrintAndLog(" Timed-out"); + continue; + } + isOK = respAid.d.asBytes[2] & 0xff; + if ( isOK != 0x00 ){ + PrintAndLog(" Can't select AID: %s",sprint_hex(resp.d.asBytes+i,3)); + continue; + } + + // Get File IDs + c.arg[CMDPOS] = NONE; + c.arg[LENPOS] = 0x01; + c.d.asBytes[0] = GET_FILE_IDS; // 0x6f + SendCommand(&c); + + if ( !WaitForResponseTimeout(CMD_ACK,&respFiles,1500) ) { + PrintAndLog(" Timed-out"); + continue; + } else { + isOK = respFiles.d.asBytes[2] & 0xff; + if ( !isOK ){ + PrintAndLog(" Can't get file ids "); + } else { + int respfileLen = resp.arg[1]-3-2; + for (int j=0; j< respfileLen; ++j){ + PrintAndLog(" Fileid %d :", resp.d.asBytes[j+3]); + } + } + } + + // Get ISO File IDs + c.arg[CMDPOS] = DISCONNECT; + c.arg[LENPOS] = 0x01; + c.d.asBytes[0] = GET_ISOFILE_IDS; // 0x61 + SendCommand(&c); + + if ( !WaitForResponseTimeout(CMD_ACK,&respFiles,1500) ) { + PrintAndLog(" Timed-out"); + continue; + } else { + isOK = respFiles.d.asBytes[2] & 0xff; + if ( !isOK ){ + PrintAndLog(" Can't get ISO file ids "); + } else { + int respfileLen = resp.arg[1]-3-2; + for (int j=0; j< respfileLen; ++j){ + PrintAndLog(" ISO Fileid %d :", resp.d.asBytes[j+3]); + } + } + } + + + } + PrintAndLog("-------------------------------------------------------------"); + + + return 1; +} + +// MIAFRE DesFire Authentication +// +#define BUFSIZE 256 +int CmdHF14ADesAuth(const char *Cmd){ + + // NR DESC KEYLENGHT + // ------------------------ + // 1 = DES 8 + // 2 = 3DES 16 + // 3 = 3K 3DES 24 + // 4 = AES 16 + + uint8_t keylength = 8; + unsigned char key[24]; + + if (strlen(Cmd)<3) { + PrintAndLog("Usage: hf mfdes auth <1|2|3> <1|2|3|4> "); + PrintAndLog(" Auth modes"); + PrintAndLog(" 1 = normal, 2 = iso, 3 = aes"); + PrintAndLog(" Crypto"); + PrintAndLog(" 1 = DES 2 = 3DES 3 = 3K3DES 4 = AES"); + PrintAndLog(""); + PrintAndLog(" sample: hf mfdes auth 1 1 0 11223344"); + PrintAndLog(" sample: hf mfdes auth 3 4 0 404142434445464748494a4b4c4d4e4f"); + return 0; + } + uint8_t cmdAuthMode = param_get8(Cmd,0); + uint8_t cmdAuthAlgo = param_get8(Cmd,1); + uint8_t cmdKeyNo = param_get8(Cmd,2); + + switch (cmdAuthMode) + { + case 1: + if ( cmdAuthAlgo != 1 && cmdAuthAlgo != 2) { + PrintAndLog("Crypto algo not valid for the auth mode"); + return 1; + } + break; + case 2: + if ( cmdAuthAlgo != 1 && cmdAuthAlgo != 2 && cmdAuthAlgo != 3) { + PrintAndLog("Crypto algo not valid for the auth mode"); + return 1; + } + break; + case 3: + if ( cmdAuthAlgo != 4) { + PrintAndLog("Crypto algo not valid for the auth mode"); + return 1; + } + break; + default: + PrintAndLog("Wrong Auth mode"); + return 1; + break; + } + + switch (cmdAuthAlgo){ + case 2: + keylength = 16; + PrintAndLog("3DES selected"); + break; + case 3: + keylength = 24; + PrintAndLog("3 key 3DES selected"); + break; + case 4: + keylength = 16; + PrintAndLog("AES selected"); + break; + default: + cmdAuthAlgo = 1; + keylength = 8; + PrintAndLog("DES selected"); + break; + } + + // key + if (param_gethex(Cmd, 3, key, keylength*2)) { + PrintAndLog("Key must include %d HEX symbols", keylength); + return 1; + } + // algo, nyckellängd, + UsbCommand c = {CMD_MIFARE_DESFIRE_AUTH1, { cmdAuthMode, cmdAuthAlgo, cmdKeyNo }}; + + c.d.asBytes[0] = keylength; + memcpy(c.d.asBytes+1, key, keylength); + + SendCommand(&c); + UsbCommand resp; + + if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) { + PrintAndLog("Client command execute timeout"); + return 0; + } + + uint8_t isOK = resp.arg[0] & 0xff; + if ( isOK) { + uint8_t * data= resp.d.asBytes; + + PrintAndLog(" Key :%s",sprint_hex(key, keylength)); + PrintAndLog(" SESSION :%s",sprint_hex(data, keylength)); + PrintAndLog("-------------------------------------------------------------"); + //PrintAndLog(" Expected :B5 21 9E E8 1A A7 49 9D 21 96 68 7E 13 97 38 56"); + } else{ + PrintAndLog("Client command failed."); + } + PrintAndLog("-------------------------------------------------------------"); + return 1; +} + + +static void xor(unsigned char * dst, unsigned char * src, size_t len) { + for( ; len > 0; len--,dst++,src++) + *dst ^= *src; +} + +static int32_t le24toh (uint8_t data[3]) { + return (data[2] << 16) | (data[1] << 8) | data[0]; +} + +static command_t CommandTable[] = +{ + {"help", CmdHelp, 1, "This help"}, + {"auth", CmdHF14ADesAuth, 0, "Tries a MIFARE DesFire Authentication"}, + {"rb", CmdHF14ADesRb, 0, "Read MIFARE DesFire block"}, + {"wb", CmdHF14ADesWb, 0, "write MIFARE DesFire block"}, + {"info", CmdHF14ADesInfo, 0, "Get MIFARE DesFire information"}, + {"enum", CmdHF14ADesEnumApplications,0, "Tries enumerate all applications"}, + {NULL, NULL, 0, NULL} +}; + +int CmdHFMFDes(const char *Cmd) +{ + // flush + WaitForResponseTimeout(CMD_ACK,NULL,100); + CmdsParse(CommandTable, Cmd); + return 0; +} + +int CmdHelp(const char *Cmd) +{ + CmdsHelp(CommandTable); + return 0; +} + + diff --cc client/cmdhfmfu.c index 75080f25,8dfb9a3b..f85c160a --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@@ -7,7 -7,7 +7,6 @@@ //----------------------------------------------------------------------------- // High frequency MIFARE ULTRALIGHT (C) commands //----------------------------------------------------------------------------- --//#include #include "loclass/des.h" #include "cmdhfmfu.h" #include "cmdhfmf.h" @@@ -391,7 -391,7 +390,7 @@@ int CmdHF14AMfucAuth(const char *Cmd) //Change key to user defined one if (cmdp == 'k' || cmdp == 'K'){ keyNo = param_get8(Cmd, 1); -- if(keyNo >= 4) errors = true; ++ if(keyNo > 4) errors = true; } if (cmdp == 'h' || cmdp == 'H') { @@@ -430,7 -430,7 +429,6 @@@ uint8_t * data= resp.d.asBytes; if (isOK){ -- PrintAndLog("enc(RndB):%s", sprint_hex(data+1, 8)); memcpy(enc_random_b,data+1,8); } else { PrintAndLog("Auth failed"); @@@ -440,10 -440,10 +438,7 @@@ PrintAndLog("Command execute timeout"); return 1; } -- uint8_t iv[8] = { 0 }; -- // Do we need random ? Right now we use all ones, is that random enough ? --// DES_random_key(&RndA); PrintAndLog(" RndA :%s",sprint_hex(random_a, 8)); PrintAndLog(" e_RndB:%s",sprint_hex(enc_random_b, 8)); @@@ -490,6 -490,6 +485,23 @@@ if (isOK){ PrintAndLog("enc(RndA'):%s", sprint_hex(data2+1, 8)); ++ ++ uint8_t foo[8] = { 0 }; ++ uint8_t bar[8] = { 0 }; ++ memcpy(foo, data2+1, 8); ++ des3_set2key_enc(&ctx, key); ++ ++ des3_crypt_cbc(&ctx // des3_context *ctx ++ , DES_DECRYPT // int mode ++ , 8 // size_t length ++ , enc_random_b // unsigned char iv[8] ++ , foo // const unsigned char *input ++ , bar // unsigned char *output ++ ); ++ ++ PrintAndLog("BAR:%s",sprint_hex(bar, 8)); ++ ++ } else { return 2; } diff --cc client/cmdhfmfu.h index c4bc0341,c4bc0341..ccb53ad0 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@@ -1,6 -1,6 +1,9 @@@ #include "cmdhfmf.h" #include "cmdhf14a.h" ++#ifndef CMDHFMFU_H__ ++#define CMDHFMFU_H__ ++ //standard ultralight int CmdHF14AMfUWrBl(const char *Cmd); int CmdHF14AMfURdBl(const char *Cmd); @@@ -14,6 -14,6 +17,6 @@@ int CmdHF14AMfucAuth(const char *Cmd) int CmdHF14AMfUDump(const char *Cmd); void rol (uint8_t *data, const size_t len); -- int CmdHFMFUltra(const char *Cmd); int CmdHF14AMfUInfo(const char *Cmd); ++#endif diff --cc client/cmdlf.c index 46927f74,0fab2adf..30c8bb22 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@@ -486,15 -488,11 +488,16 @@@ int CmdLFRead(const char *Cmd { return usage_lf_read(); } + if (param_getchar(Cmd, cmdp) == 's') arg1 = true; //suppress print //And ship it to device - UsbCommand c = {CMD_ACQUIRE_RAW_ADC_SAMPLES_125K}; + UsbCommand c = {CMD_ACQUIRE_RAW_ADC_SAMPLES_125K, {arg1,0,0}}; SendCommand(&c); - WaitForResponse(CMD_ACK,NULL); + //WaitForResponse(CMD_ACK,NULL); + if ( !WaitForResponseTimeout(CMD_ACK,NULL,2500) ) { + PrintAndLog("command execution time out"); + return 1; + } + return 0; } @@@ -1045,9 -1044,8 +1048,9 @@@ int CmdLFfind(const char *Cmd PrintAndLog("NOTE: some demods output possible binary\n if it finds something that looks like a tag"); PrintAndLog("False Positives ARE possible\n"); PrintAndLog("\nChecking for known tags:\n"); - + ans=CmdFSKdemodIO(""); + if (ans>0) { PrintAndLog("\nValid IO Prox ID Found!"); return 1; @@@ -1156,21 -1132,15 +1163,21 @@@ static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"cmdread", CmdLFCommandRead, 0, " <'0' period> <'1' period> ['h'] -- Modulate LF reader field to send command before read (all periods in microseconds) (option 'h' for 134)"}, {"em4x", CmdLFEM4X, 1, "{ EM4X RFIDs... }"}, + {"hid", CmdLFHID, 1, "{ HID RFIDs... }"}, + {"hitag", CmdLFHitag, 1, "{ HITAG RFIDs... }"}, + {"io", CmdLFIO, 1, "{ IOPROX RFIDs... }"}, + {"pcf7931", CmdLFPCF7931, 1, "{ PCF7931 RFIDs... }"}, + {"ti", CmdLFTI, 1, "{ TI RFIDs... }"}, + {"t55xx", CmdLFT55XX, 1, "{ T55X7 RFIDs... }"}, + {"config", CmdLFSetConfig, 0, "Set config for LF sampling, bit/sample, decimation, frequency"}, + + {"cmdread", CmdLFCommandRead, 0, " <'0' period> <'1' period> ['h'] -- Modulate LF reader field to send command before read (all periods in microseconds) (option 'h' for 134)"}, {"flexdemod", CmdFlexdemod, 1, "Demodulate samples for FlexPass"}, - {"hid", CmdLFHID, 1, "{ HID RFIDs... }"}, - {"io", CmdLFIO, 1, "{ ioProx tags... }"}, {"indalademod", CmdIndalaDemod, 1, "['224'] -- Demodulate samples for Indala 64 bit UID (option '224' for 224 bit)"}, {"indalaclone", CmdIndalaClone, 0, " ['l']-- Clone Indala to T55x7 (tag must be in antenna)(UID in HEX)(option 'l' for 224 UID"}, - {"read", CmdLFRead, 0, "Read 125/134 kHz LF ID-only tag. Do 'lf read h' for help"}, + {"read", CmdLFRead, 0, "['s' silent] Read 125/134 kHz LF ID-only tag. Do 'lf read h' for help"}, {"search", CmdLFfind, 1, "[offline] ['u'] Read and Search for valid known tag (in offline mode it you can load first then search) - 'u' to search for unknown tags"}, {"sim", CmdLFSim, 0, "[GAP] -- Simulate LF tag from buffer with optional GAP (in microseconds)"}, {"simask", CmdLFaskSim, 0, "[clock] [invert <1|0>] [manchester/raw <'m'|'r'>] [msg separator 's'] [d ] -- Simulate LF ASK tag from demodbuffer or input"}, diff --cc common/lfdemod.c index 5b90f1c4,c7acb404..3305c8b0 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@@ -142,8 -97,8 +97,9 @@@ uint8_t Em410xDecode(uint8_t *BitStream for (uint8_t extraBitChk=0; extraBitChk<5; extraBitChk++){ errChk = preambleSearch(BitStream+extraBitChk+*startIdx, preamble, sizeof(preamble), size, startIdx); if (errChk == 0) return 0; + if (*size<64) return 0; if (*size>64) FmtLen = 22; + if (*size<64) return 0; idx = *startIdx + 9; for (i=0; i